graph_graph.h#

GraphGraph::Optimize captures ordered edits. Applying them belongs to GraphBuilder::ApplyRewritings, which returns a new builder and retains model metadata, shared function definitions and new opset imports. Existing imports cannot be changed; identical function definitions are reused and conflicting definitions with the same domain/name/overload are rejected unless a registered operator takes precedence. Registration uses normalized domain/name identity at the merged model opset and each local-function caller’s own imports, independently of function overload. Existing colliding definitions are retained unchanged unless explicitly replaced; captured body replacements remain replayable when a rewrite introduces a colliding domain. New declarations remain available for matching nonempty node overloads, but do not override the operator. Imported functions use a namespace independent of graph values and subgraphs; different domains and overloads may share a function name. Shape inference preserves those identities, including the overload on imported call nodes. Identity components escape percent signs and colons so a colon in a function name cannot be confused with an overload separator. Model-level imports include additions in nested graph scopes, while each function keeps its own imports.

Initializer calls run once before the edit removes their source constants. They may consume immutable initializers, new literals and preceding call outputs. Public graph inputs remain overridable and cannot be consumed as constants, including defaults introduced by literals or preceding calls in the same edit. Their flattened outputs and literal additions share one resulting initializer coordinate system. Preparation validates the complete reachable function tree before execution: inputs must be explicit, operations deterministic and backed by registered CPU implementations. Control flow, stateful/random operations, recursive calls (or nesting beyond 64 functions), graph-valued attributes and function attribute parameters are not supported for preparation. Ordinary added functions are not restricted to this preparation subset.

GraphGraph::Optimize records folded computations as shared, canonicalized functions rather than duplicate tensor payloads. Retained initializers keep their existing ownership during edits and internal metadata analysis; public graph exports retain value semantics. ApplyRewritings executes recipes once. Use the returned builder’s ToModel() to export functions and imports; BuildGraph() exports only its graph. Native constant folding skips operations shadowed by model-local functions, so it cannot disagree with function-first dispatch during replay. Serialized folding also excludes operations outside the preparation subset, including inference-mode Dropout, which remain ordinary added nodes. Optimization rejects a completed plan if a function introduced later would override a native operation already captured in an initializer recipe.

ApplyRewritings applies serialized edits directly to a new GraphBuilder, preserving the source builder. Added functions must be compatible with existing calls before any edit is applied: an incompatible signature or a conflicting function name raises an error rather than postponing validation or renaming the function, except for ignored registered-operator collisions. Identical definitions are reused after normalizing builder-generated annotations and imports. Each edit updates affected shapes and annotations in dependency order; the returned builder preserves recorded node positions and has up-to-date memory metadata.

Consecutive node-only edits in the same graph are coalesced when they replace original nodes at their first matched position. Live-rank queries translate sequential positions without rebuilding the node order for every record. Edits consuming previously added nodes, modifying initializers or renames, or replacing nested graphs end the batch. Coordinates, initializer conflicts and preparation eligibility are checked when applying each edit. Subgraph identities remain stable across edits even when their referencing nodes move.

Graph index and pattern-rewrite driver over a :cpp:class:core::builder::GraphBuilder.

:cpp:class:core::builder::GraphGraph owns an index over the builder nodes and applies graph-rewrite patterns directly to that builder. It rebuilds its index after every optimization iteration.

Nodes are identified by their address, so the index stores const NodeProto * and maps each to its position in :cpp:func:GraphBuilder::Nodes (this mirrors make_idn / id(node) in Python). The index tracks:

  • the producing node of every value (predecessors);

  • the consuming nodes of every value, deduplicated and in insertion order (successors);

  • the declared graph outputs;

  • the values captured by a nested subgraph from the enclosing scope, so a rewrite never deletes a producer a subgraph still relies on.

On top of the structural index the class also exposes the read-only value queries a pattern needs — shapes, element types and constants — drawing on the builder’s inferred information and constant analysis rather than re-implementing them. Constant-folding results are cached by value name because a name is assigned once and never reused.

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 core
namespace builder
class GraphGraph#
#include <graph_graph.h>

Index and rewrite driver over the nodes of a :cpp:class:GraphBuilder.

The referenced :cpp:class:GraphBuilder must outlive this object. Mutating the builder outside :cpp:func:Optimize invalidates the index.

Public Types

using DoNotRemovePredicate = std::function<bool(const NodeProto&)>#

Predicate that protects matching nodes from removal.

using OptimizationCallback = std::function<bool(const GraphGraph&, const MatchResult&)>#

Observes an eligible match and returns whether it may be applied.

Public Functions

explicit GraphGraph(GraphBuilder &builder)#

Builds the index with registered device-independent patterns. The builder must outlive the index; its device does not change this selection.

GraphGraph(GraphBuilder &builder, std::vector<std::unique_ptr<PatternOptimization>> patterns, DoNotRemovePredicate do_not_remove = {})#

Builds the index and uses the supplied patterns in their given order.

GraphGraph(GraphBuilder &builder, std::vector<std::shared_ptr<PatternOptimization>> patterns)#

Builds the index and shares ownership of the supplied patterns.

inline GraphBuilder &Builder() noexcept#

Returns the builder being indexed and optimized.

inline const GraphBuilder &Builder() const noexcept#

Returns the builder for read-only inspection.

const NodeProto *FirstPatternCandidate() const#

Returns the first node without unresolved attribute references, or nullptr.

void SetTargetDevice(symbolic::Device device)#

Sets a concrete target on this builder, its local functions and their subgraphs. Rejects conflicting existing devices before modifying any builder.

std::size_t Canonicalize(bool move_shape_and_size_nodes = true)#

Establishes canonical value names and export-stable Shape/Size ordering before capture.

RewritingProto Optimize(int max_iter = -1, OptimizationReport *report = nullptr, const ConstantFoldingOptions &folding_options = {}, bool remove_unused = true, const OptimizationCallback &callback = {}, bool parallel = false, bool canonicalize = false, bool move_shape_and_size_nodes = true)#

Applies patterns and cleanup passes until convergence.

Patterns are considered in ascending priority order. A negative max_iter selects max(node_count, 10) * priority_count. Replacement nodes whose inputs are all materialized constants are folded into initializers before cleanup, subject to folding_options. remove_unused=false disables unused-node and initializer cleanup. canonicalize=true explicitly establishes a cleaned reference before capture. By default, capture starts from the input graph. move_shape_and_size_nodes=true records metadata-reader hoisting after pattern optimization. It is enabled by default and reported separately. parallel=true matches candidates concurrently when the pattern’s CanMatchInParallel returns true. Python-defined patterns are evaluated sequentially, including in mixed native/Python pattern lists. Concurrent matchers may read the frozen structural index through NodeBefore, NextNodes, Predecessors, Successors, IsOutput, IsUsed, IsUsedMoreThanOnce, IsUsedBySubgraph, and Position. They must not mutate Builder or call SetComputedConstant. Other queries require their own thread-safety audit, including any lazy evaluation or cache writes in their dependencies. callback observes each eligible, disjoint match before its nodes are reserved, including matches in nested subgraphs. Returning false rejects that match without blocking other patterns. It does not intercept cleanup. The callback must not mutate the graph, patterns, or match, and must not retain references to the graph or matched nodes beyond the call.

Returns: Self-contained edits, global structural hashes and final simultaneous moves, replayable against the input graph, or its explicitly canonicalized reference when canonicalize=true.

inline const std::vector<std::shared_ptr<PatternOptimization>> &Patterns() const noexcept#

Returns the patterns owned by this graph optimizer.

const FunctionProto *FunctionBeforeOptimization(const std::string &domain, const std::string &name, const std::string &overload = "") const#

Returns a function captured before this optimization pass, or nullptr outside a pass. The definition remains valid only during the current pattern invocation.

const NodeProto *NodeBefore(const std::string &name) const#

Returns the node producing name, or nullptr when name is a graph input, an initializer or otherwise not produced by any node.

const std::vector<const NodeProto*> &NextNodes(const std::string &name) const#

Returns the nodes consuming name (in insertion order, deduplicated). Returns a reference to a shared empty vector when name is unused.

std::vector<const NodeProto*> Predecessors(const NodeProto &node) const#

Returns the nodes producing the inputs of node (its immediate predecessors in the data-flow graph), deduplicated and in input order. Inputs that are graph inputs or initializers contribute no predecessor.

std::vector<const NodeProto*> Successors(const NodeProto &node) const#

Returns the nodes consuming the outputs of node (its immediate successors in the data-flow graph), deduplicated and in output order.

bool IsOutput(const std::string &name) const#

Returns true when name is a declared graph output.

bool IsUsed(const std::string &name) const#

Returns true when name is consumed by a node, captured by a nested subgraph, or declared as a graph output.

bool IsUsedMoreThanOnce(const std::string &name) const#

Returns true when name is consumed by more than one node, captured by a nested subgraph, or declared as a graph output.

bool IsUsedBySubgraph(const std::string &name) const#

Returns true when name is captured by a nested subgraph from the enclosing scope.

bool IsInsideOperatorBody(const std::string &domain, const std::string &op_type) const#

Returns whether an enclosing operator body has the exact domain and operator type.

std::size_t Position(const NodeProto &node) const#

Returns the position of node in :cpp:func:GraphBuilder::Nodes. Throws :cpp:class:BuilderError when node is not part of the index.

bool HasShape(const std::string &name) const#

Returns true when the shape of name has been inferred.

const SymTensor &GetShape(const std::string &name) const#

Returns the inferred descriptor of name. Throws when it is unknown.

bool HasType(const std::string &name) const#

Returns true when the element type of name is known.

TensorType GetType(const std::string &name) const#

Returns the element type of name. Throws when it is unknown.

bool IsConstant(const std::string &name) const#

Returns true when name is a constant value (an initializer, a Constant output, or the output of a deterministic node whose inputs are all constant), as tracked by the builder’s constant analysis.

bool IsConstantScalar(const std::string &name, bool broadcast = false) const#

Returns true when name is a constant scalar.

A value is scalar when its shape is () or (1,). When broadcast is true a shape whose every dimension is 1 (e.g. (1, 1)) also qualifies. This overload does not compare the stored value.

bool IsConstantScalar(const std::string &name, double value, bool broadcast) const#

Returns true when name is a constant scalar equal to value.

The scalar-shape rules of the other overload apply; in addition the stored value must be readable and compare equal to value.

const TensorProto *GetComputedConstant(const std::string &name) const#

Returns the tensor value of the constant name, or nullptr when the value is not materialised as a :cpp:class:TensorProto (for example a Constant node using value_int / value_float, or a constant that has not been folded). Registered computed constants take precedence over the builder’s initializers and Constant node attributes. Deferred payloads are loaded on demand into an index-owned copy, without loading the source tensor or unrelated weights. Source validation failures propagate to the caller, including during parallel matching.

const TensorProto *GetConstantMetadata(const std::string &name) const#

Returns the constant declaration without loading its deferred payload. Shape/type-only queries and size guards should use this method before requesting values through :cpp:func:GetComputedConstant.

const GraphGraph *GetConstantScope(const std::string &name) const#

Returns the scope providing a materialized constant, or nullptr when no visible definition exists. Local definitions never resolve to outer values.

void SetComputedConstant(const std::string &name, TensorProto value)#

Records a folded constant value for name so later queries can read it through :cpp:func:GetComputedConstant. A name is assigned once and never reused, so the cached value stays valid for the lifetime of the index.

Private Types

using OriginalFunctions = std::unordered_map<std::string, const FunctionProto*>#

Private Functions

std::size_t CanonicalizeImpl(bool &reference_changed, bool move_shape_and_size_nodes = true)#
void Rebuild()#
void RebuildSuccessors()#
std::size_t Cleanup(utils::RepeatedProtoField<LocalRewritingProto> &rewrites, bool remove_unused, detail::RewritingUndoState &undo)#
bool ConstantShape(const std::string &name, std::vector<int64_t> &dims) const#
bool ConstantScalarValue(const std::string &name, double &out) const#
bool IsVisibleBefore(const std::string &name, std::size_t position_limit) const#
GraphGraph(GraphBuilder &builder, const std::vector<std::shared_ptr<PatternOptimization>> &patterns, DoNotRemovePredicate do_not_remove, const GraphGraph *parent_graph, std::size_t parent_position_limit, const OriginalFunctions *original_functions = nullptr)#
RewritingProto OptimizeImpl(int max_iterations, OptimizationReport *report, const std::vector<std::string> &graph_path, const ConstantFoldingOptions &folding_options, bool remove_unused, RewritingProto &collection, detail::RewritingUndoState &undo, const OptimizationCallback &callback, bool parallel, const std::unordered_set<std::string> &function_only_callers, bool outermost_invocation)#

Private Members

GraphBuilder &builder_#
std::vector<std::shared_ptr<PatternOptimization>> patterns_#
DoNotRemovePredicate do_not_remove_#
const GraphGraph *parent_graph_ = nullptr#
std::size_t parent_position_limit_ = 0#
const OriginalFunctions *original_functions_ = nullptr#
const NodeProto *first_pattern_candidate_ = nullptr#
std::unordered_map<std::string, const NodeProto*> predecessors_#
std::unordered_map<std::string, std::vector<const NodeProto*>> successors_#
std::unordered_map<const NodeProto*, std::size_t> positions_#
std::unordered_set<std::string> output_names_#
std::unordered_set<std::string> subgraph_captured_#
std::unordered_map<std::string, const TensorProto*> initializers_#
std::unordered_map<std::string, TensorProto> computed_constants_#
mutable std::mutex materialized_constants_mutex_#
mutable std::unordered_map<std::string, TensorProto> materialized_constants_#