onnx_patterns#
This module documents the C++ optimization-pattern headers used by
lib_onnx_patterns.
Core
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns#
Functions
-
void RegisterPatterns()#
Registers every built-in ONNX graph-rewriting pattern.
Registration is idempotent. Call this function before :cpp:func:
core::builder::CreateRegisteredPatternswhen the standard ONNX pattern set is required.
-
void RegisterPatterns()#
-
namespace onnx_patterns#
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class FunctionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <function_pattern.h>
Creates a rewrite from two ONNX function bodies with fixed input/output lists.
Inputs and outputs correspond by position, not by name. Node arities, domains, overloads, literal attributes and imported opset versions must match exactly. A template attribute with ref_attr_name captures the candidate attribute; the replacement may reference that capture, including under another attribute name. Repeated references must capture equal values of the declared type. Tensor literals compare exact element types, dimensions and payload bytes, independently of raw or typed inline storage.
Before: inputs ──→ ┌──────────────────┐ ──→ outputs │ template body │ └──────────────────┘ After: inputs ──→ ┌──────────────────┐ ──→ outputs │ replacement body │ └──────────────────┘With
as_function=true, After is a call to the replacement function instead of its inlined body. One compatible definition is shared by all occurrences, including calls in subgraphs. Captures become call attributes; shape inference follows the registered local body. Function-call replacement outputs must be distinct. This mode does not rewrite local-function bodies or their subgraphs, preventing the introduction of recursive function dependencies.Bodies must be topologically sorted SSA graphs without graph-valued attributes. Template inputs must be used, and template outputs must be distinct node results. Template nodes must be connected through nonempty values (including shared inputs). Matching follows local producers and consumers from the selected anchor, never scans unrelated graph nodes. Replacement outputs may alias inputs, and in inline mode may alias each other. Configured target nodes are conservatively rejected. Intermediates may not escape the match. Subgraph captures and matches needing interleaved external consumers are conservatively rejected. Function definitions are copied. Forwarded or aliased outputs need a default ONNX opset for Identity.
Unlike built-in rewrites, this configurable class has no default factory: register an instance with the desired function pair instead.
Public Functions
-
FunctionPattern(const FunctionProto &pattern, const FunctionProto &replacement, int priority = 1, std::string name = "FunctionPattern", core::symbolic::Device device = core::symbolic::Device::kUndefined, int anchor = -1, bool as_function = false)#
Creates a pattern; anchor selects a zero-based template node (-1 means the last).
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
FunctionPattern(const FunctionProto &pattern, const FunctionProto &replacement, int priority = 1, std::string name = "FunctionPattern", core::symbolic::Device device = core::symbolic::Device::kUndefined, int anchor = -1, bool as_function = false)#
-
class FunctionPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Algebra
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class SameChildrenFromInputPattern : public onnx_light::onnx_patterns::SameChildrenPattern#
- #include <common_pattern.h>
Merges identical nodes that consume the same graph input.
Before: ┌─────────┐ graph_input, c ──────→│ Op │──────→ a └─────────┘ ┌─────────┐ graph_input, c ──────→│ Op │──────→ b └─────────┘ After: ┌─────────┐ graph_input, c ──────→│ Op │──────→ a └─────────┘ │ ↓ ┌──────────┐ │ Identity │──────→ b └──────────┘It uses the same replacement as SameChildrenPattern, retaining one node and preserving every removed sibling output with an Identity.
Public Functions
-
inline explicit SameChildrenFromInputPattern(int priority = 0)#
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
inline explicit SameChildrenFromInputPattern(int priority = 0)#
-
class SameChildrenPattern : public onnx_light::core::builder::PatternOptimization#
- #include <common_pattern.h>
Merges pairs of identical sibling nodes, and any identical descendant chains.
Before: ┌────┐ ┌──────┐ ┌──────→│ Op │────→ a ─────────────→│ Next │────→ p │ └────┘ └──────┘ │ x, c ────┤ │ │ ┌────┐ ┌──────┐ └──────→│ Op │────→ b ─────────────→│ Next │────→ q └────┘ └──────┘ After: ┌────┐ ┌──────┐ x, c ────→│ Op │────→ a ────→│ Next │────→ p └────┘ │ └──────┘ │ │ │ ↓ ↓ ┌──────────┐ ┌──────────┐ │ Identity │────→ b │ Identity │────→ q └──────────┘ └──────────┘One copy of every equivalent node is retained. Identity nodes preserve all output names from the removed copy, including outputs used by later nodes.
Subclassed by onnx_light::onnx_patterns::SameChildrenFromInputPattern
Public Functions
-
inline explicit SameChildrenPattern(int priority = 0)#
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
Protected Functions
-
core::builder::MatchResult MatchWithNodes(core::builder::GraphGraph &graph, const NodeProto &candidate, const std::vector<const NodeProto*> &next_nodes) const#
-
inline explicit SameChildrenPattern(int priority = 0)#
-
class ShapeBasedIdentityPattern : public onnx_light::core::builder::PatternOptimization#
- #include <common_pattern.h>
Replaces a shape-preserving Slice by an Identity.
Before: x, starts, ends, axes, steps=1 │ ↓ ┌─────────┐ │ Slice │ └─────────┘ │ ↓ y After: ┌──────────┐ x ────→│ Identity │────→ y └──────────┘The rewrite requires equal inferred input and output shapes. When the optional steps input is present, it must be a materialized all-one constant.
Public Functions
-
inline explicit ShapeBasedIdentityPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ShapeBasedIdentityPattern(int priority = 0)#
-
class ShapeBasedSameChildrenPattern : public onnx_light::core::builder::PatternOptimization#
- #include <common_pattern.h>
Merges Expand or Reshape siblings whose inferred output shapes are equal.
Before: ┌─────────┐ x, shape1 ──────→│ Reshape │──────→ a └─────────┘ ┌─────────┐ x, shape2 ──────→│ Reshape │──────→ b └─────────┘ After: ┌─────────┐ x, shape1 ──────→│ Reshape │──────→ a └─────────┘ │ ↓ ┌──────────┐ │ Identity │──────→ b └──────────┘The inferred shapes of
aandbmust be equal, although the shape inputs may differ. The first operation is retained and each other sibling is replaced by an Identity that retains its original output name.Public Functions
-
inline explicit ShapeBasedSameChildrenPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ShapeBasedSameChildrenPattern(int priority = 0)#
-
class SwapUnaryPattern : public onnx_light::core::builder::PatternOptimization#
- #include <common_pattern.h>
Moves a rank-preserving layout operation after a compatible following operation.
Before: x, perm/shape │ ↓ ┌───────────────────┐ │ Transpose/Reshape │ └───────────────────┘ │ ↓ ┌─────────┐ │ Unary │←──── extra inputs └─────────┘ │ ↓ y After: ┌─────────┐ x ────→│ Unary │←──── extra inputs └─────────┘ │ ↓ ┌───────────────────┐ │ Transpose/Reshape │←──── perm/shape └───────────────────┘ │ ↓ yThe layout node is a Transpose or Reshape. The following node is unary-like, or is Add, Sub, Mul, or Div with a shape-[1] second input; its extra inputs and the final output name are retained.
Public Functions
-
inline explicit SwapUnaryPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit SwapUnaryPattern(int priority = 0)#
-
class SameChildrenFromInputPattern : public onnx_light::onnx_patterns::SameChildrenPattern#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class DivMulPattern : public onnx_light::core::builder::PatternOptimization#
- #include <mul_pattern.h>
Fuses a reciprocal followed by multiplication into one division.
Before: ┌─────────────┐ one ───────────────→│ │ │ Div │───→ reciprocal ───┐ denominator ───────→│ │ │ └─────────────┘ ↓ ┌─────────────┐ value ─────────────────────────────────────────→│ Mul │───→ output └─────────────┘ After: ┌─────────────┐ value ─────────────→│ │ │ Div │───→ output denominator ───────→│ │ └─────────────┘onemust be a one-element FLOAT, FLOAT16, DOUBLE, INT32, or INT64 constant equal to one. The intermediate Div output must have no other use.Public Functions
-
inline explicit DivMulPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit DivMulPattern(int priority = 0)#
-
class MulMulMulScalarPattern : public onnx_light::core::builder::PatternOptimization#
- #include <mul_pattern.h>
Combines the scalar constants from three nested Mul or Div nodes.
Before: ┌─────────┐ a, c1 ────→│ LeftOp │──┐ └─────────┘ │ │ ┌─────────┐ │ ┌─────────┐ b, c2 ────→│ RightOp │──┴───→│ OuterOp │────→ y └─────────┘ └─────────┘ After: ┌─────────┐ a, b ────→│ OuterOp │────→ t └─────────┘ ┌─────────┐ t, combined scalar ───→│ Mul/Div │────→ y └─────────┘c1andc2are scalar or one-element constants. The replacement retains the outer output and combines or reciprocates the constants as required by the inner Mul/Div operators; two inner Div nodes produce the final Div, while all other combinations produce the final Mul.Public Functions
-
inline explicit MulMulMulScalarPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit MulMulMulScalarPattern(int priority = 0)#
-
class SwitchOrderBinaryPattern : public onnx_light::core::builder::PatternOptimization#
- #include <mul_pattern.h>
Reassociates nested Add or Mul nodes to reduce broadcasting rank.
Before: ┌─────────┐ b, c ────→│ Add/Mul │────→ t └─────────┘ │ ↓ ┌─────────┐ │ Add/Mul │←──── a └─────────┘ │ ↓ y After: ┌─────────┐ b, a ────→│ Add/Mul │────→ t2 └─────────┘ │ ↓ ┌─────────┐ │ Add/Mul │←──── c └─────────┘ │ ↓ y Alternative matched forms may group (c, a), or place the inner node on the right input of the outer node.The symmetric right-nested form is also handled, and the alternative
Op(c, a)grouping may be selected. The inner output must be unshared; the outer output name is retained.Public Functions
-
inline explicit SwitchOrderBinaryPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit SwitchOrderBinaryPattern(int priority = 0)#
-
class DivMulPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class SwapRangeAddScalarPattern : public onnx_light::core::builder::PatternOptimization#
- #include <range_pattern.h>
Moves a shape-[1] second Add input from after Range into its start and limit inputs.
Before: start, limit, delta │ ↓ ┌───────┐ │ Range │────→ r └───────┘ │ ↓ ┌─────┐ │ Add │←──── offset └─────┘ │ ↓ y After: ┌─────┐ start ───────────────────────→│ Add │────→ start2 ────────────────┐ └─────┘ │ ↑ │ │ │ ┌─────────┐ │ │ offset ────→│ Squeeze │────→ s ─┤ │ └─────────┘ │ │ ↓ │ ┌─────┐ │ limit ───────────────────────→│ Add │────→ limit2 ────────────────┴──┐ └─────┘ │ ↓ ┌───────┐ delta ──────────────────────────────────────────────────────────→│ Range │────→ y └───────┘ After (start is constant zero): ┌─────────┐ offset ────→│ Squeeze │────→ s ───────────────────────────────────┐ └─────────┘ │ │ │ ↓ │ ┌─────┐ │ limit ──────────────────────→│ Add │────→ limit2 ─────────────────┴──┐ └─────┘ │ ↓ ┌───────┐ delta ───────────────────────────────────────────────────────────→│ Range │────→ y └───────┘When
startis the constant zero,start2issand its Add is omitted. The Range and Add are replaced while the Add outputy, the offset, and any Range step input are retained.Public Functions
-
inline explicit SwapRangeAddScalarPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit SwapRangeAddScalarPattern(int priority = 0)#
-
class SwapRangeAddScalarPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class ReduceArgTopKPattern : public onnx_light::core::builder::PatternOptimization#
- #include <reduce_pattern.h>
Fuses matching ReduceMin/ReduceMax and ArgMin/ArgMax nodes into TopK with K=1.
Before: ┌───────────────┐ ┌──────→│ ReduceMax/Min │────→ values │ └───────────────┘ │ x ───────┤ │ │ ┌────────────┐ └──────→│ ArgMax/Min │────→ indices └────────────┘ After: ┌──────┐ x, K=[1] ────→│ TopK │ └──────┘ │ ┌─────┴─────┐ │ │ ↓ ↓ values indices After (keepdims=0): ┌──────┐ x, K=[1] ────→│ TopK │ └──────┘ │ ┌─────┴─────┐ │ │ ↓ ↓ temporary values temporary indices │ │ ↓ ↓ ┌─────────┐ ┌─────────┐ axes ──→│ Squeeze │ │ Squeeze │←── axes └─────────┘ └─────────┘ │ │ ↓ ↓ values indicesThe Min variant sets
largest=0. Whenkeepdims=0, TopK produces temporary singleton-axis outputs and two Squeeze nodes restore the originalvaluesandindicesoutput names.Public Functions
-
inline explicit ReduceArgTopKPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ReduceArgTopKPattern(int priority = 0)#
-
class ReduceSumNormalizePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reduce_pattern.h>
Moves a Cast-ReduceSum-Mul-Sub-Cast normalization chain to the result type.
Before: ┌──────┐ x ────→│ Cast │────→ xc └──────┘ │ ↓ ┌───────────┐ │ ReduceSum │←──── axes └───────────┘ │ ↓ ┌─────┐ │ Mul │←──── scale └─────┘ │ ↓ ┌─────┐ │ Sub │←──── xc (or axes) └─────┘ │ ↓ ┌──────┐ │ Cast │────→ y └──────┘ After: ┌───────────┐ x ────→│ ReduceSum │←──── axes └───────────┘ │ ↓ ┌─────┐ ┌──────┐ │ Mul │←──── │ Cast │←──── scale └─────┘ └──────┘ │ ↓ ┌─────┐ │ Sub │←──── x └─────┘ │ ↓ yThe reversed Sub operand order is retained. The five matched nodes become ReduceSum, Cast, Mul, and Sub nodes in
Twhile preservingaxes,scale, ReduceSum attributes, and the final outputy. The matcher also acceptsaxesinstead ofxcas the reused Sub input; Apply replaces that reused input withxin either case.Public Functions
-
inline explicit ReduceSumNormalizePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ReduceSumNormalizePattern(int priority = 0)#
-
class ReduceArgTopKPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class ShapeBasedShapeShapeAddPattern : public onnx_light::core::builder::PatternOptimization#
- #include <shape_pattern.h>
Recognizes an Add fed by two Shape nodes but performs no rewrite.
Before: ┌───────┐ x ────→│ Shape │────────────┐ └───────┘ │ │ ↓ ┌───────┐ ┌─────┐ z ────→│ Shape │───────→│ Add │────→ y └───────┘ └─────┘ After: ┌───────┐ x ────→│ Shape │────────────┐ └───────┘ │ │ ↓ ┌───────┐ ┌─────┐ z ────→│ Shape │───────→│ Add │────→ y └───────┘ └─────┘ The graph is unchanged because this pattern deliberately reports no match.Match deliberately returns no match and Apply throws because the intended Shape-plus-Shape replacement is not implemented.
Public Functions
-
inline explicit ShapeBasedShapeShapeAddPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ShapeBasedShapeShapeAddPattern(int priority = 0)#
-
class ShapeBasedShapeShapeAddPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class Sub1MulPattern : public onnx_light::core::builder::PatternOptimization#
- #include <sub_pattern.h>
Rewrites multiplication by
1 - xinto a product followed by subtraction.Before: ┌─────┐ one, x ────→│ Sub │────→ d └─────┘ │ ↓ ┌─────┐ │ Mul │←──── z └─────┘ │ ↓ y After: ┌─────┐ x, z ────→│ Mul │────→ p └─────┘ │ ↓ ┌─────┐ z ───────→│ Sub │────→ y └─────┘The symmetric Mul input order is supported.
onemay come from an all-one ConstantOfShape when output-shape preservation is proven;zand the final outputyare retained.Public Functions
-
inline explicit Sub1MulPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit Sub1MulPattern(int priority = 0)#
-
class Sub1MulPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Attention
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class AttentionGQAPattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Converts cached grouped-query attention into ONNX Attention cache inputs and outputs.
Before: ONNX decomposition, Reshape form: Q past K K past V V mask │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ Concat │ │ Concat │ │ │ └───────────────┘ └───────────────┘ │ │ │ axes 2 │ axes 2 │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ Unsqueeze │ │ Unsqueeze │ │ │ └───────────────┘ └───────────────┘ │ │ │ expand shape │ expand shape │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ Expand │ │ Expand │ │ │ └───────────────┘ └───────────────┘ │ │ │ gqa shape │ gqa shape │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ Reshape │ │ Reshape │ │ │ └───────────────┘ └───────────────┘ │ │ │ │ │ ↓ ↓ ↓ ↓ ┌───────────────────────────────────────────────────────────────────────────────────┐ │ Attention │ └───────────────────────────────────────────────────────────────────────────────────┘ │ ↓ Y ONNX decomposition, Squeeze form: Q past K K past V V mask │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ Concat │ │ Concat │ │ │ └───────────────┘ └───────────────┘ │ │ │ axes 2 │ axes 2 │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ Unsqueeze │ │ Unsqueeze │ │ │ └───────────────┘ └───────────────┘ │ │ │ expand shape │ expand shape │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ Expand │ │ Expand │ │ │ └───────────────┘ └───────────────┘ │ │ │ squeeze axes │ squeeze axes │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ Squeeze │ │ Squeeze │ │ │ └───────────────┘ └───────────────┘ │ │ │ │ │ ↓ ↓ ↓ ↓ ┌───────────────────────────────────────────────────────────────────────────────────┐ │ Attention │ └───────────────────────────────────────────────────────────────────────────────────┘ │ ↓ Y Local-function form: Q past K K past V V mask scale sqrt expand shape gqa shape │ │ │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ │ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ │ │ │ Concat │ │ Concat │ │ │ │ │ │ └───────────────┘ └───────────────┘ │ │ │ │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ┌───────────────────────────────────────────────────────────────────────────────────────────┐ │ intermediate::LocalAttentionGQA │ └───────────────────────────────────────────────────────────────────────────────────────────┘ │ ↓ Y After: Direct mask: Q K V mask past K past V │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Attention │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ ↓ ↓ ↓ Y present K present V Switched local mask: mask │ ↓ ┌───────┐ │ Not │ └───────┘ │ Q K V │ past K past V │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Attention │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ ↓ ↓ ↓ Y present K present VThe caches and current tensors must be compatible rank-four values, and both cache Concat nodes use normalized axis 2. Opset 23 is required. The two cache Concat results become the present-cache outputs of the new Attention node. The Not box appears only for switched local masks, which must be bool. The ONNX form copies the
scaleandis_causalattributes, while the localscale_sqrtinput is squared into the Attentionscaleattribute.Public Functions
-
inline explicit AttentionGQAPattern(int priority = 2)#
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit AttentionGQAPattern(int priority = 2)#
-
class FunctionAttentionGQAPattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Moves matching GQA repeat-interleave branches into a LocalAttention function.
Before: Reshape form: Q K axes 2 V axes 2 mask scale │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ │ Unsqueeze │ │ Unsqueeze │ │ │ │ └───────────────┘ └───────────────┘ │ │ │ │ expand shape │ expand shape │ │ │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ │ Expand │ │ Expand │ │ │ │ └───────────────┘ └───────────────┘ │ │ │ │ gqa shape │ gqa shape │ │ │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ │ Reshape │ │ Reshape │ │ │ │ └───────────────┘ └───────────────┘ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ┌─────────────────────────────────────────────────────────────────────────────────────┐ │ intermediate::LocalAttention │ └─────────────────────────────────────────────────────────────────────────────────────┘ │ ↓ Y Squeeze form: Q K axes 2 V axes 2 mask scale │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ │ Unsqueeze │ │ Unsqueeze │ │ │ │ └───────────────┘ └───────────────┘ │ │ │ │ expand shape │ expand shape │ │ │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ │ Expand │ │ Expand │ │ │ │ └───────────────┘ └───────────────┘ │ │ │ │ squeeze axes │ squeeze axes │ │ │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ │ ┌───────────────┐ ┌───────────────┐ │ │ │ │ Squeeze │ │ Squeeze │ │ │ │ └───────────────┘ └───────────────┘ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ┌─────────────────────────────────────────────────────────────────────────────────────┐ │ intermediate::LocalAttention │ └─────────────────────────────────────────────────────────────────────────────────────┘ │ ↓ Y After: Q K V mask scale expand shape gqa shape │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ┌───────────────────────────────────────────────────────────────────────────┐ │ intermediate::LocalAttentionGQA │ └───────────────────────────────────────────────────────────────────────────┘ │ ↓ YKey and value branches must use identical constant shapes, rank-five Expand targets with singleton non-repeat dimensions, and the same final operation. The Reshape form ends on a rank-four shape while the Squeeze form ends on a single axis, so the last call input is a shape or an axis accordingly. Inputs must be floating and every removed repeat intermediate unshared. The concrete local-function name records Reshape versus Squeeze and retains the original attention suffix.
Public Functions
-
inline explicit FunctionAttentionGQAPattern(int priority = 1)#
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit FunctionAttentionGQAPattern(int priority = 1)#
-
class FunctionAttentionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Fuses a masked scaled-dot-product attention graph into a local function.
Before: Rank-four MatMul with an additive mask: Q scale K scale │ │ │ │ ↓ ↓ ↓ ↓ ┌───────────────┐ ┌───────────────┐ │ Mul │ │ Mul │ └───────────────┘ └───────────────┘ │ │ │ ↓ │ ┌───────────┐ │ │ Transpose │ perm 0, 1, 3, 2 │ └───────────┘ │ │ ↓ ↓ ┌───────────────────────────────┐ │ MatMul │ └───────────────────────────────┘ │ │ scores │ mask zero minus infinity │ │ │ │ │ ↓ ↓ ↓ │ ┌─────────────────────────────┐ │ │ Where │ │ └─────────────────────────────┘ │ │ ↓ ↓ ┌──────────────────────────────────────────┐ │ Add │ └──────────────────────────────────────────┘ │ ↓ ┌─────────┐ │ Softmax │ └─────────┘ │ ┌──────────────────┴────────────┐ │ │ ↓ │ ┌───────────┐ │ │ IsNaN │ │ └───────────┘ │ │ │ │ zero │ │ │ │ ↓ ↓ ↓ ┌───────────────────────────────────────┐ │ Where │ └───────────────────────────────────────┘ │ │ V │ │ ↓ ↓ ┌─────────────────────┐ │ MatMul │ └─────────────────────┘ │ ↓ Y FusedMatMul with a direct Where mask: Q scale K scale │ │ │ │ ↓ ↓ ↓ ↓ ┌───────────────┐ ┌───────────────┐ │ Mul │ │ Mul │ └───────────────┘ └───────────────┘ │ │ ↓ ↓ ┌─────────────────────────────────┐ │ FusedMatMul │ └─────────────────────────────────┘ │ │ scores mask │ minus infinity │ │ │ ↓ ↓ ↓ ┌───────────────────────────────────┐ │ Where │ └───────────────────────────────────┘ │ ↓ ┌─────────┐ │ Softmax │ └─────────┘ │ ┌──────────────────┴────────────┐ │ │ ↓ │ ┌───────────┐ │ │ IsNaN │ │ └───────────┘ │ │ │ │ zero │ │ │ │ ↓ ↓ ↓ ┌───────────────────────────────────────┐ │ Where │ └───────────────────────────────────────┘ │ │ V │ │ ↓ ↓ ┌─────────────────────┐ │ MatMul │ └─────────────────────┘ │ ↓ Y Rank-three inputs with a switched Where mask: Q scale K scale │ │ │ │ ↓ ↓ ↓ ↓ ┌───────────────┐ ┌───────────────┐ │ Mul │ │ Mul │ └───────────────┘ └───────────────┘ │ │ │ shape │ shape │ │ │ │ ↓ ↓ ↓ ↓ ┌───────────────────┐ ┌───────────────────┐ │ Reshape │ │ Reshape │ └───────────────────┘ └───────────────────┘ │ │ ↓ ↓ ┌───────────┐ ┌───────────┐ │ Transpose │ perm 0, 2, 1, 3 │ Transpose │ perm 0, 2, 3, 1 └───────────┘ └───────────┘ │ │ ↓ ↓ ┌─────────────────────────────────────────────┐ │ MatMul │ └─────────────────────────────────────────────┘ │ mask minus infinity │ scores │ │ │ ↓ ↓ ↓ ┌───────────────────────────────────────────────────────┐ │ Where │ └───────────────────────────────────────────────────────┘ │ ↓ ┌─────────┐ │ Softmax │ └─────────┘ │ ┌──────────────────┴────────────┐ │ │ ↓ │ ┌───────────┐ │ │ IsNaN │ │ └───────────┘ │ │ │ │ zero │ │ │ │ ↓ ↓ ↓ ┌───────────────────────────────────────┐ │ Where │ └───────────────────────────────────────┘ │ │ V │ │ ↓ ↓ ┌─────────────────────┐ │ MatMul │ └─────────────────────┘ │ ↓ Y Grouped-query repeat-interleave on keys and values: Q scale K axes 2 │ │ │ │ ↓ ↓ ↓ ↓ ┌───────────────┐ ┌───────────────┐ │ Mul │ │ Unsqueeze │ └───────────────┘ └───────────────┘ │ │ scale │ │ │ │ ↓ ↓ │ ┌───────────────┐ │ │ Mul │ │ └───────────────┘ │ │ expand shape │ │ │ │ ↓ ↓ │ ┌───────────────┐ │ │ Expand │ │ └───────────────┘ │ │ gqa shape │ │ │ │ ↓ ↓ │ ┌───────────────┐ │ │ Reshape │ │ └───────────────┘ │ │ │ ↓ │ ┌───────────┐ │ │ Transpose │ perm 0, 1, 3, 2 │ └───────────┘ │ │ ↓ ↓ ┌───────────────────────────────────────────┐ │ MatMul │ └───────────────────────────────────────────┘ │ │ scores │ mask zero minus infinity │ │ │ │ │ ↓ ↓ ↓ │ ┌───────────────────────────────┐ │ │ Where │ │ └───────────────────────────────┘ │ │ ↓ ↓ ┌─────────────────────────────────┐ │ Add │ └─────────────────────────────────┘ │ ↓ ┌─────────┐ │ Softmax │ └─────────┘ │ ┌──────────────────┴────────────┐ │ │ ↓ │ ┌───────────┐ │ │ IsNaN │ │ └───────────┘ │ │ │ │ zero │ │ │ │ ↓ ↓ ↓ ┌───────────────────────────────────────┐ │ Where │ └───────────────────────────────────────┘ │ │ V axes 2 │ │ │ │ ↓ ↓ │ ┌───────────────┐ │ │ Unsqueeze │ │ └───────────────┘ │ │ expand shape │ │ │ │ ↓ ↓ │ ┌───────────────┐ │ │ Expand │ │ └───────────────┘ │ │ gqa shape │ │ │ │ ↓ ↓ │ ┌───────────────┐ │ │ Reshape │ │ └───────────────┘ │ │ ↓ ↓ ┌───────────────────────────────┐ │ MatMul │ └───────────────────────────────┘ │ ↓ Y After: Rank-four inputs: Q K V mask scale │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ┌─────────────────────────────────────────────────────┐ │ intermediate::LocalAttention │ └─────────────────────────────────────────────────────┘ │ ↓ Y Rank-three inputs: Q shape K shape │ │ │ │ ↓ ↓ ↓ ↓ ┌───────────────────┐ ┌───────────────────┐ │ Reshape │ │ Reshape │ └───────────────────┘ └───────────────────┘ │ │ ↓ ↓ ┌───────────┐ ┌───────────┐ │ Transpose │ perm 0, 2, 1, 3 │ Transpose │ perm 0, 2, 1, 3 └───────────┘ └───────────┘ │ │ V mask scale │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ┌───────────────────────────────────────────────────────────────────────────┐ │ intermediate::LocalAttention │ └───────────────────────────────────────────────────────────────────────────┘ │ ↓ YThe four score paths and the three masking forms combine freely; each drawing shows one legal pairing. The additive form needs
, the direct form places negative infinity on the third Where input, and the switched form places it on the second one. Softmax uses axis -1 and opset 18 or newer is required. The rank-four key Transpose uses permutation 0, 1, 3, 2 and the rank-three one 0, 2, 3, 1, while FusedMatMul must setWhere(mask, zero, minus
infinity)
transA=0,transB=1, andalpha=1. Rank-three inputs need matching Reshape targets, and Apply rebuilds both branches with permutation 0, 2, 1, 3. Query and key scales must be equal floating scalars, the GQA key and value repeat shapes must match, and every removed result is unshared. The emitted function name encodes GQA, the switched mask, the missing transpose, and the element type; GQA additionally appends the expand and repeat shapes to the call.Public Functions
-
inline explicit FunctionAttentionPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit FunctionAttentionPattern(int priority = 0)#
-
class FunctionCausalMaskMulAddPattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Fuses an additive causal-mask index construction into a local function.
Before: A B │ │ ↓ ↓ ┌─────────┐ ┌─────────┐ │ Squeeze │ │ Squeeze │ └─────────┘ └─────────┘ │ │ │ limit │ limit zero │ one zero │ one │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ↓ ┌────────────────┐ ┌────────────────┐ │ Range │ │ Range │ └────────────────┘ └────────────────┘ │ │ │ axes 0, 1, 2 │ axes 1, 2, 3 │ │ │ │ ↓ ↓ ↓ ↓ ┌─────────────────┐ ┌─────────────────┐ │ Unsqueeze │ │ Unsqueeze │ └─────────────────┘ └─────────────────┘ │ │ │ │ C │ │ │ │ ↓ ↓ │ ┌───────────────┐ │ │ Mul │ │ └───────────────┘ │ │ ↓ ↓ ┌─────────────────────────────────────────────┐ │ Add │ └─────────────────────────────────────────────┘ │ ↓ mask After: A B C │ │ │ ↓ ↓ ↓ ┌────────────────────────────────┐ │ intermediate::CausalMaskMulAdd │ └────────────────────────────────┘ │ ↓ maskBoth Range nodes are zero-based with unit steps and keep their own constant inputs. The first and second Unsqueeze axes are respectively 0, 1, 2 and 1, 2, 3. All removed intermediates must be unshared, and opset 13 is required.
Public Functions
-
inline explicit FunctionCausalMaskMulAddPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit FunctionCausalMaskMulAddPattern(int priority = 1)#
-
class FunctionCausalMaskPattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Fuses a causal-mask index construction into a local function.
Before: Unshifted form: B │ ↓ ┌─────────┐ │ Squeeze │ └─────────┘ │ │ limit ┌───────────┴─────────────────────────────────┐ │ │ zero │ one │ │ │ │ │ ↓ ↓ ↓ │ ┌────────────────┐ │ │ Range │ │ └────────────────┘ │ │ │ │ A │ │ │ │ │ ↓ │ │ ┌─────────┐ │ │ │ Squeeze │ │ │ └─────────┘ │ │ │ │ │ axes 0, 1, 2 │ start │ one │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ┌─────────────────┐ ┌────────────────────────────────┐ │ Unsqueeze │ │ Range │ └─────────────────┘ └────────────────────────────────┘ │ │ │ │ axes 0, 1, 3 │ │ │ │ ↓ ↓ │ ┌─────────────────┐ │ │ Unsqueeze │ │ └─────────────────┘ │ │ ↓ ↓ ┌─────────────────────────────────────────────────┐ │ LessOrEqual │ └─────────────────────────────────────────────────┘ │ ↓ mask Shifted form: B │ ↓ ┌─────────┐ │ Squeeze │ └─────────┘ │ │ limit ┌───────────┴─────────────────────────────────┐ │ │ zero │ one │ │ │ │ │ ↓ ↓ ↓ │ ┌────────────────┐ │ │ Range │ │ └────────────────┘ │ │ │ │ A │ │ │ │ │ ↓ │ │ ┌─────────┐ │ │ │ Squeeze │ │ │ └─────────┘ │ │ │ │ │ axes 0, 1, 2 │ start │ one │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ┌─────────────────┐ ┌────────────────────────────────┐ │ Unsqueeze │ │ Range │ └─────────────────┘ └────────────────────────────────┘ │ │ │ │ axes 0, 1, 3 │ │ │ │ ↓ ↓ │ ┌─────────────────┐ │ │ Unsqueeze │ │ └─────────────────┘ │ │ │ │ shift │ │ │ │ ↓ ↓ │ ┌─────────────┐ │ │ Sub │ │ └─────────────┘ │ │ ↓ ↓ ┌────────────────────────────────────────────────────┐ │ Greater │ └────────────────────────────────────────────────────┘ │ ↓ mask After: Unshifted form: A B │ │ ↓ ↓ ┌──────────────────────────┐ │ intermediate::CausalMask │ └──────────────────────────┘ │ ↓ mask Shifted form: A B shift │ │ │ ↓ ↓ ↓ ┌─────────────────────────────────┐ │ intermediate::ShiftedCausalMask │ └─────────────────────────────────┘ │ ↓ maskBoth Range nodes share the same limit, the row Range starts at zero, and both use unit steps. The row and column Unsqueeze axes are respectively 0, 1, 2 and 0, 1, 3. Opset 13 or newer is required; shared upstream construction nodes are preserved instead of being removed.
Public Functions
-
inline explicit FunctionCausalMaskPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit FunctionCausalMaskPattern(int priority = 1)#
-
class FunctionCosSinCachePattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Fuses cosine and sine rotary-cache generation into a local function.
Before: Direct position ids, Unsqueeze before Cast, uncast outputs: position ids axes 1 │ │ ↓ ↓ ┌─────────────────────┐ │ Unsqueeze │ └─────────────────────┘ │ ↓ ┌───────────┐ │ Cast │ └───────────┘ │ │ float positions shape 0, -1, 1 │ │ ↓ ↓ ┌──────────────────────────────────────┐ │ Reshape │ └──────────────────────────────────────┘ │ │ reshaped weights │ │ │ ↓ ↓ ┌────────────────────┐ │ Mul │ └────────────────────┘ │ │ weighted ┌────────┴────────┐ │ │ ↓ ↓ ┌─────────┐ ┌─────────┐ │ Cos │ │ Sin │ └─────────┘ └─────────┘ │ │ ↓ ↓ cosine sine Ranged ids, Cast before Unsqueeze, cast outputs: dim 1 dim 2 │ │ ↓ ↓ ┌─────────┐ ┌─────────┐ │ Squeeze │ │ Squeeze │ └─────────┘ └─────────┘ │ │ │ start │ limit one │ │ │ ↓ ↓ ↓ ┌────────────────────────────────────────────────────────┐ │ Range │ └────────────────────────────────────────────────────────┘ │ │ positions ↓ ┌───────────┐ │ Cast │ └───────────┘ │ │ axes 0, 1 │ │ ↓ ↓ ┌────────────────────────┐ │ Unsqueeze │ └────────────────────────┘ │ │ shape 0, -1, 1 │ │ ↓ ↓ ┌───────────────────────────┐ │ Reshape │ └───────────────────────────┘ │ │ reshaped weights │ │ │ ↓ ↓ ┌────────────────────┐ │ Mul │ └────────────────────┘ │ │ weighted ┌────────┴────────┐ │ │ ↓ ↓ ┌─────────┐ ┌─────────┐ │ Cos │ │ Sin │ └─────────┘ └─────────┘ │ │ ↓ ↓ ┌─────────┐ ┌─────────┐ │ Cast │ │ Cast │ └─────────┘ └─────────┘ │ │ ↓ ↓ cosine sine After: Direct position ids: position ids weights │ │ ↓ ↓ ┌───────────────────────────┐ │ intermediate::CosSinCache │ └───────────────────────────┘ │ │ ↓ ↓ cosine sine Ranged ids: dim 1 dim 2 weights │ │ │ ↓ ↓ ↓ ┌────────────────────────────────────┐ │ intermediate::CosSinCacheWithRange │ └────────────────────────────────────┘ │ │ ↓ ↓ cosine sineThe three choices drawn above are independent: ids may be direct or ranged, Cast and Unsqueeze may appear in either order, and the two output Cast boxes must either both appear with the same target or both be absent. Weights and the position Cast are float, the Reshape target is exactly
[0,-1,1], both ranges use a unit step, and removed intermediates must be unshared. Direct ids use Unsqueeze axis 1; ranged ids use axes[0,1]or[1]. The emitted function name also encodes the output Cast target and non-default axes.Public Functions
-
inline explicit FunctionCosSinCachePattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit FunctionCosSinCachePattern(int priority = 1)#
-
class FunctionHalfRotaryEmbeddingPattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Fuses the canonical half-rotary decomposition into a local function.
Before: X │ ├───────────────────────┐ │ │ │ │ sizes │ │ │ │ ↓ ↓ │ ┌─────────────────────┐ │ │ Split │ │ └─────────────────────┘ │ or two contiguous equal-width │ last-axis Slice operators │ │ │ │ │ first │ second │ │ ↓ │ │ ┌─────┐ │ │ │ Neg │ │ │ └─────┘ │ │ │ │ │ │ negated second │ ↓ ↓ │ ┌─────────────────────┐ │ │ Concat │ inputs in order: negated second, first │ └─────────────────────┘ │ │ │ │ sine cache │ │ │ │ ↓ ↓ │ ┌────────────────────────────┐ │ │ Mul │ │ └────────────────────────────┘ │ │ │ cosine cache │ │ │ │ ↓ ↓ │ ┌────────────────────┐ │ │ Mul │ │ └────────────────────┘ │ │ │ ↓ ↓ ┌───────────────────────────────────────────────────┐ │ Add │ └───────────────────────────────────────────────────┘ │ ↓ Y After: X cosine cache sine cache │ │ │ ↓ ↓ ↓ ┌───────────────────────────────────┐ │ intermediate::HalfRotaryEmbedding │ └───────────────────────────────────┘ │ ↓ YXmust be rank four, opset 18 or newer is required, and the halves and Concat both act on the last axis. Split either receives equal INT64 sizes, as drawn, or carriesnum_outputs=2with no second input. Alternatively, two Slice nodes must cover a known even width using nonnegative contiguous equal halves and unit steps. The Concat is canonical only when it rebuildsNeg(second), first. Either Mul may hold its cache on either input, both Mul results reach the same Add, and every removed intermediate must be unshared. Function registration requiresintermediateopset 1 and throwsBuilderErrorif the calling builder already imports a different version.Public Functions
-
inline explicit FunctionHalfRotaryEmbeddingPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit FunctionHalfRotaryEmbeddingPattern(int priority = 1)#
-
class LinearAttentionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Fuses a single-token linear-attention recurrence into
LinearAttention.Before: query shape key shape value shape │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ↓ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ Reshape │ │ Reshape │ │ Reshape │ └───────────┘ └───────────┘ └───────────┘ │ │ │ ↓ ↓ ↓ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ Transpose │ │ Transpose │ │ Transpose │ └───────────┘ └───────────┘ └───────────┘ │ │ │ ↓ ↓ ↓ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ Squeeze │ │ Squeeze │ │ Squeeze │ └───────────┘ └───────────┘ └───────────┘ │ │ │ │ ↓ ↓ │ ┌───────────┐ ┌───────────┐ │ │ Unsqueeze │ │ Unsqueeze │ │ └───────────┘ └───────────┘ │ │ │ │ └─────────┬─────────┘ │ ↓ │ ┌─────┐ │ │ Mul │ │ └─────┘ │ │ │ past_state │ │ │ │ │ ├─────────────────────┘ │ ↓ │ ┌─────┐ │ │ Add │────→ present_state │ └─────┘ ↓ ↓ ┌───────────┐ │ │ Unsqueeze │ │ └───────────┘ │ │ │ └───┬───┘ ↓ ┌────────┐ │ MatMul │ └────────┘ │ ↓ ┌─────────┐ │ Squeeze │ └─────────┘ │ scale └─────┬ ↓ ┌─────┐ │ Mul │ └─────┘ │ ↓ Unsqueeze → Transpose → Reshape │ ↓ output For the gated rule, ``past_state`` first passes through ``Mul(past_state, Unsqueeze(Exp(unpacked_decay)))``. After: query key value past_state [decay] │ │ │ │ │ └──────┴──────┴─────────┴───────────┘ ↓ ┌─────────────────┐ │ LinearAttention │ └─────────────────┘ │ │ ↓ ↓ output present_stateThe matched graph unpacks packed rank-three query, key, and value tensors, updates a recurrent state with either the linear or gated rule, computes the scaled query/state product, and repacks the result. The replacement preserves both the packed output and updated-state value names.
Public Functions
-
inline explicit LinearAttentionPattern(int priority = 2)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit LinearAttentionPattern(int priority = 2)#
-
class RotaryConcatPartPattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Collapses two zero-padded rotary branches into Split, Neg, and Concat.
Before: Concat form, Split source: x sizes │ │ ↓ ↓ ┌───────────────┐ │ Split │ └───────────────┘ │ │ ┌─────┘ └───────────────────────────────┐ │ │ │ first │ second │ ↓ │ ┌─────┐ │ │ Neg │ │ └─────┘ │ │ │ │ negated second │ shape A shape B │ │ │ │ │ │ ↓ ↓ │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │ ConstantOfShape │ │ ConstantOfShape │ │ │ └─────────────────┘ └─────────────────┘ │ │ │ │ │ │ │ zeros A │ zeros B │ ↓ ↓ ↓ ↓ ┌───────────────────────┐ ┌───────────────────────┐ │ Concat │ │ Concat │ └───────────────────────┘ └───────────────────────┘ │ │ │ padded first │ padded second ↓ ↓ ┌────────────────────────────────────────────┐ │ Add │ └────────────────────────────────────────────┘ │ ↓ y Concat form, Slice source: x │ ┌──────────────────────┴──────────────────────┐ │ │ ↓ ↓ ┌───────┐ ┌───────┐ 0, mid, axis ────→│ Slice │ mid, dim, axis ────→│ Slice │ └───────┘ └───────┘ │ │ │ first │ second │ ↓ │ ┌─────┐ │ │ Neg │ │ └─────┘ │ │ │ │ negated second │ shape A shape B │ │ │ │ │ │ ↓ ↓ │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │ ConstantOfShape │ │ ConstantOfShape │ │ │ └─────────────────┘ └─────────────────┘ │ │ │ │ │ │ │ zeros A │ zeros B │ ↓ ↓ ↓ ↓ ┌───────────────────────┐ ┌───────────────────────┐ │ Concat │ │ Concat │ └───────────────────────┘ └───────────────────────┘ │ │ │ padded first │ padded second ↓ ↓ ┌────────────────────────────────────────────┐ │ Add │ └────────────────────────────────────────────┘ │ ↓ y ScatterND form, Split source: x sizes │ │ ↓ ↓ ┌───────────────┐ │ Split │ └───────────────┘ │ │ ┌─────────────────┘ └───────────────────────────────┐ │ │ │ first │ second │ ↓ │ ┌─────┐ │ │ Neg │ │ └─────┘ │ │ shape A │ shape B │ │ │ │ │ ↓ │ ↓ │ ┌─────────────────┐ │ ┌─────────────────┐ │ │ ConstantOfShape │ │ │ ConstantOfShape │ │ └─────────────────┘ │ └─────────────────┘ │ │ │ │ │ ↓ ↓ ↓ ↓ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ Transpose │ │ Transpose │ │ Transpose │ │ Transpose │ └───────────┘ └───────────┘ └───────────┘ └───────────┘ │ │ │ │ │ indices A │ │ indices B │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ↓ ┌───────────────────────────┐ ┌─────────────────────────────────┐ │ ScatterND │ │ ScatterND │ └───────────────────────────┘ └─────────────────────────────────┘ │ │ ↓ ↓ ┌───────────┐ ┌───────────┐ │ Transpose │ │ Transpose │ └───────────┘ └───────────┘ │ │ ↓ ↓ ┌─────────────────────────────────────────────────────────────┐ │ Add │ └─────────────────────────────────────────────────────────────┘ │ ↓ y After: Second part negated: x sizes │ │ ↓ ↓ ┌───────────────┐ │ Split │ └───────────────┘ │ │ │ └────────────┐ │ │ │ ↓ │ ┌─────┐ │ │ Neg │ │ └─────┘ │ │ │ first │ negated second ↓ ↓ ┌──────────────────────────────┐ │ Concat │ └──────────────────────────────┘ │ ↓ y First part negated: x sizes │ │ ↓ ↓ ┌───────────────┐ │ Split │ └───────────────┘ │ │ │ └───────────────────────┐ ↓ │ ┌─────┐ │ │ Neg │ │ └─────┘ │ │ │ │ negated first │ second ↓ ↓ ┌─────────────────────────────────────────┐ │ Concat │ └─────────────────────────────────────────┘ │ ↓ yThe ScatterND form accepts the same contiguous Slice pair as the Concat form, and Apply then emits the Split node drawn above. The zero padding sits on opposite Concat inputs, so Apply mirrors the emitted Concat operand order when the matched pair negated the first part. The two parts cover the source axis, existing Split parts are equal in the ScatterND form, padding is exactly zero, branch placements or indices are complementary, and removed branch results must be unshared.
Public Functions
-
inline explicit RotaryConcatPartPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit RotaryConcatPartPattern(int priority = 1)#
-
class RotaryEmbeddingPattern : public onnx_light::core::builder::PatternOptimization#
- #include <attention_pattern.h>
Replaces a half-rotary local function and doubled caches with RotaryEmbedding.
Before: Full rotation: x cos sin │ │ │ │ ├────┐ ├────┐ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ ┌────────┐ ┌────────┐ │ │ Concat │ │ Concat │ │ └────────┘ └────────┘ │ │ │ ↓ ↓ ↓ ┌───────────────────────────────┐ │ HalfRotaryEmbedding │ └───────────────────────────────┘ │ ↓ y Partial rotation: full x sizes │ │ ↓ ↓ ┌──────────────┐ │ Split │ └──────────────┘ │ │ │ └────── tail ─────────────────────────┐ │ │ │ first │ │ │ │ cos sin │ │ │ │ │ │ ├────┐ ├────┐ │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ │ ┌────────┐ ┌────────┐ │ │ │ Concat │ │ Concat │ │ │ └────────┘ └────────┘ │ │ │ │ │ ↓ ↓ ↓ │ ┌───────────────────────────────────────┐ │ │ HalfRotaryEmbedding │ │ └───────────────────────────────────────┘ │ │ │ │ rotated part │ ↓ ↓ ┌─────────────────────────────────┐ │ Concat │ └─────────────────────────────────┘ │ ↓ y After: ``x`` is the rotary input of the full rotation and the Split input of the partial rotation. x │ ├───────┐ │ │ │ ↓ │ ┌───────┐ │ │ Shape │ │ └───────┘ │ │ │ │ batch ones │ │ │ │ ↓ ↓ │ ┌──────────────────┐ │ │ Concat │ │ └──────────────────┘ │ │ │ │ cache shape │ └─────────┬───────────────────────────┐ │ │ │ │ cos one │ sin one │ │ │ │ │ │ │ │ │ ↓ ↓ │ ↓ ↓ │ │ ┌───────────┐ │ ┌───────────┐ │ │ │ Squeeze │ │ │ Squeeze │ │ │ └───────────┘ │ └───────────┘ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ │ ┌────────────────────┐ ┌────────────────────┐ │ │ Expand │ │ Expand │ │ └────────────────────┘ └────────────────────┘ │ │ │ ↓ ↓ ↓ ┌─────────────────────────────────────────────────────────┐ │ RotaryEmbedding │ └─────────────────────────────────────────────────────────┘ │ ↓ yThe rewrite requires opset 23, rank-four inputs, equal
[*,1,*,*]caches doubled on the last axis, and a static head count that becomesnum_heads.oneis the constant[1]andonesthe constant[1,1]. A partial rotation additionally setsrotary_embedding_dimfrom the first Split size.Public Functions
-
inline explicit RotaryEmbeddingPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit RotaryEmbeddingPattern(int priority = 1)#
-
class AttentionGQAPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Canonicalization
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class CastCastBinaryPattern : public onnx_light::core::builder::PatternOptimization#
- #include <cast_pattern.h>
Moves matching floating-point Cast nodes after a binary arithmetic operation.
Before: ┌───────────┐ x:A ────→│ Cast to B │──┐ └───────────┘ │ │ ┌───────────┐ │ ┌────────┐ y:A ────→│ Cast to B │──┴───→│ Binary │────→ z:B └───────────┘ └────────┘ After: ┌────────┐ x:A, y:A ───→│ Binary │────→ t:A └────────┘ │ ↓ ┌───────────┐ │ Cast to B │────→ z:B └───────────┘Public Functions
-
inline explicit CastCastBinaryPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns the supported binary arithmetic operator types.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds two compatible Cast nodes feeding a binary arithmetic operation.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched Cast-Cast-binary sequence with binary-Cast.
-
inline explicit CastCastBinaryPattern(int priority = 1)#
-
class CastCastPattern : public onnx_light::core::builder::PatternOptimization#
- #include <cast_pattern.h>
Canonicalizes consecutive Cast nodes when a single conversion is equivalent.
Before: ┌───────────┐ ┌───────────┐ x:A ────→│ Cast to B │────→ m:B ────→│ Cast to C │────→ y:C └───────────┘ └───────────┘ After: ┌────────────┐ x:A ────→│ Cast to C* │────→ y:C └────────────┘ After (no conversion is needed): ┌──────────┐ x:A ────→│ Identity │────→ y:C └──────────┘ After (the intermediate m:B is shared): ┌───────────┐ x:A ────→│ Cast to B │────→ m:B ───→ other consumer └───────────┘ ┌────────────┐ x:A ────→│ Cast to C* │────→ y:C └────────────┘C*denotes the single safe replacement type selected from the input, intermediate, and final types. Ifmhas another consumer, the first Cast is retained for that consumer whileyis still produced directly fromx.Public Functions
-
inline explicit CastCastPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Castas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a safe consecutive-Cast rewrite rooted at
candidate.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces a matched Cast pair with one Cast or Identity node.
Private Static Functions
-
static core::symbolic::TensorType OneCastType(core::symbolic::TensorType input_type, core::symbolic::TensorType middle_type, core::symbolic::TensorType final_type)#
-
inline explicit CastCastPattern(int priority = 1)#
-
class CastOpCastPattern : public onnx_light::core::builder::PatternOptimization#
- #include <cast_pattern.h>
Moves an operation from a temporary floating-point type to its result type.
Before: ┌───────────┐ y:R ────→│ Cast to C │──┐ └───────────┘ │ ↓ ┌────┐ x:C ─────────────────→│ Op │────→ t:C └────┘ │ ↓ ┌───────────┐ │ Cast to R │────→ z:R └───────────┘ After: ┌───────────┐ x:C ────→│ Cast to R │──┐ └───────────┘ │ ↓ ┌────┐ y:R ─────────────────→│ Op │────→ z:R └────┘ After (the original Op output t:C is shared): ┌───────────┐ z:R ────→│ Cast to C │────→ t:C └───────────┘ The unary form uses the same rewrite with one input.Inputs already produced in
Rlose their Cast; other inputs gain one. The unary case follows the same transformation with a single input. If the originalOp:Coutput is retained elsewhere, a Cast fromz:Rback to that output inCis also emitted.Public Functions
-
inline explicit CastOpCastPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns the supported unary and binary operator types.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an operation between compatible input and output Cast nodes.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rebuilds the operation in the output type and removes the surrounding Cast nodes.
-
inline explicit CastOpCastPattern(int priority = 1)#
-
class CastPattern : public onnx_light::core::builder::PatternOptimization#
- #include <cast_pattern.h>
Canonicalizes a Cast to Identity when its input already has the target type.
Before: ┌───────────┐ x:T ────→│ Cast to T │────→ y:T └───────────┘ After: ┌──────────┐ x:T ────→│ Identity │────→ y:T └──────────┘Public Functions
-
inline explicit CastPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Castas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a redundant type-preserving Cast rooted at
candidate.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces one matched Cast with an Identity node.
-
inline explicit CastPattern(int priority = 0)#
-
class CastCastBinaryPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class ClipClipPattern : public onnx_light::core::builder::PatternOptimization#
- #include <clip_pattern.h>
Merges two consecutive Clip nodes when one defines the minimum and the other the maximum.
Before: ┌──────┐ x, min ────→│ Clip │────→ t └──────┘ │ ↓ ┌──────┐ │ Clip │←──── max └──────┘ │ ↓ y After: ┌──────┐ x, min, max ────→│ Clip │────→ y └──────┘The rewrite requires exactly one of the two Clip nodes to supply the minimum bound and exactly one to supply the maximum bound, so the merged Clip carries both bounds and retains the second Clip output. The first Clip output must not have another consumer.
Public Functions
-
inline explicit ClipClipPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Clipas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds two consecutive Clip nodes with complementary bounds rooted at
candidate.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched Clip pair with a single Clip carrying both bounds.
-
inline explicit ClipClipPattern(int priority = 1)#
-
class ReluClipFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <clip_pattern.h>
Removes a Relu immediately followed by a Clip whose effective minimum is non-negative.
Clip attributes are supported for opsets 6 through 10 and constant minimum inputs are supported from opset 11 onward. A missing, dynamic, negative, or NaN minimum is rejected, as is a shared Relu output.
Before: ┌──────┐ ┌──────┐ x → │ Relu │ → │ Clip │ → y └──────┘ └──────┘ After: ┌──────┐ x → │ Clip │ → y └──────┘Public Functions
-
inline explicit ReluClipFusionPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Clipas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a Clip with a redundant preceding Relu.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the pair by the Clip applied directly to the Relu input.
-
inline explicit ReluClipFusionPattern(int priority = 1)#
-
class ClipClipPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class ConstantToInitializerPattern : public onnx_light::core::builder::PatternOptimization#
- #include <constant_pattern.h>
Replaces a Constant node by an initializer and an Identity node.
Before: ┌──────────┐ value=tensor ────→│ Constant │────→ cst └──────────┘ After: tensor initializer │ ↓ ┌──────────┐ │ Identity │────→ cst └──────────┘The rewrite applies only when the Constant value can be materialised as a :cpp:class:
TensorProtoand retains the original Constant output name.Public Functions
-
inline explicit ConstantToInitializerPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Constantas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a materialisable Constant node rooted at
candidate.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched Constant with an initializer and an Identity node.
-
inline explicit ConstantToInitializerPattern(int priority = 1)#
-
class ConstantToInitializerPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class ConvAddFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <conv_pattern.h>
Fuses a channel-wise Add following a Conv into the Conv bias.
The Conv output must have no other consumer or graph use. The Conv weights, optional bias, and Add constant must be FLOAT or DOUBLE constants with matching element types and valid channel-broadcast shapes. The replacement remains a standard-domain Conv and keeps any following activation unchanged.
Before: +------+ +-----+ X, W, B ------->| Conv |------>| Add |-------> Y +------+ +-----+ ^ | channel constant After: +------+ X, W, folded B ---------->| Conv |-----------> Y +------+
Public Functions
-
inline explicit ConvAddFusionPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Convas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a Conv followed by a foldable channel-wise Add.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the Conv-Add pair with a Conv carrying the folded bias.
-
inline explicit ConvAddFusionPattern(int priority = 0)#
-
class ConvBatchNormalizationFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <conv_pattern.h>
Fuses inference BatchNormalization following a Conv into the Conv weights and bias.
Scale, bias, mean, variance, Conv weights, and an optional Conv bias must be one-dimensional/channel-compatible FLOAT or DOUBLE constants of one matching type. Optional BatchNormalization outputs must be absent or unused.
Before: +------+ +--------------------+ X, W, B ---->| Conv |------>| BatchNormalization |----> Y +------+ +--------------------+ ^ ^ ^ ^ | | | | scale bias mean variance After: +------+ X, folded W, folded B -------->| Conv |-------------> Y +------+
Public Functions
-
inline explicit ConvBatchNormalizationFusionPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Convas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a Conv followed by a foldable inference BatchNormalization.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the Conv-BatchNormalization pair with one folded Conv.
-
inline explicit ConvBatchNormalizationFusionPattern(int priority = 0)#
-
class ConvBiasNullPattern : public onnx_light::core::builder::PatternOptimization#
- #include <conv_pattern.h>
Removes a null (all-zero) bias input from a Conv node.
Before: ┌──────┐ X, W, B=0 ────→│ Conv │────→ Y └──────┘ After: ┌──────┐ X, W ───────→│ Conv │────→ Y └──────┘The Conv node is rebuilt without its known all-zero constant bias while all attributes and output names are retained.
Public Functions
-
inline explicit ConvBiasNullPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Convas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a Conv node whose bias input is a known all-zero constant or a safe expansion of one.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rebuilds the Conv node without its bias input.
-
inline explicit ConvBiasNullPattern(int priority = 0)#
-
class ConvMulFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <conv_pattern.h>
Fuses a scalar or channel-wise Mul following a Conv into its weights and optional bias.
The Conv output must have no other consumer or graph use. All folded constants must be FLOAT or DOUBLE tensors of one matching type.
Before: +------+ +-----+ X, W, B ------->| Conv |------>| Mul |-------> Y +------+ +-----+ ^ | channel/scalar constant After: +------+ X, folded W, folded B -------->| Conv |-------> Y +------+
Public Functions
-
inline explicit ConvMulFusionPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Convas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a Conv followed by a foldable scalar or channel-wise Mul.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the Conv-Mul pair with a Conv carrying folded constants.
-
inline explicit ConvMulFusionPattern(int priority = 0)#
-
class PadConvPattern : public onnx_light::core::builder::PatternOptimization#
- #include <conv_pattern.h>
Fuses a Pad node followed by a Conv node into a single Conv node whose
padsattribute absorbs the spatial padding.Before: ┌─────┐ X, pads, value=0 ────→│ Pad │────→ p └─────┘ │ ↓ ┌──────┐ │ Conv │←──── W, B └──────┘ │ ↓ Y After: ┌────────────────────┐ X, W, B ────→│ Conv with new pads │────→ Y └────────────────────┘The fusion applies when the Pad uses the default
constantmode with a zero constant value, pads only the spatial dimensions, and the Conv does not useauto_pad. The optional Conv bias, other attributes, and every Conv output name are retained.Public Functions
-
inline explicit PadConvPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Convas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a Pad node feeding a Conv node with foldable spatial padding.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched Pad-Conv sequence with one padded Conv node.
-
inline explicit PadConvPattern(int priority = 0)#
-
class PadPoolPattern : public onnx_light::core::builder::PatternOptimization#
- #include <conv_pattern.h>
Fuses zero-valued spatial Pad into AveragePool or UINT8 MaxPool.
Requires opset >= 11 (>= 12 for UINT8 MaxPool), constant non-negative padding, known input rank and type, explicit pooling pads, and no other use of the Pad output. Constant axes are supported from opset 18. MaxPool indices are not supported: their offsets refer to the padded input rather than the original tensor.
AveragePool sets count_include_pad=1. Existing nonzero pooling pads require that flag to already be set. With ceil_mode, explicit trailing padding is rejected; AveragePool additionally requires count_include_pad=1 to preserve the divisor of partial windows. Each summed pad must be smaller than its kernel dimension. Strides and supported dilations are retained.
Before: ┌─────┐ ┌──────┐ X, pads, value=0 ───→│ Pad │──→│ Pool │──→ Y └─────┘ └──────┘ After: ┌────────────────────┐ X ─→│ Pool with new pads │──→ Y └────────────────────┘Public Functions
-
inline explicit PadPoolPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns the supported pooling root operators.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a Pad feeding a pooling node with equivalent implicit padding.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the Pad-pooling pair with one pooling node.
-
inline explicit PadPoolPattern(int priority = 0)#
-
class ConvAddFusionPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class DropoutPattern : public onnx_light::core::builder::PatternOptimization#
- #include <dropout_pattern.h>
Replaces an eligible Dropout by an Identity node.
Before: ┌─────────┐ x ────→│ Dropout │────→ y └─────────┘ After: ┌──────────┐ x ────→│ Identity │────→ y └──────────┘The rewrite applies only when the optional mask output is unused and the
training_modeinput is not a materialized nonzero scalar. The data input and first Dropout output name are retained; unused mask outputs are removed.Public Functions
-
inline explicit DropoutPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Dropoutas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an eligible Dropout rooted at
candidate.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched Dropout with an Identity node.
-
inline explicit DropoutPattern(int priority = 1)#
-
class DropoutPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class IdentityPattern : public onnx_light::core::builder::PatternOptimization#
- #include <identity_pattern.h>
Replaces no-op operations by an Identity node.
The pattern recognises redundant arithmetic and layout operations such as
Add(x, 0),Mul(x, 1),Sub(x, 0),Div(x, 1),Or(x, false),And(x, true),Transpose(x, perm=[0, 1, 2, ...]),Reshape(x, [0, 0, ...]), a full-rangeSlice, anExpandwith an all-one target shape of the input rank, and a half-precision inferenceBatchNormalizationwith scale/bias/mean/variance constants1/0/0/1.Before: ┌─────┐ x, zero ───→│ Add │────→ y └─────┘ After: ┌──────────┐ x ────→│ Identity │────→ y └──────────┘The no-op node is replaced while its selected data input and first output name are retained; neutral constants no longer feed that output. Vector arithmetic constants are scanned without materialising decoded copies; their payload count and last-dimension broadcasting must match exactly.
Public Functions
-
inline explicit IdentityPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns the operator types this pattern can start from.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a redundant operation rooted at
candidate.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched operation with an Identity node.
-
inline explicit IdentityPattern(int priority = 0)#
-
class IdentityPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class IfIdenticalBranchesPattern : public onnx_light::core::builder::PatternOptimization#
- #include <if_pattern.h>
Inlines an If whose branches are structurally identical up to local names.
Before: ┌──────────────────────────┐ cond ──→│ If: Neg(x) / Neg(x) │──→ y └──────────────────────────┘ After: ┌─────┐ x ─────→│ Neg │────────────────────────→ y └─────┘Captured names must agree; local initializers and tensor attributes are compared by value, loading deferred payloads only when their backing sources differ. Graph attributes are compared recursively with lexical bindings. Output order and declared types must agree. Configured nodes, external tensors, sparse/extended initializers, quantization annotations, non-tensor value declarations, value and initializer metadata, and persistent bindings are conservatively excluded, as are If nodes carrying metadata. Branch nodes without shape inference are excluded because their type declarations cannot be retained during inlining. Local values receive fresh names; forwarded outputs use Identity nodes. Materialized GRAPH attributes are accepted by Match/Apply, including directly forwarded captures. GraphBuilder imports retain their stricter requirement that a subgraph output has a local definition.
Public Functions
-
inline explicit IfIdenticalBranchesPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns If as the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an If with equivalent branches.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Inlines one branch, preserving the If output names.
-
inline explicit IfIdenticalBranchesPattern(int priority = 1)#
-
class IfIdenticalBranchesPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class InitializerUnsqueezeCastPattern : public onnx_light::core::builder::PatternOptimization#
- #include <initializer_unsqueeze_cast_pattern.h>
Folds an initializer’s Unsqueeze and Cast into the initializer consumed by Add.
Before: initializer ──→ ┌───────────┐ ──→ ┌──────┐ ──→ ┌─────┐ ──→ output │ Unsqueeze │ │ Cast │ │ Add │ └───────────┘ └──────┘ └─────┘ After: folded initializer ──────────────────────────→ ┌─────┐ ──→ output │ Add │ └─────┘Only folds single-use intermediates and a non-overridable initializer when a registered Cast kernel can evaluate the requested conversion.
Public Functions
-
inline explicit InitializerUnsqueezeCastPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit InitializerUnsqueezeCastPattern(int priority = 1)#
-
class InitializerUnsqueezeCastPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class NotNotPattern : public onnx_light::core::builder::PatternOptimization#
- #include <not_pattern.h>
Fuses two consecutive Not nodes into an Identity.
Before: ┌─────┐ ┌─────┐ x ────→│ Not │────→ m ────→│ Not │────→ y └─────┘ └─────┘ │ │ ┌───────┐ └───────────→│ Other │────→ u └───────┘ After: ┌──────────┐ x ───────────────────────→│ Identity │────→ y └──────────┘ When m is shared: ┌─────┐ ┌───────┐ x ────→│ Not │────→ m ────→│ Other │────→ u └─────┘ └───────┘The two Not nodes become an Identity retaining
y. The first Not and its outputmare also retained whenmis consumed elsewhere.Public Functions
-
inline explicit NotNotPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Notas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds two consecutive Not nodes rooted at
candidate.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched Not pair with an Identity node.
-
inline explicit NotNotPattern(int priority = 1)#
-
class NotNotPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class PadPadFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <pad_pattern.h>
Merges two adjacent constant-mode Pad nodes with equal constant values.
Both padding vectors must be constant, non-negative, and describe the same rank. Attribute-form Pad nodes are supported before opset 11, input-form Pad nodes from opset 11 onward, and constant axes inputs from opset 18 onward. The fused padding is the element-wise sum of the two full-rank vectors.
Before: ┌─────┐ ┌─────┐ x → │ Pad │ → │ Pad │ → y └─────┘ └─────┘ After: ┌─────────────┐ x → │ Pad(p0+p1) │ → y └─────────────┘Public Functions
-
inline explicit PadPadFusionPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Padas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds two compatible adjacent constant-mode Pad nodes.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the pair with one Pad whose padding vectors are summed.
-
inline explicit PadPadFusionPattern(int priority = 1)#
-
class PadPadFusionPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class STFTFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <stft_pattern.h>
Fuses a canonical convolution-based DFT into a standard ONNX STFT.
Before: +-----------+ +------------+ +-----------+ signal -->| Transpose |--+->| Conv(real) |---->| Unsqueeze |--+ +-----------+ | +------------+ +-----------+ | | +------------+ +-----------+ | +--------+ +->| Conv(imag) |---->| Unsqueeze |--+->| Concat | +------------+ +-----------+ +--------+ | +-----------+ | Transpose |--> output +-----------+ After: +------+ signal, frame_step, window, frame_length -->| STFT |--> output +------+
The Conv weights must be matching FLOAT or DOUBLE tensors shaped
[bins, 1, frame_length]and must equal the real and imaginary DFT bases multiplied by one common window. The convolution stride becomesframe_step. A half spectrum selectsonesided=1and a full spectrum selectsonesided=0. For frame lengths one and two, the coincident half/full bin counts are represented asonesided=1.Public Functions
-
inline explicit STFTFusionPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Transposeas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a private canonical convolution-based DFT subgraph.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched subgraph with one standard-domain STFT node.
-
inline explicit STFTFusionPattern(int priority = 0)#
-
class STFTFusionPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Collections
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
namespace collections#
Functions
-
inline bool IsDefaultOp(const NodeProto &node, const char *op_type)#
Returns
truewhennodeisop_typefrom the default ONNX domain.
-
inline std::string FreeInitializerName(core::builder::GraphBuilder &builder, const std::string &base)#
Returns a fresh initializer name derived from
basethat is not already used bybuilder(without reserving it, so :ref:MakeInitializercan).
-
inline int64_t GetAxis(const NodeProto &node, int64_t default_value = 0)#
Returns the
axisinteger attribute ofnodeordefault_value.
-
inline bool ReadScalarInt(const TensorProto &tensor, int64_t &out)#
Reads the leading integer element of the scalar constant
tensorintoout. Returnsfalsewhen the tensor holds no integer payload.
-
template<typename T>
inline TensorProto MakeScalarTensor(const std::string &name, TensorProto::DataType type, const std::vector<int64_t> &dims, T value)# Creates a one-element tensor with an arithmetic value stored in little-endian raw_data. FLOAT16 and BFLOAT16 values are rounded from float; integer values retain their precision.
-
inline bool IsDefaultOp(const NodeProto &node, const char *op_type)#
-
namespace collections#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class ConcatEmptyPattern : public onnx_light::core::builder::PatternOptimization#
- #include <concat_pattern.h>
Removes
Concatinputs that are empty along the concatenation axis.An input is dropped when its inferred size along
axisis exactly zero, so it contributes nothing to the output. When a single input remains theConcatbecomes anIdentity; otherwise a narrowerConcatis emitted with the sameaxis.Before: ┌──────────────┐ x, e, z ──→│ Concat axis0 │────→ y └──────────────┘ After: ┌──────────────┐ x, z ──→│ Concat axis0 │────→ y └──────────────┘ After (one non-empty input remains): ┌──────────┐ x ────→│ Identity │────→ y └──────────┘The inferred size of
ealong axis 0 is zero.Public Functions
-
inline explicit ConcatEmptyPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Concatas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Concatwith at least one empty input along its axis.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rebuilds the
Concat(or anIdentity) without the empty inputs.
-
inline explicit ConcatEmptyPattern(int priority = 0)#
-
class ConcatGatherPattern : public onnx_light::core::builder::PatternOptimization#
- #include <concat_pattern.h>
Simplifies
Gather(Concat(...), cst_index)when the index is a constant single-elementint64tensor and everyConcatinput is a 1-D tensor of a statically known size.The pattern locates which
Concatinput holds the addressed element and replaces theGatherwith anIdentity(single-element input), a narrowerShape(input produced by a rangedShape), or aGatherwith a locally adjusted index.Before: ┌──────────────┐ a, b, c ────→│ Concat axis0 │────→ t └──────────────┘ │ ↓ ┌──────────────┐ │ Gather axis0 │←──── index=[3] └──────────────┘ │ ↓ y After: ┌──────────────┐ b, index=[1] ────→│ Gather axis0 │────→ y └──────────────┘ After (the selected input has one element): ┌──────────┐ b ────→│ Identity │────→ y └──────────┘ After (the selected input is produced by Shape): ┌─────────────────────────┐ x ────→│ Shape adjusted interval │────→ y └─────────────────────────┘If
thas another consumer, the originalConcatis retained for that consumer.Public Functions
-
inline explicit ConcatGatherPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Gatheras the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a constant-index
Gatherover a fully-shapedConcat.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rewrites the
Gatheragainst the locatedConcatinput.
-
inline explicit ConcatGatherPattern(int priority = 0)#
-
class ConcatSliceEliminationPattern : public onnx_light::core::builder::PatternOptimization#
- #include <concat_pattern.h>
Removes a
Concatwhose consumers are exact, non-overlappingSlicenodes that recover every input in order along the concatenation axis.Before: +--------+ +--------------------+ x0, x1 -->| Concat |--+--->| Slice(range of x0) |---> y0 +--------+ | +--------------------+ | +--------------------+ +--->| Slice(range of x1) |---> y1 +--------------------+ After: +----------+ x0 ->| Identity |---> y0 +----------+ +----------+ x1 ->| Identity |---> y1 +----------+
Public Functions
-
inline explicit ConcatSliceEliminationPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Concatas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds exact slices that partition a statically shaped Concat output.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces every Slice with an Identity from its corresponding Concat input.
-
inline explicit ConcatSliceEliminationPattern(int priority = 0)#
-
class ConcatTwiceUnaryPattern : public onnx_light::core::builder::PatternOptimization#
- #include <concat_pattern.h>
Pushes a shape-preserving unary operator through a
Concat(x, x)so thatUnary(Concat(x, x))becomesConcat(Unary(x), Unary(x)), exposing the sharedUnary(x)for common-subexpression elimination.The rewrite requires opset >= 18, a two-input
Concatwhose inputs are the same value, and a consumer that is a shape-preserving unary op (or a broadcastingMul/Add/Div/Sub/Unsqueezewith a constant scalar second input).Before: ┌────────┐ x, x ──→│ Concat │────→ t └────────┘ ┌───────┐ t ────→│ Unary │────→ y └───────┘ After: ┌───────┐ x ────→│ Unary │────→ u └───────┘ │ ┌─┴─┐ │ │ ↓ ↓ ┌────────┐ │ Concat │────→ y └────────┘If
thas another consumer,Concat(x, x)is retained for it.Public Functions
-
inline explicit ConcatTwiceUnaryPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Concatas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Concat(x, x)consumed by a shape-preserving unary op.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Moves the unary op ahead of the
Concat.
-
inline explicit ConcatTwiceUnaryPattern(int priority = 0)#
-
class SliceConcatToSpaceToDepthPattern : public onnx_light::core::builder::PatternOptimization#
- #include <concat_pattern.h>
Replaces the canonical rank-4 four-phase slicing and channel concatenation used by focus layers with the standard ONNX
SpaceToDepth(blocksize=2).Before: +--> Slice(0::2, 0::2) --+ | | +--> Slice(0::2, 1::2) --+ | | +----------------+ x --+--> Slice(1::2, 0::2) --+--->| Concat(axis=1) |---> y | | +----------------+ +--> Slice(1::2, 1::2) --+ After: +---------------------------+ x -->| SpaceToDepth(blocksize=2) |---> y +---------------------------+
Public Functions
-
inline explicit SliceConcatToSpaceToDepthPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Concatas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds four canonical spatial phase slices concatenated on channels.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the five-node subgraph with a standard SpaceToDepth node.
-
inline explicit SliceConcatToSpaceToDepthPattern(int priority = 0)#
-
class ConcatEmptyPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class GatherConcatPattern : public onnx_light::core::builder::PatternOptimization#
- #include <gather_pattern.h>
Simplifies
Gather(Concat(..., X, ..., axis=0), cst)intoGather(X, cst - offset)when exactly oneConcatinputXis non-constant, all others are constants of known size,Xis 1-D, and every requested index falls insideX’s slice of the concatenation.offsetis the total size of the constant inputs precedingX.Before: ┌──────────────┐ c0, X, c1 ────→│ Concat axis0 │────→ t └──────────────┘ │ ↓ ┌──────────────┐ │ Gather axis0 │←──── indices=[2,4] └──────────────┘ │ ↓ y After: ┌──────────────┐ X, indices=[0,2] ────→│ Gather axis0 │────→ y └──────────────┘If
thas another consumer, the originalConcatis retained.Public Functions
-
inline explicit GatherConcatPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Gatheras the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an
axis=0constant-indexGatherover aConcat.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rewrites the
Gatheragainst the single non-constantConcatinput.
-
inline explicit GatherConcatPattern(int priority = 0)#
-
class GatherGatherPattern : public onnx_light::core::builder::PatternOptimization#
- #include <gather_pattern.h>
Composes two consecutive
axis=0Gathernodes with constant indices into a singleGather.The inner indices
cst1must be a 1-D constant array and the outer indicescst2a constant integer tensor; the fused indices arecst1[cst2]. Scalar outer indices remain scalar, while non-scalar fused indices are materialised as a vector.Before: x, [4,1,7] │ ↓ ┌──────────────┐ │ Gather axis0 │──┐ └──────────────┘ │ │ t ↓ ┌──────────────┐ │ Gather axis0 │←──── [2,0] └──────────────┘ │ ↓ y After: x, [7,4] │ ↓ ┌──────────────┐ │ Gather axis0 │────→ y └──────────────┘If
thas another consumer, the innerGatheris retained.Public Functions
-
inline explicit GatherGatherPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Gatheras the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds two consecutive constant-index
axis=0Gathernodes.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the pair with a single
Gatheron the composed indices.
-
inline explicit GatherGatherPattern(int priority = 0)#
-
class GatherToSlicePattern : public onnx_light::core::builder::PatternOptimization#
- #include <gather_pattern.h>
Replaces a
Gatherselecting a constant scalar index, a constant single-element vector index, or a constant arithmetic-progression vector of indices (a “range” with a fixed, strictly ascending step) by an equivalentSlice.Sliceis generally cheaper to execute thanGatherand, unlikeGather, it never triggers a data-dependent gather kernel.A negative
axisis normalized against the rank ofxand negative index values are normalized against the static size of that axis; both normalizations require the corresponding dimension to be statically known, otherwise the rewrite is rejected. A non-unit step is rejected when the default domain opset is known to predate opset 10 (the attribute-onlySliceform has nostepsinput). TheSliceuses the input form (with anaxesinitializer) from opset 10 onward and the attribute form (starts/ends/axes) before that.A scalar index reduces the rank of its axis, so the replacement additionally appends a
Squeezeof that axis (input form from opset 13 onward, attribute form before that) to preserve the original output rank. A vector index, singleton or not, keeps the axis (with a size equal to the number of selected elements), soSlicealone reproduces theGatheroutput.Before (scalar index): ┌────────┐ x, idx ────→│ Gather │────→ y └────────┘ After: ┌───────┐ ┌─────────┐ x, [idx],[idx+1],[axis] ─→│ Slice │────────→│ Squeeze │────→ y └───────┘ [axis]→└─────────┘ Before (vector index, singleton or arithmetic progression): ┌────────┐ x, idx ────→│ Gather │────→ y └────────┘ After: ┌───────┐ x, [start],[end],[axis],[step] ───────→│ Slice │────→ y └───────┘Public Functions
-
inline explicit GatherToSlicePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Gatheras the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Gatherwhose index is a safely representable constant.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rewrites the
Gatherinto aSlice(plusSqueezefor a scalar index).
-
inline explicit GatherToSlicePattern(int priority = 0)#
-
class GatherUpstreamPropagationPattern : public onnx_light::core::builder::PatternOptimization#
- #include <gather_pattern.h>
Moves a scalar or vector constant-index
Gatherupstream across one compatible producer node, so that the producer runs on the smaller (already gathered) tensor(s) instead of the original full-size ones.The producer is left in place and the pattern is applied again on its (possibly further) inputs by the optimizer’s fix-point loop, so a chain of compatible producers is crossed one hop per iteration until an unsupported, shared, or otherwise unsafe producer is reached.
Before: a [M,N,K] b [N,K] \ / ┌─────┐ │ Add │────→ t [M,N,K] └─────┘ │ ↓ ┌──────────────┐ │ Gather axis1 │←──── indices └──────────────┘ │ ↓ y After: a [M,N,K] b [N,K] │ │ ↓ ↓ ┌──────────────┐ ┌──────────────┐ │ Gather axis1 │ │ Gather axis0 │←──── indices (both) └──────────────┘ └──────────────┘ \ / ┌─────┐ │ Add │────→ y └─────┘Supported producers (default
ai.onnxdomain only), one hop per match:Add,Div,Cast,Dropout: every tensor input whose dimension at the (right-aligned) sliced axis is provably equal to the producer’s own output dimension is gathered too; an input that does not reach that axis (a lower-rank, right-aligned broadcast input, e.g. a bias vector) is left untouched. An input with an actual broadcasting dimension of1at that axis is left untouched for a vector index, but the whole match is rejected for a scalar index, because removing the axis from the gathered inputs would silently shift that broadcasting input out of alignment (no rank-adaptationSqueezeis inserted).Transpose: only a rank-preserving (vector-index)Gatheris propagated, remapping the axis throughperm. A scalar-indexGatherdirectly downstream of aTransposeis intentionally left to :cpp:class:TransposeGatherPattern, which already rebuilds thepermfor that rank-reducing case; duplicating that logic here would risk two patterns disagreeing on the same rewrite.Reshape: only propagated when the sliced axis can be traced back to exactly one input axis (matched left-aligned or right-aligned, asReshapenever redistributes elements across the boundary of an unrelated axis) and theshapeconstant either already spells0(copy the input dimension) at that position, or, for a vector index, holds a concrete value that is rewritten to the new gathered length. A negative (-1, inferred) entry, or a scalar index paired with a non-0entry, is rejected because the new dimension cannot be recomputed without re-deriving the whole reshape.MatMul: a batch axis (strictly before the last two, contracted-adjacent dimensions) is propagated, using the same equal / broadcast / not-present rule as the pointwise operators, independently for each of the two inputs. A vector-indexGatheron the output row axis (output rank minus two) is propagated only to the left operand’s row axis (left rank minus two), leaving the right operand and all batch dimensions untouched. ThusGather(A @ B, indices, axis=-2)becomesGather(A, indices, axis=-2) @ B, preserving batch broadcasting, including[B,S,D] @ [D,V]. Scalar row indices are rejected because dropping a matrix axis can changeMatMulsemantics. Both operands must have rank at least two; column and contracted dimensions are never gathered.Softmax,LayerNormalization: only a rank-preserving (vector-index)Gatherstrictly before the operator’s own reductionaxisis propagated to the (sole) data input; the reductionaxisattribute is never rewritten, so its semantics are always preserved.
The match is rejected whenever the producer’s matched output is a graph output, is captured by a nested subgraph, or feeds more than the candidate
Gather(:cpp:func:GraphGraph::IsUsedMoreThanOnce), or when the producer has another output that is used at all — resizing that producer would otherwise silently change a value some other part of the graph still relies on at the original size. TheGatherindex must be a materialised scalar or 1-D integer constant; a negative index is only accepted when the sliced dimension is statically known and the normalised index is in range, except for vector-indexMatMulrow selection: its input and output row dimensions are provably identical, so negative indices also preserve their meaning and runtime bounds checks for a symbolic row dimension.Public Functions
-
inline explicit GatherUpstreamPropagationPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Gatheras the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a constant-index
Gatherfed by one compatible, unshared producer node.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Duplicates the
Gatheronto the producer’s compatible inputs and rewrites the producer to output directly under the originalGathername.
-
class GatherConcatPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class RepeatedLayerPattern : public onnx_light::core::builder::PatternOptimization#
- #include <layer_pattern.h>
Extracts repeated operator regions using core::graph::ProposeRepeatedLayers.
Runs detection at the first eligible graph node of each optimizer scan and delegates function construction to core::graph::MakeRepeatedLayerReplacements. Preserves the core algorithm’s boundary, scheduling and reuse safeguards. The pattern is opt-in and does not wrap existing ai.rt Layer bodies.
Before: ┌─────────────────┐ ┌─────────────────┐ x, w0 ───→│ repeated region │───y───→│ repeated region │───→ z └─────────────────┘ └─────────────────┘ ↑ w1 After: ┌─────────────────┐ ┌─────────────────┐ x, w0 ───→│ Layer(x, w0) │───y───→│ Layer(y, w1) │───→ z └─────────────────┘ └─────────────────┘Public Functions
-
inline explicit RepeatedLayerPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns an empty filter because local-function names are unrestricted.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds occurrences from the first eligible node using the core analysis.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Delegates match verification and local-function construction to core.
-
inline explicit RepeatedLayerPattern(int priority = 0)#
-
class RepeatedLayerPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class PartitionGroupPattern : public onnx_light::core::builder::PatternOptimization#
- #include <partition_group_pattern.h>
Extracts low-transfer operator intervals as model-local ai.rt functions.
Calls core::graph::ProposePartitionGroups only at the first node of each optimizer scan, using the builder’s inferred tensor descriptors. The core algorithm owns interval selection and transfer accounting; this opt-in pattern only materializes its proposals. Small constants and redundant Shape arguments use the shared core internalization. Intervening Constant nodes stay before the calls that use them.
Retains boundary names, side outputs, node metadata, source opsets and lexical captures. Unknown boundary sizes are supported without a byte cap. Device-configured nodes and enclosing-function attribute references are not extracted. Local-function bodies and their subgraphs are left unchanged, and generated PartitionGroup calls are never wrapped again.
Before: ┌───────────┐ ┌───────────┐ x, w ────→│ operators │───v──→│ operators │───→ y └───────────┘ └───────────┘ After: ┌───────────────────────────────┐ x, w ────→│ PartitionGroup(x, w) → y │───→ y └───────────────────────────────┘Public Functions
-
explicit PartitionGroupPattern(int priority = 0, std::optional<uint64_t> max_boundary_bytes = std::nullopt, uint64_t min_group_nodes = 2, uint64_t max_group_nodes = 128, std::optional<uint64_t> max_constant_inputs = std::nullopt)#
Creates an opt-in pattern with the core grouping limits.
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
Private Members
-
core::graph::OperatorGroupOptions options_#
-
explicit PartitionGroupPattern(int priority = 0, std::optional<uint64_t> max_boundary_bytes = std::nullopt, uint64_t min_group_nodes = 2, uint64_t max_group_nodes = 128, std::optional<uint64_t> max_constant_inputs = std::nullopt)#
-
class PartitionGroupPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class SequenceConstructAtPattern : public onnx_light::core::builder::PatternOptimization#
- #include <sequence_pattern.h>
Replaces
SequenceConstruct(x0, x1, ...)followed by the matchingSequenceAt(seq, 0),SequenceAt(seq, 1), … with oneIdentityperSequenceAt, forwarding the original tensor directly.The rewrite requires every consumer of the sequence to be a
SequenceAtwith a constant scalar index, and the indices to cover0 .. n-1exactly once, so the sequence value becomes dead and is removed.Before: ┌───────────────────┐ x0, x1 ────→│ SequenceConstruct │────→ s └───────────────────┘ │ │ ↓ ↓ ┌────────────┐ ┌────────────┐ │ SequenceAt │ │ SequenceAt │ └────────────┘ └────────────┘ │ index=0 │ index=1 ↓ ↓ y0 y1 After: ┌──────────┐ x0 ────→│ Identity │────→ y0 └──────────┘ ┌──────────┐ x1 ────→│ Identity │────→ y1 └──────────┘Public Functions
-
inline explicit SequenceConstructAtPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
SequenceConstructas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
SequenceConstructfully consumed by constantSequenceAt.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces each
SequenceAtwith anIdentityon the built tensor.
-
inline explicit SequenceConstructAtPattern(int priority = 0)#
-
class SplitToSequenceSequenceAtPattern : public onnx_light::core::builder::PatternOptimization#
- #include <sequence_pattern.h>
Replaces
SplitToSequence(x, [split], axis=a)followed by the matchingSequenceAt(seq, 0),SequenceAt(seq, 1), … with a singleSplit.When
keepdims=0, the replacement inserts aSqueezeon the split axis after everySplitoutput to reproduce the correspondingSequenceAtresult.The indices of the
SequenceAtconsumers must be constant scalars that cover0 .. n-1exactly once.Before: ┌─────────────────┐ x ────→│ SplitToSequence │────→ s └─────────────────┘ │ │ ↓ ↓ ┌────────────┐ ┌────────────┐ │ SequenceAt │ │ SequenceAt │ └────────────┘ └────────────┘ │ index=0 │ index=1 ↓ ↓ y0 y1 After (keepdims=0): ┌───────┐ x ────→│ Split │ └───────┘ │ │ ┌─────────┐ ├── t0, axes=[1] ──→│ Squeeze │────→ y0 │ ├─────────┤ │ ├─────────┤ └── t1, axes=[1] ──→│ Squeeze │────→ y1 └─────────┘ After (keepdims=1): ┌───────┐ x ────→│ Split │────→ y0, y1 └───────┘With an explicit
splitinput,keepdimsis ignored and theSplitwrites theSequenceAtoutputs directly. A constant scalar split is expanded into chunk lengths, including the final remainder; a vector split is forwarded unchanged.Public Functions
-
inline explicit SplitToSequenceSequenceAtPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
SplitToSequenceas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
SplitToSequencefully consumed by constantSequenceAt.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the sequence with a
Split(andSqueezewhen needed).
-
inline explicit SplitToSequenceSequenceAtPattern(int priority = 0)#
-
class SequenceConstructAtPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class GatherShapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <shape_pattern.h>
Simplifies
Gather(Shape(X), indices)intoShape(X, start, end)whenindicesis a constantint64scalar or a contiguous ascending 1-D range.The
start/endattributes possibly carried by the originalShapenode are folded into the new bounds. A scalar index yields aShapefollowed by aSqueezeof the leading axis to recover the 0-D result.Before: ┌─────────────────────┐ x ────→│ Shape start=1 end=5 │────→ s └─────────────────────┘ │ ↓ ┌──────────────┐ │ Gather axis0 │←──── indices=[1,2] └──────────────┘ │ ↓ y After: ┌─────────────────────┐ x ────→│ Shape start=2 end=4 │────→ y └─────────────────────┘ After (scalar index): ┌─────────────────────┐ x ────→│ Shape start=2 end=3 │────→ s └─────────────────────┘ │ ↓ ┌─────────┐ │ Squeeze │←──── axes=[0] └─────────┘ │ ↓ yFor scalar index
1, the result isSqueeze(Shape(x,start=2,end=3),axes=[0]). Ifshas another consumer, the originalShapeis retained.Public Functions
-
inline explicit GatherShapePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Gatheras the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a contiguous constant-index
Gatherover aShape.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rewrites the pair into a bounded
Shape(plusSqueezeif scalar).
-
inline explicit GatherShapePattern(int priority = 0)#
-
class PreShapeNodeEliminationPattern : public onnx_light::core::builder::PatternOptimization#
- #include <shape_pattern.h>
Removes a
Castnode whose output only feedsShapeconsumers, redirecting each suchShapenode directly to theCast’s input.Shapereports the input tensor’s dimensions and never depends on its element type, so aCastimmediately followed only byShapenodes can be bypassed without changing anyShapeoutput, for any opset. Because only theShapenode’s input is rewritten, itsstart/endattributes (available since opset 15), name, and metadata are preserved unchanged, and its rank / dimension reporting is unaffected. When theCastoutput is also consumed elsewhere (another op, a graph output, or a subgraph capture), theCastis retained for that use and only the matchedShapenode is rewritten; it is dropped once its lastShapeconsumer has been rewritten.Before: ┌──────┐ ┌─────────────────────┐ x:A ────→│ Cast │────→ c:B ────→│ Shape start=s end=e │────→ y └──────┘ └─────────────────────┘ After: ┌─────────────────────┐ x:A ─────────────→│ Shape start=s end=e │────→ y └─────────────────────┘ After (c:B is also consumed elsewhere): ┌──────┐ x:A ────→│ Cast │────→ c:B ────→ other consumer └──────┘ ┌─────────────────────┐ x:A ─────────────→│ Shape start=s end=e │────→ y └─────────────────────┘Public Functions
-
inline explicit PreShapeNodeEliminationPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Castas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Castwhose output feeds at least oneShapenode.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rewrites the matched
Shapenode to read directly from theCast’s input, keeping theCastalive only if still needed elsewhere.
-
inline explicit PreShapeNodeEliminationPattern(int priority = 0)#
-
class ShapeTransposePattern : public onnx_light::core::builder::PatternOptimization#
- #include <shape_pattern.h>
Replaces
Shape(Transpose(X, perm))byGather(Shape(X), perm)so the expensiveTransposeon the full data tensor is avoided.Before: ┌────────────────────────┐ x ────→│ Transpose perm=[2,0,1] │────→ t └────────────────────────┘ │ ↓ ┌─────────────────────┐ │ Shape start=1 end=3 │────→ y └─────────────────────┘ After: ┌───────┐ x ────→│ Shape │────→ sx └───────┘ │ ↓ ┌──────────────┐ │ Gather axis0 │←──── indices=[0,1] └──────────────┘ │ ↓ yThe permutation is a compile-time attribute of the
Transposenode, so the requested dimensions are read directly fromShape(X). The optionalstart/endattributes of theShapenode select the sub-rangeperm[start:end]used as theGatherindices. TheTransposeis preserved when its output is consumed elsewhere.Public Functions
-
inline explicit ShapeTransposePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Shapeas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Shapeconsuming the output of aTransposewith a perm.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rewrites the pair into
Gather(Shape(X), perm).
-
inline explicit ShapeTransposePattern(int priority = 0)#
-
class UnsqueezeShapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <shape_pattern.h>
Replaces
Shape(Unsqueeze(X, axes))by aConcatofShape(X)slices interleaved with constant[1]tensors at the inserted axis positions.Before: x, axes=[1] │ ↓ ┌───────────┐ │ Unsqueeze │────→ u └───────────┘ │ ↓ ┌───────┐ │ Shape │────→ y └───────┘ After: ┌─────────────────────┐ ┌─────────────────────┐ x ────→│ Shape start=0 end=1 │ [1] │ Shape start=1 end=3 │←──── x └─────────────────────┘ │ └─────────────────────┘ │ ↓ │ ↓ ↓ ┌────────────────────────────────────────────────────────────┐ │ Concat │────→ y └────────────────────────────────────────────────────────────┘Shape(Unsqueeze(X, axes))equalsShape(X)with1entries inserted at theaxespositions, so the (potentially large)Unsqueezeon the data tensor is avoided entirely while the shape vector stays identical. Theaxesinput must be a one-dimensional constant and the rank ofXmust be known. The optionalstart/endattributes of theShapenode are honoured. TheUnsqueezeis preserved when its output is consumed elsewhere.Public Functions
-
inline explicit UnsqueezeShapePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Unsqueezeas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an
Unsqueezewhose output feeds aShapenode.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rewrites the pair into a
Concatof rangedShapeslices and[1]s.
-
inline explicit UnsqueezeShapePattern(int priority = 0)#
-
class GatherShapePattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class SliceEliminationPattern : public onnx_light::core::builder::PatternOptimization#
- #include <slice_pattern.h>
Replaces a full-range Slice by an Identity.
The pattern supports the attribute form used before opset 10 and the input form used from opset 10 onward. Starts must all be zero, ends must all be
INT64_MAX, and optional steps must all be one. All dynamic parameters and malformed parameter vectors are rejected.Before: ┌───────┐ x, ranges →│ Slice │→ y └───────┘ After: ┌──────────┐ x → │ Identity │→ y └──────────┘Public Functions
-
inline explicit SliceEliminationPattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Sliceas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a default-domain Slice that selects its complete input.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the redundant Slice with an Identity preserving its output.
-
inline explicit SliceEliminationPattern(int priority = 1)#
-
class SliceSlicePattern : public onnx_light::core::builder::PatternOptimization#
- #include <slice_pattern.h>
Merges two consecutive
Slicenodes acting on disjoint axes into a singleSlicewhosestarts/ends/axes(andstepswhen present) are the concatenation of the two operand vectors.The intermediate result must be consumed by the second
Slicealone and both nodes must provide a constantaxesinput; a missingstepsinput on either side is materialised as a vector of ones.Before: x, s0, e0, a0, st0 │ ↓ ┌───────┐ │ Slice │──┐ └───────┘ │ │ t ↓ ┌───────┐ │ Slice │←──── s1, e1, a1, st1 └───────┘ │ ↓ y After: ┌────────┐ s0, s1 ────→│ Concat │──────────────┐ ├────────┤ │ ├────────┤ │ e0, e1 ────→│ Concat │──────────────┤ ├────────┤ │ ├────────┤ │ a0, a1 ────→│ Concat │──────────────┤ ├────────┤ │ ├────────┤ │ st0,st1 ───→│ Concat │──────────────┤ └────────┘ │ ↓ ┌───────┐ x ────────────────────────────→│ Slice │────→ y └───────┘Public Functions
-
inline explicit SliceSlicePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Sliceas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Slicefed by anotherSliceoperating on disjoint axes.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Fuses the two slices into a single
Slicewith concatenated inputs.
-
inline explicit SliceSlicePattern(int priority = 0)#
-
class SliceEliminationPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class GatherSliceToSplitPattern : public onnx_light::core::builder::PatternOptimization#
- #include <split_pattern.h>
Replaces compatible sibling scalar
Gatherand contiguousSliceranges covering a complete static axis with oneSplit. Scalar Gather outputs are restored withSqueeze.Before: +--> Gather(index=0) ----------> y0 x --+ +--> Slice(starts=1, ends=3) --> y1 After: +--------------------+ +---------+ x -->| Split(sizes=[1,2]) |--+->| Squeeze |---> y0 +--------------------+ | +---------+ +---------------> y1
Public Functions
-
inline explicit GatherSliceToSplitPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns Gather and Slice as possible roots.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a complete, non-overlapping sibling partition on one axis.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Emits Split and any Squeeze nodes required by scalar Gather outputs.
-
inline explicit GatherSliceToSplitPattern(int priority = 0)#
-
class GathersSplitPattern : public onnx_light::core::builder::PatternOptimization#
- #include <split_pattern.h>
Merges several sibling
Gathernodes reading consecutive constant indices0, 1, ..., n-1on the same axis of a common input into a singleSplit(followed bySqueezenodes when the indices are scalars).The axis dimension of the shared input must be statically equal to the number of gathers, so the
Splitreproduces every original slice.Before: ┌──────────────┐ x, index=0 ────→│ Gather axis1 │────→ y0 ├──────────────┤ ├──────────────┤ x, index=1 ────→│ Gather axis1 │────→ y1 ├──────────────┤ ├──────────────┤ x, index=2 ────→│ Gather axis1 │────→ y2 └──────────────┘ After: ┌───────┐ x ────→│ Split │ └───────┘ │ │ ┌─────────┐ ├── t0, axes=[1] ──→│ Squeeze │────→ y0 │ ├─────────┤ │ ├─────────┤ ├── t1, axes=[1] ──→│ Squeeze │────→ y1 │ ├─────────┤ │ ├─────────┤ └── t2, axes=[1] ──→│ Squeeze │────→ y2 └─────────┘ After (single-element vector indices): ┌───────┐ x ────→│ Split │────→ y0, y1, y2 └───────┘Single-element vector indices
[i]retain the axis, so theSplitwritesyidirectly withoutSqueezenodes.Public Functions
-
inline explicit GathersSplitPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Gatheras the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds sibling
Gathernodes covering an axis with constant indices.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the sibling
Gathernodes with aSplit(plusSqueeze).
-
inline explicit GathersSplitPattern(int priority = 0)#
-
class SlicesSplitPattern : public onnx_light::core::builder::PatternOptimization#
- #include <split_pattern.h>
Merges several sibling
Slicenodes that partition a common input along a single axis into contiguous, non-overlapping ranges into oneSplit.Each slice must use a unit step, share the same axis, start where the previous one ends, begin at zero and end at the axis dimension (or the
INT64_MAXsentinel used to denote “until the end”).Before: ┌───────┐ x, [0], [2], [0] ──────────→│ Slice │────→ y0 ├───────┤ ├───────┤ x, [2], [5], [0] ──────────→│ Slice │────→ y1 ├───────┤ ├───────┤ x, [5], [INT64_MAX], [0] ──→│ Slice │────→ y2 └───────┘ After: x, splits=[2,3,1] ───→┌───────┐────→ y0 │ Split │────→ y1 └───────┘────→ y2Public Functions
-
inline explicit SlicesSplitPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Sliceas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds sibling
Slicenodes partitioning an axis into contiguous ranges.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the sibling
Slicenodes with a singleSplit.
-
inline explicit SlicesSplitPattern(int priority = 0)#
-
class SplitConcatPattern : public onnx_light::core::builder::PatternOptimization#
- #include <split_pattern.h>
Replaces a
Splitimmediately followed by aConcatthat re-joins all of its outputs, in order and on the same axis, with a singleIdentity.Before: ┌───────┐ x ────→│ Split │ └───────┘ │ ┌────┴────┐ │ │ ↓ ↓ s0 s1 │ │ ↓ ↓ └────┬────┘ ↓ ┌────────┐ │ Concat │────→ y └────────┘ After: ┌──────────┐ x ────→│ Identity │────→ y └──────────┘The rewrite only fires when every
Splitoutput feeds the sameConcatnode, the concatenated inputs are exactly the split outputs in order, and the two axes match (after normalising negative axes against the input rank).Public Functions
-
inline explicit SplitConcatPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Splitas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Splitwhose outputs are re-joined by a singleConcat.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched
Split/Concatpair with anIdentity.
-
inline explicit SplitConcatPattern(int priority = 0)#
-
class GatherSliceToSplitPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Expand
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class ExpandBroadcastPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Drops an
Expandfeeding an element-wise binary operator.Before: ┌────────┐ x, S ────→│ Expand │ └────────┘ │ ↓ ┌────────┐ z ───────→│ Binary │────→ y └────────┘ After: ┌────────┐ x, z ───→│ Binary │────→ y └────────┘Sis constant,xandzhave the same rank, and every aligned dimension is equal or one. The unsharedExpandis removed becauseOpcan broadcastxdirectly; operand order is preserved.Public Functions
-
inline explicit ExpandBroadcastPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Expandas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an
Expandconsumed by a single broadcasting binary operator.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rebuilds the binary operator on the pre-expanded input.
-
inline explicit ExpandBroadcastPattern(int priority = 0)#
-
class ExpandPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Removes an
Expandthat does not change the shape of its input.Before: ┌────────┐ x, shape=[D0,...,Dn] ────→│ Expand │────→ y └────────┘ After: ┌──────────┐ x ──────────────────────→│ Identity │────→ y └──────────┘The rewrite replaces
Expand(x, shape)withIdentity(x)when the shape ofxis fully known and equals the constantshapefed toExpand.Public Functions
-
inline explicit ExpandPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Expandas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an
Expandwhose constant target shape equals its input shape.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the redundant
ExpandwithIdentity.
-
inline explicit ExpandPattern(int priority = 0)#
-
class ExpandSwapPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Moves an
Expandpast a following unary-like operator.Before: ┌────────┐ x, S ────→│ Expand │────→ e └────────┘ │ ↓ ┌──────────┐ │ UnaryOp │←──── optional inputs └──────────┘ │ ↓ y After: ┌──────────┐ x ────→│ UnaryOp │←──── optional inputs └──────────┘ │ ↓ ┌────────┐ │ Expand │←──── S └────────┘ │ ↓ yThe
Expandoutput must be unshared andOpmust preserve the shape of its first input. Attributes and any additional inputs ofOpare retained, so the operator runs on the smaller tensor.Public Functions
-
inline explicit ExpandSwapPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Expandas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an
Expandconsumed by a single unary-like operator.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Emits the unary operator first and re-expands its output.
-
inline explicit ExpandSwapPattern(int priority = 0)#
-
class ExpandUnsqueezeExpandPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Fuses
Expand,UnsqueezeandExpandintoUnsqueezethenExpand.Before: ┌────────┐ x, [2,3] ────→│ Expand │────→ e1 └────────┘ │ ↓ ┌───────────┐ │ Unsqueeze │←──── axes=[1] └───────────┘ │ ↓ ┌────────┐ │ Expand │←──── [1,4,3] └────────┘ │ ↓ y After: ┌───────────┐ x, axes=[1] ────→│ Unsqueeze │────→ u2 └───────────┘ │ ↓ ┌────────┐ │ Expand │←──── [2,4,3] └────────┘ │ ↓ yBoth targets and the axes are constant (opset 13 or later), intermediate outputs are unshared, and the ranks agree. The new target is
max(insert_ones(first_target, axes), second_target)element by element.Public Functions
-
inline explicit ExpandUnsqueezeExpandPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Expandas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds
ExpandthenUnsqueezethenExpandwith constant shapes.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Emits
Unsqueezeon the original tensor and a single trailingExpand.
-
inline explicit ExpandUnsqueezeExpandPattern(int priority = 0)#
-
class ShapeBasedConcatExpandPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Simplifies a dynamic
Concatused as anExpandtarget shape.Before: ┌────────┐ p0,...,pk,...,pn ────→│ Concat │────→ s └────────┘ │ ↓ ┌────────┐ │ Expand │←──── x └────────┘ │ ↓ y After: ┌────────┐ [1],...,pk,...,[1] ──→│ Concat │────→ s2 └────────┘ │ ↓ ┌────────┐ │ Expand │←──── x └────────┘ │ ↓ yEvery
piis a one-element vector. The known input and output shapes have equal rank and differ only at dimensionk;pkis retained while all unchanged dimensions become1so broadcasting preserves them.Public Functions
-
inline explicit ShapeBasedConcatExpandPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Expandas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an
Expandwhose dynamic Concat target changes one dimension.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rebuilds the target shape with
[1]for every unchanged dimension.
-
inline explicit ShapeBasedConcatExpandPattern(int priority = 0)#
-
class ShapeBasedExpandBroadcastMatMulPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Removes dynamic
Expandnodes beforeMatMul.Before: ┌────────┐ a, sa ────→│ Expand │──┐ └────────┘ │ │ ┌────────┐ │ ┌────────┐ b, sb ────→│ Expand │──┴───→│ MatMul │────→ y └────────┘ └────────┘ After: ┌────────┐ a, b ───→│ MatMul │────→ y └────────┘ Either input may already be unexpanded.Either input may already be unexpanded. Only the leading batch dimensions must broadcast to the output batch shape; the trailing two dimensions retain standard
MatMulsemantics. SharedExpandnodes remain for other uses.Public Functions
-
inline explicit ShapeBasedExpandBroadcastMatMulPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
MatMulas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a MatMul whose input Expand nodes are unnecessary.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rebuilds MatMul on the pre-expanded inputs.
-
inline explicit ShapeBasedExpandBroadcastMatMulPattern(int priority = 0)#
-
class ShapeBasedExpandBroadcastPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Removes dynamic
Expandnodes before a broadcasting binary operator.Before: ┌────────┐ a, sa ────→│ Expand │──┐ └────────┘ │ │ ┌────────┐ │ ┌────────┐ b, sb ────→│ Expand │──┴───→│ Binary │────→ y └────────┘ └────────┘ After: ┌────────┐ a, b ───→│ Binary │────→ y └────────┘ Either input may already be unexpanded.The input, pre-expansion, and output symbolic shapes must prove that broadcasting
aandbproduces the shape ofy. Either input may already be unexpanded. SharedExpandnodes are preserved for other consumers, but the rebuilt binary operator bypasses them.Public Functions
-
inline explicit ShapeBasedExpandBroadcastPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns broadcasting binary operators as possible roots.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a binary operator whose input Expand nodes are unnecessary.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rebuilds the binary operator on the pre-expanded inputs.
-
inline explicit ShapeBasedExpandBroadcastPattern(int priority = 0)#
-
class ShapeBasedExpandCastWhereSwapPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Moves an
ExpandafterCastandWhere.Before: ┌────────┐ ┌──────┐ x, S ────→│ Expand │────→ e ───┬─────→│ Cast │────→ condition └────────┘ │ └──────┘ │ └────────────────────┐ │ ↓ ┌───────┐ z ──────────────────────────────────────────────→│ Where │────→ y └───────┘ After: ┌──────┐ x ────→│ Cast │────→ condition └──────┘ │ └──────────────────────────┐ │ ↓ ┌───────┐ z ───────────────────────────────→│ Where │────→ w └───────┘ │ ↓ ┌────────┐ │ Expand │←──── S └────────┘ │ ↓ y The expanded value may occupy either Where branch.The expanded value may instead be the false branch.
Cast(e)must be the unshared condition, and symbolic shapes must prove that the smallerWherebroadcasts to the original output shape.Public Functions
-
inline explicit ShapeBasedExpandCastWhereSwapPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Whereas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an Expand/Cast/Where chain that can run before expansion.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Emits Cast and Where on the pre-expanded input, then expands the result.
-
inline explicit ShapeBasedExpandCastWhereSwapPattern(int priority = 0)#
-
class ShapeBasedExpandSwapPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Moves input
Expandnodes after a broadcasting binary operator.Before: ┌────────┐ a, S ────→│ Expand │──┐ └────────┘ │ │ ┌────────┐ │ ┌────────┐ b, S ────→│ Expand │──┴───→│ Binary │────→ y └────────┘ └────────┘ After: ┌────────┐ a, b ────→│ Binary │ └────────┘ │ t ↓ ┌────────┐ S ─────────→│ Expand │────→ y └────────┘ Either input may already be unexpanded.One input may already be unexpanded. Symbolic shapes must prove that the smaller inputs broadcast safely and that the trailing
Expandrestores the original output shape. Shared inputExpandnodes remain for other consumers.Public Functions
-
inline explicit ShapeBasedExpandSwapPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns broadcasting binary operators as possible roots.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a binary operator whose input expansions can be delayed.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Emits the binary operator before one trailing Expand.
-
inline explicit ShapeBasedExpandSwapPattern(int priority = 0)#
-
class ShapeBasedStaticExpandPattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Replaces a dynamic
Expandtarget with an equivalent constant target.Before: ┌────────┐ x, dynamic shape graph ────→│ Expand │────→ y └────────┘ After: ┌────────┐ x, constant [1,M,1] ───────→│ Expand │────→ y └────────┘Dimensions that are unchanged become
1; changed dimensions must be statically known in both input and output and become their output size. TheExpandremains, but its dynamic shape computation is replaced.Public Functions
-
inline explicit ShapeBasedStaticExpandPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Expandas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a dynamic Expand whose effective broadcast target is static.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rebuilds Expand with a constant broadcast target.
-
inline explicit ShapeBasedStaticExpandPattern(int priority = 0)#
-
class SwapExpandReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Swaps an
Expandwith a following constant-shapeReshape.Before: ┌────────┐ x, S=[D,1,1] ────→│ Expand │────→ e └────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── [0,1,-1] └─────────┘ │ ↓ y After: ┌─────────┐ x, [0,1,-1] ────→│ Reshape │────→ r └─────────┘ │ ↓ ┌────────┐ │ Expand │←──── S=[D,1,1] └────────┘ │ ↓ yxmust have rank three, theExpandoutput must be unshared, and its inferred target value must end in[1,1]. This specialized form moves the fixedReshapebefore expansion.Public Functions
-
inline explicit SwapExpandReshapePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Reshapeas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds the supported Expand/Reshape rank-three form.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Emits Reshape before Expand.
-
inline explicit SwapExpandReshapePattern(int priority = 0)#
-
class SwapExpandUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
- #include <expand_pattern.h>
Swaps an
Expandand a followingUnsqueeze.Before: ┌────────┐ x, [A,B] ────→│ Expand │────→ e └────────┘ │ ↓ ┌───────────┐ │ Unsqueeze │←──── axes=[1] └───────────┘ │ ↓ y After: ┌───────────┐ x, axes=[1] ────→│ Unsqueeze │────→ u └───────────┘ │ ↓ ┌────────┐ │ Expand │←──── [A,1,B] └────────┘ │ ↓ yThe axes are constant (opset 13 or later), the
Expandoutput is unshared, and its target or output shape is known. The new target inserts a1at every normalized axis, lettingUnsqueezerun before expansion.Public Functions
-
inline explicit SwapExpandUnsqueezePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Expandas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an
Expandconsumed by a singleUnsqueezewith constant axes.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Emits the
Unsqueezefirst and re-expands its output.
-
inline explicit SwapExpandUnsqueezePattern(int priority = 0)#
-
class ExpandBroadcastPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class NotWherePattern : public onnx_light::core::builder::PatternOptimization#
- #include <where_pattern.h>
Rewrites
Where(Not(c), x, y)intoWhere(c, y, x).Before: ┌─────┐ c ────→│ Not │ └─────┘ │ ↓ ┌───────┐ x, y ──→│ Where │────→ z └───────┘ After: ┌───────┐ c, y, x ──→│ Where │────→ z └───────┘The two branches are swapped. A shared
Notis preserved for its other consumers while the replacementWherebypasses it.Public Functions
-
inline explicit NotWherePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Whereas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Wherefed by a default-domainNotcondition.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Swaps
Wherebranches and removes or preserves the matchedNot.
-
inline explicit NotWherePattern(int priority = 0)#
-
class UnsqueezeEqualPattern : public onnx_light::core::builder::PatternOptimization#
- #include <where_pattern.h>
Moves
Equal(x, c)after a compatible siblingUnsqueeze(x, a)and preserves the rank ofEqual(Unsqueeze(x, a), Unsqueeze(y, a)).Before (upstream form): ┌───────────┐ x, axes=a ──────→│ Unsqueeze │────→ ux └───────────┘ ┌───────┐ x, c ────→│ Equal │────→ q └───────┘ │ ↓ ┌───────────┐ axes=a ──→│ Unsqueeze │────→ z └───────────┘ After (upstream form): ┌───────────┐ x, axes=a ──────→│ Unsqueeze │────→ ux └───────────┘ ┌───────┐ ux, c ───→│ Equal │────→ z └───────┘ Before (local form): ┌───────────┐ x, axes=a ─────→│ Unsqueeze │──┐ └───────────┘ │ │ ┌───────────┐ │ ┌───────┐ y, axes=a ─────→│ Unsqueeze │──┴───→│ Equal │────→ z └───────────┘ └───────┘ After (local form): ┌───────┐ x, y ────→│ Equal │ └───────┘ │ ↓ ┌───────────┐ axes=a ───→│ Unsqueeze │────→ z └───────────┘All axes are equal constant tensors. The upstream form requires a rank-zero
cunless inferred shapes prove thatEqual(x,c)preservesx’s rank. The local form requires equal pre-Unsqueezeranks and unshared expanded inputs.Public Functions
-
inline explicit UnsqueezeEqualPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Equalas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an upstream or local
Equal/Unsqueezetopology.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rebuilds the topology without changing the final output rank.
-
inline explicit UnsqueezeEqualPattern(int priority = 0)#
-
class WhereAddPattern : public onnx_light::core::builder::PatternOptimization#
- #include <where_pattern.h>
Rewrites an additive mask or factors a common term from
Wherebranches.Before (mask form): ┌───────┐ c, 0, -inf ──→│ Where │ └───────┘ │ ↓ ┌─────┐ k ────────────→│ Add │────→ y └─────┘ After (mask form): ┌───────┐ c, k, -inf ────→│ Where │────→ y └───────┘ Before (factoring form): c │ │ ┌─────┐ │ a, z ────→│ Add │──┐ │ └─────┘ │ │ │ ↓ ┌─────┐ │ ┌───────┐ b, z ────→│ Add │──┴───→│ Where │────→ y └─────┘ └───────┘ After (factoring form): ┌───────┐ c, a, b ───→│ Where │ └───────┘ │ ↓ ┌─────┐ z ──────────→│ Add │────→ y └─────┘The mask form requires an unshared
Whereoutput and accepts either operand order forAdd. The factoring form requires both branchAddoutputs to be unshared and recognizes the common input in either position.Public Functions
-
inline explicit WhereAddPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Whereas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an additive mask or two
Addbranches sharing one input.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Emits the upstream
Whereor the local factoredWhereandAdd.
-
inline explicit WhereAddPattern(int priority = 0)#
-
class NotWherePattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Layout
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class MulUnsqueezeUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
- #include <layout_pattern.h>
Moves equal, unshared
Unsqueezeoperations after aMul.Before: ┌───────────┐ x, axes=a ───→│ Unsqueeze │──┐ └───────────┘ │ │ ┌───────────┐ │ ┌─────┐ z, axes=a ───→│ Unsqueeze │──┴───→│ Mul │────→ y └───────────┘ └─────┘ After: ┌─────┐ x, z ────→│ Mul │ └─────┘ │ ↓ ┌───────────┐ axes=a →│ Unsqueeze │────→ y └───────────┘Public Functions
-
inline explicit MulUnsqueezeUnsqueezePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit MulUnsqueezeUnsqueezePattern(int priority = 0)#
-
class SqueezeAddPattern : public onnx_light::core::builder::PatternOptimization#
- #include <layout_pattern.h>
Moves equal
Squeezeoperations after anAdd.Before: ┌─────────┐ x, axes=a ───→│ Squeeze │──┐ └─────────┘ │ │ ┌─────────┐ │ ┌─────┐ z, axes=a ───→│ Squeeze │──┴───→│ Add │────→ y └─────────┘ └─────┘ After: ┌─────┐ x, z ────→│ Add │ └─────┘ │ ↓ ┌─────────┐ axes=a →│ Squeeze │────→ y └─────────┘The axes must be equal constants (or inferred axis
0for a[1]input). ASqueezeis retained if its output has another consumer.Public Functions
-
inline explicit SqueezeAddPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit SqueezeAddPattern(int priority = 0)#
-
class SqueezeBinaryUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
- #include <layout_pattern.h>
Cancels a scalar-producing
Squeeze/binary/Unsqueezechain by expanding the scalar right operand instead.Before: ┌─────────┐ x ────→│ Squeeze │────→ s └─────────┘ │ ↓ ┌────────┐ │ Binary │←──── c └────────┘ │ ↓ ┌───────────┐ │ Unsqueeze │←──── axes=[0] └───────────┘ │ ↓ y After: ┌───────────┐ c, axes=[0] ────→│ Unsqueeze │────→ uc └───────────┘ │ ↓ ┌────────┐ x ─────────────────→│ Binary │────→ y └────────┘The binary operator may be
Add,Div,Mul, orSub. Its left input and output must be unshared, and the finalUnsqueezeaxis must be the scalar constant0.Public Functions
-
inline explicit SqueezeBinaryUnsqueezePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit SqueezeBinaryUnsqueezePattern(int priority = 0)#
-
class SwapUnsqueezeTransposePattern : public onnx_light::core::builder::PatternOptimization#
- #include <layout_pattern.h>
Swaps an unshared
UnsqueezeandTranspose, remapping both axes and permutation.Requires the input-axes form of
Unsqueeze(opset 13 or later), a constant one-dimensional INT64 axes tensor, and an explicit valid permutation. Negative axes are normalized against the expanded rank; duplicates and out-of-range axes are rejected. The permutation supplies the expanded rank when shape metadata is absent; any known operand rank must agree.For normalized inserted axes A and permutation P, the replacement axes are the output positions i for which P[i] belongs to A (the inverse permutation, not P[A]). The replacement permutation removes those entries from P and renumbers the remaining original operand axes in their natural order.
Before: ┌───────────┐ x, axes=[0] ────→│ Unsqueeze │────→ u └───────────┘ │ ↓ ┌───────────────────┐ │ Transpose [1,2,0] │────→ y └───────────────────┘ After: ┌───────────────────┐ x ────→│ Transpose [0,1] │────→ t └───────────────────┘ │ ↓ ┌───────────┐ │ Unsqueeze │←──── axes=[2] └───────────┘ │ ↓ yPublic Functions
-
inline explicit SwapUnsqueezeTransposePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit SwapUnsqueezeTransposePattern(int priority = 0)#
-
class TransposeEqualReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <layout_pattern.h>
Replaces a
Transposethat only repositions size-one axes around at most one other dimension with aReshape.Before: ┌──────────────────────┐ x ────→│ Transpose [0,2,1,3] │────→ y └──────────────────────┘ After: x, [0,3,1,0] │ ↓ ┌─────────┐ │ Reshape │────→ y └─────────┘ Both graphs produce shape [2,3,1,1] from input shape [2,1,3,1].Public Functions
-
inline explicit TransposeEqualReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit TransposeEqualReshapePattern(int priority = 0)#
-
class TransposeReshapeTransposePattern : public onnx_light::core::builder::PatternOptimization#
- #include <layout_pattern.h>
Moves a constant
Reshapeacross one of two adjacentTransposenodes when the input and target dimensions can be aligned by merging or splitting contiguous dimensions.Before: ┌───────────────────┐ x ────→│ Transpose [1,0,2] │────→ t0 └───────────────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── [6,4] └─────────┘ │ ↓ ┌─────────────────┐ │ Transpose [1,0] │────→ y └─────────────────┘ After: ┌───────────────────┐ x ────→│ Transpose [1,0,2] │────→ t0 └───────────────────┘ │ ↓ ┌───────────────────┐ │ Transpose [2,0,1] │────→ t1 └───────────────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── [4,6] └─────────┘ │ ↓ y Before (dual rank-expanding form): ┌───────────┐ x ────→│ Transpose │────→ t0 └───────────┘ │ ↓ ┌─────────┐ │ Reshape │────→ r └─────────┘ │ ↓ ┌───────────┐ │ Transpose │────→ y └───────────┘ After (dual rank-expanding form): ┌─────────┐ x, target ────→│ Reshape │────→ r └─────────┘ │ ↓ ┌────────────────────┐ │ Remapped Transpose │────→ y └────────────────────┘In the dual rank-expanding case, the first
Transposeis removed and theReshapeis moved before a remappedTranspose; the finalTransposeand output are retained.Public Functions
-
inline explicit TransposeReshapeTransposePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit TransposeReshapeTransposePattern(int priority = 0)#
-
class MulUnsqueezeUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
MatMul
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class GemmOutputTransposePattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Absorbs a matrix output Transpose into an unbiased Gemm.
Before: ┌─────────────────────────┐ ┌─────────────────┐ A, B ─→│ Gemm transA=a, transB=b │────→│ Transpose [1,0] │──→ y └─────────────────────────┘ └─────────────────┘ After: ┌─────────────────────────────┐ B, A ─→│ Gemm transA=1-b, transB=1-a │──→ y └─────────────────────────────┘Requires opset 11 or later and rank-two inputs, with dynamic or constant dimensions. Transpose flags must be zero or one. An omitted permutation reverses the two matrix axes. The Gemm intermediate cannot be shared, exported, or captured. Biases, unresolved attributes, function overloads and device configurations are not supported. Coefficients, final output names and compatible metadata survive. Each application removes one output Transpose without introducing another.
Public Functions
-
inline explicit GemmOutputTransposePattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit GemmOutputTransposePattern(int priority = 1)#
-
class GemmSumFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Fuses a two-input Sum following an unbiased Gemm into the Gemm bias input.
The Gemm output must be private to the Sum, and the other Sum input must be unidirectionally broadcastable to the rank-two Gemm output.
Before: +------+ +-----+ A, B ->| Gemm |------>| Sum |---> y +------+ +-----+ ^ | C After: +--------------+ A, B, C ->| Gemm(beta=1) |---> y +--------------+
Public Functions
-
inline explicit GemmSumFusionPattern(int priority = 2)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit GemmSumFusionPattern(int priority = 2)#
-
class GemmTransposePattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Absorbs one or both matrix input Transposes into Gemm transpose flags.
Before: ┌─────────────────┐ A ────→│ Transpose [1,0] │────→ At └─────────────────┘ ┌─────────────────┐ B ────→│ Transpose [1,0] │────→ Bt └─────────────────┘ ┌─────────────────┐ At, Bt, optional C ──→│ Gemm transA/B │────→ y └─────────────────┘ After: ┌───────────────────────┐ A, B, optional C ──→│ Gemm toggled transA/B │────→ y └───────────────────────┘At least one input must be produced by a rank-two Transpose with
perm=[1,0]or the equivalent default permutation. Only flags for absorbed sides are toggled. Inputs may be dynamic or constant; alpha, beta, legacy broadcast, bias and output names are preserved. Shared Transposes are retained, and on GPU a shared side is not absorbed.Public Functions
-
inline explicit GemmTransposePattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit GemmTransposePattern(int priority = 1)#
-
class GroupedMatMulPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Fuses per-token expert selection into an opset-29 GroupedMatMul.
Before (batched Gather): ┌─────────────────────┐ x[M,K] ──→│ Unsqueeze axes=1,2 │────┐ └─────────────────────┘ │ ┌─────────────────────┐ ↓ W, I ────→│ Gather axis=0 │→┌────────┐ └─────────────────────┘ │ MatMul │ └────────┘ ↓ ┌────────────────┐ │ Squeeze axis=2 │──→ y[M,S,N] └────────────────┘ Before (unrolled per-token MatMuls, M >= 2): ┌────────────────────────────────┐ x, W, I, m ───→│ Gather rows and expert weights │ └────────────────────────────────┘ ↓ ┌────────────────────────────────┐ │ MatMul, optional gathered bias │ └────────────────────────────────┘ ↓ ┌────────────────────────────────┐ │ Unsqueeze(0), Concat(0) │──→ y[M,S,N] └────────────────────────────────┘ Before (stateless, fixed-trip Loop): ┌────────────────────────────────────┐ M, true, x, W, I, B ─→│ Loop: Gather rows/weights by iter │ │ MatMul, optional gathered bias │ │ condition forwarded, scan [S,N] │──→ y[M,S,N] └────────────────────────────────────┘ After (all three forms): ┌────────────────────────┐ x, W, I, optional B ─→│ GroupedMatMul │──→ y[M,S,N] └────────────────────────┘W has shape [G,K,N] and I has shape [M,S]. G must be a positive static dimension representable in the index dtype. Negative Gather indices are normalized with Less, Where, and Add before GroupedMatMul. A following Add of Gather(bias[G,N], I, axis=0) may be absorbed in either input order. Removed intermediates must not be shared, exported, or captured. Concat and Loop forms require fully static compatible shapes and positive M. Concat branches must cover every token in order. The Loop condition is true or omitted, and the body cannot terminate early, carry state, shadow captures, contain extra operations, or reference nested subgraphs. The default priority precedes GatherToSlice, which would obscure scalar rows.
Public Functions
-
inline explicit GroupedMatMulPattern(int priority = 2)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
Private Functions
-
core::builder::MatchResult MatchConcat(core::builder::GraphGraph &graph, const NodeProto &candidate) const#
-
core::builder::MatchResult MatchLoop(core::builder::GraphGraph &graph, const NodeProto &candidate) const#
-
inline explicit GroupedMatMulPattern(int priority = 2)#
-
class MatMulAddPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Fuses an Add bias into a MatMul or Gemm.
Before: ┌─────────────┐ A, B, optional C ────→│ MatMul/Gemm │ └─────────────┘ │ ↓ ┌─────┐ bias ───────────────────→│ Add │────→ y └─────┘ After (rank-two A): ┌─────┐ optional C, bias ─→│ Add │ └─────┘ │ combined bias ↓ ┌──────┐ A, B ────────────→│ Gemm │────→ y └──────┘ Without C, bias feeds the boxed Gemm directly. After (higher-rank A): B │ ↓ ┌───────────────────┐ │ A ───────→│ Reshape to rank 2 │──┐ │ └───────────────────┘ │ │ │ │ ┌───────────────────┐ │ ┌──────┐ bias ────→│ Reshape if needed │──┴───→│ Gemm │────→ t └───────────────────┘ └──────┘ │ ↓ ┌───────────────────────┐ shape ────────────────────────────────→│ Reshape to final rank │────→ y └───────────────────────┘The bias last dimension must match the output width. For a higher-rank left input, when enabled, the rewrite flattens it to rank two, applies
Gemm, and restores the output shape; a higher-rank bias is flattened as needed.Higher-rank reshaping remains opt-in, including in the standard collection. It requires rank-two weights and either a vector bias or a bias with exactly the matrix output shape, not arbitrary Add broadcasting. Callers must ensure nonempty dimensions: the generated Reshapes use -1 inference and default zero-as-copy semantics. Symbolic input shapes or symbolic full-bias widths also require opset 15 or newer for Shape start/end attributes. These runtime and opset preconditions are not checked by the opt-in matcher. The extra Reshape/Shape/Concat nodes are not a guaranteed performance win, particularly around attention layout changes; batched attention score MatMuls are not supported.
Public Functions
-
inline explicit MatMulAddPattern(int priority = 2, bool allow_reshape = false)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
Private Members
-
bool allow_reshape_#
-
inline explicit MatMulAddPattern(int priority = 2, bool allow_reshape = false)#
-
class MatMulBatchNormalizationFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Folds inference BatchNormalization parameters into a constant MatMul weight.
Both MatMul inputs must be rank two. At opset 9 or newer, a private chain of Reshape and Transpose nodes may separate MatMul from BatchNormalization. The chain must keep column j as channel j on axis 1. Reshape shapes must be constant INT64 vectors; all intermediate shapes must have concrete positive dimensions. Unknown, empty, or dynamically specified layouts are not fused. The MatMul weight and all four BatchNormalization parameters must be floating-point constants. The replacement is a standard Gemm with folded weight and bias initializers, followed by the unchanged shape operations.
Before: ┌────────┐ ┌────────────────────┐ ┌────────────────────┐ x, W → │ MatMul │ → │ Reshape/Transpose* │ → │ BatchNormalization │ → y └────────┘ └────────────────────┘ └────────────────────┘ ↑ ↑ ↑ ↑ scale bias mean variance After: ┌──────┐ ┌────────────────────┐ x, folded_W, folded_bias → │ Gemm │ → │ Reshape/Transpose* │ → y └──────┘ └────────────────────┘Public Functions
-
inline explicit MatMulBatchNormalizationFusionPattern(int priority = 2)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit MatMulBatchNormalizationFusionPattern(int priority = 2)#
-
class MatMulReshape2Of3Pattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Normalizes adjacent Reshapes around a MatMul to the final batch shape.
Before: ┌──────────┐ A ───────────→│ Reshape? │──┐ └──────────┘ │ │ ┌──────────┐ │ ┌────────────────────┐ B ───────────→│ Reshape? │──┴───→│ MatMul/FusedMatMul │────→ m └──────────┘ └────────────────────┘ │ ↓ ┌──────────┐ │ Reshape? │────→ y └──────────┘ At least two of the three optional Reshape nodes are present. After: ┌───────────────────┐ A ───────────→│ Reshape if needed │──┐ └───────────────────┘ │ │ ┌───────────────────┐ │ ┌────────────────────┐ B ───────────→│ Reshape if needed │──┴───→│ MatMul/FusedMatMul │────→ y └───────────────────┘ └────────────────────┘ A boxed restoring Reshape is emitted when the intermediate MatMul shape is still required.All participating shapes must be static, preserve element counts and the last two matrix dimensions, and describe equal batch element counts. Shared pre-Reshapes are retained for their other consumers. If the old MatMul result also needs its intermediate shape, a restoring Reshape is emitted.
Public Functions
-
inline explicit MatMulReshape2Of3Pattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit MatMulReshape2Of3Pattern(int priority = 1)#
-
class MatMulScaleFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Absorbs one scalar Mul or safe Div adjacent to a rank-two MatMul.
A constant matrix operand is folded when available. Otherwise the MatMul is replaced by a standard Gemm whose
alphaattribute carries the scalar. Divisions with the scalar in the numerator and zero or non-finite factors are rejected.Before: +--------+ +-----+ x, W ->| MatMul |------>| Mul |---> y +--------+ +-----+ ^ | scale After: +--------+ x, folded_W -->| MatMul |---> y +--------+
Public Functions
-
inline explicit MatMulScaleFusionPattern(int priority = 2)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit MatMulScaleFusionPattern(int priority = 2)#
-
class MulMulMatMulPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Moves scalar factors from both MatMul inputs to one multiplication after the MatMul.
Before: ┌─────┐ x, c1 ───────→│ Mul │──┐ └─────┘ │ │ ┌─────┐ │ ┌────────┐ z, c2 ───────→│ Mul │──┴───→│ MatMul │────→ y └─────┘ └────────┘ After: ┌────────┐ x, z ────→│ MatMul │────→ t └────────┘ ┌─────┐ t, combined scalar ───→│ Mul │────→ y └─────┘Each input Mul must contain exactly one scalar constant and have an unshared output. The constants are multiplied into one initializer.
Public Functions
-
inline explicit MulMulMatMulPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit MulMulMatMulPattern(int priority = 1)#
-
class ReshapeMatMulReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Removes batch-flattening Reshapes around a MatMul.
Before: ┌───────────────────┐ A ───────────→│ Reshape to rank 3 │──┐ └───────────────────┘ │ │ ┌───────────────────┐ │ ┌────────┐ B ───────────→│ Reshape to rank 3 │──┴───→│ MatMul │────→ m └───────────────────┘ └────────┘ │ ↓ ┌──────────────────────────┐ │ Reshape to original rank │────→ y └──────────────────────────┘ After: A ─────────────────────┐ │ ↓ ┌────────┐ │ MatMul │────→ y └────────┘ ↑ B ─────────────────────┘The original inputs and final output have equal rank of at least four. Reshapes must preserve element counts and matrix suffixes, and the original batch prefixes must broadcast directly to the final shape. Shared input Reshapes are retained for their other consumers.
Public Functions
-
inline explicit ReshapeMatMulReshapePattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ReshapeMatMulReshapePattern(int priority = 1)#
-
class ShapeBasedMatMulToMulPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Replaces a MatMul with unit reduction dimensions by element-wise Mul.
Before: ┌───────────────────────┐ A, B ────→│ MatMul unit reduction │────→ m └───────────────────────┘ │ ↓ ┌──────────────────────┐ │ Optional Transpose │────→ y │ swapping last 2 axes │ └──────────────────────┘ After (no Transpose): ┌─────┐ A, B ────→│ Mul │────→ y └─────┘ After (last-two Transpose present): ┌──────────────────┐ A ───────────→│ Reshape ...,1,-1 │──┐ └──────────────────┘ │ │ ┌──────────────────┐ │ ┌─────┐ B ───────────→│ Reshape ...,-1,1 │──┴───→│ Mul │────→ y └──────────────────┘ └─────┘The last dimension of
Aand penultimate dimension ofBmust both be one. A following last-two-dimension Transpose is removed only when both input ranks exceed two.Public Functions
-
inline explicit ShapeBasedMatMulToMulPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ShapeBasedMatMulToMulPattern(int priority = 1)#
-
class SwitchReshapeActivationPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Moves an element-wise activation before a Reshape or Transpose.
Before: ┌─────────────┐ A, B ────→│ MatMul/Gemm │────→ m └─────────────┘ │ ↓ ┌───────────────────┐ │ Reshape/Transpose │────→ l └───────────────────┘ │ ↓ ┌────────────┐ │ Activation │────→ y └────────────┘ After: ┌─────────────┐ A, B ────→│ MatMul/Gemm │────→ m └─────────────┘ │ ↓ ┌────────────┐ │ Activation │────→ a └────────────┘ │ ↓ ┌───────────────────┐ │ Reshape/Transpose │────→ y └───────────────────┘Layoutis aReshapeorTranspose. Its input and output must be unshared, so the activation can commute across the layout without changing other consumers.Public Functions
-
inline explicit SwitchReshapeActivationPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit SwitchReshapeActivationPattern(int priority = 1)#
-
class TransposeMatMulPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Absorbs rank-two input Transposes into Gemm transpose attributes.
Before: ┌────────────────────────┐ A ────→│ Optional Transpose 1,0 │────→ At └────────────────────────┘ ┌────────────────────────┐ B ────→│ Optional Transpose 1,0 │────→ Bt └────────────────────────┘ ┌─────────────┐ A or At, B or Bt, optional C ──→│ MatMul/Gemm │────→ y └─────────────┘ At least one boxed Transpose is present. After: ┌────────────────────────┐ A, B, optional C ────→│ Gemm toggled transA/B │────→ y └────────────────────────┘At least one input must be transposed. Existing Gemm flags are toggled for the absorbed sides; shared Transposes are retained, and on GPU a shared side is not absorbed.
Public Functions
-
inline explicit TransposeMatMulPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit TransposeMatMulPattern(int priority = 1)#
-
class TransposeReshapeMatMulPattern : public onnx_light::core::builder::PatternOptimization#
- #include <matmul_pattern.h>
Swaps a last-two-dimension Transpose with a following Reshape on one MatMul input.
Before: ┌───────────────────────┐ A ────→│ Transpose last 2 axes │────→ t └───────────────────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── matrix-preserving target └─────────┘ │ └───────────────────────┐ │ ↓ ┌────────┐ B ────────────────────────────────────→│ MatMul │────→ y └────────┘ After: ┌────────────────────────┐ A ────→│ Reshape swapped target │────→ r └────────────────────────┘ │ ↓ ┌───────────────────────┐ │ Transpose last 2 axes │ └───────────────────────┘ │ └───────────────────────┐ │ ↓ ┌────────┐ B ────────────────────────────────────→│ MatMul │────→ y └────────┘ The same rewrite may be applied to the right MatMul input.The selected Reshape target must be constant and preserve the transposed matrix suffix. Both intermediate outputs must be unshared. The same rewrite may be applied to the right input instead.
Public Functions
-
inline explicit TransposeReshapeMatMulPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit TransposeReshapeMatMulPattern(int priority = 1)#
-
class GemmOutputTransposePattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Normalization
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class GeluPattern : public onnx_light::core::builder::PatternOptimization#
- #include <activation_pattern.h>
Fuses exact Erf-based Gelu and its tanh approximation.
Before (exact): ┌─────┐ ┌─────┐ ┌─────┐ x ───────→│ Div │─────→│ Erf │─────→│ Add │←── one │ └─────┘ └─────┘ └─────┘ │ ↑ │ │ sqrt(2) │ │ ┌─────┐ ┌─────┐ └────────→│ Mul │─────────────────→│ Mul │────→ y half ────→└─────┘ └─────┘ After (exact): ┌──────────────────────────┐ x ────→│ Gelu(approximate="none") │────→ y └──────────────────────────┘The exact form requires a known default-domain opset of at least 20 and FLOAT, FLOAT16, or DOUBLE data. Commutative inputs may be swapped. Scaling by one half must precede the final multiplication on either branch; division by two on either branch is also supported. Final scaling by one half is refused because the preceding product can overflow before scaling.
x / sqrt(2)may instead multiply by1 / sqrt(2). Constants must equal their dtype-rounded values; division also accepts ORT’s historical sqrt(2) constants for FLOAT tensors only. DOUBLE tensors require the canonical double-precision constant. Unlike ORT’s general relative tolerance, the one and one-half constants must be exact. Tensor constants must have exactly one inline element and must not be overridable graph inputs. Known intermediate shapes and types must agree with the input, and intermediates must be unshared. Overloads, attributes, device configurations, and intermediate metadata are refused. Final node metadata and output names are preserved. Exact fusion does not use a configured non-default replacement domain.Before: x, three │ ↓ ┌─────┐ │ Pow │ └─────┘ │ powered ↓ ┌─────┐ │ Mul │←──── cubic coefficient └─────┘ │ cubic x │ │ │ ↓ ↓ ┌─────┐ │ Add │ └─────┘ │ polynomial ↓ ┌─────┐ │ Mul │←──── tanh scale └─────┘ │ scaled polynomial ↓ ┌──────┐ │ Tanh │ └──────┘ │ tanh value ↓ ┌─────┐ │ Add │←──── one └─────┘ │ tanh term ┌─────┐ │ x, one half ─────→│ Mul │────→ half input │ └─────┘ │ │ └──────────┬───────────┘ ↓ ┌─────┐ │ Mul │────→ y └─────┘ After: ┌──────┐ x ────→│ Gelu │────→ y └──────┘The replacement uses
approximate="tanh". The cubic coefficient may also be the float16 value0.044708251953125; its usual value is0.044715. The exponent, tanh scale, final offset, and input scale are respectively3,0.7978515625,1, and0.5. All decomposition intermediates must be unshared, and the configured default-domain opset minimum must be met.Public Functions
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
virtual std::set<std::string> FastOpType() const override#
-
class LeakyReluPattern : public onnx_light::core::builder::PatternOptimization#
- #include <activation_pattern.h>
Fuses a Where-based LeakyRelu decomposition.
Before: x │ │ ┌─────────┐ │ x, zero ──→│ Greater │──┐ │ └─────────┘ │ │ │ ↓ ┌─────┐ │ ┌───────┐ x, alpha ─→│ Mul │──────┴───→│ Where │────→ y └─────┘ └───────┘ After: ┌───────────┐ x ────→│ LeakyRelu │────→ y └───────────┘The comparison threshold must be exactly zero, the slope must be scalar, and the Greater and Mul outputs must have no other consumers.
Public Functions
-
inline explicit LeakyReluPattern(int priority = 0, int min_opset = 6)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
Private Members
-
int min_opset_#
-
inline explicit LeakyReluPattern(int priority = 0, int min_opset = 6)#
-
class MaxReluPattern : public onnx_light::core::builder::PatternOptimization#
- #include <activation_pattern.h>
Replaces a maximum with scalar zero by Relu.
Before: ┌─────┐ x, zero ──→│ Max │────→ y └─────┘ After: ┌──────┐ x ────→│ Relu │────→ y └──────┘Exactly one Max input must be scalar zero. Supported element types are float, float16, int16, and int32; integer inputs require opset 14 or newer.
Public Functions
-
inline explicit MaxReluPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit MaxReluPattern(int priority = 1)#
-
class SoftmaxCrossEntropyLossCastPattern : public onnx_light::core::builder::PatternOptimization#
- #include <activation_pattern.h>
Fuses a float16 mean cross-entropy loss decomposition.
Before: ┌───────┐ ┌─────┐ labels, -100 →│ Equal │─→│ Not │ └───────┘ └─────┘ │ valid │ │ ├── valid, labels, zero_i64 ──→┌───────┐ ┌───────────┐ │ │ Where │─→│ Unsqueeze │ │ └───────┘ └───────────┘ │ │ │ │ gather indices │ │ │ ┌────────────┐ │ │ scores ──→│ LogSoftmax │ │ │ └────────────┘ │ │ │ │ │ ↓ ↓ │ ┌───────────────────────────┐ │ │ GatherElements │ │ └───────────────────────────┘ │ │ │ ↓ │ ┌─────────┐ │ │ Squeeze │ │ └─────────┘ │ │ │ ↓ │ ┌─────┐ │ │ Neg │ │ └─────┘ │ │ losses │ │ │ ↓ ├── valid, zero_f16 ──→┌────────────┐ │ │ Where │────→ masked losses │ └────────────┘ │ │ │ ↓ │ ┌──────┐ │ │ Cast │ │ └──────┘ │ │ │ ↓ │ ┌───────────┐ │ │ ReduceSum │ │ └───────────┘ │ │ │ ↓ │ ┌──────┐ │ │ Cast │ │ └──────┘ │ │ numerator │ ↓ └── valid ──→┌──────┐ │ │ Cast │ │ └──────┘ │ │ │ ↓ │ ┌───────────┐ │ │ ReduceSum │ │ └───────────┘ │ │ │ ↓ │ ┌──────┐ │ │ Cast │ │ └──────┘ │ │ denominator │ ↓ │ └──────────────┬──────────────┘ ↓ ┌─────┐ │ Div │─────→ loss └─────┘ After: ┌─────────────────────────┐ scores, labels ──→│ SoftmaxCrossEntropyLoss │────→ loss └─────────────────────────┘LogSoftmax, GatherElements, Unsqueeze, and Squeeze use axis one. Scores, masked losses, and the result must be float16; labels and the index zero must be int64. The reduction inputs are cast to float, both reductions use
keepdims=0, and their results are cast back to float16. The fused loss usesignore_index=-100andreduction="mean".Public Functions
-
inline explicit SoftmaxCrossEntropyLossCastPattern(int priority = 0, int min_opset = 14, std::string domain = "")#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit SoftmaxCrossEntropyLossCastPattern(int priority = 0, int min_opset = 14, std::string domain = "")#
-
class GeluPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class BatchNormalizationPattern : public onnx_light::core::builder::PatternOptimization#
- #include <normalization_pattern.h>
Removes an identity BatchNormalization in inference mode.
Before: ┌────────────────────┐ x, scale, bias, mean, variance ─────→│ BatchNormalization │────→ y └────────────────────┘ After: ┌──────────┐ x ────→│ Identity │────→ y └──────────┘Scale and variance must be constant ones; bias and mean must be constant zeros. Epsilon is zero, training mode is disabled, and running-statistic outputs must be unused.
Public Functions
-
inline explicit BatchNormalizationPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit BatchNormalizationPattern(int priority = 0)#
-
class BatchNormalizationTrainingPattern : public onnx_light::core::builder::PatternOptimization#
- #include <normalization_pattern.h>
Expands training BatchNormalization into primitive operators.
Before: ┌────────────────────┐ x, scale, bias, running mean, running variance ─→│ BatchNormalization │────→ y └────────────────────┘ After: x │ ├──────────────┐ │ ↓ │ ┌────────────┐ │ │ ReduceMean │────→ mean │ └────────────┘ ↓ ↓ ┌────────────────┐ │ Sub │────→ centered └────────────────┘ │ ├──────────────────────────────────────────────────────┐ │ │ ┌─┴─┐ │ │ │ │ ↓ ↓ │ ┌───┐ │ │Mul│ │ └───┘ │ │ │ ↓ │ ┌────────────┐ │ │ ReduceMean │────→ variance │ └────────────┘ │ │ │ │ epsilon │ ↓ │ │ ┌─────┐ ┌──────┐ │ │ Add │─→│ Sqrt │────→ deviation │ └─────┘ └──────┘ │ ↑ │ │ │ variance │ │ │ ↓ ↓ └──────────────────┬───────────────────┘ ↓ ┌─────┐ │ Div │────→ normalized └─────┘ │ │ ┌─────────┐ │ scale ──→│ Reshape │──┐ │ └─────────┘ │ │ │ broadcast scale │ ↓ ↓ └──────────┬───────────┘ ↓ ┌─────┐ │ Mul │────→ scaled └─────┘ │ scaled └──────────────────┐ │ ┌─────────┐ │ bias ───→│ Reshape │──┐ │ └─────────┘ │ │ │ broadcast bias │ ↓ ↓ └──────────────┬──────────────┘ ↓ ┌─────┐ │ Add │────→ y └─────┘The rewrite requires opset 18, a known input rank of at least two, known scale and bias ranks, and unused running-statistic outputs. Both ReduceMean nodes reduce every axis except channel axis 1. Reshape is emitted only for rank-one scale or bias inputs.
Public Functions
-
inline explicit BatchNormalizationTrainingPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit BatchNormalizationTrainingPattern(int priority = 0)#
-
class CastLayerNormalizationCastPattern : public onnx_light::core::builder::PatternOptimization#
- #include <normalization_pattern.h>
Removes FP32 promotion around eligible standard FP16 normalization.
Before: ┌──────┐ ┌───────────────┐ ┌──────┐ x ────→│ Cast │────→ promoted ────→│ Normalization │──────→│ Cast │────→ y └──────┘ └───────────────┘ └──────┘ ↑ │ unit scale (FP32) After: ┌──────┐ unit scale ───────→│ Cast │ └──────┘ │ converted parameters ↓ ┌───────────────┐ x ─────────────────→│ Normalization │────→ y └───────────────┘Supports only standard LayerNormalization (opset 17+) and RMSNormalization (opset 23+), with FLOAT stash_type, constant unit scale and no bias (an empty optional bias is allowed). Both schemas round normalized values to the I/O type before the affine stage, so even FP16-representable arbitrary weights are unsafe. Bias is conservatively rejected, including zero bias, to preserve signed-zero rounding. FP32 unit weights are converted exactly; existing FP16-to-FP32 scale casts are bypassed. Saved statistics retain their FP32 computation and names, including live outputs. The FP32 data output must be exclusive to the output Cast; shared upstream casts are preserved.
Public Functions
-
inline explicit CastLayerNormalizationCastPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit CastLayerNormalizationCastPattern(int priority = 1)#
-
class LayerNormalizationPattern : public onnx_light::core::builder::PatternOptimization#
- #include <normalization_pattern.h>
Fuses an explicit layer-normalization decomposition.
Before: x │ ├──────────────┐ │ ↓ │ ┌────────────┐ │ │ ReduceMean │────→ mean │ └────────────┘ ↓ ↓ ┌────────────────┐ │ Sub │────→ centered └────────────────┘ │ ├────────────────────────────────────────────┐ │ │ │ │ ↓ │ ┌─────┐ │ │ Pow │←──── two │ └─────┘ │ │ squared │ ↓ │ ┌────────────┐ │ │ ReduceMean │────→ variance │ └────────────┘ │ │ │ │ epsilon │ ↓ │ │ ┌─────┐ ┌──────┐ │ │ Add │─→│ Sqrt │────→ deviation │ └─────┘ └──────┘ │ │ │ ↓ ↓ └────────────┬─────────────┘ ↓ ┌─────┐ │ Div │────→ y └─────┘ Alternate final path: ┌────────────┐ deviation ──→│ Reciprocal │──┐ └────────────┘ │ │ inverse ↓ ┌─────┐ │ Mul │────→ y └─────┘ ↑ │ centered After: ┌───────┐ x ────→│ Shape │────→ normalized shape └───────┘ ┌─────────────────┐ normalized shape ──→│ ConstantOfShape │─────── scale ┐ ├─────────────────┤ │ ├─────────────────┤ │ normalized shape ──→│ ConstantOfShape │──────── bias ┤ └─────────────────┘ │ ↓ ┌────────────────────┐ x ────────────────────────────────────────────→│ LayerNormalization │────→ y └────────────────────┘Both means must keep dimensions and reduce the same trailing axes. All removed intermediates must be unshared. Scale and bias are initializers when the final dimension is static; otherwise the shown Shape branches create one and zero tensors.
Public Functions
-
inline explicit LayerNormalizationPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit LayerNormalizationPattern(int priority = 1)#
-
class LayerNormalizationScalePattern : public onnx_light::core::builder::PatternOptimization#
- #include <normalization_pattern.h>
Folds a following affine transform into LayerNormalization parameters.
Before: ┌────────────────────┐ x, scale, bias ──→│ LayerNormalization │ └────────────────────┘ │ ↓ ┌─────┐ ┌─────┐ extra scale ────────────→│ Mul │────→ scaled ──→│ Add │────→ y └─────┘ └─────┘ ↑ │ extra bias After: ┌─────┐ scale, extra scale ───→│ Mul │──────────────────────────────────────────┐ └─────┘ │ │ new scale │ ┌─────┐ ┌─────┐ │ bias, extra scale ────→│ Mul │────→ scaled bias ──→│ Add │ │ └─────┘ └─────┘ │ ↑ │ │ │ │ │ extra bias │ │ ↓ ↓ └───────┬────────┘ ↓ ┌────────────────────┐ x ─────────────────────────────────────────────→│ LayerNormalization │────→ y └────────────────────┘The extra scale, optional bias, and original scale must have equal shapes. The normalization and Mul outputs must not have unrelated consumers. Parameter Mul or Add nodes are omitted when an existing unit scale or a missing bias makes them unnecessary.
Public Functions
-
inline explicit LayerNormalizationScalePattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit LayerNormalizationScalePattern(int priority = 1)#
-
class RMSNormalizationMulPattern : public onnx_light::core::builder::PatternOptimization#
- #include <normalization_pattern.h>
Folds a constant post-scale into RMSNormalization.
Before: ┌──────────────────┐ x, scale1 ──→│ RMSNormalization │ └──────────────────┘ │ ↓ ┌─────┐ scale2 ───────────→│ Mul │────→ y └─────┘ After: ┌──────────────────┐ x, combined scale ─→│ RMSNormalization │────→ y └──────────────────┘Both scales must be constants with identical shapes and a representable elementwise product. The RMSNormalization output must be unshared.
Public Functions
-
inline explicit RMSNormalizationMulPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit RMSNormalizationMulPattern(int priority = 1)#
-
class RMSNormalizationPattern : public onnx_light::core::builder::PatternOptimization#
- #include <normalization_pattern.h>
Fuses an explicit root-mean-square normalization decomposition.
Before: Optional input conversion: ┌──────┐ x ────→│ Cast │────→ z └──────┘ z │ ├────────────────────────────────────────────┐ │ │ │ │ ↓ │ ┌─────┐ │ │ Pow │←──── two │ └─────┘ │ │ squared │ ↓ │ ┌────────────┐ │ │ ReduceMean │────→ mean square │ └────────────┘ │ │ │ │ epsilon │ ↓ │ │ ┌─────┐ ┌──────┐ │ │ Add │─→│ Sqrt │────→ deviation │ └─────┘ └──────┘ │ │ │ ↓ │ ┌────────────┐ │ │ Reciprocal │────→ inverse │ └────────────┘ │ │ │ ↓ ↓ └───────┬────────┘ ↓ ┌─────┐ │ Mul │────→ normalized └─────┘ Alternate inverse path: ┌─────┐ one, deviation ───→│ Div │────→ inverse └─────┘ Optional output conversion: ┌──────┐ normalized ─→│ Cast │────→ y └──────┘ After: ┌───────┐ ┌─────────────────┐ x ────→│ Shape │──────→│ ConstantOfShape │────→ scale └───────┘ └─────────────────┘ ┌──────────────────┐ x, scale ──→│ RMSNormalization │────→ y └──────────────────┘The optional Cast pair must convert to the reduction stash type and restore the original type. The rewrite requires opset 23, suffix reduction axes, and unshared intermediates. The scale is a static initializer when its shape is known; otherwise the shown Shape branch creates an all-ones tensor.
Public Functions
-
inline explicit RMSNormalizationPattern(int priority = 1)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit RMSNormalizationPattern(int priority = 1)#
-
class BatchNormalizationPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Reshape
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class ConcatReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Replaces dynamic dimensions in a concatenated Reshape target with one inferred dimension.
Before: ┌────────┐ constant, dynamic, Shape dims →│ Concat │ └────────┘ │ ↓ ┌─────────┐ x ─────────────────────────────→│ Reshape │────→ y └─────────┘ After: ┌────────┐ constant, [-1], Shape dims ─→│ Concat │ └────────┘ │ ↓ ┌─────────┐ x ───────────────────────────→│ Reshape │────→ y └─────────┘Every non-
Shapedynamic slot is replaced by[-1]; when all dynamic slots come fromShape, the last such slot is replaced. Dynamic inputs must each describe one dimension and the target may contain only one inferred dimension. A shared originalConcatis retained for its other consumers.Public Functions
-
inline explicit ConcatReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ConcatReshapePattern(int priority = 0)#
-
class ReduceReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Fuses a dimension-removing Reshape into a reduction.
Before: ┌───────────────────┐ x, axes ────→│ Reduce keepdims=1 │────→ t └───────────────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── target without reduced axes └─────────┘ │ ↓ y After: ┌───────────────────┐ x, axes ────→│ Reduce keepdims=0 │────→ y └───────────────────┘The reduction output must be unshared, and the final shape must equal the input shape with the reduced axes removed.
Public Functions
-
inline explicit ReduceReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ReduceReshapePattern(int priority = 0)#
-
class Reshape2Of3Pattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Moves a binary operation to the common outer shape represented by surrounding Reshapes.
Before: ┌──────────┐ x ───────────→│ Reshape? │──┐ └──────────┘ │ │ ┌──────────┐ │ ┌────────┐ z ───────────→│ Reshape? │──┴───→│ Binary │────→ b └──────────┘ └────────┘ │ ↓ ┌──────────┐ │ Reshape? │────→ y └──────────┘ At least two of the three optional Reshape nodes are present. After: ┌───────────────────┐ x ───────────→│ Reshape if needed │──┐ └───────────────────┘ │ │ ┌───────────────────┐ │ ┌────────┐ z ───────────→│ Reshape if needed │──┴───→│ Binary │────→ t └───────────────────┘ └────────┘ │ ↓ ┌───────────────────┐ │ Reshape if needed │────→ y └───────────────────┘The binary operation must not broadcast, and the available source/final shapes must be equal. Existing input Reshapes are removed; a missing input Reshape or output Reshape is inserted only when needed to preserve the original output shape. Shared input Reshapes are retained for their other consumers.
Public Functions
-
inline explicit Reshape2Of3Pattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit Reshape2Of3Pattern(int priority = 0)#
-
class ReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Removes a Reshape whose constant target already equals its input shape.
Before: ┌─────────┐ x, target=S ────→│ Reshape │────→ y └─────────┘ After: ┌──────────┐ x ────────────→│ Identity │────→ y └──────────┘The input shape must be fully static and match every rank and dimension of the materialized target
S.Public Functions
-
inline explicit ReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ReshapePattern(int priority = 0)#
-
class ReshapeReshapeBinaryPattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Moves equal input Reshapes after an element-wise binary operation.
Before: ┌─────────┐ x, target=s ─→│ Reshape │──┐ └─────────┘ │ │ ┌─────────┐ │ ┌────────┐ z, target=s ─→│ Reshape │──┴───→│ Binary │────→ y └─────────┘ └────────┘ After: ┌────────┐ x, z ────→│ Binary │────→ t └────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── target=s └─────────┘ │ ↓ yThe two source tensors must have equal shapes, both targets must be the same constant, and neither input Reshape output may be shared.
Public Functions
-
inline explicit ReshapeReshapeBinaryPattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ReshapeReshapeBinaryPattern(int priority = 0)#
-
class ReshapeReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Composes two consecutive Reshapes into one.
Before: ┌─────────┐ x, target=s1 ────→│ Reshape │────→ t └─────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── target=s2 └─────────┘ │ ↓ y After: ┌─────────┐ x, target=s2' ───→│ Reshape │────→ y └─────────┘The first output must be unshared. The replacement normally uses
s2; copied zero dimensions are substituted or rebuilt when they refer tos1, and unsafe combinations of inferred dimensions are rejected.Public Functions
-
inline explicit ReshapeReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ReshapeReshapePattern(int priority = 0)#
-
class ReshapeSqueezePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Fuses a Squeeze into the constant target of a preceding Reshape.
Before: ┌─────────┐ x, target=[...,1,...] ────→│ Reshape │────→ t └─────────┘ │ ↓ ┌─────────┐ │ Squeeze │←──── axes=a └─────────┘ │ ↓ y After: ┌─────────┐ x, target without axes ────→│ Reshape │────→ y └─────────┘Every explicit Squeeze axis must select a unit target dimension. Removed dimensions are deleted from the replacement target; copied zero dimensions may not follow a removed axis.
Public Functions
-
inline explicit ReshapeSqueezePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ReshapeSqueezePattern(int priority = 0)#
-
class ShapeBasedEditDistanceReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Materializes a Concat-built Reshape target from inferred input and output shapes.
Before: ┌────────┐ shape pieces ────→│ Concat │────→ target └────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── x └─────────┘ │ ↓ y After: ┌─────────┐ x, aligned target initializer ────→│ Reshape │────→ y └─────────┘Input and output dimensions must admit an unambiguous alignment with at most one inferred dimension. Only the Reshape is replaced; the old target branch remains if it has other uses.
Public Functions
-
inline explicit ShapeBasedEditDistanceReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ShapeBasedEditDistanceReshapePattern(int priority = 0)#
-
class ShapeBasedReshapeIsSqueezePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Replaces a Reshape or all-one Expand that only inserts or removes unit dimensions.
Before: ┌────────────────┐ x, target ────→│ Reshape/Expand │────→ y └────────────────┘ After (unit dimensions are removed): ┌─────────┐ x, axes=a ────→│ Squeeze │────→ y └─────────┘ After (unit dimensions are inserted): ┌───────────┐ x, axes=a ────→│ Unsqueeze │────→ y └───────────┘Known input and output shapes must differ only by dimensions of size one.
Expandadditionally requires an all-one constant target. The rewrite requires opset 18 or later.Public Functions
-
inline explicit ShapeBasedReshapeIsSqueezePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ShapeBasedReshapeIsSqueezePattern(int priority = 0)#
-
class ShapedBasedReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Removes a same-rank Reshape whose target copies every dimension but the last.
Before: ┌─────────┐ x, [0,...,0,d] ────→│ Reshape │────→ y └─────────┘ After: ┌──────────┐ x ────────────────→│ Identity │────→ y └──────────┘The target must be constant, non-empty, have the input rank, contain only leading zeros, and end in a nonzero dimension.
Public Functions
-
inline explicit ShapedBasedReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit ShapedBasedReshapePattern(int priority = 0)#
-
class StaticConcatReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Replaces the sole dynamic element of a concatenated Reshape target with
[-1].Before: ┌────────┐ constant dims, dynamic dim ─→│ Concat │ └────────┘ │ ↓ ┌─────────┐ x ───────────────────────────→│ Reshape │────→ y └─────────┘ After: ┌────────┐ constant dims, [-1] ─→│ Concat │ └────────┘ │ ↓ ┌─────────┐ x ────────────────────→│ Reshape │────→ y └─────────┘Constants may not already contain
-1and exactly one dynamic input must have shape[1]. A shared originalConcatis retained for its other consumers.Public Functions
-
inline explicit StaticConcatReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit StaticConcatReshapePattern(int priority = 0)#
-
class UnsqueezeOrSqueezeReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Removes a Squeeze or Unsqueeze immediately before a Reshape.
Before: ┌───────────────────┐ x, axes=a ────→│ Squeeze/Unsqueeze │────→ t └───────────────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── target └─────────┘ │ ↓ y After: ┌─────────┐ x, target ────→│ Reshape │────→ y └─────────┘The intermediate value must be unshared. If the constant Reshape target uses copied zero dimensions, all such dimensions must precede the first changed axis so that they still refer to the same source dimensions.
Public Functions
-
inline explicit UnsqueezeOrSqueezeReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit UnsqueezeOrSqueezeReshapePattern(int priority = 0)#
-
class UnsqueezeReshapePattern : public onnx_light::core::builder::PatternOptimization#
- #include <reshape_pattern.h>
Collapses a specific Unsqueeze-Reshape sequence into one Unsqueeze.
Before: ┌───────────┐ x, axes=[2] ────→│ Unsqueeze │────→ t └───────────┘ │ ↓ ┌─────────┐ │ Reshape │←──── [0,1,-1,0] └─────────┘ │ ↓ y After: ┌───────────┐ x, axes=[1] ────→│ Unsqueeze │────→ y └───────────┘The source rank must be three and the intermediate Unsqueeze output must be unshared.
Public Functions
-
inline explicit UnsqueezeReshapePattern(int priority = 0)#
-
virtual std::set<std::string> FastOpType() const override#
Returns the invariant operator types from which this pattern can start. The optimization driver caches this value once per optimization.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Returns the match rooted at
candidate. A null pattern means no match.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Builds the replacement nodes for one match.
-
inline explicit UnsqueezeReshapePattern(int priority = 0)#
-
class ConcatReshapePattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Traditional ML
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class LabelEncoderFusionPattern : public onnx_light::core::builder::PatternOptimization#
- #include <label_encoder_pattern.h>
Composes two consecutive
ai.onnx.ml::LabelEncodermappings, including propagation of the first encoder’s default through the second encoder.The portable subset supports the standard string and int64 list attributes used by LabelEncoder versions 2 and 4.
Before: +------------------------------+ +------------------------------+ x -->| LabelEncoder(keys1, values1) |---->| LabelEncoder(keys2, values2) |---> y +------------------------------+ +------------------------------+ After: +-----------------------------------------+ x -->| LabelEncoder(composed keys and values) |---> y +-----------------------------------------+
Public Functions
-
inline explicit LabelEncoderFusionPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns LabelEncoder as the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a single-use pair with compatible list mappings and defaults.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the pair with the composed LabelEncoder.
-
inline explicit LabelEncoderFusionPattern(int priority = 0)#
-
class LabelEncoderFusionPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class TreeEnsemblePattern : public onnx_light::core::builder::PatternOptimization#
- #include <tree_ensemble_pattern.h>
Replaces classic TreeEnsembleRegressor and TreeEnsembleClassifier nodes with the unified ai.onnx.ml TreeEnsemble operator from opset 5.
Before (regressor): ┌───────────────────────┐ x ────→│ TreeEnsembleRegressor │────→ y └───────────────────────┘ After (regressor): ┌──────────────┐ x ────→│ TreeEnsemble │────→ y └──────────────┘ After (regressor with base values): ┌──────────────┐ x ────→│ TreeEnsemble │ └──────────────┘ │ ↓ ┌─────┐ base values ─→│ Add │────→ y └─────┘ Before (classifier): ┌────────────────────────┐ x ────→│ TreeEnsembleClassifier │────→ labels, scores └────────────────────────┘ After (classifier with integer labels): ┌──────────────┐ x ────→│ TreeEnsemble │────→ scores └──────────────┘ │ ↓ ┌────────┐ │ ArgMax │────→ indices └────────┘ │ ↓ ┌────────┐ labels ────→│ Gather │────→ labels output └────────┘ After (classifier with string labels): ┌──────────────┐ x ────→│ TreeEnsemble │────→ scores └──────────────┘ │ ↓ ┌────────┐ │ ArgMax │────→ indices └────────┘ │ ↓ ┌──────────────┐ │ LabelEncoder │────→ labels output └──────────────┘The rewrite applies to FLOAT ensembles already imported with ai.onnx.ml opset 5, using SUM aggregation and no post-transform. Classifier labels are reconstructed with ArgMax followed by Gather for integer labels or by LabelEncoder for string labels. Base values insert Add between TreeEnsemble and its final numeric output when the default-domain opset supports multidirectional broadcasting.
Public Functions
-
inline explicit TreeEnsemblePattern(int priority = 1)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns the two classic tree ensemble operators as possible roots.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a classic tree ensemble whose semantics are representable by opset 5.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the classic operator with TreeEnsemble and output adapter nodes.
-
inline explicit TreeEnsemblePattern(int priority = 1)#
-
class TreeEnsemblePattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Transpose
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class TransposeGatherPattern : public onnx_light::core::builder::PatternOptimization#
- #include <transpose_pattern.h>
Removes an unnecessary
Transposefeeding aGatherwith a scalar index.Before: ┌───────────────────┐ x ────→│ Transpose [2,0,1] │────→ t └───────────────────┘ │ ↓ ┌──────────────┐ │ Gather axis0 │←──── scalar k └──────────────┘ │ ↓ y After (remaining permutation is sorted): ┌──────────────┐ x, scalar k ────→│ Gather axis2 │────→ y └──────────────┘ After (remaining permutation is not sorted): ┌──────────────┐ x, scalar k ────→│ Gather axis2 │────→ g └──────────────┘ │ ↓ ┌─────────────────┐ │ Transpose [1,0] │────→ y └─────────────────┘When the remaining permutation is no longer sorted the rewrite gathers on the original tensor first and transposes the smaller result. For example,
Transpose(x,[1,2,0])followed by scalarGather(axis=1)becomesGather(x,axis=2)followed byTranspose([1,0]). The originalTransposeis preserved when its output is consumed elsewhere.Public Functions
-
inline explicit TransposeGatherPattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Gatheras the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Gatherwith a scalar index fed by a default-domainTranspose.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Rewrites the matched pair, swapping the
Transposepast theGather.
-
inline explicit TransposeGatherPattern(int priority = 0)#
-
class TransposeTransposePattern : public onnx_light::core::builder::PatternOptimization#
- #include <transpose_pattern.h>
Merges two
Transposenodes, optionally separated byIdentitynodes.Before: ┌───────────────────┐ x ────→│ Transpose [1,0,2] │────→ t └───────────────────┘ │ ↓ ┌───────────────────┐ │ Identity (0 or N) │ └───────────────────┘ │ ↓ ┌───────────────────┐ │ Transpose [0,2,1] │────→ y └───────────────────┘ After: ┌───────────────────┐ x ────→│ Transpose [1,2,0] │────→ y └───────────────────┘ After (identity composed permutation): ┌──────────┐ x ────→│ Identity │────→ y └──────────┘Intervening default-domain
Identitynodes are transparent to matching. When the composed permutation is the identity the chain is replaced by anIdentitynode. A prefix is preserved when an intermediate value is consumed elsewhere or exported; in that case the rewrite only applies when the composed permutation is the identity, so no additionalTransposeis introduced.Public Functions
-
inline explicit TransposeTransposePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Transposeas the only possible root operator.
-
inline virtual bool CanMatchInParallel() const noexcept override#
Enables reentrant matching using immutable nodes and structural index queries.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds default-domain
Transposenodes through optionalIdentitynodes.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched pair with a single
Transposeor anIdentity.
-
inline explicit TransposeTransposePattern(int priority = 0)#
-
class TransposeGatherPattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns
Unsqueeze
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_patterns
-
class SqueezeUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
- #include <unsqueeze_pattern.h>
Simplifies a
Squeeze/Unsqueezepair intoIdentityorSqueeze.Before: ┌───────────┐ x, axes=[1] ────→│ Unsqueeze │────→ t └───────────┘ │ ↓ ┌─────────┐ │ Squeeze │←──── axes=[1] └─────────┘ │ ↓ y After (matching axes): ┌──────────┐ x ────→│ Identity │────→ y └──────────┘ After (the following Squeeze removes additional axes): ┌─────────┐ x, adjusted axes ────→│ Squeeze │────→ y └─────────┘ The inverse Squeeze-then-Unsqueeze order is also matched.The two nodes must be a
Squeezeand anUnsqueeze(in either order). Equal axes collapse toIdentity(multiple axes must be contiguous). If the first node is anUnsqueezewhose axes are a strict subset of the followingSqueeze, the pair collapses to a singleSqueezeon the adjusted remaining axes; for example,Unsqueeze(x,[1])thenSqueeze([1,3])becomesSqueeze(x,[2]). The first node is preserved when its output is consumed elsewhere.Public Functions
-
inline explicit SqueezeUnsqueezePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
SqueezeandUnsqueezeas the possible root operators.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds a
Squeeze/Unsqueezepair feeding anUnsqueeze/Squeeze.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched pair with an
Identityor a singleSqueeze.
-
inline explicit SqueezeUnsqueezePattern(int priority = 0)#
-
class UnsqueezeUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
- #include <unsqueeze_pattern.h>
Merges two consecutive
Unsqueezenodes into a single one.Before: ┌───────────┐ x, axes=[1] ────→│ Unsqueeze │────→ t └───────────┘ │ ↓ ┌───────────┐ │ Unsqueeze │←──── axes=[0] └───────────┘ │ ↓ y After: ┌───────────┐ x, axes=[0,2] ────→│ Unsqueeze │────→ y └───────────┘Both
axesinputs must be scalar or one-dimensional non-negative constants. When one of the two nodes inserts more than one axis the rank of the source tensor must be known so the combined axes can be computed. The firstUnsqueezeis preserved when its output is consumed elsewhere.Public Functions
-
inline explicit UnsqueezeUnsqueezePattern(int priority = 0)#
Creates the pattern with the given optimization priority.
-
virtual std::set<std::string> FastOpType() const override#
Returns
Unsqueezeas the only possible root operator.
-
virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#
Finds an
Unsqueezefeeding another default-domainUnsqueeze.
-
virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#
Replaces the matched pair with a single
Unsqueeze.
-
inline explicit UnsqueezeUnsqueezePattern(int priority = 0)#
-
class SqueezeUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
-
namespace onnx_patterns