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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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::CreateRegisteredPatterns when the standard ONNX pattern set is required.

std::unique_ptr<core::builder::PatternOptimization> CreatePattern(const std::string &name, std::optional<int> priority = std::nullopt)#

Creates one standard ONNX pattern by registered name.

Registration is ensured before lookup. When priority is specified, it overrides the pattern default.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

Private Members

FunctionProto pattern_#
FunctionProto replacement_#
bool as_function_#
std::size_t anchor_index_#
std::vector<std::size_t> match_order_#

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

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

inline SameChildrenPattern(int priority, std::string name)#
core::builder::MatchResult MatchWithNodes(core::builder::GraphGraph &graph, const NodeProto &candidate, const std::vector<const NodeProto*> &next_nodes) const#

Protected Static Functions

static bool SameNode(const NodeProto &first, const NodeProto &second)#
static bool SameNodeWithAliases(const NodeProto &first, const NodeProto &second, const std::unordered_map<std::string, std::unordered_set<std::string>> &aliases)#
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.

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 a and b must 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.

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
       └───────────────────┘
              │
              ↓
              y

The 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 ───────→│             │
                      └─────────────┘

one must 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.

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
                         └─────────┘

c1 and c2 are 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.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 start is the constant zero, start2 is s and its Add is omitted. The Range and Add are replaced while the Add output y, 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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      indices

The Min variant sets largest=0. When keepdims=0, TopK produces temporary singleton-axis outputs and two Squeeze nodes restore the original values and indices output 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.

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
           └─────┘
              │
              ↓
              y

The reversed Sub operand order is retained. The five matched nodes become ReduceSum, Cast, Mul, and Sub nodes in T while preserving axes, scale, ReduceSum attributes, and the final output y. The matcher also accepts axes instead of xc as the reused Sub input; Apply replaces that reused input with x in 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class Sub1MulPattern : public onnx_light::core::builder::PatternOptimization#
#include <sub_pattern.h>

Rewrites multiplication by 1 - x into 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. one may come from an all-one ConstantOfShape when output-shape preservation is proven; z and the final output y are 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 V

The 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 scale and is_causal attributes, while the local scale_sqrt input is squared into the Attention scale attribute.

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.

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                      │
  └───────────────────────────────────────────────────────────────────────────┘
                                        │
                                        ↓
                                        Y

Key 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.

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                        │
              └───────────────────────────────────────────────────────────────────────────┘
                                                    │
                                                    ↓
                                                    Y

The four score paths and the three masking forms combine freely; each drawing shows one legal pairing. The additive form needs

Where(mask, zero, minus

infinity)

, 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 set transA=0, transB=1, and alpha=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.

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 │
   └────────────────────────────────┘
                   │
                   ↓
                  mask

Both 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.

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 │
   └─────────────────────────────────┘
                   │
                   ↓
                  mask

Both 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.

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            sine

The 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.

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 │
   └───────────────────────────────────┘
                   │
                   ↓
                   Y

X must 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 carries num_outputs=2 with 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 rebuilds Neg(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 requires intermediate opset 1 and throws BuilderError if 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.

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_state

The 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.

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                  │
  └─────────────────────────────────────────┘
                      │
                      ↓
                      y

The 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.

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                     │
└─────────────────────────────────────────────────────────┘
                             │
                             ↓
                             y

The rewrite requires opset 23, rank-four inputs, equal [*,1,*,*] caches doubled on the last axis, and a static head count that becomes num_heads. one is the constant [1] and ones the constant [1,1]. A partial rotation additionally sets rotary_embedding_dim from 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

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. If m has another consumer, the first Cast is retained for that consumer while y is still produced directly from x.

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 Cast as 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)#
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 R lose their Cast; other inputs gain one. The unary case follows the same transformation with a single input. If the original Op:C output is retained elsewhere, a Cast from z:R back to that output in C is 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.

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 Cast as 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 Clip as 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.

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 Clip as 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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:TensorProto and 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 Constant as 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 Conv as 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.

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 Conv as 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.

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 Conv as 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.

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 Conv as 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.

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 pads attribute 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 constant mode with a zero constant value, pads only the spatial dimensions, and the Conv does not use auto_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 Conv as 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.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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_mode input 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 Dropout as 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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-range Slice, an Expand with an all-one target shape of the input rank, and a half-precision inference BatchNormalization with scale/bias/mean/variance constants 1/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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 output m are also retained when m is 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 Not as 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 Pad as 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 becomes frame_step. A half spectrum selects onesided=1 and a full spectrum selects onesided=0. For frame lengths one and two, the coincident half/full bin counts are represented as onesided=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 Transpose as 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
namespace collections#

Functions

inline bool IsDefaultOp(const NodeProto &node, const char *op_type)#

Returns true when node is op_type from the default ONNX domain.

inline std::string FreeInitializerName(core::builder::GraphBuilder &builder, const std::string &base)#

Returns a fresh initializer name derived from base that is not already used by builder (without reserving it, so :ref:MakeInitializer can).

inline int64_t GetAxis(const NodeProto &node, int64_t default_value = 0)#

Returns the axis integer attribute of node or default_value.

inline bool ReadScalarInt(const TensorProto &tensor, int64_t &out)#

Reads the leading integer element of the scalar constant tensor into out. Returns false when 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class ConcatEmptyPattern : public onnx_light::core::builder::PatternOptimization#
#include <concat_pattern.h>

Removes Concat inputs that are empty along the concatenation axis.

An input is dropped when its inferred size along axis is exactly zero, so it contributes nothing to the output. When a single input remains the Concat becomes an Identity; otherwise a narrower Concat is emitted with the same axis.

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 e along 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 Concat as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a Concat with 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 an Identity) without the empty inputs.

class ConcatGatherPattern : public onnx_light::core::builder::PatternOptimization#
#include <concat_pattern.h>

Simplifies Gather(Concat(...), cst_index) when the index is a constant single-element int64 tensor and every Concat input is a 1-D tensor of a statically known size.

The pattern locates which Concat input holds the addressed element and replaces the Gather with an Identity (single-element input), a narrower Shape (input produced by a ranged Shape), or a Gather with 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 t has another consumer, the original Concat is 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 Gather as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a constant-index Gather over a fully-shaped Concat.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Rewrites the Gather against the located Concat input.

class ConcatSliceEliminationPattern : public onnx_light::core::builder::PatternOptimization#
#include <concat_pattern.h>

Removes a Concat whose consumers are exact, non-overlapping Slice nodes 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 Concat as 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.

class ConcatTwiceUnaryPattern : public onnx_light::core::builder::PatternOptimization#
#include <concat_pattern.h>

Pushes a shape-preserving unary operator through a Concat(x, x) so that Unary(Concat(x, x)) becomes Concat(Unary(x), Unary(x)), exposing the shared Unary(x) for common-subexpression elimination.

The rewrite requires opset >= 18, a two-input Concat whose inputs are the same value, and a consumer that is a shape-preserving unary op (or a broadcasting Mul / Add / Div / Sub / Unsqueeze with a constant scalar second input).

Before:
          ┌────────┐
  x, x ──→│ Concat │────→ t
          └────────┘

         ┌───────┐
  t ────→│ Unary │────→ y
         └───────┘

After:
         ┌───────┐
  x ────→│ Unary │────→ u
         └───────┘      │
                      ┌─┴─┐
                      │   │
                      ↓   ↓
                     ┌────────┐
                     │ Concat │────→ y
                     └────────┘

If t has 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 Concat as 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.

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 Concat as 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class GatherConcatPattern : public onnx_light::core::builder::PatternOptimization#
#include <gather_pattern.h>

Simplifies Gather(Concat(..., X, ..., axis=0), cst) into Gather(X, cst - offset) when exactly one Concat input X is non-constant, all others are constants of known size, X is 1-D, and every requested index falls inside X’s slice of the concatenation.

offset is the total size of the constant inputs preceding X.

Before:
                 ┌──────────────┐
  c0, X, c1 ────→│ Concat axis0 │────→ t
                 └──────────────┘
                        │
                        ↓
                   ┌──────────────┐
                   │ Gather axis0 │←──── indices=[2,4]
                   └──────────────┘
                        │
                        ↓
                        y

After:
                        ┌──────────────┐
  X, indices=[0,2] ────→│ Gather axis0 │────→ y
                        └──────────────┘

If t has another consumer, the original Concat is 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 Gather as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds an axis=0 constant-index Gather over a Concat.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Rewrites the Gather against the single non-constant Concat input.

class GatherGatherPattern : public onnx_light::core::builder::PatternOptimization#
#include <gather_pattern.h>

Composes two consecutive axis=0 Gather nodes with constant indices into a single Gather.

The inner indices cst1 must be a 1-D constant array and the outer indices cst2 a constant integer tensor; the fused indices are cst1[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 t has another consumer, the inner Gather is 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 Gather as 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=0 Gather nodes.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Replaces the pair with a single Gather on the composed indices.

class GatherToSlicePattern : public onnx_light::core::builder::PatternOptimization#
#include <gather_pattern.h>

Replaces a Gather selecting 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 equivalent Slice. Slice is generally cheaper to execute than Gather and, unlike Gather, it never triggers a data-dependent gather kernel.

A negative axis is normalized against the rank of x and 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-only Slice form has no steps input). The Slice uses the input form (with an axes initializer) 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 Squeeze of 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), so Slice alone reproduces the Gather output.

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 Gather as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a Gather whose 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 Gather into a Slice (plus Squeeze for a scalar index).

class GatherUpstreamPropagationPattern : public onnx_light::core::builder::PatternOptimization#
#include <gather_pattern.h>

Moves a scalar or vector constant-index Gather upstream 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.onnx domain 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 of 1 at 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-adaptation Squeeze is inserted).

  • Transpose: only a rank-preserving (vector-index) Gather is propagated, remapping the axis through perm. A scalar-index Gather directly downstream of a Transpose is intentionally left to :cpp:class:TransposeGatherPattern, which already rebuilds the perm for 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, as Reshape never redistributes elements across the boundary of an unrelated axis) and the shape constant either already spells 0 (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-0 entry, 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-index Gather on 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. Thus Gather(A @ B, indices, axis=-2) becomes Gather(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 change MatMul semantics. Both operands must have rank at least two; column and contracted dimensions are never gathered.

  • Softmax, LayerNormalization: only a rank-preserving (vector-index) Gather strictly before the operator’s own reduction axis is propagated to the (sole) data input; the reduction axis attribute 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 &#8212; resizing that producer would otherwise silently change a value some other part of the graph still relies on at the original size. The Gather index 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-index MatMul row 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 Gather as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a constant-index Gather fed 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 Gather onto the producer’s compatible inputs and rewrites the producer to output directly under the original Gather name.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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_#
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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class SequenceConstructAtPattern : public onnx_light::core::builder::PatternOptimization#
#include <sequence_pattern.h>

Replaces SequenceConstruct(x0, x1, ...) followed by the matching SequenceAt(seq, 0), SequenceAt(seq, 1), … with one Identity per SequenceAt, forwarding the original tensor directly.

The rewrite requires every consumer of the sequence to be a SequenceAt with a constant scalar index, and the indices to cover 0 .. n-1 exactly 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 SequenceConstruct as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a SequenceConstruct fully consumed by constant SequenceAt.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Replaces each SequenceAt with an Identity on the built tensor.

class SplitToSequenceSequenceAtPattern : public onnx_light::core::builder::PatternOptimization#
#include <sequence_pattern.h>

Replaces SplitToSequence(x, [split], axis=a) followed by the matching SequenceAt(seq, 0), SequenceAt(seq, 1), … with a single Split.

When keepdims=0, the replacement inserts a Squeeze on the split axis after every Split output to reproduce the corresponding SequenceAt result.

The indices of the SequenceAt consumers must be constant scalars that cover 0 .. n-1 exactly 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 split input, keepdims is ignored and the Split writes the SequenceAt outputs 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 SplitToSequence as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a SplitToSequence fully consumed by constant SequenceAt.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Replaces the sequence with a Split (and Squeeze when needed).

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class GatherShapePattern : public onnx_light::core::builder::PatternOptimization#
#include <shape_pattern.h>

Simplifies Gather(Shape(X), indices) into Shape(X, start, end) when indices is a constant int64 scalar or a contiguous ascending 1-D range.

The start / end attributes possibly carried by the original Shape node are folded into the new bounds. A scalar index yields a Shape followed by a Squeeze of 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]
              └─────────┘
                   │
                   ↓
                   y

For scalar index 1, the result is Squeeze(Shape(x,start=2,end=3),axes=[0]). If s has another consumer, the original Shape is 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 Gather as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a contiguous constant-index Gather over a Shape.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Rewrites the pair into a bounded Shape (plus Squeeze if scalar).

class PreShapeNodeEliminationPattern : public onnx_light::core::builder::PatternOptimization#
#include <shape_pattern.h>

Removes a Cast node whose output only feeds Shape consumers, redirecting each such Shape node directly to the Cast’s input.

Shape reports the input tensor’s dimensions and never depends on its element type, so a Cast immediately followed only by Shape nodes can be bypassed without changing any Shape output, for any opset. Because only the Shape node’s input is rewritten, its start / end attributes (available since opset 15), name, and metadata are preserved unchanged, and its rank / dimension reporting is unaffected. When the Cast output is also consumed elsewhere (another op, a graph output, or a subgraph capture), the Cast is retained for that use and only the matched Shape node is rewritten; it is dropped once its last Shape consumer 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 Cast as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a Cast whose output feeds at least one Shape node.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Rewrites the matched Shape node to read directly from the Cast’s input, keeping the Cast alive only if still needed elsewhere.

class ShapeTransposePattern : public onnx_light::core::builder::PatternOptimization#
#include <shape_pattern.h>

Replaces Shape(Transpose(X, perm)) by Gather(Shape(X), perm) so the expensive Transpose on 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]
       └──────────────┘
             │
             ↓
             y

The permutation is a compile-time attribute of the Transpose node, so the requested dimensions are read directly from Shape(X). The optional start / end attributes of the Shape node select the sub-range perm[start:end] used as the Gather indices. The Transpose is 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 Shape as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a Shape consuming the output of a Transpose with 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).

class UnsqueezeShapePattern : public onnx_light::core::builder::PatternOptimization#
#include <shape_pattern.h>

Replaces Shape(Unsqueeze(X, axes)) by a Concat of Shape(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)) equals Shape(X) with 1 entries inserted at the axes positions, so the (potentially large) Unsqueeze on the data tensor is avoided entirely while the shape vector stays identical. The axes input must be a one-dimensional constant and the rank of X must be known. The optional start / end attributes of the Shape node are honoured. The Unsqueeze is 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 Unsqueeze as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds an Unsqueeze whose output feeds a Shape node.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Rewrites the pair into a Concat of ranged Shape slices and [1]s.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 Slice as 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.

class SliceSlicePattern : public onnx_light::core::builder::PatternOptimization#
#include <slice_pattern.h>

Merges two consecutive Slice nodes acting on disjoint axes into a single Slice whose starts / ends / axes (and steps when present) are the concatenation of the two operand vectors.

The intermediate result must be consumed by the second Slice alone and both nodes must provide a constant axes input; a missing steps input 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 Slice as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a Slice fed by another Slice operating 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 Slice with concatenated inputs.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class GatherSliceToSplitPattern : public onnx_light::core::builder::PatternOptimization#
#include <split_pattern.h>

Replaces compatible sibling scalar Gather and contiguous Slice ranges covering a complete static axis with one Split. Scalar Gather outputs are restored with Squeeze.

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.

class GathersSplitPattern : public onnx_light::core::builder::PatternOptimization#
#include <split_pattern.h>

Merges several sibling Gather nodes reading consecutive constant indices 0, 1, ..., n-1 on the same axis of a common input into a single Split (followed by Squeeze nodes when the indices are scalars).

The axis dimension of the shared input must be statically equal to the number of gathers, so the Split reproduces 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 the Split writes yi directly without Squeeze nodes.

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 Gather as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds sibling Gather nodes 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 Gather nodes with a Split (plus Squeeze).

class SlicesSplitPattern : public onnx_light::core::builder::PatternOptimization#
#include <split_pattern.h>

Merges several sibling Slice nodes that partition a common input along a single axis into contiguous, non-overlapping ranges into one Split.

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_MAX sentinel 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
                        └───────┘────→ y2

Public Functions

inline explicit SlicesSplitPattern(int priority = 0)#

Creates the pattern with the given optimization priority.

virtual std::set<std::string> FastOpType() const override#

Returns Slice as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds sibling Slice nodes 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 Slice nodes with a single Split.

class SplitConcatPattern : public onnx_light::core::builder::PatternOptimization#
#include <split_pattern.h>

Replaces a Split immediately followed by a Concat that re-joins all of its outputs, in order and on the same axis, with a single Identity.

Before:
         ┌───────┐
  x ────→│ Split │
         └───────┘
                 │
            ┌────┴────┐
            │         │
            ↓         ↓
            s0        s1
            │         │
            ↓         ↓
            └────┬────┘
                 ↓
             ┌────────┐
             │ Concat │────→ y
             └────────┘

After:
         ┌──────────┐
  x ────→│ Identity │────→ y
         └──────────┘

The rewrite only fires when every Split output feeds the same Concat node, 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 Split as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a Split whose outputs are re-joined by a single Concat.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Replaces the matched Split/Concat pair with an Identity.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class ExpandBroadcastPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Drops an Expand feeding an element-wise binary operator.

Before:
            ┌────────┐
  x, S ────→│ Expand │
            └────────┘
                 │
                 ↓
            ┌────────┐
  z ───────→│ Binary │────→ y
            └────────┘

After:
           ┌────────┐
  x, z ───→│ Binary │────→ y
           └────────┘

S is constant, x and z have the same rank, and every aligned dimension is equal or one. The unshared Expand is removed because Op can broadcast x directly; 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 Expand as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds an Expand consumed 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.

class ExpandPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Removes an Expand that 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) with Identity(x) when the shape of x is fully known and equals the constant shape fed to Expand.

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 Expand as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds an Expand whose 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 Expand with Identity.

class ExpandSwapPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Moves an Expand past a following unary-like operator.

Before:
            ┌────────┐
  x, S ────→│ Expand │────→ e
            └────────┘
                 │
                 ↓
            ┌──────────┐
            │ UnaryOp  │←──── optional inputs
            └──────────┘
                 │
                 ↓
                 y

After:
         ┌──────────┐
  x ────→│ UnaryOp  │←──── optional inputs
         └──────────┘
              │
              ↓
         ┌────────┐
         │ Expand │←──── S
         └────────┘
              │
              ↓
              y

The Expand output must be unshared and Op must preserve the shape of its first input. Attributes and any additional inputs of Op are 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 Expand as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds an Expand consumed 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.

class ExpandUnsqueezeExpandPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Fuses Expand, Unsqueeze and Expand into Unsqueeze then Expand.

Before:
                ┌────────┐
  x, [2,3] ────→│ Expand │────→ e1
                └────────┘
                    │
                    ↓
              ┌───────────┐
              │ Unsqueeze │←──── axes=[1]
              └───────────┘
                    │
                    ↓
                ┌────────┐
                │ Expand │←──── [1,4,3]
                └────────┘
                    │
                    ↓
                    y

After:
                   ┌───────────┐
  x, axes=[1] ────→│ Unsqueeze │────→ u2
                   └───────────┘
                         │
                         ↓
                    ┌────────┐
                    │ Expand │←──── [2,4,3]
                    └────────┘
                         │
                         ↓
                         y

Both 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 Expand as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds Expand then Unsqueeze then Expand with constant shapes.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Emits Unsqueeze on the original tensor and a single trailing Expand.

class ShapeBasedConcatExpandPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Simplifies a dynamic Concat used as an Expand target shape.

Before:
                        ┌────────┐
  p0,...,pk,...,pn ────→│ Concat │────→ s
                        └────────┘
                            │
                            ↓
                       ┌────────┐
                       │ Expand │←──── x
                       └────────┘
                            │
                            ↓
                            y

After:
                        ┌────────┐
  [1],...,pk,...,[1] ──→│ Concat │────→ s2
                        └────────┘
                            │
                            ↓
                       ┌────────┐
                       │ Expand │←──── x
                       └────────┘
                            │
                            ↓
                            y

Every pi is a one-element vector. The known input and output shapes have equal rank and differ only at dimension k; pk is retained while all unchanged dimensions become 1 so 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 Expand as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds an Expand whose 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.

class ShapeBasedExpandBroadcastMatMulPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Removes dynamic Expand nodes before MatMul.

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 MatMul semantics. Shared Expand nodes 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 MatMul as 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.

class ShapeBasedExpandBroadcastPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Removes dynamic Expand nodes 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 a and b produces the shape of y. Either input may already be unexpanded. Shared Expand nodes 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.

class ShapeBasedExpandCastWhereSwapPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Moves an Expand after Cast and Where.

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 smaller Where broadcasts 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 Where as 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.

class ShapeBasedExpandSwapPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Moves input Expand nodes 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 Expand restores the original output shape. Shared input Expand nodes 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.

class ShapeBasedStaticExpandPattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Replaces a dynamic Expand target 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. The Expand remains, 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 Expand as 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.

class SwapExpandReshapePattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Swaps an Expand with a following constant-shape Reshape.

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]
                   └────────┘
                        │
                        ↓
                        y

x must have rank three, the Expand output must be unshared, and its inferred target value must end in [1,1]. This specialized form moves the fixed Reshape before 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 Reshape as 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.

class SwapExpandUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
#include <expand_pattern.h>

Swaps an Expand and a following Unsqueeze.

Before:
                ┌────────┐
  x, [A,B] ────→│ Expand │────→ e
                └────────┘
                    │
                    ↓
              ┌───────────┐
              │ Unsqueeze │←──── axes=[1]
              └───────────┘
                    │
                    ↓
                    y

After:
                   ┌───────────┐
  x, axes=[1] ────→│ Unsqueeze │────→ u
                   └───────────┘
                         │
                         ↓
                    ┌────────┐
                    │ Expand │←──── [A,1,B]
                    └────────┘
                         │
                         ↓
                         y

The axes are constant (opset 13 or later), the Expand output is unshared, and its target or output shape is known. The new target inserts a 1 at every normalized axis, letting Unsqueeze run 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 Expand as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds an Expand consumed by a single Unsqueeze with constant axes.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Emits the Unsqueeze first and re-expands its output.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class NotWherePattern : public onnx_light::core::builder::PatternOptimization#
#include <where_pattern.h>

Rewrites Where(Not(c), x, y) into Where(c, y, x).

Before:
          ┌─────┐
   c ────→│ Not │
          └─────┘
             │
             ↓
           ┌───────┐
   x, y ──→│ Where │────→ z
           └───────┘

After:
             ┌───────┐
  c, y, x ──→│ Where │────→ z
             └───────┘

The two branches are swapped. A shared Not is preserved for its other consumers while the replacement Where bypasses 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 Where as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a Where fed by a default-domain Not condition.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Swaps Where branches and removes or preserves the matched Not.

class UnsqueezeEqualPattern : public onnx_light::core::builder::PatternOptimization#
#include <where_pattern.h>

Moves Equal(x, c) after a compatible sibling Unsqueeze(x, a) and preserves the rank of Equal(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 c unless inferred shapes prove that Equal(x,c) preserves x’s rank. The local form requires equal pre-Unsqueeze ranks 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 Equal as 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/Unsqueeze topology.

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.

class WhereAddPattern : public onnx_light::core::builder::PatternOptimization#
#include <where_pattern.h>

Rewrites an additive mask or factors a common term from Where branches.

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 Where output and accepts either operand order for Add. The factoring form requires both branch Add outputs 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 Where as 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 Add branches sharing one input.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Emits the upstream Where or the local factored Where and Add.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class MulUnsqueezeUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
#include <layout_pattern.h>

Moves equal, unshared Unsqueeze operations after a Mul.

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.

class SqueezeAddPattern : public onnx_light::core::builder::PatternOptimization#
#include <layout_pattern.h>

Moves equal Squeeze operations after an Add.

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 0 for a [1] input). A Squeeze is 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.

class SqueezeBinaryUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
#include <layout_pattern.h>

Cancels a scalar-producing Squeeze/binary/Unsqueeze chain 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, or Sub. Its left input and output must be unshared, and the final Unsqueeze axis must be the scalar constant 0.

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.

class SwapUnsqueezeTransposePattern : public onnx_light::core::builder::PatternOptimization#
#include <layout_pattern.h>

Swaps an unshared Unsqueeze and Transpose, 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]
             └───────────┘
                    │
                    ↓
                    y

Public 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.

class TransposeEqualReshapePattern : public onnx_light::core::builder::PatternOptimization#
#include <layout_pattern.h>

Replaces a Transpose that only repositions size-one axes around at most one other dimension with a Reshape.

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.

class TransposeReshapeTransposePattern : public onnx_light::core::builder::PatternOptimization#
#include <layout_pattern.h>

Moves a constant Reshape across one of two adjacent Transpose nodes 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 Transpose is removed and the Reshape is moved before a remapped Transpose; the final Transpose and 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

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.

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.

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#
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_#
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.

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.

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 alpha attribute 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.

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.

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.

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 A and penultimate dimension of B must 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.

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
          └───────────────────┘

Layout is a Reshape or Transpose. 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.

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.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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 by 1 / 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 value 0.044708251953125; its usual value is 0.044715. The exponent, tanh scale, final offset, and input scale are respectively 3, 0.7978515625, 1, and 0.5. All decomposition intermediates must be unshared, and the configured default-domain opset minimum must be met.

Public Functions

inline explicit GeluPattern(int priority = 0, int min_opset = 20, 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.

Private Members

int min_opset_#
std::string domain_#
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_#
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.

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 uses ignore_index=-100 and reduction="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.

Private Members

int min_opset_#
std::string domain_#
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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

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.

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.

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.

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.

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.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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-Shape dynamic slot is replaced by [-1]; when all dynamic slots come from Shape, the last such slot is replaced. Dynamic inputs must each describe one dimension and the target may contain only one inferred dimension. A shared original Concat is 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.

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.

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.

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.

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
           └─────────┘
                │
                ↓
                y

The 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.

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 to s1, 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.

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.

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.

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. Expand additionally 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.

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.

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 -1 and exactly one dynamic input must have shape [1]. A shared original Concat is 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.

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.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class LabelEncoderFusionPattern : public onnx_light::core::builder::PatternOptimization#
#include <label_encoder_pattern.h>

Composes two consecutive ai.onnx.ml::LabelEncoder mappings, 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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

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.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class TransposeGatherPattern : public onnx_light::core::builder::PatternOptimization#
#include <transpose_pattern.h>

Removes an unnecessary Transpose feeding a Gather with 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 scalar Gather(axis=1) becomes Gather(x,axis=2) followed by Transpose([1,0]). The original Transpose is 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 Gather as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a Gather with a scalar index fed by a default-domain Transpose.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Rewrites the matched pair, swapping the Transpose past the Gather.

class TransposeTransposePattern : public onnx_light::core::builder::PatternOptimization#
#include <transpose_pattern.h>

Merges two Transpose nodes, optionally separated by Identity nodes.

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 Identity nodes are transparent to matching. When the composed permutation is the identity the chain is replaced by an Identity node. 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 additional Transpose is 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 Transpose as 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 Transpose nodes through optional Identity nodes.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Replaces the matched pair with a single Transpose or an Identity.

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_NAMESPACE so 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_proto uses hidden visibility by default.

Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal onnx namespace — rather than the ONNX_NAMESPACE macro — resolves to the onnx-light namespace. The standard onnx package lives in namespace onnx; onnx-light uses onnx_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 from onnx.

namespace onnx_patterns
class SqueezeUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
#include <unsqueeze_pattern.h>

Simplifies a Squeeze/Unsqueeze pair into Identity or Squeeze.

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 Squeeze and an Unsqueeze (in either order). Equal axes collapse to Identity (multiple axes must be contiguous). If the first node is an Unsqueeze whose axes are a strict subset of the following Squeeze, the pair collapses to a single Squeeze on the adjusted remaining axes; for example, Unsqueeze(x,[1]) then Squeeze([1,3]) becomes Squeeze(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 Squeeze and Unsqueeze as the possible root operators.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds a Squeeze/Unsqueeze pair feeding an Unsqueeze/Squeeze.

virtual utils::RepeatedProtoField<NodeProto> Apply(core::builder::GraphGraph &graph, const std::vector<const NodeProto*> &nodes) const override#

Replaces the matched pair with an Identity or a single Squeeze.

class UnsqueezeUnsqueezePattern : public onnx_light::core::builder::PatternOptimization#
#include <unsqueeze_pattern.h>

Merges two consecutive Unsqueeze nodes into a single one.

Before:
                   ┌───────────┐
  x, axes=[1] ────→│ Unsqueeze │────→ t
                   └───────────┘
                         │
                         ↓
                  ┌───────────┐
                  │ Unsqueeze │←──── axes=[0]
                  └───────────┘
                         │
                         ↓
                         y

After:
                     ┌───────────┐
  x, axes=[0,2] ────→│ Unsqueeze │────→ y
                     └───────────┘

Both axes inputs 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 first Unsqueeze is 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 Unsqueeze as the only possible root operator.

virtual core::builder::MatchResult Match(core::builder::GraphGraph &graph, const NodeProto &candidate) const override#

Finds an Unsqueeze feeding another default-domain Unsqueeze.

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.