GraphBuilder#
yobx.xbuilder.GraphBuilder simplifies the programmatic construction
and optimization of ONNX graphs. It is the primary tool used to convert a
torch.fx.Graph into a onnx.ModelProto, but it can equally
be used standalone to build or transform any ONNX graph from scratch.
Class Hierarchy#
GraphBuilder is an alias for
OnnxLightGraphBuilder. It delegates graph
storage and construction to onnx-light’s native GraphBuilder, pattern
optimization to GraphGraph, and symbolic shape inference to
ShapesContext. The former Python graph and shape engines are not used
as fallbacks.
The scikit-learn and PyTorch converters use dedicated subclasses,
SklearnOnnxLightGraphBuilder and TorchOnnxLightGraphBuilder, to
preserve their converter-specific APIs while sharing the native engine.
The exported models contain native onnx-light protobufs, not objects from
the reference onnx package.
Two helper classes round out the public API:
FunctionOptions— controls whether (and how) a sub-graph is exported as a reusable ONNX local function.OptimizationOptions— selects which optimization passes run insideto_onnx.
Protocol API#
GraphBuilder satisfies a hierarchy of
protocols defined in yobx.typing. Callers that do not need the
full concrete class should type-annotate against the narrowest protocol that
covers the methods they actually use:
Protocol |
Scope |
|---|---|
Core construction API: inputs, outputs, initializers, nodes,
opset registration, type/shape/sequence accessors, and
|
|
Extends the core protocol with |
|
Extends |
The op property returns an
object that satisfies OpsetProtocol,
which resolves g.op.Add(x, y)-style attribute-access dispatch to ONNX
node creation.
Building a graph from scratch#
The simplest workflow is:
Construct a
GraphBuilderwith an opset version.Call
make_tensor_inputto declare each graph input.Call
make_node(or the short-handg.op.<OpType>(…)syntax) to add operators.Call
make_tensor_outputto declare each graph output.Call
to_onnxto obtain aonnx.ModelProto.
<<<
import numpy as np
from yobx._onnx_shim import onnx
from yobx.helpers.onnx_helper import pretty_onnx
from yobx.xbuilder import GraphBuilder
TFLOAT = onnx.TensorProto.FLOAT
# 1. create builder targeting opset 18
g = GraphBuilder(18, ir_version=10)
# 2. declare inputs
g.make_tensor_input("X", TFLOAT, ("batch", "seq", 64))
g.make_tensor_input("W", TFLOAT, (64, 32))
# 3. add a MatMul node via the short-hand op accessor
result = g.op.MatMul("X", "W")
# 4. declare the output and export
g.make_tensor_output(
result, elem_type=TFLOAT, shape=("batch", "seq", 32), indexed=False
)
model = g.to_onnx()
print(f"nodes : {len(model.graph.node)}")
print(f"opset : {model.opset_import[0].version}")
print(f"output : {model.graph.output[0].name}")
print(pretty_onnx(model))
>>>
nodes : 1
opset : 18
output : matmul
opset: domain='' version=18
input: name='X' type=dtype('float32') shape=['batch', 'seq', 64]
input: name='W' type=dtype('float32') shape=[64, 32]
MatMul(X, W) -> matmul
output: name='matmul' type=dtype('float32') shape=['batch', 'seq', 32]
Loading an existing model#
Passing an existing onnx.ModelProto to the constructor loads it into
the builder so its nodes and initializers can be inspected, modified, or
re-optimized.
<<<
from yobx._onnx_shim import onnx
import onnx_light.onnx.helper as oh
from yobx.xbuilder import GraphBuilder
TFLOAT = onnx.TensorProto.FLOAT
model = oh.make_model(
oh.make_graph(
[
oh.make_node("Add", ["X", "Y"], ["T"]),
oh.make_node("Relu", ["T"], ["Z"]),
],
"add_relu",
[
oh.make_tensor_value_info("X", TFLOAT, ["batch", 4]),
oh.make_tensor_value_info("Y", TFLOAT, ["batch", 4]),
],
[oh.make_tensor_value_info("Z", TFLOAT, ["batch", 4])],
),
opset_imports=[oh.make_opsetid("", 18)],
ir_version=10,
)
g = GraphBuilder(model)
print("input shapes:", {n: g.get_shape(n) for n in g.input_names})
print("nodes :", [node.op_type for node in g.nodes])
>>>
input shapes: {'X': ('batch', 4), 'Y': ('batch', 4)}
nodes : ['Add', 'Relu']
Initializers#
Initializers (model weights and constants) are added with
make_initializer.
The builder deduplicates small integer arrays automatically: if the same
value is added twice it returns the name of the first occurrence rather than
creating a duplicate node.
<<<
import numpy as np
from yobx._onnx_shim import onnx
from yobx.xbuilder import GraphBuilder
TFLOAT = onnx.TensorProto.FLOAT
g = GraphBuilder(18, ir_version=10)
g.make_tensor_input("X", TFLOAT, ("batch", 64))
# Add a weight matrix as an initializer
W = np.random.randn(64, 32).astype(np.float32)
w_name = g.make_initializer("W", W, source="example")
result = g.op.MatMul("X", w_name)
g.make_tensor_output(result, elem_type=TFLOAT, shape=("batch", 32), indexed=False)
model = g.to_onnx()
print("initializer name :", list(g.initializers_dict)[0])
print("initializer shape:", tuple(g.initializers_dict[w_name].dims))
>>>
initializer name : W
initializer shape: (64, 32)
Shape and type tracking#
GraphBuilder inherits the full
ShapeBuilder interface. Shapes and types
are registered for every intermediate result as nodes are added, and are used
during optimization and for populating value_info in the exported proto.
See Expected API.
Native optimization#
GraphBuilder delegates optimization to the native onnx-light
GraphGraph engine through OptimizationOptions
(published as OnnxLightOptimizationOptions
in the native bridge). patterns=None or "default" selects the
wheel’s registered standard patterns, an empty sequence disables pattern
rewrites, and every other value must be an exact registered pattern name.
Python pattern classes, legacy pattern groups, and historical Python
registries are no longer supported.
The default selection excludes CastOpCast to preserve lower-precision
rounding and Reshape2Of3 because version 0.2.0 can produce incompatible
broadcasts when merging expanded operands. It also excludes
SoftmaxCrossEntropyLossCast because version 0.2.1 can abort when matching
division by a constant inside a local function. Explicit pattern names still
allow opting into these rewrites. Native causal-mask fusion is conditional:
supported masks may remain as boolean comparisons instead of CausalMask
local functions.
After rewriting, the bridge folds newly introduced constant expressions when
constant_folding=True, removes redundant identities, and removes unused
nodes when remove_unused=True. Floating-point min/max metadata
emitted by the native engine is discarded because its rounded bounds can
contradict the actual folded tensor values. Tensor types and shapes are retained.
Execution lifetime and in-place-reuse hints are also removed from the exported
graphs and local functions, since rewrites and renaming can make them stale.
For graphs containing bfloat16 tensors, Where is excluded from constant
folding because its native kernel in onnx-light 0.2.0 does not support that
dtype. ReduceProd is likewise excluded when a reduction input is not
float32, since its 0.2.0 kernel only supports float32. Float32-only reductions
and other supported operators still undergo constant folding.
Native inlining may retain local functions whose operator-domain opset versions differ from the model’s. These functions keep their own opset imports; inspecting the exported operators must also include their bodies.
Dynamic shapes#
When some input dimensions are unknown at graph-construction time, they are
represented as strings (e.g. "batch", "seq"). For graphs that are
later exported for dynamic-shape inference with torch.export, the builder
accepts a dynamic_shapes dictionary that maps input names to per-axis
dimension objects (torch.export.Dim or WrapDim).
register_dynamic_objects_from_shape
registers any string dimension names encountered in a shape so that they are
tracked as symbolic dimensions.
<<<
from yobx._onnx_shim import onnx
from yobx.xbuilder import GraphBuilder
TFLOAT = onnx.TensorProto.FLOAT
g = GraphBuilder(18, ir_version=10)
g.make_tensor_input("X", TFLOAT, ("batch", "seq", 64))
g.make_tensor_input("Y", TFLOAT, ("batch", "seq", 64))
# symbolic dimensions are tracked automatically once shapes are set
result = g.op.Add("X", "Y")
g.make_tensor_output(
result, elem_type=TFLOAT, shape=("batch", "seq", 64), indexed=False
)
model = g.to_onnx()
out = model.graph.output[0]
dims = [
d.dim_param if d.dim_param else d.dim_value for d in out.type.tensor_type.shape.dim
]
print("output shape:", dims)
>>>
output shape: ['batch', 'seq', 64]
Optimizations#
to_onnx delegates optimization to
the native onnx-light GraphGraph engine through
OptimizationOptions.
Only the native pattern selection knobs are exposed here:
patterns=Noneorpatterns="default"selects the wheel’s registered standard patterns.patterns=[]disables rewrites.any other value must be an exact registered pattern name such as
"TransposeTranspose"or"MulMulMatMul".max_iterlimits the number of native rewrite iterations.
Python pattern classes, legacy pass flags, and historical reorder /
constant-folding options are not supported by the native bridge.
With onnx-light>=0.1.25, dependency ordering and lifetime metadata are
finalized by the native engine; the adapter does not reorder serialized nodes
or reconstruct the optimized graph to repair them. Local function imports,
nested calls, and referenced attributes likewise use the native builder
without replaying typed function bodies in Python.
<<<
from onnx_light import onnx
from onnx_light.onnx import helper
from onnx_light.onnx_core.optimization import standard_pattern_names
from yobx.builder.onnxlight import (
OnnxLightGraphBuilder,
OnnxLightOptimizationOptions,
)
assert "TransposeTranspose" in standard_pattern_names()
model = helper.make_model(
helper.make_graph(
[
helper.make_node("Transpose", ["X"], ["T"], perm=[1, 0]),
helper.make_node("Transpose", ["T"], ["Y"], perm=[1, 0]),
],
"transpose_transpose",
[helper.make_tensor_value_info("X", onnx.TensorProto.FLOAT, [2, 3])],
[helper.make_tensor_value_info("Y", onnx.TensorProto.FLOAT, [2, 3])],
),
opset_imports=[helper.make_opsetid("", 18)],
ir_version=8,
)
builder = OnnxLightGraphBuilder(
model,
optimization_options=OnnxLightOptimizationOptions(patterns=["TransposeTranspose"]),
)
optimized = builder.to_onnx()
print("nodes before:", len(model.graph.node))
print("nodes after :", len(optimized.proto.graph.node))
>>>
nodes before: 2
nodes after : 1
Optimization report#
Passing return_optimize_report=True to
to_onnx returns an
ExportArtifact whose report.stats list contains one
entry per native rewrite. Each entry records the rewrite name, the number of
nodes added or removed, and the time spent in that rewrite.
Key |
Description |
|---|---|
|
Native rewrite name such as |
|
Number of nodes added by the rewrite. |
|
Number of nodes removed by the rewrite. |
|
Wall-clock time spent in this rewrite (seconds). |
The list can be converted to a pandas.DataFrame for quick
exploration:
<<<
import pandas
from onnx_light import onnx
from onnx_light.onnx import helper
from yobx.builder.onnxlight import OnnxLightGraphBuilder
model = helper.make_model(
helper.make_graph(
[
helper.make_node("Identity", ["X"], ["X2"]),
helper.make_node("Transpose", ["X2"], ["T"], perm=[1, 0]),
helper.make_node("Transpose", ["T"], ["Y"], perm=[1, 0]),
],
"demo",
[helper.make_tensor_value_info("X", onnx.TensorProto.FLOAT, [3, 4])],
[helper.make_tensor_value_info("Y", onnx.TensorProto.FLOAT, [3, 4])],
),
opset_imports=[helper.make_opsetid("", 18)],
ir_version=8,
)
art = OnnxLightGraphBuilder(model).to_onnx(return_optimize_report=True)
df = pandas.DataFrame(art.report.stats)
if df.empty:
print("no rewrites")
else:
print(df[["pattern", "added", "removed", "time_in"]].to_string(index=False))
print(f"\nnodes before: {len(model.graph.node)}")
print(f"nodes after : {len(art.proto.graph.node)}")
>>>
pattern added removed time_in
TransposeTranspose 1 2 0.000005
nodes before: 3
nodes after : 1
The report can be aggregated by rewrite name:
<<<
import pandas
from onnx_light import onnx
from onnx_light.onnx import helper
from yobx.builder.onnxlight import OnnxLightGraphBuilder
model = helper.make_model(
helper.make_graph(
[
helper.make_node("Identity", ["X"], ["X2"]),
helper.make_node("Transpose", ["X2"], ["T"], perm=[1, 0]),
helper.make_node("Transpose", ["T"], ["Y"], perm=[1, 0]),
],
"demo",
[helper.make_tensor_value_info("X", onnx.TensorProto.FLOAT, [3, 4])],
[helper.make_tensor_value_info("Y", onnx.TensorProto.FLOAT, [3, 4])],
),
opset_imports=[helper.make_opsetid("", 18)],
ir_version=8,
)
art = OnnxLightGraphBuilder(model).to_onnx(return_optimize_report=True)
df = pandas.DataFrame(art.report.stats)
if df.empty:
print("no rewrites")
else:
for c in ["added", "removed"]:
df[c] = df[c].fillna(0).astype(int)
agg = df.groupby("pattern")[["added", "removed", "time_in"]].sum()
agg = agg[(agg["added"] > 0) | (agg["removed"] > 0)].sort_values(
"removed", ascending=False
)
print(agg.to_string())
>>>
added removed time_in
pattern
TransposeTranspose 1 2 0.000006
Local functions#
A sub-graph can be exported as a reusable ONNX local function (a
FunctionProto) by passing a FunctionOptions instance to
to_onnx.
<<<
from yobx._onnx_shim import onnx
from yobx.xbuilder import GraphBuilder, FunctionOptions
TFLOAT = onnx.TensorProto.FLOAT
g = GraphBuilder(18, ir_version=10, as_function=True)
g.make_tensor_input("X", TFLOAT, ("batch", 64))
r = g.op.Relu("X")
g.make_tensor_output(r, indexed=False)
func = g.to_onnx(
function_options=FunctionOptions(
export_as_function=True,
name="MyRelu",
domain="my.domain",
),
inline=False,
)
proto = func.proto
print(type(proto).__name__)
print("function name :", proto.name)
print("function domain:", proto.domain)
>>>
FunctionProto
function name : MyRelu
function domain: my.domain
Debugging GraphBuilder with Environment Variables#
GraphBuilder respects several
environment variables that help narrow down construction or optimization
problems:
Environment variable |
Effect |
|---|---|
|
Raises an exception the moment result |
|
Raises an exception the moment result |
|
Raises an exception the moment result |
|
Raises an exception the moment a node produces output |
|
Prints extra information for shape-as-value tracking (e.g. inputs
to |
|
Prints which constant is being evaluated. |
|
Prints details when nodes from a local function domain are added. |
|
Raises an exception when a shape is missing for a result that should have one. |
|
Raises an exception as soon as a null/empty shape is encountered. |
|
Prints a message every time dynamic dimension |
|
Prints a message every time a node producing |
In addition,
get_debug_msg
returns a detailed text dump of the builder’s internal state (known shapes,
types, ranks, constants, and node list) which can be printed or logged whenever
an assertion fails.
pretty_text returns a
human-readable representation of the whole graph (inputs, initializers, nodes,
outputs) and is useful for quick visual inspection:
<<<
from yobx._onnx_shim import onnx
import onnx_light.onnx.helper as oh
from yobx.xbuilder import GraphBuilder
TFLOAT = onnx.TensorProto.FLOAT
model = oh.make_model(
oh.make_graph(
[
oh.make_node("Add", ["X", "Y"], ["T"]),
oh.make_node("Relu", ["T"], ["Z"]),
],
"add_relu",
[
oh.make_tensor_value_info("X", TFLOAT, ["batch", 4]),
oh.make_tensor_value_info("Y", TFLOAT, ["batch", 4]),
],
[oh.make_tensor_value_info("Z", TFLOAT, ["batch", 4])],
),
opset_imports=[oh.make_opsetid("", 18)],
ir_version=10,
)
g = GraphBuilder(model)
print(g.pretty_text())
>>>
GraphBuilder(name=add_relu)
opsets: ai.onnx=18
inputs (2):
X: SymTensor(dtype=Float, shape=[batch,4])
Y: SymTensor(dtype=Float, shape=[batch,4])
initializers (0):
nodes (2):
Add(X, Y) -> T
Relu(T) -> Z
outputs (1):
Z: SymTensor(dtype=Float, shape=[batch,4])
See also
GraphBuilderProtocol,
GraphBuilderExtendedProtocol,
GraphBuilderTorchProtocol,
OpsetProtocol —
formal protocol interfaces satisfied by
GraphBuilder.
Expected API — the full list of methods and attributes
every graph builder must expose for use with to_onnx().
l-design-graph-builder-optimization — how native optimization
selects registered pattern names through OptimizationOptions.