onnx_light.onnx_core.graph_builder#

Full builds load the compiled kernel registry when this module is imported, so constant folding does not depend on importing ReferenceEvaluator first. Reduced builds without the kernels extension still support graph authoring. Required shape constant folding in such builds raises an error identifying the missing operator kernel; importing the builder does not suppress extension loading failures when the extension is present.

GraphBuilder.to_onnx() returns a ModelProto by default. To export another proto type, use the ProtoKind enum instead of a string:

from onnx_light.onnx_core.graph_builder import GraphBuilder, ProtoKind

builder = GraphBuilder("g")
model = builder.to_onnx()
graph = builder.to_onnx(ProtoKind.kGraph)
function = builder.to_onnx(ProtoKind.kFunction, domain="custom")

ProtoKind.kModel explicitly selects a model. The ir_version argument applies to models, and domain applies to functions. String selectors such as "model", "graph" and "function" are no longer accepted.

The keyword-only optimize option selects an optimization/export workflow:

from onnx_light.onnx_core.graph_builder import OptimizationMode

canonical = builder.to_onnx()
materialized = builder.to_onnx(optimize=OptimizationMode.kOptimize)
bundled = builder.to_onnx(optimize=OptimizationMode.kRewritings)
replayed = GraphBuilder(bundled).apply_rewritings("optimized").to_standard_model()

OptimizationMode.kNone is the default and preserves the existing export behavior. OptimizationMode.kOptimize optimizes a copy with the global and builder-local pattern registrations and returns the optimized result without rewrite plans. Model exports use to_standard_model and reject constructs that standard ONNX cannot represent. Graph and function exports also accept OptimizationMode.kOptimize. Function export represents dense initializers as leading Constant nodes, including initializers introduced by optimization, without changing the source builder. Tensor payloads and external-data descriptors are preserved. This requires a default-domain opset import. Overridable input defaults and extended initializers cannot be represented this way and are rejected explicitly.

OptimizationMode.kRewritings returns the finalized, non-optimized canonical model with the captured plan in ModelProto.rewritings["optimized"]. This mode requires ProtoKind.kModel; graphs and functions cannot contain the map. Other attached plans are retained, but an existing "optimized" key is an error rather than being overwritten. Loading a bundle does not execute its plan. The option accepts only OptimizationMode members, not booleans, integers, strings, or members of another enum.

Both optimization modes preserve the source builder’s graph and registrations after ordinary export finalization. The working copy retains each scope’s device, including subgraphs with a different target from their parent and exported local functions. Both modes keep a canonical copy rather than trying to invert destructive edits. Builder-local Python patterns remain live callbacks during capture; only their resulting proto records are serialized.

Load external weights with onnx_light.onnx.load(path, load_external_data=True) before optimization. Save either exported model with the existing onnx_light.onnx.save(..., save_as_external_data=True) to write its weights beside the new model instead of retaining references to the old directory. Deferred loading through load_external_data_for_model and streaming alignment also cover function defaults and rewrite payloads, including tensors in repeated tensor and graph attributes. See Replaying graph-rewriting patterns for a save/load/replay example.

Builder-local operator registries#

OperatorRegistry supplies local schemas and shape-inference callbacks without changing process-wide registrations:

from onnx_light.onnx_core.graph_builder import GraphBuilder, OperatorRegistry

def infer_custom(ctx, node):
    ctx.set(str(node.output[0]), ctx.get(str(node.input[0])))

registry = OperatorRegistry()
registry.register_shape_inference("custom", "CustomOp", infer_custom)
builder = GraphBuilder(
    "g", opsets={"": 18, "custom": 1}, local_registry=registry
)

registry.register_schema(schema) adds or replaces a LightOpSchema identified by domain, name and version. Schema lookup chooses the newest applicable local schema before consulting the configured global provider. A local history containing only newer versions falls back to a compatible global schema; if neither applies, it raises instead of bypassing validation. Global-only histories with no applicable version also raise before node creation. The compact builder.op API uses the same lookup.

Shape resolution prioritizes model-local functions, then local callbacks, then global inference. A local callback failure propagates without retrying the global implementation. Callbacks receive the current ShapesContext and node, so they can inspect the selected opset.

Builders snapshot the registry before importing any nodes. Subgraphs, local functions, optimization copies and replay/undo copies inherit that snapshot. Editing the original registry affects only builders constructed afterwards; builder.local_registry() returns an independent copy. Callback captures retain ordinary Python callable / C++ std::function ownership semantics. Registrations are not serialized into ONNX: pass the registry again when importing a saved model. The standalone ONNX checker keeps its own schema registry and is not modified by these builder-local registrations.

Incremental ONNX graph builder backed by a C++ library.

This module exposes GraphBuilder, an incremental builder for ONNX graphs, models and functions. A builder starts empty, holds a compute context and records every value name it hands out so a name can never be reused. Nodes are added with GraphBuilder.make_node(), which requires a selected opset, validates the node against the built-in ONNX operator schemas, assigns output names when the caller leaves them empty and runs incremental shape inference. GraphBuilder.to_onnx() finalises the accumulated graph into a ModelProto by default, or a GraphProto or FunctionProto selected with ProtoKind, writing the inferred shapes, the in-place / release-after metadata, the value tags and the peak-memory estimates. to_onnx(optimize=OptimizationMode.kOptimize) optimizes a copy and exports the result; to_onnx(optimize=OptimizationMode.kRewritings) exports the canonical model with the captured plan named "optimized" instead.

Typical usage:

from onnx_light.onnx_core.graph_builder import GraphBuilder
from onnx_light.onnx_proto import TensorProto

builder = GraphBuilder("g", opsets=18)
builder.make_input("x", TensorProto.FLOAT, [2, 3])
builder.make_input("y", TensorProto.FLOAT, [2, 3])
(z,) = builder.make_node("Add", ["x", "y"])
builder.make_output(z)
model = builder.to_onnx()

The module is exposed as onnx_light.onnx_core.graph_builder.

class onnx_light.onnx_core.graph_builder.ConstantFoldingOptions(*args, **kwargs)#

Options controlling GraphBuilder.constant_fold.

property enabled#

when False constant_fold is a no-op and returns 0 without touching the graph.

Type:

Master switch

property excluded_ops#

Set of (domain, op_type) tuples that must never be folded. An empty domain matches every domain and an empty op_type matches every operator, so an empty-empty pair disables folding for every node.

property fold_weights#

Controls whether nodes whose results are tagged "weight" (or untagged) are folded. Shape-tagged results are always foldable; when False only shape-tagged results are folded, so a caller can fold shapes early and defer weight folding to a final pass.

property max_element_count#

Skips folding a node when any of its outputs would hold strictly more than this many elements. A negative value (the default) means no limit.

property raise_on_missing_weight_kernel#

When True a weight/untagged node for which no runtime kernel is registered raises instead of being left untouched. Shape-tagged results always raise when their kernel is missing, regardless of this flag.

class onnx_light.onnx_core.graph_builder.GraphBuilder(name: str = 'graph', schema_lookup: ~collections.abc.Callable[[str], list[~onnx_light.onnx_py._onnxpyprotoop.onnx_op.LightOpSchema]] | None = <function _default_schema_lookup>, *, opsets: int | dict[str, int] | None = None, local_registry: ~onnx_light.onnx_py._onnxpycore.builder.OperatorRegistry | None = None)#

Incrementally builds an ONNX graph, model or function.

See onnx_light.onnx_core.graph_builder for details. By default the builder validates nodes at selected opsets using the built-in ONNX operator schemas; pass schema_lookup=None to disable this, or a custom op_type -> list[LightOpSchema] callable to use different schemas. For an empty builder, opsets selects the default ONNX version (an integer) or explicit domain-to-version imports (a dictionary). The default None selects {"": onnx_opset_version()}; an empty dictionary selects no imports. When importing a model, None preserves its declared imports. local_registry snapshots operator schemas and shape callbacks before importing any node. Model-local functions take precedence over local registrations, which take precedence over global registrations. Nested builders and optimization/replay copies retain this snapshot.

clear_registered_patterns() → None#

Removes every builder-local pattern.

init(value: ndarray, name: str | None = None, *, copy: bool = True) → str#

Adds a NumPy initializer and returns its final name.

By default, copies the payload. With copy=False, borrows C-contiguous, dtype-aligned, little-endian storage without conversion. Supports bool, 8/16/32/64-bit integers, float16/32/64 and complex64/128; rejects other dtypes and layouts. Retains the array until the last borrowed payload owner releases it, including models exported from this builder.

Writable arrays remain writable and mutations are visible to all owners. The caller must finish mutations before optimization or creating an execution session, which may cache derived values, and must not resize or reallocate storage while borrowed. Use copy=True for an independent snapshot; setting an array read-only does not freeze its aliases.

inp(name: str, elem_type: int, shape: list[str | int | None]) → str#

Declares and returns a compact graph input.

property op: _OperatorProxy#

Returns the cached compact operator proxy.

out(name: str, elem_type: int | None = None, shape: list[str | int | None] | None = None) → str#

Declares and returns a compact graph output.

register_pattern(pattern: PatternOptimization) → None#

Registers or replaces a pattern for this builder.

registered_pattern_names() → tuple[str, ...]#

Returns builder-local pattern names in registration order.

registered_patterns() → tuple[PatternOptimization, ...]#

Returns builder-local patterns in registration order.

to_onnx(kind: ProtoKind = ProtoKind.kModel, ir_version: int = 0, domain: str = '', *, optimize: OptimizationMode = OptimizationMode.kNone, canonicalize: bool = False, move_shape_and_size_nodes: bool = True) → ModelProto | GraphProto | FunctionProto#

Exports the current graph, an optimized copy, or captured rewritings.

With OptimizationMode.kNone (the default), preserves the existing export behavior. With OptimizationMode.kOptimize, optimizes an independent builder using the global and builder-local pattern registrations, then exports the result without attached plans. Model export requires standard ONNX constructs.

With OptimizationMode.kRewritings, returns the finalized reference ModelProto and attaches the captured plan as rewritings["optimized"]. canonicalize=True explicitly cleans this reference before capture; it is disabled by default. Shape/Size hoisting is enabled by default and can be disabled with move_shape_and_size_nodes=False. Requires kind=ProtoKind.kModel and rejects an existing plan with that name. Other named plans are retained unless explicit canonicalization changes their reference. Optimization never edits the source builder; export never reorders the graph.

unregister_pattern(name: str) → bool#

Removes a builder-local pattern and returns whether it existed.

class onnx_light.onnx_core.graph_builder.OperatorRegistry(*args, **kwargs)#

Collects local operator registrations snapshotted by builders.

register_schema(self, schema: onnx_light.onnx_py._onnxpyprotoop.onnx_op.LightOpSchema) → None#

Registers or replaces a local domain/name/version schema.

register_shape_inference(self, domain: str, op_type: str, fn: collections.abc.Callable) → None#

Registers local shape inference receiving (ctx, node). Errors propagate; global inference is consulted only when no local registration exists.

class onnx_light.onnx_core.graph_builder.OptimizationMode(*values)#

Selects the optimization workflow used by GraphBuilder.to_onnx.

class onnx_light.onnx_core.graph_builder.ProtoKind(*values)#

Selects the proto returned by to_onnx.