Separating cleanup from reversible rewrites#

Explicit cleanups that redirect value references establish the canonical graph before capture. Reversible records restore this cleaned graph, not the source graph containing the removed identities and duplicate initializers.

# sphinx_gallery_thumbnail_path = "_static/gallery_thumbnails/pattern_replay_cleanup.png"

from __future__ import annotations

from onnx_light.onnx import TensorProto
import onnx_light.onnx.helper as oh
from onnx_light.onnx_core.optimization import (
    GraphBuilder,
    GraphGraph,
    apply_rewritings,
    standard_patterns,
)
from onnx_light.tools import pretty_onnx

Create and clean up the source model#

This graph contains an Identity node, a redundant Cast, a dead-end Neg node, and two equal initializers used by retained nodes.

model = oh.make_model(
    oh.make_graph(
        [
            oh.make_node("Add", ["x", "weight"], ["summed"]),
            oh.make_node("Identity", ["summed"], ["forwarded"]),
            oh.make_node("Cast", ["forwarded"], ["casted"], to=TensorProto.FLOAT),
            oh.make_node("Add", ["summed", "duplicate_weight"], ["direct"]),
            oh.make_node("Add", ["casted", "direct"], ["y"]),
            oh.make_node("Neg", ["x"], ["dead_end"]),
        ],
        "cleanup",
        [oh.make_tensor_value_info("x", TensorProto.FLOAT, [1])],
        [oh.make_tensor_value_info("y", TensorProto.FLOAT, [1])],
        initializer=[
            oh.make_tensor("weight", TensorProto.FLOAT, [1], [1.0]),
            oh.make_tensor("duplicate_weight", TensorProto.FLOAT, [1], [1.0]),
        ],
    ),
    opset_imports=[oh.make_opsetid("", 18)],
)

builder = GraphBuilder(model)
graph = GraphGraph(builder, standard_patterns(["Cast"]))
rewrites = graph.optimize(canonicalize=True)
canonical = oh.make_model(
    builder.undo_rewritings(rewrites).build_graph(), opset_imports=[oh.make_opsetid("", 18)]
)
assert all(node.op_type != "Identity" for node in canonical.graph.node)
assert [value.name for value in canonical.graph.initializer] == ["weight"]
optimized_graph = builder.build_graph()

assert rewrites.rewrites
assert not {"RemoveIdentityNodes", "RemoveDuplicateNodes", "RemoveDuplicateInitializers"} & {
    rewrite.pattern_name for rewrite in rewrites.rewrites
}

print("Original graph:")
print(pretty_onnx(model))
print("Cleaned canonical graph:")
print(pretty_onnx(canonical))
print("Optimized graph:")
print(pretty_onnx(optimized_graph))
Original graph:
opset: domain='' version=18
graph: name='cleanup'
input: float[1] x
init: float[1] weight
init: float[1] duplicate_weight
0: Add(x, weight) -> summed
1: Identity(summed) -> forwarded
2: Cast(forwarded) -> casted
3: Add(summed, duplicate_weight) -> direct
4: Add(casted, direct) -> y
5: Neg(x) -> dead_end
output: float[1] y
Cleaned canonical graph:
opset: domain='' version=18
graph: name='cleanup'
input: float[1] x
init: float[1] weight
0: Add(x, weight) -> summed
1: Cast(summed) -> casted
2: Add(summed, weight) -> direct
3: Add(casted, direct) -> y
4: Neg(x) -> dead_end
output: float[1] y
Optimized graph:
graph: name='cleanup'
input: float[1] x
init: float[1] weight
0: Add(x, weight) -> summed
1: Identity(summed) -> casted
2: Add(summed, weight) -> direct
3: Add(casted, direct) -> y
output: float[1] y

Replay and undo only the captured modifications#

Forward replay starts from the cleaned canonical model. Inverse replay restores the Cast and dead-end node, but not the pre-capture Identity or duplicate weight. Undo uses history retained by the builder that optimized the graph. That history is never exported in the model or rewriting protos.

for rewrite in rewrites.rewrites:
    print(rewrite)

replayed_graph = apply_rewritings(canonical, rewrites)
assert replayed_graph.SerializeToString() == optimized_graph.SerializeToString()
print("Replayed graph:")
print(pretty_onnx(replayed_graph))

restored = builder.undo_rewritings(rewrites).build_graph()
assert restored.SerializeToString() == canonical.graph.SerializeToString()
assert all(node.op_type != "Identity" for node in restored.node)
assert restored.SerializeToString() != model.graph.SerializeToString()
print("Restored cleaned canonical graph:")
print(pretty_onnx(restored))
{ pattern_name: "Cast" matched_nodes: [1] added_nodes: [ { input: [ "summed" ] output: [ "casted" ] name: "CastPattern--" op_type: "Identity" domain: "" } ] added_nodes_positions: [1] }
{ pattern_name: "RemoveUnusedNodes" matched_nodes: [4] }
Replayed graph:
graph: name='cleanup'
input: float[1] x
init: float[1] weight
0: Add(x, weight) -> summed
1: Identity(summed) -> casted
2: Add(summed, weight) -> direct
3: Add(casted, direct) -> y
output: float[1] y
Restored cleaned canonical graph:
graph: name='cleanup'
input: float[1] x
init: float[1] weight
0: Add(x, weight) -> summed
1: Cast(summed) -> casted
2: Add(summed, weight) -> direct
3: Add(casted, direct) -> y
4: Neg(x) -> dead_end
output: float[1] y

Total running time of the script: (0 minutes 0.004 seconds)

Related examples

Replaying graph-rewriting patterns

Replaying graph-rewriting patterns

Separating cleanup from reversible rewrites

Separating cleanup from reversible rewrites

Gallery generated by Sphinx-Gallery

Example last updated

Date:

2026-11-17