Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Onnx Onnx OpSchema System

From Leeroopedia


Knowledge Sources
Domains Schema Validation, Operator Registry, Type System
Last Updated 2026-02-10 00:00 GMT

Overview

schema.cc implements the OpSchema system for ONNX operator definitions, providing schema registration, node validation, type checking, function body management, versioned operator set loading, and the global OpSchemaRegistry singleton.

Description

This file is the core implementation of the ONNX operator schema infrastructure. It contains several major subsystems:

Schema registration is handled by RegisterSchema() (two overloads: const reference and rvalue reference) and DeregisterSchema(). Registration calls OpSchemaRegistry::OpSchemaRegisterOnce::OpSchemaRegisterImpl() which finalizes the schema, checks for duplicates, validates version ranges against DomainToVersionRange, and inserts into the global map. The OpSchemaRegistry::map() function initializes the registry on first access using a static SchemasRegisterer class that calls registration functions for all domains: RegisterOnnxOperatorSetSchema(), RegisterOnnxMLOperatorSetSchema() (if ONNX_ML defined), RegisterOnnxTrainingOperatorSetSchema(), and RegisterOnnxPreviewOperatorSetSchema().

Node validation via OpSchema::Verify() checks deprecated status, verifies input/output counts against min/max constraints, validates that single-marked parameters are not empty, checks for duplicate attributes, verifies attribute types match expected types, validates attribute field presence (e.g., tensor attributes must have field 't'), ensures required attributes are present, and ignores internal symbols (names starting with "__").

Type checking via OpSchema::CheckInputOutputType() validates input types against allowed type sets, enforces homogeneous type constraints across inputs sharing the same type parameter, infers output types when possible (from single-type constraints or matched type parameters), and validates output types similarly.

Schema builder methods implement the fluent API pattern: SinceVersion() (with function body version reindexing), Deprecate(), NumInputs()/NumOutputs() with allowed sets, Input()/Output() with formal parameter options, Attr() with various default value types (expanded via macros for int64_t, float, string, TensorProto, GraphProto, TypeProto and their vector variants), TypeConstraint(), TypeAndShapeInferenceFunction(), PartialDataPropagationFunction(), and SetContextDependentFunctionBodyBuilder().

Function body management supports multiple function body versions via opset_version_to_function_body_ and opset_version_to_function_builder_ maps. FunctionBody() accepts text (parsed via OnnxParser), node vectors, or node vectors with opset imports. GetFunction() retrieves the appropriate function body for a requested opset version with optional validation. BuildContextDependentFunction() uses registered builder callbacks. ValidateReferencedOpsInFunction() ensures ops used in function bodies have not changed between the function's since_version and the requested version.

Type constants provide pre-defined type constraint vectors for different IR versions (e.g., all_tensor_types(), all_numeric_types_ir9(), all_float_types_ir4(), etc.), covering types from basic (tensor(float), tensor(int32)) through low-precision formats (tensor(float8e4m3fn), tensor(uint4), tensor(int2)).

Finalization via Finalize() calculates min/max input/output counts from formal parameter options, validates all parameters have names, resolves type constraints, and builds function protobuf structures.

Usage

This file is compiled as part of the ONNX core library and provides the runtime infrastructure for all operator schema operations. It is not used directly by external code but is invoked through the OpSchema and OpSchemaRegistry APIs defined in schema.h.

Code Reference

Source Location

Signature

// Schema registration
void RegisterSchema(const OpSchema& schema, int opset_version_to_load = 0,
    bool fail_duplicate_schema = true, bool fail_with_exception = false);
void RegisterSchema(OpSchema&& schema, int opset_version_to_load = 0,
    bool fail_duplicate_schema = true, bool fail_with_exception = false);
void DeregisterSchema(const std::string& op_type, int version, const std::string& domain);

// Core OpSchema methods
void OpSchema::Verify(const NodeProto& node) const;
void OpSchema::CheckInputOutputType(struct InferenceContext& ctx) const;
OpSchema& OpSchema::SinceVersion(OperatorSetVersion v);
OpSchema& OpSchema::FunctionBody(const char* func_body, int opset_version);
const FunctionProto* OpSchema::GetFunction(int requested_opset_version, bool validate) const;
bool OpSchema::BuildContextDependentFunction(const FunctionBodyBuildContext& ctx,
    FunctionProto& function_proto, int requested_opset_version) const;
void OpSchema::Finalize();

// Registry
OpSchemaRegistry* OpSchemaRegistry::Instance();
OpName_Domain_Version_Schema_Map& OpSchemaRegistry::map();

Import

#include "onnx/defs/schema.h"

I/O Contract

Inputs

Name Type Required Description
schema OpSchema (const& or &&) Yes The operator schema to register, containing name, domain, version, inputs, outputs, attributes, type constraints, and optional function body
opset_version_to_load int No Target opset version for version-specific registration. 0 means register all versions (default).
node const NodeProto& Yes (for Verify) The node to validate against this schema
ctx InferenceContext& Yes (for CheckInputOutputType) The inference context providing input/output types for validation
requested_opset_version int No The opset version to retrieve a function body for (defaults to since_version)

Outputs

Name Type Description
(side effect) OpSchemaRegistry Registered schemas are stored in the global registry singleton and become available for lookup
FunctionProto* const FunctionProto* GetFunction returns a pointer to the function body matching the requested version, or nullptr if not found
(exception) SchemaError Verify and registration throw SchemaError on validation failures

Usage Examples

#include "onnx/defs/schema.h"

using namespace ONNX_NAMESPACE;

// Register a custom operator schema
OpSchema schema;
schema.SetName("MyOp")
    .SetDomain("com.example")
    .SinceVersion(1)
    .Input(0, "X", "Input tensor", "T")
    .Output(0, "Y", "Output tensor", "T")
    .TypeConstraint("T", {"tensor(float)", "tensor(double)"}, "Constrained types")
    .SetDoc("My custom operator.");
RegisterSchema(std::move(schema));

// Look up an operator schema
const OpSchema* add_schema = OpSchemaRegistry::Schema("Add", 13, "");

// Verify a node against its schema
NodeProto node;
node.set_op_type("Add");
node.add_input("A");
node.add_input("B");
node.add_output("C");
add_schema->Verify(node);

// Get a function body for a function op
const OpSchema* layernorm = OpSchemaRegistry::Schema("LayerNormalization", 17, "");
const FunctionProto* func = layernorm->GetFunction(18, true);

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment