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 Cpp2py Export

From Leeroopedia


Knowledge Sources
Domains Python Bindings, FFI, Core Infrastructure
Last Updated 2026-02-10 00:00 GMT

Overview

Creates the Python bindings for ONNX's C++ functionality using the nanobind library, exposing core features such as schema management, model checking, shape inference, version conversion, inlining, parsing, and printing to Python code.

Description

The cpp2py_export.cc file is the critical bridge between ONNX's high-performance C++ implementation and Python's ease of use. It uses the nanobind framework to create the onnx_cpp2py_export Python extension module, which is the foundation of the ONNX Python package.

The file begins by defining the ONNX_DEFINE_TYPE_CASTER macro, which creates custom type casters for automatic conversion between Python protobuf objects and their C++ counterparts. This macro generates bidirectional conversion: Python-to-C++ via SerializeToString()/ParseProtoFromPyBytes(), and C++-to-Python via SerializeAsString()/ParseFromString(). Type casters are registered for nine protobuf types: AttributeProto, TypeProto, TensorProto, SparseTensorProto, ValueInfoProto, NodeProto, GraphProto, ModelProto, and FunctionProto.

The module is organized into six submodules:

defs (schema submodule): Exposes OpSchema class with full constructor support, property accessors (name, domain, doc, inputs, outputs, attributes, type_constraints), and methods for schema querying (get_schema, get_all_schemas, has_schema), registration (register_schema, deregister_schema), and inference (_infer_node_outputs). Also exposes nested classes Attribute, TypeConstraintParam, FormalParameter, and enums FormalParameterOption, DifferentiationCategory, NodeDeterminism, AttrType, SupportType.

checker submodule: Exposes validation functions for all ONNX entities: check_value_info, check_tensor, check_sparse_tensor, check_attribute, check_node, check_function, check_graph, check_model, and check_model_path. Exposes CheckerContext and LexicalScopeContext classes and ValidationError exception.

version_converter submodule: Exposes convert_version which converts ONNX models between opset versions, automatically running shape inference before conversion.

inliner submodule: Exposes inline_local_functions, inline_selected_functions, and inline_selected_functions2 for expanding function definitions within models.

shape_inference submodule: Exposes infer_shapes (from bytes), infer_shapes_path (from file), infer_function_output_types, and the InferenceContext/GraphInferencer classes for custom inference functions.

parser and printer submodules: Expose text-format parsing (parse_model, parse_graph, parse_function, parse_node) and printing (model_to_text, function_to_text, graph_to_text).

The CallNodeInferenceFunction helper performs node-level type and shape inference by constructing a full InferenceContextImpl with type maps, input data, and graph inference context.

Usage

This module is imported internally by the ONNX Python package. Users do not import it directly; instead, they use the Python-level wrappers in onnx.defs, onnx.checker, onnx.shape_inference, etc. The module is built as a native extension during ONNX package installation.

Code Reference

Source Location

Signature

namespace ONNX_NAMESPACE {

NB_MODULE(onnx_cpp2py_export, onnx_cpp2py_export) {
    // Submodule: defs
    auto defs = onnx_cpp2py_export.def_submodule("defs");
    nb::class_<OpSchema> op_schema(defs, "OpSchema");
    // ... schema bindings ...

    // Submodule: checker
    auto checker = onnx_cpp2py_export.def_submodule("checker");
    // ... checker bindings ...

    // Submodule: version_converter
    auto version_converter = onnx_cpp2py_export.def_submodule("version_converter");
    // ... version converter bindings ...

    // Submodule: inliner
    auto inliner = onnx_cpp2py_export.def_submodule("inliner");
    // ... inliner bindings ...

    // Submodule: shape_inference
    auto shape_inference = onnx_cpp2py_export.def_submodule("shape_inference");
    // ... shape inference bindings ...

    // Submodule: parser
    auto parser = onnx_cpp2py_export.def_submodule("parser");
    // ... parser bindings ...

    // Submodule: printer
    auto printer = onnx_cpp2py_export.def_submodule("printer");
    // ... printer bindings ...
}

} // namespace ONNX_NAMESPACE

Import

# Python-side imports (internal to ONNX package)
from onnx import onnx_cpp2py_export
from onnx.onnx_cpp2py_export import defs as C
from onnx.onnx_cpp2py_export import checker as C_checker
from onnx.onnx_cpp2py_export import shape_inference as C_shape_inference

I/O Contract

Inputs

Name Type Required Description
bytes nb::bytes Yes (most functions) Serialized protobuf message as bytes
op_type std::string Yes (get_schema) Operator type name
domain std::string No Operator domain; defaults to ONNX_DOMAIN
max_inclusive_version int No Maximum opset version for schema lookup
check_type bool No Enable type checking in shape inference (default: false)
strict_mode bool No Enable strict mode in shape inference (default: false)
target int Yes (convert_version) Target opset version for version conversion
schema OpSchema Yes (register_schema) Schema object to register

Outputs

Name Type Description
OpSchema OpSchema Operator schema object with full metadata
bytes nb::bytes Serialized protobuf result (shape inference, version conversion, parsing)
tuple(bool, bytes, bytes) tuple Parse result: (success, error_message, serialized_proto)
str std::string Text representation (printer functions)
vector<OpSchema> list All schemas (get_all_schemas, get_all_schemas_with_history)

Usage Examples

import onnx
from onnx import onnx_cpp2py_export

# Get operator schema
schema = onnx_cpp2py_export.defs.get_schema("Conv", 11)
print(schema.name, schema.since_version, schema.domain)

# Check a model
model = onnx.load("model.onnx")
onnx_cpp2py_export.checker.check_model(
    model.SerializeToString(), full_check=True
)

# Run shape inference
inferred_bytes = onnx_cpp2py_export.shape_inference.infer_shapes(
    model.SerializeToString(), check_type=True
)
inferred_model = onnx.ModelProto()
inferred_model.ParseFromString(inferred_bytes)

# Parse model from text
ok, err, proto_bytes = onnx_cpp2py_export.parser.parse_model(text_repr)

# Print model as text
text = onnx_cpp2py_export.printer.model_to_text(model.SerializeToString())

Related Pages

Page Connections

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