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 composed of three cooperative base classes:

  • _BuilderRuntime — evaluates small constant sub-expressions (e.g. the [0, 0, -1] passed to a Reshape node) so the builder can resolve -1 to the correct symbolic formula and fold constants early.

  • _ShapeRuntime — handles value-as-shape tracking needed by operators such as Shape, Gather, Concat, and Slice when their outputs feed directly into a Reshape.

  • _InferenceRuntime — walks the graph node by node, dispatching each node to the matching per-operator handler in yobx.xshape.shape_type_compute so that shapes and types are tracked for every intermediate result.

Two helper classes round out the public API:

Building a graph from scratch#

The simplest workflow is:

  1. Construct a GraphBuilder with an opset version.

  2. Call make_tensor_input to declare each graph input.

  3. Call make_node (or the short-hand g.op.<OpType>(…) syntax) to add operators.

  4. Call make_tensor_output to declare each graph output.

  5. Call to_onnx to obtain a onnx.ModelProto.

<<<

import numpy as np
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 : _onx_matmul_X
    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) -> _onx_matmul_X
    output: name='_onx_matmul_X' 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.

<<<

import onnx
import 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
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:", list(g.initializers_dict.values())[0].shape)

>>>

    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.

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.

<<<

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 runs a sequence of optimization passes by default. The set of passes is controlled by OptimizationOptions.

Default passes (in order):

Pass

Effect

remove_unused

Remove nodes whose outputs are never consumed.

constant_folding

Evaluate operators such as Transpose, Cast, Reshape, Concat, Add, Mul, etc. when all inputs are constants and fold the result into an initializer.

remove_identity

Remove Identity nodes.

remove_duplicated_initializer

Merge identical constant initializers into a single tensor, removing redundant copies.

patterns

Apply user-supplied or built-in fusion patterns (e.g. "default" enables the default set of ONNX-to-ONNX rewrites).

order

Reorder nodes to reduce peak memory by moving each Shape / Size node immediately after the node that produces its input (controlled by OrderAlgorithm, default SHAPE).

<<<

import onnx
import onnx.helper as oh
from yobx.xbuilder import GraphBuilder, OptimizationOptions

TFLOAT = onnx.TensorProto.FLOAT

model = oh.make_model(
    oh.make_graph(
        [
            oh.make_node("Identity", ["X"], ["X2"]),
            oh.make_node("Relu", ["X2"], ["Z"]),
        ],
        "id_relu",
        [oh.make_tensor_value_info("X", TFLOAT, [None, 4])],
        [oh.make_tensor_value_info("Z", TFLOAT, [None, 4])],
    ),
    opset_imports=[oh.make_opsetid("", 18)],
    ir_version=10,
)

opts = OptimizationOptions(remove_identity=True)
g = GraphBuilder(model, optimization_options=opts)
optimized = g.to_onnx()
print("nodes before:", len(model.graph.node))
print("nodes after :", len(optimized.graph.node))

>>>

    nodes before: 2
    nodes after : 1

Optimization report#

Passing return_optimize_report=True to to_onnx makes the method return a (model, stats) tuple instead of just the model. stats is a list of dictionaries — one entry per optimization pass — that records how many nodes were added or removed and how long each pass took.

Key

Description

pattern

Name of the optimization pass (e.g. "remove_identity", "constant_folding", "TransposeTranspose" …).

added

Number of nodes added by this pass.

removed

Number of nodes removed by this pass.

time_in

Wall-clock time spent in this pass (seconds).

iteration

Iteration number (only for pattern-based passes).

match_index

Sequential index of the match within the iteration (pattern passes).

instances

Number of times the pattern was matched (pattern passes).

The list can be converted to a pandas.DataFrame for quick exploration:

<<<

import pandas
import onnx
import onnx.helper as oh
from yobx.xbuilder import GraphBuilder, OptimizationOptions

TFLOAT = onnx.TensorProto.FLOAT

model = oh.make_model(
    oh.make_graph(
        [
            oh.make_node("Identity", ["X"], ["X2"]),
            oh.make_node("Transpose", ["X2"], ["T"], perm=[1, 0]),
            oh.make_node("Transpose", ["T"], ["Z"], perm=[1, 0]),
        ],
        "demo",
        [oh.make_tensor_value_info("X", TFLOAT, [3, 4])],
        [oh.make_tensor_value_info("Z", TFLOAT, [3, 4])],
    ),
    opset_imports=[oh.make_opsetid("", 18)],
    ir_version=10,
)

opts = OptimizationOptions(patterns="default")
g = GraphBuilder(model, infer_shapes_options=True, optimization_options=opts)
optimized = g.to_onnx(return_optimize_report=True)

df = pandas.DataFrame(optimized.report.stats)
# keep only rows that have numeric added/removed counts
df["added"] = df["added"].fillna(0).astype(int)
df["removed"] = df["removed"].fillna(0).astype(int)
print(df[["pattern", "added", "removed", "time_in"]].to_string(index=False))
print(f"\nnodes before: {len(model.graph.node)}")
print(f"nodes after : {len(optimized.graph.node)}")

>>>

                                         pattern  added  removed      time_in
                        dynamic_dimension_naming      0        0 1.890000e-05
                check_A-dynamic_dimension_naming      0        0 9.862997e-06
                                 check_A-opt-sub      0        0 8.260002e-06
                                 remove_identity      1        2 3.602000e-05
                         check_remove_identity-0      0        0 6.582995e-06
                                   remove_unused      0        0 2.405200e-05
                           check_remove_unused-1      0        0 5.993999e-06
                                constant_folding      0        0 9.128998e-06
                apply_constant_folding_new_inits      0        0          NaN
                        check_constant_folding-2      0        0 5.436996e-06
                                   remove_unused      0        0 1.118999e-05
                           check_remove_unused-3      0        0 5.034999e-06
                                        patterns      0        1 4.840417e-03
                                check_pattern_00      0        0 1.238000e-05
                 match_BatchNormalizationPattern      0        0 7.495997e-06
         match_BatchNormalizationTrainingPattern      0        0 3.458998e-06
                               match_CastPattern      0        0 2.553999e-06
                           match_CastCastPattern      0        0 2.647997e-06
                       match_ConcatGatherPattern      0        0 3.437999e-06
                      match_ConcatReshapePattern      0        0 2.647001e-06
                       match_ConvBiasNullPattern      0        0 2.774002e-06
                             match_ExpandPattern      0        0 3.323999e-06
              match_ExpandUnsqueezeExpandPattern      0        0 2.751003e-06
                               match_GeluPattern      0        0 1.216002e-06
                           match_IdentityPattern      0        0 2.130600e-05
                          match_LeakyReluPattern      0        0 8.992850e-04
              match_MulUnsqueezeUnsqueezePattern      0        0 4.453999e-06
                            match_ReshapePattern      0        0 2.756002e-06
         match_ShapeBasedReshapeIsSqueezePattern      0        0 3.736001e-06
             match_ShapeBasedStaticExpandPattern      0        0 2.355002e-06
      match_ShapeBasedEditDistanceReshapePattern      0        0 2.105997e-06
                 match_ShapeBasedIdentityPattern      0        0 7.661001e-06
                 match_ShapedBasedReshapePattern      0        0 2.981003e-06
             match_ShapeBasedSameChildrenPattern      0        0 2.798006e-06
            match_ShapeBasedShapeShapeAddPattern      0        0 2.437999e-06
                     match_ReshapeReshapePattern      0        0 2.713001e-06
                       match_SameChildrenPattern      0        0 6.253002e-06
              match_SameChildrenFromInputPattern      0        0 6.032002e-06
        match_SoftmaxCrossEntropyLossCastPattern      0        0 1.683041e-03
                         match_SqueezeAddPattern      0        0 5.612004e-06
             match_SqueezeBinaryUnsqueezePattern      0        0 3.086003e-06
                   match_SqueezeUnsqueezePattern      0        0 4.014997e-06
                match_StaticConcatReshapePattern      0        0 2.662004e-06
                  match_SwapExpandReshapePattern      0        0 2.253997e-06
                match_SwapExpandUnsqueezePattern      0        0 2.613000e-06
                          match_SwapUnaryPattern      0        0 2.263800e-05
             match_SwapUnsqueezeTransposePattern      0        0 9.027004e-06
                    match_TransposeGatherPattern      0        0 2.531000e-06
          match_TransposeReshapeTransposePattern      0        0 6.237999e-06
                 match_TransposeTransposePattern      0        0 3.554400e-05
          match_UnsqueezeOrSqueezeReshapePattern      0        0 3.419002e-06
                   match_UnsqueezeReshapePattern      0        0 2.569999e-06
                 match_UnsqueezeUnsqueezePattern      0        0 2.485001e-06
                  match_FunctionAttentionPattern      0        0 3.074005e-06
               match_FunctionAttentionGQAPattern      0        0 3.821995e-06
                         insert_and_remove_nodes      0        0 7.886600e-05
                 apply_TransposeTransposePattern      1        2 1.442550e-04
                               check_pattern_A10      0        0 1.166998e-06
                               check_pattern_A20      0        0 9.042000e-06
                         remove_duplicated_shape      0        0 2.813998e-06
                               check_pattern_BD0      0        0 4.947004e-06
                           remove_identity_nodes      0        0 1.667000e-05
                               check_pattern_BI0      0        0 4.522000e-06
                                   remove_unused      0        0 1.237200e-05
                              check_pattern_BUS0      0        0 3.869005e-06
                         build_graph_for_pattern      0        0 9.308002e-06
                                     iteration_0      0        0 3.088410e-03
                 match_BatchNormalizationPattern      0        0 4.262001e-06
         match_BatchNormalizationTrainingPattern      0        0 2.480003e-06
                               match_CastPattern      0        0 2.162000e-06
                           match_CastCastPattern      0        0 1.663000e-06
                       match_ConcatGatherPattern      0        0 1.868997e-06
                      match_ConcatReshapePattern      0        0 1.591994e-06
                       match_ConvBiasNullPattern      0        0 1.640001e-06
                             match_ExpandPattern      0        0 1.820001e-06
              match_ExpandUnsqueezeExpandPattern      0        0 1.500004e-06
                               match_GeluPattern      0        0 9.509968e-07
                           match_IdentityPattern      0        0 2.514003e-06
                          match_LeakyReluPattern      0        0 5.296999e-06
              match_MulUnsqueezeUnsqueezePattern      0        0 1.834000e-06
                            match_ReshapePattern      0        0 1.526998e-06
         match_ShapeBasedReshapeIsSqueezePattern      0        0 1.911998e-06
             match_ShapeBasedStaticExpandPattern      0        0 1.262000e-06
      match_ShapeBasedEditDistanceReshapePattern      0        0 1.288994e-06
                 match_ShapeBasedIdentityPattern      0        0 1.786997e-06
                 match_ShapedBasedReshapePattern      0        0 1.709006e-06
             match_ShapeBasedSameChildrenPattern      0        0 1.499000e-06
            match_ShapeBasedShapeShapeAddPattern      0        0 1.549000e-06
                     match_ReshapeReshapePattern      0        0 1.538996e-06
                       match_SameChildrenPattern      0        0 3.221001e-06
              match_SameChildrenFromInputPattern      0        0 3.775996e-06
        match_SoftmaxCrossEntropyLossCastPattern      0        0 4.121001e-06
                         match_SqueezeAddPattern      0        0 1.433000e-06
             match_SqueezeBinaryUnsqueezePattern      0        0 1.233006e-06
                   match_SqueezeUnsqueezePattern      0        0 1.394998e-06
                match_StaticConcatReshapePattern      0        0 1.398999e-06
                  match_SwapExpandReshapePattern      0        0 1.041997e-06
                match_SwapExpandUnsqueezePattern      0        0 1.207998e-06
                          match_SwapUnaryPattern      0        0 1.383996e-06
             match_SwapUnsqueezeTransposePattern      0        0 1.243003e-06
                    match_TransposeGatherPattern      0        0 1.136999e-06
          match_TransposeReshapeTransposePattern      0        0 1.034998e-06
                 match_TransposeTransposePattern      0        0 1.275002e-06
          match_UnsqueezeOrSqueezeReshapePattern      0        0 1.398002e-06
                   match_UnsqueezeReshapePattern      0        0 1.657005e-06
                 match_UnsqueezeUnsqueezePattern      0        0 1.215994e-06
                  match_FunctionAttentionPattern      0        0 1.547000e-06
               match_FunctionAttentionGQAPattern      0        0 2.212000e-06
                               check_pattern_A20      0        0 7.545001e-06
                         remove_duplicated_shape      0        0 1.757006e-06
                               check_pattern_BD0      0        0 4.670001e-06
                           remove_identity_nodes      0        0 1.542100e-05
                               check_pattern_BI0      0        0 4.091999e-06
                                   remove_unused      0        0 1.111900e-05
                              check_pattern_BUS0      0        0 3.533998e-06
                         build_graph_for_pattern      0        0 8.092000e-06
                                     iteration_1      0        0 1.982500e-04
                 match_BatchNormalizationPattern      0        0 2.020002e-06
         match_BatchNormalizationTrainingPattern      0        0 1.498003e-06
         match_CastLayerNormalizationCastPattern      0        0 3.168003e-06
                               match_CastPattern      0        0 1.453001e-06
                     match_CastCastBinaryPattern      0        0 4.873000e-06
                           match_CastCastPattern      0        0 1.403998e-06
                         match_CastOpCastPattern      0        0 3.886002e-06
                           match_ClipClipPattern      0        0 1.756001e-06
                        match_ConcatEmptyPattern      0        0 2.339002e-06
                       match_ConcatGatherPattern      0        0 1.269000e-06
                      match_ConcatReshapePattern      0        0 1.175002e-06
                   match_ConcatTwiceUnaryPattern      0        0 2.020999e-06
              match_ConstantToInitializerPattern      0        0 2.018998e-06
                       match_ConvBiasNullPattern      0        0 1.137996e-06
                            match_DropoutPattern      0        0 1.992004e-06
                             match_ExpandPattern      0        0 1.225002e-06
                    match_ExpandBroadcastPattern      0        0 1.699002e-06
                         match_ExpandSwapPattern      0        0 1.616005e-06
              match_ExpandUnsqueezeExpandPattern      0        0 1.142995e-06
                       match_GathersSplitPattern      0        0 1.813998e-06
                               match_GeluPattern      0        0 4.800022e-07
                           match_IdentityPattern      0        0 1.542001e-06
                 match_LayerNormalizationPattern      0        0 2.096000e-06
            match_LayerNormalizationScalePattern      0        0 1.651002e-06
                          match_LeakyReluPattern      0        0 3.305002e-06
                            match_MaxReluPattern      0        0 1.870001e-06
                    match_MulMulMulScalarPattern      0        0 1.963002e-06
              match_MulUnsqueezeUnsqueezePattern      0        0 1.062996e-06
                             match_NotNotPattern      0        0 2.027999e-06
                           match_NotWherePattern      0        0 2.200002e-06
                      match_ReduceArgTopKPattern      0        0 2.474000e-06
                      match_ReduceReshapePattern      0        0 2.004999e-06
                 match_ReduceSumNormalizePattern      0        0 2.133995e-06
                            match_ReshapePattern      0        0 1.138003e-06
               match_ReshapeMatMulReshapePattern      0        0 2.052999e-06
                        match_Reshape2Of3Pattern      0        0 2.228000e-06
               match_ReshapeReshapeBinaryPattern      0        0 1.777997e-06
                      match_GemmTransposePattern      0        0 2.089000e-06
                  match_MatMulReshape2Of3Pattern      0        0 2.351997e-06
                       match_MulMulMatMulPattern      0        0 2.205001e-06
         match_ShapeBasedReshapeIsSqueezePattern      0        0 1.303000e-06
             match_ShapeBasedStaticExpandPattern      0        0 1.129003e-06
             match_ShapeBasedConcatExpandPattern      0        0 2.015004e-06
      match_ShapeBasedEditDistanceReshapePattern      0        0 1.255001e-06
                 match_ShapeBasedIdentityPattern      0        0 1.162000e-06
          match_ShapeBasedExpandBroadcastPattern      0        0 1.902001e-06
    match_ShapeBasedExpandBroadcastMatMulPattern      0        0 1.938999e-06
      match_ShapeBasedExpandCastWhereSwapPattern      0        0 2.007000e-06
               match_ShapeBasedExpandSwapPattern      0        0 2.121997e-06
              match_ShapeBasedMatMulToMulPattern      0        0 2.729998e-06
                 match_ShapedBasedReshapePattern      0        0 1.225999e-06
             match_ShapeBasedSameChildrenPattern      0        0 1.196000e-06
            match_ShapeBasedShapeShapeAddPattern      0        0 1.107997e-06
                     match_ReshapeReshapePattern      0        0 1.127002e-06
                    match_RotaryEmbeddingPattern      0        0 1.771004e-06
                       match_SameChildrenPattern      0        0 3.137000e-06
              match_SameChildrenFromInputPattern      0        0 3.262998e-06
                match_SequenceConstructAtPattern      0        0 2.385001e-06
                         match_SliceSlicePattern      0        0 2.182998e-06
                        match_SlicesSplitPattern      0        0 1.699998e-06
        match_SoftmaxCrossEntropyLossCastPattern      0        0 4.904003e-06
                        match_SplitConcatPattern      0        0 2.025001e-06
                         match_SqueezeAddPattern      0        0 1.132001e-06
             match_SqueezeBinaryUnsqueezePattern      0        0 1.122004e-06
                   match_SqueezeUnsqueezePattern      0        0 1.383660e-04
                match_StaticConcatReshapePattern      0        0 4.524998e-06
                            match_Sub1MulPattern      0        0 2.444001e-06
                  match_SwapExpandReshapePattern      0        0 1.478002e-06
                match_SwapExpandUnsqueezePattern      0        0 1.105000e-06
                 match_SwapRangeAddScalarPattern      0        0 1.836001e-06
                          match_SwapUnaryPattern      0        0 1.984001e-06
             match_SwapUnsqueezeTransposePattern      0        0 1.248001e-06
                  match_SwitchOrderBinaryPattern      0        0 2.400004e-06
            match_SwitchReshapeActivationPattern      0        0 2.311994e-06
              match_TransposeEqualReshapePattern      0        0 2.139001e-06
                    match_TransposeGatherPattern      0        0 1.261003e-06
                    match_TransposeMatMulPattern      0        0 1.842003e-06
             match_TransposeReshapeMatMulPattern      0        0 1.940003e-06
          match_TransposeReshapeTransposePattern      0        0 1.139997e-06
                 match_TransposeTransposePattern      0        0 1.150001e-06
                     match_UnsqueezeEqualPattern      0        0 1.841996e-06
          match_UnsqueezeOrSqueezeReshapePattern      0        0 1.150001e-06
                   match_UnsqueezeReshapePattern      0        0 1.315995e-06
                 match_UnsqueezeUnsqueezePattern      0        0 1.127002e-06
                           match_WhereAddPattern      0        0 2.091001e-06
                   match_RotaryConcatPartPattern      0        0 2.312998e-06
                  match_FunctionAttentionPattern      0        0 1.603999e-06
               match_FunctionAttentionGQAPattern      0        0 2.338005e-06
                 match_FunctionCausalMaskPattern      0        0 2.062996e-06
           match_FunctionCausalMaskMulAddPattern      0        0 1.665998e-06
                match_FunctionCosSinCachePattern      0        0 2.006003e-06
        match_FunctionHalfRotaryEmbeddingPattern      0        0 1.551001e-06
                   match_RMSNormalizationPattern      0        0 2.012996e-06
                match_RMSNormalizationMulPattern      0        0 1.597997e-06
                               check_pattern_A20      0        0 1.196100e-05
                         remove_duplicated_shape      0        0 2.232999e-06
                               check_pattern_BD0      0        0 5.261005e-06
                           remove_identity_nodes      0        0 1.787600e-05
                               check_pattern_BI0      0        0 4.740003e-06
                                   remove_unused      0        0 1.304400e-05
                              check_pattern_BUS0      0        0 4.280999e-06
                         build_graph_for_pattern      0        0 9.418000e-06
                                     iteration_2      0        0 4.962030e-04
                 match_BatchNormalizationPattern      0        0 2.195004e-06
         match_BatchNormalizationTrainingPattern      0        0 1.362001e-06
         match_CastLayerNormalizationCastPattern      0        0 1.911998e-06
                               match_CastPattern      0        0 1.345004e-06
                     match_CastCastBinaryPattern      0        0 1.480999e-06
                           match_CastCastPattern      0        0 1.105000e-06
                         match_CastOpCastPattern      0        0 1.723005e-06
                           match_ClipClipPattern      0        0 1.266002e-06
                        match_ConcatEmptyPattern      0        0 1.838001e-06
                       match_ConcatGatherPattern      0        0 1.282002e-06
                      match_ConcatReshapePattern      0        0 1.303000e-06
                   match_ConcatTwiceUnaryPattern      0        0 1.449000e-06
              match_ConstantToInitializerPattern      0        0 1.416003e-06
                       match_ConvBiasNullPattern      0        0 1.305001e-06
                            match_DropoutPattern      0        0 1.357002e-06
                             match_ExpandPattern      0        0 1.451001e-06
                    match_ExpandBroadcastPattern      0        0 1.560002e-06
                         match_ExpandSwapPattern      0        0 1.605003e-06
              match_ExpandUnsqueezeExpandPattern      0        0 1.346001e-06
                       match_GathersSplitPattern      0        0 1.421002e-06
                               match_GeluPattern      0        0 4.639951e-07
                           match_IdentityPattern      0        0 1.504995e-06
                 match_LayerNormalizationPattern      0        0 1.533001e-06
            match_LayerNormalizationScalePattern      0        0 1.410997e-06
                          match_LeakyReluPattern      0        0 4.255002e-06
                            match_MaxReluPattern      0        0 1.629000e-06
                    match_MulMulMulScalarPattern      0        0 1.501998e-06
              match_MulUnsqueezeUnsqueezePattern      0        0 1.244000e-06
                             match_NotNotPattern      0        0 1.360997e-06
                           match_NotWherePattern      0        0 1.644999e-06
                      match_ReduceArgTopKPattern      0        0 2.305002e-06
                      match_ReduceReshapePattern      0        0 1.767999e-06
                 match_ReduceSumNormalizePattern      0        0 1.470995e-06
                            match_ReshapePattern      0        0 1.102999e-06
               match_ReshapeMatMulReshapePattern      0        0 1.209999e-06
                        match_Reshape2Of3Pattern      0        0 1.330998e-06
               match_ReshapeReshapeBinaryPattern      0        0 1.369997e-06
                      match_GemmTransposePattern      0        0 1.499000e-06
                  match_MatMulReshape2Of3Pattern      0        0 1.413006e-06
                       match_MulMulMatMulPattern      0        0 1.963999e-06
         match_ShapeBasedReshapeIsSqueezePattern      0        0 1.357002e-06
             match_ShapeBasedStaticExpandPattern      0        0 1.177999e-06
             match_ShapeBasedConcatExpandPattern      0        0 1.452005e-06
      match_ShapeBasedEditDistanceReshapePattern      0        0 1.087996e-06
                 match_ShapeBasedIdentityPattern      0        0 1.361004e-06
          match_ShapeBasedExpandBroadcastPattern      0        0 1.289001e-06
    match_ShapeBasedExpandBroadcastMatMulPattern      0        0 1.264001e-06
      match_ShapeBasedExpandCastWhereSwapPattern      0        0 1.171997e-06
               match_ShapeBasedExpandSwapPattern      0        0 1.437002e-06
              match_ShapeBasedMatMulToMulPattern      0        0 1.355002e-06
                 match_ShapedBasedReshapePattern      0        0 1.261003e-06
             match_ShapeBasedSameChildrenPattern      0        0 1.963002e-06
            match_ShapeBasedShapeShapeAddPattern      0        0 2.151995e-06
                     match_ReshapeReshapePattern      0        0 1.706998e-06
                    match_RotaryEmbeddingPattern      0        0 2.157001e-06
                       match_SameChildrenPattern      0        0 4.266003e-06
              match_SameChildrenFromInputPattern      0        0 4.353002e-06
                match_SequenceConstructAtPattern      0        0 2.448003e-06
                         match_SliceSlicePattern      0        0 2.508001e-06
                        match_SlicesSplitPattern      0        0 2.143999e-06
        match_SoftmaxCrossEntropyLossCastPattern      0        0 5.829002e-06
                        match_SplitConcatPattern      0        0 2.244997e-06
                         match_SqueezeAddPattern      0        0 1.868000e-06
             match_SqueezeBinaryUnsqueezePattern      0        0 1.959997e-06
                   match_SqueezeUnsqueezePattern      0        0 2.054003e-06
                match_StaticConcatReshapePattern      0        0 2.187997e-06
                            match_Sub1MulPattern      0        0 1.948996e-06
                  match_SwapExpandReshapePattern      0        0 1.654997e-06
                match_SwapExpandUnsqueezePattern      0        0 1.729000e-06
                 match_SwapRangeAddScalarPattern      0        0 1.966997e-06
                          match_SwapUnaryPattern      0        0 1.927001e-06
             match_SwapUnsqueezeTransposePattern      0        0 1.913999e-06
                  match_SwitchOrderBinaryPattern      0        0 2.351997e-06
            match_SwitchReshapeActivationPattern      0        0 2.362001e-06
              match_TransposeEqualReshapePattern      0        0 2.198998e-06
                    match_TransposeGatherPattern      0        0 1.969005e-06
                    match_TransposeMatMulPattern      0        0 2.811001e-06
             match_TransposeReshapeMatMulPattern      0        0 1.973000e-06
          match_TransposeReshapeTransposePattern      0        0 1.679997e-06
                 match_TransposeTransposePattern      0        0 1.838998e-06
                     match_UnsqueezeEqualPattern      0        0 2.085995e-06
          match_UnsqueezeOrSqueezeReshapePattern      0        0 1.740002e-06
                   match_UnsqueezeReshapePattern      0        0 1.909997e-06
                 match_UnsqueezeUnsqueezePattern      0        0 1.615997e-06
                           match_WhereAddPattern      0        0 2.049004e-06
                   match_RotaryConcatPartPattern      0        0 2.721004e-06
                  match_FunctionAttentionPattern      0        0 2.408000e-06
               match_FunctionAttentionGQAPattern      0        0 3.134999e-06
                 match_FunctionCausalMaskPattern      0        0 2.385998e-06
           match_FunctionCausalMaskMulAddPattern      0        0 2.271998e-06
                match_FunctionCosSinCachePattern      0        0 2.624998e-06
        match_FunctionHalfRotaryEmbeddingPattern      0        0 2.256005e-06
                   match_RMSNormalizationPattern      0        0 2.499000e-06
                match_RMSNormalizationMulPattern      0        0 2.234003e-06
                       match_AttentionGQAPattern      0        0 2.565997e-06
                               check_pattern_A20      0        0 1.466600e-05
                         remove_duplicated_shape      0        0 7.069997e-06
                               check_pattern_BD0      0        0 9.892996e-06
                           remove_identity_nodes      0        0 2.449800e-05
                               check_pattern_BI0      0        0 6.333998e-06
                                   remove_unused      0        0 1.708901e-05
                              check_pattern_BUS0      0        0 6.683003e-06
                         build_graph_for_pattern      0        0 1.459800e-05
                                     iteration_3      0        0 4.115880e-04
                 match_BatchNormalizationPattern      0        0 4.227993e-06
         match_BatchNormalizationTrainingPattern      0        0 2.293003e-06
         match_CastLayerNormalizationCastPattern      0        0 3.285997e-06
                               match_CastPattern      0        0 2.107998e-06
                     match_CastCastBinaryPattern      0        0 2.563000e-06
                           match_CastCastPattern      0        0 2.030996e-06
                         match_CastOpCastPattern      0        0 2.921995e-06
                           match_ClipClipPattern      0        0 2.267006e-06
                        match_ConcatEmptyPattern      0        0 2.358996e-06
                       match_ConcatGatherPattern      0        0 2.097004e-06
                      match_ConcatReshapePattern      0        0 2.307002e-06
                   match_ConcatTwiceUnaryPattern      0        0 2.278000e-06
              match_ConstantToInitializerPattern      0        0 2.532004e-06
                       match_ConvBiasNullPattern      0        0 2.417997e-06
                            match_DropoutPattern      0        0 2.207998e-06
                             match_ExpandPattern      0        0 2.230001e-06
                    match_ExpandBroadcastPattern      0        0 2.266002e-06
                         match_ExpandSwapPattern      0        0 2.480003e-06
              match_ExpandUnsqueezeExpandPattern      0        0 2.100001e-06
                       match_GathersSplitPattern      0        0 2.626999e-06
                               match_GeluPattern      0        0 7.730050e-07
                           match_IdentityPattern      0        0 2.460001e-06
                 match_LayerNormalizationPattern      0        0 2.311004e-06
            match_LayerNormalizationScalePattern      0        0 2.223998e-06
                          match_LeakyReluPattern      0        0 7.292001e-06
                            match_MaxReluPattern      0        0 2.499000e-06
                    match_MulMulMulScalarPattern      0        0 2.350003e-06
              match_MulUnsqueezeUnsqueezePattern      0        0 1.963999e-06
                             match_NotNotPattern      0        0 6.246002e-06
                           match_NotWherePattern      0        0 2.319997e-06
                      match_ReduceArgTopKPattern      0        0 2.910005e-06
                      match_ReduceReshapePattern      0        0 2.945999e-06
                 match_ReduceSumNormalizePattern      0        0 2.233995e-06
                            match_ReshapePattern      0        0 2.371002e-06
               match_ReshapeMatMulReshapePattern      0        0 2.096007e-06
                        match_Reshape2Of3Pattern      0        0 3.134999e-06
               match_ReshapeReshapeBinaryPattern      0        0 2.300003e-06
                          match_MatMulAddPattern      0        0 3.200999e-06
                      match_GemmTransposePattern      0        0 2.289999e-06
                  match_MatMulReshape2Of3Pattern      0        0 2.722998e-06
                       match_MulMulMatMulPattern      0        0 2.962006e-06
         match_ShapeBasedReshapeIsSqueezePattern      0        0 2.553999e-06
             match_ShapeBasedStaticExpandPattern      0        0 2.216999e-06
             match_ShapeBasedConcatExpandPattern      0        0 2.686997e-06
      match_ShapeBasedEditDistanceReshapePattern      0        0 1.951004e-06
                 match_ShapeBasedIdentityPattern      0        0 2.442997e-06
          match_ShapeBasedExpandBroadcastPattern      0        0 2.385998e-06
    match_ShapeBasedExpandBroadcastMatMulPattern      0        0 1.941000e-06
      match_ShapeBasedExpandCastWhereSwapPattern      0        0 2.278000e-06
               match_ShapeBasedExpandSwapPattern      0        0 2.624001e-06
              match_ShapeBasedMatMulToMulPattern      0        0 2.209999e-06
                 match_ShapedBasedReshapePattern      0        0 2.298999e-06
             match_ShapeBasedSameChildrenPattern      0        0 2.233995e-06
            match_ShapeBasedShapeShapeAddPattern      0        0 2.398003e-06
                     match_ReshapeReshapePattern      0        0 2.345994e-06
                    match_RotaryEmbeddingPattern      0        0 2.482004e-06
                       match_SameChildrenPattern      0        0 5.064998e-06
              match_SameChildrenFromInputPattern      0        0 5.234004e-06
                match_SequenceConstructAtPattern      0        0 2.662004e-06
                         match_SliceSlicePattern      0        0 2.114000e-06
                        match_SlicesSplitPattern      0        0 2.637003e-06
        match_SoftmaxCrossEntropyLossCastPattern      0        0 6.703995e-06
                        match_SplitConcatPattern      0        0 2.804998e-06
                         match_SqueezeAddPattern      0        0 2.272005e-06
             match_SqueezeBinaryUnsqueezePattern      0        0 2.198001e-06
                   match_SqueezeUnsqueezePattern      0        0 3.039000e-06
                match_StaticConcatReshapePattern      0        0 1.780005e-06
                            match_Sub1MulPattern      0        0 1.943001e-06
                  match_SwapExpandReshapePattern      0        0 2.177003e-06
                match_SwapExpandUnsqueezePattern      0        0 2.515997e-06
                 match_SwapRangeAddScalarPattern      0        0 2.355999e-06
                          match_SwapUnaryPattern      0        0 2.765002e-06
             match_SwapUnsqueezeTransposePattern      0        0 2.646004e-06
                  match_SwitchOrderBinaryPattern      0        0 2.569999e-06
            match_SwitchReshapeActivationPattern      0        0 2.569002e-06
              match_TransposeEqualReshapePattern      0        0 2.638000e-06
                    match_TransposeGatherPattern      0        0 2.036999e-06
                    match_TransposeMatMulPattern      0        0 2.654997e-06
             match_TransposeReshapeMatMulPattern      0        0 2.161003e-06
          match_TransposeReshapeTransposePattern      0        0 2.110995e-06
                 match_TransposeTransposePattern      0        0 2.075998e-06
                     match_UnsqueezeEqualPattern      0        0 2.061999e-06
          match_UnsqueezeOrSqueezeReshapePattern      0        0 2.472007e-06
                   match_UnsqueezeReshapePattern      0        0 1.930006e-06
                 match_UnsqueezeUnsqueezePattern      0        0 2.290995e-06
                           match_WhereAddPattern      0        0 2.091001e-06
                   match_RotaryConcatPartPattern      0        0 3.069996e-06
                  match_FunctionAttentionPattern      0        0 2.484005e-06
               match_FunctionAttentionGQAPattern      0        0 3.699999e-06
                 match_FunctionCausalMaskPattern      0        0 2.799003e-06
           match_FunctionCausalMaskMulAddPattern      0        0 2.026005e-06
                match_FunctionCosSinCachePattern      0        0 2.492001e-06
        match_FunctionHalfRotaryEmbeddingPattern      0        0 2.474000e-06
                   match_RMSNormalizationPattern      0        0 2.243003e-06
                match_RMSNormalizationMulPattern      0        0 2.403001e-06
                       match_AttentionGQAPattern      0        0 2.006003e-06
                               check_pattern_A20      0        0 1.664200e-05
                         remove_duplicated_shape      0        0 3.464003e-06
                               check_pattern_BD0      0        0 7.737006e-06
                           remove_identity_nodes      0        0 2.757100e-05
                               check_pattern_BI0      0        0 7.579001e-06
                                   remove_unused      0        0 1.861100e-05
                              check_pattern_BUS0      0        0 7.021998e-06
                         build_graph_for_pattern      0        0 1.399700e-05
                                check_patterns-4      0        0 1.192100e-05
                                   remove_unused      0        0 1.737000e-05
                           check_remove_unused-5      0        0 7.354000e-06
                                 remove_identity      0        0 1.912900e-05
                         check_remove_identity-6      0        0 6.077003e-06
                                constant_folding      0        0 1.197300e-05
                apply_constant_folding_new_inits      0        0          NaN
                        check_constant_folding-7      0        0 5.965005e-06
                                   remove_unused      0        0 1.261799e-05
                           check_remove_unused-8      0        0 5.820999e-06
                   remove_duplicated_initializer      0        0 2.285000e-06
           check_remove_duplicated_initializer-9      0        0 5.987000e-06
                                 remove_identity      0        0 1.674300e-05
                        check_remove_identity-10      0        0 5.715003e-06
                                   remove_unused      0        0 1.257700e-05
                          check_remove_unused-11      0        0 5.808004e-06
                                           order      0        0 5.281100e-05
                                    check_orderA      0        0 9.283001e-06
                                    check_orderL      0        0 6.076996e-06
                                     shape_order      0        0 2.519200e-05
                                           order      0        0          NaN
                                  check_order-12      0        0 6.309005e-06
                                    optimization      0        2 5.244711e-03
    
    nodes before: 3
    nodes after : 1

The report can be aggregated by pass name:

<<<

import pandas
import onnx
import onnx.helper as oh
from yobx.xbuilder import GraphBuilder, OptimizationOptions

TFLOAT = onnx.TensorProto.FLOAT

model = oh.make_model(
    oh.make_graph(
        [
            oh.make_node("Identity", ["X"], ["X2"]),
            oh.make_node("Transpose", ["X2"], ["T"], perm=[1, 0]),
            oh.make_node("Transpose", ["T"], ["Z"], perm=[1, 0]),
        ],
        "demo",
        [oh.make_tensor_value_info("X", TFLOAT, [3, 4])],
        [oh.make_tensor_value_info("Z", TFLOAT, [3, 4])],
    ),
    opset_imports=[oh.make_opsetid("", 18)],
    ir_version=10,
)

opts = OptimizationOptions(patterns="default")
g = GraphBuilder(model, infer_shapes_options=True, optimization_options=opts)
art = g.to_onnx(return_optimize_report=True)

df = pandas.DataFrame(art.report.stats)
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                                                  
    apply_TransposeTransposePattern      1        2  0.000339
    optimization                         0        2  0.014814
    remove_identity                      1        2  0.000212
    patterns                             0        1  0.013827

Local functions#

A sub-graph can be exported as a reusable ONNX local function (a FunctionProto) by passing a FunctionOptions instance to to_onnx.

<<<

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,
)
print(type(func).__name__)
print("function name  :", func.name)
print("function domain:", func.domain)

>>>

    FunctionProto
    function name  : MyRelu
    function domain: my.domain

Debugging#

GraphBuilder respects several environment variables that help narrow down construction or optimization problems:

Environment variable

Effect

ONNXSTOP=<name>

Raises an exception the moment result <name> is created.

ONNXSTOPSHAPE=<name>

Raises an exception the moment result <name> receives a shape.

ONNXSTOPTYPE=<name>

Raises an exception the moment result <name> receives a type.

ONNXSTOPOUTPUT=<name>

Raises an exception the moment a node produces output <name>.

ONNXSTOPVALUESHAPE=<name>

Prints extra information for shape-as-value tracking (e.g. inputs to Reshape).

ONNXCST=1

Prints which constant is being evaluated.

ONNXFUNC=1

Prints details when nodes from a local function domain are added.

ONNXSHAPECOMPUTE=1

Raises an exception when a shape is missing for a result that should have one.

NULLSHAPE=1

Raises an exception as soon as a null/empty shape is encountered.

ONNXDYNDIM=<name>

Prints a message every time dynamic dimension <name> is used.

PRINTNAME=<name>

Prints a message every time a node producing <name> is added.

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:

<<<

import onnx
import 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())

>>>

    
    dyn---: batch -> WrapSym(batch)
    dynrev: batch -> [('batch', SymInt(batch))]
    dynsrc: batch -> [{batch:('input_name', 'X'), batch:('axis', 0)}, {batch:('input_name', 'Y'), batch:('axis', 0)}, {batch:('input_name', 'Z'), batch:('axis', 0)}]
    opset: : 18
    input:: X                                                                       |T1: batch x 4
    input:: Y                                                                       |T1: batch x 4
    Add: X, Y -> T                                                                  |T1: batch x 4
    Relu: T -> Z                                                                    |T1: batch x 4
    output:: Z                                                                      |T1: batch x 4