compute_context.h#
Serialized rewrites preserve existing tags for retained values throughout tag seeding and inference, including results replaced by initializers. New value names still participate in inference; removed names lose their tags. This protection is scoped to rewriting and does not change ordinary tag propagation.
Memory timeline boundaries#
GraphBuilder maintains shapes, tags, lifetimes and reuse decisions during
construction, but does not compute memory or scratch profiles. Its
Compute().Memory() and Compute().PeakMemory() vectors remain empty.
ToGraph, ToModel and ToFunction compute profiles at export, including
nested graphs and local functions. A subsequent mutation discards those optional
profiles immediately, so callers never observe an outdated profile.
Standalone ComputeContext keeps its incremental behavior by default.
The explicit C++ MemoryProfiling::kExplicit constructor policy disables
automatic profiling during mutations without changing eager annotations;
RefreshIncrementalMemory and ComputePeakMemory explicitly compute the
requested profiles. No query triggers analysis.
ComputeContext::NodeMemory(i) (also Memory()[i]) exposes symbolic or
concrete before_bytes, during_bytes, after_bytes and
released_bytes scalars for every node, including the final node.
after_bytes is computed from the profiler’s retained allocations after
release decisions: transferring an in-place buffer to an output does not free
it, and a smaller output still owns the full reused allocation.
Call ComputeInPlaceReuseGraph after shape inference, then
ComputePeakMemory with the desired device (or use Compute).
during_bytes includes the worst-case scratch expression; released_bytes is
during_bytes - after_bytes and includes scratch deallocation, temporary
function-body allocations and unused outputs. Before scratch estimation the
scratch contribution is zero. Graph inputs protected from overwriting remain
in the retained count, as do retained initializers and graph outputs.
The existing already_allocated_bytes, output_allocation_bytes,
total_bytes and tagged buckets keep their original meaning.
Python exposes the same entries through node_memory / memory and the
NODE_MEMORY_BEFORE_BYTES_KEY, NODE_MEMORY_DURING_BYTES_KEY,
NODE_MEMORY_AFTER_BYTES_KEY and NODE_MEMORY_RELEASED_BYTES_KEY constants
in onnx_light.onnx_core.shape_inference.
NodePeakMemory(i) / Python node_peak_memory(i) return a
PeakMemoryEstimate with worst_case and optional average_case.
The Python fields are SymDim objects; .value() returns their integer or
expression string. Unknown scratch requirements remain unresolved symbols and
must be bounded before admitting execution against a memory budget.
For local functions, the maximum of average workspace estimates is not treated
as an average of the maximum; it is retained only when justified.
Export writes onnx_light.peak_memory_max and, when available,
onnx_light.peak_memory_average. The existing onnx_light.peak_memory
remains a positive concrete allocation hint for execution plans, not a complete
memory-budget guarantee. Recomputing estimates removes stale hints and averages.
Graph-level annotation context that combines value-tag inference, in-place reuse analysis, and per-node memory profiling.
:cpp:class:ComputeContext stores the results of all three analyses and exposes them in a single object, mirroring the way :cpp:class:core::shapes::ShapesContext stores inferred descriptors.
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace core
-
namespace compute#
Typedefs
-
using NodeMaterializerFn = std::function<void(NodeProto&)>#
Materializes builder-owned graph references in a temporary node for memory analysis.
-
using ComputeEventLog = std::vector<ComputeEvent>#
-
using ShapeTag = std::string#
Represents a per-node memory snapshot computed by :cpp:class:
ComputeContext.The snapshot represents the memory footprint visible while one node runs:
already_allocated_bytesis the sum of the buffers already alive before the node starts (declared inputs, initializers and still-live intermediates), after shape inference and lifetime analysis;output_allocation_bytesis the additional memory that must be allocated for the node’s outputs because no eligible in-place reuse opportunity covers them;total_bytesis their sum.
Four additional scalar entries expose execution boundaries, including the final node:
before_bytescounts live buffers before execution, excluding temporary function-body allocations;during_bytesistotal_bytesplus the node’s peak scratch estimate;after_bytescounts retained buffers after releases and scratch deallocation, using the same allocation ownership as the profiler;released_bytesisduring_bytes - after_bytes, including scratch, temporary function-body allocations and unused outputs. An in-place ownership transfer does not release the retained buffer.
Scratch is zero until :cpp:func:
ComputeContext::ComputePeakMemoryis called (or the incremental peak estimate is updated). Recomputing it updates the boundary entries without accumulating scratch.The profile is stored as a
std::mapwith eleven well-known keys:"total_bytes""already_allocated_bytes""output_allocation_bytes""before_bytes""during_bytes""after_bytes""released_bytes""inputs""initializers""intermediates""outputs"
The first seven keys map to scalar :cpp:type:
core::expressions::DimTypevalues. The other four keys map tostd::map<ShapeTag, DimType>buckets split by value tag ("shape","axes","weight", or the empty string for untagged values)."already_allocated_bytes"is the sum of the"inputs","initializers"and"intermediates"maps;"output_allocation_bytes"is the sum of"outputs"; and"total_bytes"is the sum of those two scalar entries. Every amount is represented as a :cpp:type:core::expressions::DimType, so symbolic shapes retain their expression form instead of being dropped. The"outputs"map only counts the extra allocations performed at this node; outputs that reuse an existing input buffer in place contribute no additional bytes there.
-
using TaggedMemory = std::map<ShapeTag, expressions::DimType>#
-
using NodeMemoryProfileValue = std::variant<expressions::DimType, TaggedMemory>#
-
using NodeMemoryProfile = std::map<std::string, NodeMemoryProfileValue>#
Enums
-
enum class ComputeEventAction : int32_t#
Kind of decision recorded in the optional :cpp:class:
ComputeContextdecision log.kInPlace— one output was matched to one input for in-place reuse.kRelease— one value reached its last use at a node and can be released after that node.kReleaseShapeTag— one released value was also classified as"shape"by value tagging.
Values:
-
enumerator kInPlace#
-
enumerator kRelease#
-
enumerator kReleaseShapeTag#
Functions
-
inline constexpr const char *ComputeEventActionName(ComputeEventAction action)#
Returns the short lowercase label for
action.
Variables
-
constexpr const char *kNodeMemoryTotalBytesKey = "total_bytes"#
-
constexpr const char *kNodeMemoryAlreadyAllocatedBytesKey = "already_allocated_bytes"#
-
constexpr const char *kNodeMemoryOutputAllocationBytesKey = "output_allocation_bytes"#
-
constexpr const char *kNodeMemoryBeforeBytesKey = "before_bytes"#
-
constexpr const char *kNodeMemoryDuringBytesKey = "during_bytes"#
-
constexpr const char *kNodeMemoryAfterBytesKey = "after_bytes"#
-
constexpr const char *kNodeMemoryReleasedBytesKey = "released_bytes"#
-
constexpr const char *kNodeMemoryInputsKey = "inputs"#
-
constexpr const char *kNodeMemoryInitializersKey = "initializers"#
-
constexpr const char *kNodeMemoryIntermediatesKey = "intermediates"#
-
constexpr const char *kNodeMemoryOutputsKey = "outputs"#
-
class ComputeContext#
- #include <compute_context.h>
Holds the in-place reuse opportunities computed for a graph, mirroring the way :cpp:class:
core::shapes::ShapesContextholds the inferred descriptors.The reuse guess is purely structural: it reports the opportunities implied by shape inference and value lifetimes, not whether a particular kernel actually performs the reuse. Populate the context with :cpp:func:
ComputeInPlaceReuseGraph(consuming a :cpp:class:ShapesContextalready filled by :cpp:func:ShapesContext::ComputeShapeGraphor :cpp:func:ShapesContext::ComputeShapeModel), then read the result through :cpp:func:Reuse/ :cpp:func:NodeReuseor persist it into the graph with :cpp:func:WriteToMetadata.Public Types
-
enum class MemoryProfiling#
Selects whether incremental mutations also maintain optional memory profiles.
Values:
-
enumerator kIncremental#
-
enumerator kExplicit#
-
enumerator kIncremental#
-
using CustomValueTagFn = std::function<void(ComputeContext&, const NodeProto&, std::size_t node_index)>#
Callback signature for custom value-tag behavior. Receives
(ctx, node, node_index)wherectxcan be mutated through :cpp:func:TrySetValueTag/ :cpp:func:SetNodeTag.
-
using CustomValueTagMap = std::unordered_map<std::string, CustomValueTagFn>#
-
using InputShapes = std::unordered_map<std::string, SymTensor>#
Map from value name to the :cpp:class:
SymTensordescribing its shape and element type, used to seed shape inference for a :cpp:class:FunctionProtoor a bare node list (neither of which carries declared input types).
Public Functions
-
inline explicit ComputeContext(MemoryProfiling profiling = MemoryProfiling::kIncremental)#
-
void ClearMemoryProfiles() noexcept#
Discards optional memory profiles without changing shapes, tags or lifetimes. Empty profile vectors explicitly indicate that no current profile is available.
-
inline bool IsValueTagPreserved(const std::string &name) const#
Returns whether a rewrite protects the existing tag of
name.
-
std::pair<std::unordered_map<std::string, std::string>, std::vector<std::string>> ComputeValueAndNodeTags(const GraphProto &graph)#
Infers semantic
shape/axes/weighttags for the values and nodes ingraphand stores the result in*this(replacing any previously computed tags).- Returns:
A pair
(value_tags, node_tags)wherevalue_tagsmaps value names to their inferred tag andnode_tagsfollows the order ofgraph.node().
-
std::pair<std::unordered_map<std::string, std::string>, std::vector<std::string>> ComputeValueAndNodeTags(const FunctionProto &function)#
Same as :cpp:func:
ComputeValueAndNodeTags(const GraphProto&)but for a function body.
-
std::pair<std::unordered_map<std::string, std::string>, std::vector<std::string>> ComputeValueAndNodeTags(const utils::RepeatedProtoField<NodeProto> &nodes)#
Same as :cpp:func:
ComputeValueAndNodeTags(const GraphProto&)but for an arbitrary node list.
-
void SeedValueTag(const std::string &name, const std::string &tag)#
Seeds an initial value tag for a graph input, initializer, value_info or output so it participates in the incremental tag inference driven by :cpp:func:
AppendNodeTags. Mirrors the seeding performed whole-graph by :cpp:func:CollectGraphSeedTags.
-
void SeedValueTag(const std::string &name, const std::string &tag, const utils::RepeatedProtoField<NodeProto> &nodes)#
Seeds a declaration added after nodes and propagates changed tags through the nodes that produce or consume its value.
-
void AppendNodeTags(const utils::RepeatedProtoField<NodeProto> &nodes, std::size_t node_index)#
Incrementally updates the value/node tags after the node at
node_index(the last node ofnodes) has been appended. Only that node and the nodes whose values it changes are (re)processed through a monotone worklist — no whole-graph loop — so appendingNnodes stays linear in the graph size instead of quadratic. The built-in inference rules converge to the same least fixed point as :cpp:func:ComputeValueAndNodeTags.
-
void RefreshValueTags(const utils::RepeatedProtoField<NodeProto> &nodes, const std::unordered_set<std::string> &changed_values)#
Refreshes tags of changed values and their producers and consumers.
-
inline const std::unordered_map<std::string, std::string> &ValueTags() const noexcept#
Read-only access to the last value-tag map computed through :cpp:func:
ComputeValueAndNodeTags.
-
inline const std::vector<std::string> &NodeTags() const noexcept#
Read-only access to the last per-node tag list computed through :cpp:func:
ComputeValueAndNodeTags.
-
inline TagState CaptureTagState() const#
Captures the current value and node tags for in-memory restoration.
-
void RestoreTagState(const TagState &state, const utils::RepeatedProtoField<NodeProto> &nodes, std::size_t node_offset = 0, const NodeMaterializerFn &materialize = {})#
Restores captured tags and refreshes affected release and memory metadata. The offset accounts for initializer Constants materialized in exported functions.
-
inline const std::string &NodeTag(std::size_t node_index) const#
Tag inferred for the node at
node_index.- Throws:
std::out_of_range – when
node_indexis out of bounds.
-
void SeedConstant(const std::string &name)#
Seeds
nameas a constant value (e.g. an initializer) so it participates in the incremental constant analysis driven by :cpp:func:AppendNodeConstant.
-
void AppendNodeConstant(const NodeProto &node, std::size_t node_index)#
Incrementally updates the constant analysis after the node at
node_indexhas been appended: records whether the node is constant and, when it is, marks its outputs as constant values. Appends exactly one entry to the per-node constant flag list.
-
inline bool IsConstantValue(const std::string &name) const noexcept#
Whether
nameis currently known to be a constant value.
-
void ComputeConstants(const GraphProto &graph)#
Recomputes constant values and per-node classifications for
graph.
-
inline const std::vector<ConstantInfo> &NodeConstant() const noexcept#
Read-only access to the incremental per-node constant classifications. One entry per appended node, in graph order.
-
inline bool NodeConstant(std::size_t node_index) const#
Whether the node at
node_indexproduces constant outputs.- Throws:
std::out_of_range – when
node_indexis out of bounds.
-
bool TrySetValueTag(const std::string &name, const std::string &tag)#
Sets or updates a value tag and returns
truewhen the internal map changed. Returnsfalsewhennameis empty, whentagis invalid/empty, when setting it would not change the map, or when a rewrite protects its existing tag.
-
bool SetNodeTag(std::size_t node_index, const std::string &tag)#
Sets or updates a per-node tag and returns
truewhen the internal list changed. Returnsfalsewhentagis invalid/empty or does not change the current value.- Throws:
std::out_of_range – when
node_indexis out of bounds.
-
inline void ClearCustomValueTagChangedFlag() noexcept#
Internal flag helpers used by value-tag inference around custom callbacks.
-
inline bool ConsumeCustomValueTagChangedFlag() noexcept#
-
inline void SetCustomValueTagFunction(const std::string &domain, const std::string &op_type, CustomValueTagFn fn)#
Registers or replaces a custom value-tag callback for
(domain, op_type).domain == ""is normalized toai.onnx.
-
inline const CustomValueTagFn *GetCustomValueTagFunction(const std::string &domain, const std::string &op_type) const#
Returns a pointer to the custom value-tag callback registered for
(domain, op_type), ornullptrif none is registered.
-
inline bool RemoveCustomValueTagFunction(const std::string &domain, const std::string &op_type)#
Removes the custom value-tag callback registered for
(domain, op_type).
-
inline void ClearCustomValueTagFunctions()#
Removes every custom value-tag callback.
-
inline const CustomValueTagMap &CustomValueTagFunctions() const noexcept#
Read-only access to all registered custom value-tag callbacks.
-
void ComputeInPlaceReuseGraph(const GraphProto &graph, const ShapesContext &ctx, bool allow_input_overwrite = false, const std::unordered_map<std::string, std::string> &value_tags = {})#
Guesses, for every node of
graph, which outputs may reuse which input buffers in place, using the shapes and element types already inferred intoctx, and stores the result in*this(replacing any previously computed result).- Parameters:
graph – Graph whose nodes are analysed, in topological order.
ctx – Shapes context already populated with the inferred descriptors for
graph(graph inputs, initializers, intermediates and outputs).allow_input_overwrite – When
false(the default), declared graph inputs are never offered as reusable buffers, so a caller’s input is never overwritten in place. Whentrue, a declared graph input may be reused like an intermediate (subject to the same lifetime and shape checks), allowing kernels to overwrite it.value_tags – Optional map from value name to tag string (
"shape","axes","weight"). When non-empty, values in the release list that carry the"shape"tag are also stored separately and exposed through :cpp:func:ReleaseAfterShapeTagged/ :cpp:func:NodeReleaseAfterShapeTagged, and written to :cpp:var:kReleaseAfterShapeTagMetadataKeyby :cpp:func:WriteToMetadata.
-
void ComputeInPlaceReuseGraph(const FunctionProto &function, const ShapesContext &ctx, bool allow_input_overwrite = false, const std::unordered_map<std::string, std::string> &value_tags = {})#
Analyses a function’s reuse, releases and memory without constructing a graph.
-
void SeedReuseInput(const std::string &name, bool is_graph_input, bool is_initializer, bool allow_input_overwrite)#
Seeds the incremental in-place-reuse lifetime state for a declared graph input (
is_graph_input) or initializer (is_initializer). Graph inputs are always protected from reuse;allow_input_overwrite=trueis rejected because incremental builders do not permit input shadowing.
-
void SeedReuseOutput(const std::string &name, const utils::RepeatedProtoField<NodeProto> &nodes, const ShapesContext &ctx)#
Seeds the incremental in-place-reuse lifetime state for a declared graph output: the value is kept alive and removed from the release / not-used lists of any earlier node that had treated it as releasable.
-
void AppendNodeReuse(const utils::RepeatedProtoField<NodeProto> &nodes, std::size_t node_index, const ShapesContext &ctx, const std::vector<std::string> &references)#
Incrementally updates the in-place reuse and release-after annotations after the node at
node_indexhas been appended, using the shapes already inferred intoctx.referencesincludes direct inputs and lexical captures of nested graphs. Only this node and the previous last-users of those values are touched — no whole-graph loop — via :cpp:func:ComputeSingleNodeReuse. Appends exactly one entry to each lifetime vector so they stay aligned with :cpp:func:Size.
-
void RefreshNode(const utils::RepeatedProtoField<NodeProto> &nodes, std::size_t node_index, const ShapesContext &ctx, const std::vector<std::string> &references, Device device, const NodeMaterializerFn &materialize = {})#
Refreshes one existing node after its nested references or inferred shapes changed, updating only lifetimes and profiles affected by it.
-
void RefreshNodes(const utils::RepeatedProtoField<NodeProto> &nodes, const std::map<std::size_t, std::vector<std::string>> &references, const ShapesContext &ctx, const std::unordered_set<std::string> &changed_values, Device device, const NodeMaterializerFn &materialize = {})#
Refreshes changed node references and descriptors as one batch. Preserves unchanged lifetimes, invalidates byte sizes for
changed_values, and recomputes affected reuse after shape propagation. Memory profiles are refreshed incrementally or discarded according to the profiling policy.
-
void UpdateNodes(const utils::RepeatedProtoField<NodeProto> &nodes, const std::vector<std::size_t> &old_indices, const std::vector<std::vector<std::string>> &references, const std::unordered_set<std::string> &changed_values, Device device, const NodeMaterializerFn &materialize = {})#
Reindexes retained annotations after node replacement. An index equal to the old node count denotes a new node. Refreshes only affected lifetimes, tags and constants, preserving existing value tags for retained names; descriptors are maintained by the caller.
-
void RemoveValue(const std::string &name)#
Forgets an initializer or node value removed by a graph mutation.
-
void RefreshIncrementalMemory(const utils::RepeatedProtoField<NodeProto> &nodes, const ShapesContext &ctx, Device device = Device::kUndefined, const NodeMaterializerFn &materialize = {})#
Refreshes memory profiles from the earliest node affected by incremental tag, lifetime, reuse, input, initializer, or output changes. Explicit-profiling contexts compute the complete profile when this is called.
-
void AppendNodePeakMemory(const NodeProto &node, std::size_t node_index, Device device = Device::kUndefined, const NodeMaterializerFn &materialize = {})#
Appends the peak-memory estimate for a newly appended node, using the shapes already inferred into the owned :cpp:class:
ShapesContext.
-
inline std::size_t Size() const noexcept#
Number of nodes for which reuse has been computed (one entry per node of the analysed graph, in
graph.node()order). Zero before :cpp:func:ComputeInPlaceReuseGraphhas been called.
-
inline const std::vector<std::string> &NodeReferences(std::size_t node_index) const#
Returns cached explicit and lexical inputs for a builder-owned node.
-
inline bool Empty() const noexcept#
truewhen no reuse has been computed yet.
-
inline const std::vector<std::vector<InPlaceReuse>> &Reuse() const noexcept#
Read-only access to the per-node reuse opportunities. Entry
ilists the opportunities discovered forgraph.node()[i]; nodes without any opportunity carry an empty list.
-
inline const std::vector<InPlaceReuse> &NodeReuse(std::size_t node_index) const#
Reuse opportunities discovered for the node at
node_index.- Throws:
std::out_of_range – when
node_indexis out of bounds.
-
inline const std::vector<std::vector<std::string>> &ReleaseAfterShapeTagged() const noexcept#
Read-only access to the per-node shape-tagged releasable values. When :cpp:func:
ComputeInPlaceReuseGraphwas called with a non-emptyvalue_tagsmap, this vector has one entry per node (same order asgraph.node()), and entryilists the names from therelease_afterlist that carry the"shape"value tag. WhenComputeInPlaceReuseGraphwas called withoutvalue_tags(or with an empty map), this vector is itself empty.
-
inline const std::vector<std::string> &NodeReleaseAfterShapeTagged(std::size_t node_index) const#
Shape-tagged releasable values for the node at
node_index.- Throws:
std::out_of_range – when
node_indexis out of bounds, or when :cpp:func:ComputeInPlaceReuseGraphwas called without value tags (in which case the vector is empty and every access is out of bounds).
-
inline const std::vector<NodeMemoryProfile> &Memory() const noexcept#
Read-only access to the per-node memory snapshots. Entry
idescribes the memory footprint observed while runninggraph.node()[i]. Explicit-profiling contexts leave this empty after mutations until analysis is requested.
-
inline const NodeMemoryProfile &NodeMemory(std::size_t node_index) const#
Memory snapshot for the node at
node_index.- Throws:
std::out_of_range – when
node_indexis out of bounds.
-
const ShapesContext &ComputeShapes(const GraphProto &graph)#
Runs shape inference on
graphand stores the resulting descriptors in the :cpp:class:ShapesContextowned by*this.- Parameters:
graph – Graph whose nodes are analysed, in topological order.
- Returns:
A reference to the owned :cpp:class:
ShapesContext, now populated.
-
const ShapesContext &ComputeShapes(const ModelProto &model, bool prefill_with_value_info_output = false)#
Runs shape inference on
model.graph()(also recording opset versions and local functions frommodel) and stores the resulting descriptors in the :cpp:class:ShapesContextowned by*this.- Parameters:
model – Model whose main graph is analysed.
prefill_with_value_info_output – Forwarded to :cpp:func:
ShapesContext::ComputeShapeModel.
- Returns:
A reference to the owned :cpp:class:
ShapesContext, now populated.
-
const ShapesContext &ComputeShapes(const FunctionProto &function, const InputShapes &input_shapes = {})#
Runs shape inference on the body of
functionand stores the resulting descriptors in the :cpp:class:ShapesContextowned by*this.A :cpp:class:
FunctionProtoonly names its inputs, so their shapes and element types must be supplied throughinput_shapes. Any input consumed by a node but absent frominput_shapes(and not produced by an earlier node) makes shape inference throwstd::invalid_argument.- Parameters:
function – Function whose nodes are analysed, in topological order.
input_shapes – Shapes/types for the function inputs, seeded into the owned :cpp:class:
ShapesContextbefore inference.
- Returns:
A reference to the owned :cpp:class:
ShapesContext, now populated.
-
const ShapesContext &ComputeShapes(const utils::RepeatedProtoField<NodeProto> &nodes, const InputShapes &input_shapes = {})#
Runs shape inference on the node list
nodesand stores the resulting descriptors in the :cpp:class:ShapesContextowned by*this.A bare node list has no declared inputs, so the shapes and element types of every value not produced by the list itself must be supplied through
input_shapes. Any input consumed by a node but absent frominput_shapes(and not produced by an earlier node) makes shape inference throwstd::invalid_argument.- Parameters:
nodes – Nodes analysed in topological order.
input_shapes – Shapes/types for the values consumed by
nodesbut not produced by them, seeded into the owned :cpp:class:ShapesContextbefore inference.
- Returns:
A reference to the owned :cpp:class:
ShapesContext, now populated.
-
inline const ShapesContext &Shapes() const noexcept#
Read-only access to the :cpp:class:
ShapesContextowned by*this. Empty until :cpp:func:ComputeShapes(or :cpp:func:Compute) has run.
-
inline ShapesContext &Shapes() noexcept#
Mutable access to the owned :cpp:class:
ShapesContext, allowing callers to seed it (opset versions, custom inference functions, …) before :cpp:func:ComputeShapes.
-
const std::vector<PeakMemoryEstimate> &ComputePeakMemory(const GraphProto &graph, Device device = Device::kUndefined)#
Computes the estimated peak scratch memory for every node of
graphusing the shapes already inferred into the owned :cpp:class:ShapesContext(via :cpp:func:ComputeShapes), storing one entry per node ingraph.node()order. Unknown bounds remain symbolic, never zero.- Parameters:
graph – Graph whose nodes are analysed, in topological order.
device – Logical device passed to the peak-memory dispatch function.
- Returns:
A reference to the stored per-node peak-memory vector.
-
const std::vector<PeakMemoryEstimate> &ComputePeakMemory(const FunctionProto &function, Device device = Device::kUndefined)#
Computes per-node peak scratch memory directly for a function.
-
inline const std::vector<PeakMemoryEstimate> &PeakMemory() const noexcept#
Read-only access to the per-node peak-memory estimates computed by :cpp:func:
ComputePeakMemory. Empty before it has been called.
-
inline const PeakMemoryEstimate &NodePeakMemory(std::size_t node_index) const#
Peak-memory estimate for the node at
node_index.- Throws:
std::out_of_range – when
node_indexis out of bounds.
-
void Compute(const GraphProto &graph, Device device = Device::kUndefined, bool allow_input_overwrite = false)#
Runs every analysis on
graphin order and stores all results in*this: shape inference (:cpp:func:ComputeShapes), value / node tagging (:cpp:func:ComputeValueAndNodeTags), in-place reuse together with the release-after and shape-tag classification (:cpp:func:ComputeInPlaceReuseGraph) and per-node peak memory (:cpp:func:ComputePeakMemory).Requires fixed-width dense tensor allocations and resolved shapes. Expressions in declared input dimensions remain symbolic; new unresolved output dimensions, strings, sparse and extended initializers are rejected. Local-function bodies are validated recursively. Graph-valued attributes are rejected because their internal allocations are not accounted for. Unlike this complete-analysis entry point, the lower-level reuse analysis permits partially inferred graphs for incremental graph construction. Concrete allocation products, live sums and tensor-plus-scratch totals must fit
int64_t; valid zero-byte allocations are preserved.- Throws:
std::invalid_argument – on unsupported or unresolved allocations or integer overflow.
- Parameters:
graph – Graph whose nodes are analysed, in topological order.
device – Logical device passed to the peak-memory dispatch function.
allow_input_overwrite – Forwarded to :cpp:func:
ComputeInPlaceReuseGraph.
-
void Compute(const ModelProto &model, Device device = Device::kUndefined, bool allow_input_overwrite = false, bool prefill_with_value_info_output = false)#
Same as :cpp:func:
Compute(const GraphProto&, ...)but seeds shape inference frommodel(opset versions and local functions) before analysingmodel.graph().
-
void WriteToGraph(GraphProto &graph) const#
Pushes every computed result into
graph: the inferred shapes are written intograph(value_info / outputs, via :cpp:func:ShapesContext::ApplyInferredShapesToGraph), the in-place / release / shape-tag information into nodemetadata_props(via :cpp:func:WriteToMetadata) and the per-node peak-memory estimates under :cpp:var:kNodePeakMemoryMaxMetadataKeyand the optional average key. Concrete positive maxima also refresh the legacy allocation hint.- Parameters:
graph – Graph whose value_info and node metadata are mutated in place; must be the same graph passed to :cpp:func:
Compute/ :cpp:func:ComputeInPlaceReuseGraph.
-
void WriteToFunction(FunctionProto &function) const#
Writes inferred value_info and computed node metadata directly into a function.
-
void WriteToModel(ModelProto &model) const#
Same as :cpp:func:
WriteToGraph(GraphProto&)applied tomodel.graph().
-
runtime::ExecutionPlan BuildExecutionPlan(GraphProto &graph) const#
Creates the :cpp:class:
runtime::ExecutionPlanderived from every result stored in*this. It first pushes the information intograph(see :cpp:func:WriteToGraph) and then builds the plan from the annotated graph, so the schedule is driven entirely by the analyses held by this context.
-
runtime::ExecutionPlan BuildExecutionPlan(ModelProto &model) const#
Same as :cpp:func:
BuildExecutionPlan(GraphProto&, ...)applied tomodel.graph().
-
inline void set_events_enabled(bool enabled) noexcept#
-
inline bool events_enabled() const noexcept#
-
inline const ComputeEventLog &Events() const noexcept#
Append-only log of decisions made by :cpp:func:
ComputeInPlaceReuseGraph.
-
inline ComputeEventLog &Events() noexcept#
-
inline void ClearEvents() noexcept#
Empties the decision log without touching computed results.
-
void WriteToMetadata(GraphProto &graph) const#
Records the computed opportunities into each node’s
metadata_propsofgraphunder :cpp:var:kInPlaceReuseMetadataKey, :cpp:var:kReleaseAfterMetadataKey, :cpp:var:kNotUsedAfterMetadataKey, and (when :cpp:func:ComputeInPlaceReuseGraphwas called with value tags) :cpp:var:kReleaseAfterShapeTagMetadataKey.For every node that has at least one in-place opportunity, a single metadata entry is added (or updated in place if the key already exists) whose value lists the opportunities as
output_index:input_index:kindtriplets separated by;(kindbeingequalorgreater).For every node that has releasable last-use inputs, one metadata entry is added (or updated in place) under :cpp:var:
kReleaseAfterMetadataKey; the value is a;-separated list of releasable names.For every node that has declared graph inputs / initializers reaching their last use, one metadata entry is added (or updated in place) under :cpp:var:
kNotUsedAfterMetadataKey; the value is a;-separated list of those names.When shape-tag information was provided to :cpp:func:
ComputeInPlaceReuseGraph, a further metadata entry is added under :cpp:var:kReleaseAfterShapeTagMetadataKeyfor every node that has at least one shape-tagged releasable value; the value is a;-separated list of those names.When names contain
;or%, all three name lists on that node percent-encode those characters and :cpp:var:kLifetimeNamesEncodingMetadataKeyis set to"percent". Unmarked metadata retains the legacy literal name representation.Nodes without in-place opportunities, without releasable names, and without last-use input/initializer names are left untouched.
graphmust be the same graph passed to :cpp:func:ComputeInPlaceReuseGraph, so that node indices line up with the stored result.
-
void Clear() noexcept#
Empties the stored result.
-
void ResetMetadata() noexcept#
Clears computed annotations and incremental bookkeeping while preserving shapes, registered custom tag callbacks, event configuration, and events.
Private Functions
-
void PropagateNodeTags(const utils::RepeatedProtoField<NodeProto> &nodes, const std::vector<int> &seeds, const std::vector<std::string> &initial_changes = {})#
-
void RefreshNodeReuse(const utils::RepeatedProtoField<NodeProto> &nodes, std::size_t index, const ShapesContext &ctx)#
-
void PrepareMemoryRefresh(const utils::RepeatedProtoField<NodeProto> &nodes, std::size_t end_exclusive)#
-
template<typename GraphOrFunction>
void ComputeInPlaceReuseGraphImpl(const GraphOrFunction &graph, const ShapesContext &ctx, bool allow_input_overwrite, const std::unordered_map<std::string, std::string> &value_tags, bool validate_allocations = false)#
-
template<typename GraphOrFunction>
void WriteToMetadataImpl(GraphOrFunction &graph) const#
-
const std::vector<PeakMemoryEstimate> &ComputePeakMemoryNodes(const utils::RepeatedProtoField<NodeProto> &nodes, Device device)#
-
void WritePeakMemoryToNodes(utils::RepeatedProtoField<NodeProto> &nodes) const#
Private Members
-
MemoryProfiling memory_profiling_#
-
std::vector<ConstantInfo> node_constant_#
-
bool custom_value_tags_changed_ = false#
-
CustomValueTagMap custom_value_tags_#
-
std::vector<std::vector<InPlaceReuse>> reuse_#
-
std::vector<NodeMemoryProfile> memory_#
-
bool memory_matches_shapes_ = false#
-
ShapesContext shapes_#
-
ComputeEventLog events_#
-
bool events_enabled_ = false#
-
std::unordered_map<std::string, expressions::DimType> incr_allocation_bytes_#
-
bool incr_memory_refresh_prepared_ = false#
Private Static Functions
-
struct TagState#
- #include <compute_context.h>
Stores exact incremental tags without copying shapes or graph definitions.
-
class ValueTagPreservationGuard#
- #include <compute_context.h>
Preserves existing value tags during a rewrite while allowing new tags to converge.
Public Functions
-
explicit ValueTagPreservationGuard(ComputeContext &context)#
-
~ValueTagPreservationGuard()#
-
ValueTagPreservationGuard(const ValueTagPreservationGuard&) = delete#
-
ValueTagPreservationGuard &operator=(const ValueTagPreservationGuard&) = delete#
Private Members
-
ComputeContext &context_#
-
explicit ValueTagPreservationGuard(ComputeContext &context)#
-
enum class MemoryProfiling#
-
struct ComputeEvent#
- #include <compute_context.h>
One entry of the optional :cpp:class:
ComputeContextdecision log.Public Members
-
ComputeEventAction action = ComputeEventAction::kInPlace#
Decision kind.
-
int64_t output_index = -1#
Output index for
kInPlacedecisions;-1otherwise.
-
int64_t input_index = -1#
Input index for
kInPlacedecisions;-1otherwise.
-
InPlaceReuseKind kind = InPlaceReuseKind::kEqual#
Match kind for
kInPlacedecisions.
-
ComputeEventAction action = ComputeEventAction::kInPlace#
-
using NodeMaterializerFn = std::function<void(NodeProto&)>#
-
namespace compute#
-
namespace core