shapes_context.h#
Name → :cpp:class:OptimTensor map shared by all onnx_optim shape-inference functions.
ShapesContext is the in/out parameter consumed and produced by the per-operator ComputeShape* functions (for example :cpp:func:ComputeShapeAbs). It holds the :cpp:class:OptimTensor descriptors of every named value (graph input, initializer or intermediate result) currently known to a shape-inference pass. ComputeShape* functions read the entries corresponding to a node’s inputs and insert new entries for the node’s outputs.
-
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.
Defined as empty because onnx-light does not require explicit
__declspec(dllexport)or__attribute__((visibility("default")))annotations — visibility is controlled at the shared-library level. The macro is provided so that vendored ONNX headers that decorate their declarations withONNX_APIcompile without modification.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_optim
-
namespace shapes
Typedefs
-
using ShapeEventLog = std::vector<ShapeEvent>#
Append-only log of shape-inference events recorded by :cpp:class:
ShapesContext.
Enums
-
enum class ShapeEventAction : int32_t#
Kind of shape-inference event recorded in the :cpp:class:
ShapesContextevent log. Mirrors the runtime :cpp:enum:onnx_kernels::RuntimeEventActiondesign.kAdd— a new tensor descriptor was inserted via :cpp:func:ShapesContext::Seton a previously absent name.kReplace— an existing tensor descriptor was overwritten via :cpp:func:ShapesContext::Set.kComputeNode— shape inference was dispatched for a single :cpp:class:NodeProto. The event records the node’sop_domain/op_typeand the list ofinputsit consumed. It does not mutate the tensor map by itself.kConstraint— a new symbolic-dimension equality constraint (a == b) was recorded via :cpp:func:ShapesContext::AddConstraint. The two operands are stored ininputs.kConstraintMax— a new symbolic-dimension upper-bound constraint (lhs <= rhs) was recorded via :cpp:func:ShapesContext::AddLessEqualConstraint. The two operands are stored ininputs.
Values:
-
enumerator kAdd#
-
enumerator kReplace#
-
enumerator kComputeNode#
-
enumerator kConstraint#
-
enumerator kConstraintMax#
Functions
-
const char *ShapeEventActionName(ShapeEventAction action) noexcept#
Returns a short lowercase label for
action("add","replace","compute_node"). Useful for human-readable rendering of the event log.
Variables
-
constexpr int kUnknownOpsetVersion = -1#
Sentinel value returned by :cpp:func:
ShapesContext::OpsetVersionwhen no opset version has been recorded for the requested domain.
-
struct ShapeEvent#
- #include <shapes_context.h>
Single entry of the :cpp:class:
ShapesContextevent log.Each insertion or replacement of a tensor descriptor performed through :cpp:func:
ShapesContext::Setproduces oneShapeEventcapturing the action, the name of the value and a snapshot of the descriptor’s element type and shape. Because shape inference works on descriptors rather than data, no element values are captured; theshapeis recorded as a list of per-dimension strings so symbolic dimensions ("N","2*N") are preserved alongside concrete integer dimensions.:cpp:enumerator:
ShapeEventAction::kComputeNodeevents instead summarise the dispatch of a singleNodeProto: they carry the node’sop_domain/op_typeand the list ofinputsconsumed;data_typeis set toDataType::UNDEFINEDandshapeis left empty.:cpp:enumerator:
ShapeEventAction::kConstraint/ :cpp:enumerator:ShapeEventAction::kConstraintMaxevents record a newly inserted symbolic-dimension constraint; the two operands are stored ininputs({a, b}for an equalitya == b,{lhs, rhs}for an upper boundlhs <= rhs).Public Members
-
ShapeEventAction action = ShapeEventAction::kAdd#
Kind of event recorded by this entry.
-
int32_t data_type = 0#
Element data type of the descriptor at the moment of the event, encoded as a
TensorProto::DataTypeinteger value. Set toDataType::UNDEFINEDforkComputeNode/kConstraint/kConstraintMaxevents.
-
std::vector<std::string> shape#
Descriptor shape at the moment of the event, with each dimension rendered as a string (a decimal integer for concrete dims, the symbolic expression otherwise). Empty for
kComputeNode/kConstraint/kConstraintMaxevents.
-
std::string op_domain#
For
kComputeNodeevents: ONNX op domain of the dispatched node, normalised so the default domain is reported as"ai.onnx". Empty for other events.
-
std::string op_type#
For
kComputeNodeevents: ONNXop_typeof the dispatched node. Empty for other events.
-
std::vector<std::string> inputs#
For
kComputeNodeevents: ordered list of input names consumed by the node, matchingNodeProto::input. ForkConstraint/kConstraintMaxevents: the two constraint operands ({a, b}or{lhs, rhs}). Empty forkAdd/kReplaceevents.
-
int64_t node_index = -1#
Index of the node this event is associated with. For graph inputs it is
-1and for initializers it is-2. For intermediate / output descriptors and forkComputeNode/kConstraint/kConstraintMaxevents it is the position (>= 0) of the producing / dispatched node in its graph node list.-1when no producing node is known.
-
int64_t subgraph_node_index = -1#
Index of the control-flow node in the parent graph whose attribute subgraph produced this event.
-1for events from the top-level graph. Combined with :cpp:var:subgraph_attr_namethis uniquely identifies which operator and which attribute subgraph an event originated from.
-
ShapeEventAction action = ShapeEventAction::kAdd#
-
class ShapesContext#
- #include <shapes_context.h>
Lightweight container shared by the per-operator
ComputeShape*shape-inference functions.ShapesContextcarries two pieces of information:a
name → OptimTensormap describing every named value (graph input, initializer or intermediate result) currently known to the shape-inference pass;a
name → OptimSequencemap describing every named sequence-typed value (the output ofSequenceConstruct,SequenceEmpty,SplitToSequence, …);a
domain → opset_versionmap mirroring theopset_importentries of the surroundingModelProto, so thatComputeShape*functions can pick the correct schema revision when shape inference depends on the operator’s opset version.
The context is a thin wrapper and does not own any tensor data: the :cpp:class:
OptimTensorvalues stored here are themselves non-owning views.Public Types
-
using CustomComputeShapeFn = std::function<void(ShapesContext&, const NodeProto&)>#
-
using CustomShapeInferenceMap = std::unordered_map<std::string, CustomComputeShapeFn>#
-
using SubgraphContextKey = std::pair<int64_t, std::string>#
Key identifying a child :cpp:class:
ShapesContextretained while inferring a control-flow node’s attribute subgraph: the index of the control-flow node in this context’s graph paired with the name of the attribute carrying the subgraph ("body"for :onnx:Loop/ :onnx:Scan,"then_branch"/"else_branch"for :onnx:If).
Public Functions
-
ShapesContext() = default#
-
inline void Set(const std::string &name, OptimTensor &&tensor)#
Inserts or replaces the descriptor for
name.tensoris consumed; callers must pass an rvalue (usestd::move). When event logging is enabled (see :cpp:func:set_events_enabled) a :cpp:class:ShapeEventdescribing the new state is appended to the event log — with action :cpp:enumerator:ShapeEventAction::kAddwhennamewas absent and :cpp:enumerator:ShapeEventAction::kReplaceotherwise.
-
inline void Set(const char *name, OptimTensor &&tensor)#
Overload:
namegiven as a null-terminated C string.
-
inline void Set(const utils::String &name, OptimTensor &&tensor)#
Overload:
namegiven as a :cpp:class:utils::String.
-
inline bool Has(const utils::String &name) const#
Overload:
namegiven as a :cpp:class:utils::String.
-
inline const OptimTensor &Get(const std::string &name) const#
Returns the descriptor for
name. Throwsstd::out_of_rangeif no such entry exists.
-
inline const OptimTensor &Get(const utils::String &name) const#
Overload:
namegiven as a :cpp:class:utils::String.
-
inline bool Empty() const noexcept#
truewhen no entries are stored.
-
inline void Clear() noexcept#
Removes every entry (both tensor descriptors and opset versions).
-
inline const std::string &TopKKDimName(const std::string &k_input_name)#
Returns (and records) the symbolic dimension name to use for the TopK output axis driven by the K input named
k_input_name. The first unique K input seen returns"TopK_k"; each subsequent distinct K input gets"TopK_k_2","TopK_k_3", and so on. Calling this method twice with the samek_input_namealways returns the same string.
-
inline const std::unordered_map<std::string, OptimTensor> &Tensors() const noexcept#
Read-only access to the underlying map (useful for iteration).
-
inline void SetSequence(const std::string &name, OptimSequence &&sequence)#
Inserts or replaces the descriptor for a sequence-typed value named
name.sequenceis consumed; callers must pass an rvalue (usestd::move).
-
inline void SetSequence(const char *name, OptimSequence &&sequence)#
Overload:
namegiven as a null-terminated C string.
-
inline void SetSequence(const utils::String &name, OptimSequence &&sequence)#
Overload:
namegiven as a :cpp:class:utils::String.
-
inline bool HasSequence(const std::string &name) const#
Returns
truewhen a sequence-typed entry exists forname.
-
inline bool HasSequence(const utils::String &name) const#
Overload:
namegiven as a :cpp:class:utils::String.
-
inline const OptimSequence &GetSequence(const std::string &name) const#
Returns the sequence descriptor for
name. Throwsstd::out_of_rangeif no such entry exists.
-
inline const OptimSequence &GetSequence(const utils::String &name) const#
Overload:
namegiven as a :cpp:class:utils::String.
-
inline std::size_t SequencesSize() const noexcept#
Number of sequence-typed entries currently stored.
-
inline const std::unordered_map<std::string, OptimSequence> &Sequences() const noexcept#
Read-only access to the underlying sequence map (useful for iteration).
-
void RegisterSubgraphContext(int64_t node_index, const std::string &attr_name, ShapesContext context)#
Retains the child context
contextproduced while inferring the subgraphattr_nameof the control-flow node atnode_indexso that the subgraph’s internal descriptors stay inspectable once the parent inference has completed.contextis consumed (moved into the store). Any context previously registered for the same key is replaced.
-
inline bool HasSubgraphContext(int64_t node_index, const std::string &attr_name) const#
Returns
truewhen a child context was registered for the subgraphattr_nameof the control-flow node atnode_index.
-
inline const ShapesContext &GetSubgraphContext(int64_t node_index, const std::string &attr_name) const#
Returns the child context registered for the subgraph
attr_nameof the control-flow node atnode_index. Throwsstd::out_of_rangeif no such context exists.
-
inline const std::map<SubgraphContextKey, std::shared_ptr<ShapesContext>> &SubgraphContexts() const noexcept#
Read-only access to the retained child-context map (useful for iteration).
-
inline void ClearSubgraphContexts() noexcept#
Empties the retained child-context map without modifying other context state (tensor / sequence descriptors, opsets, constraints, events, …).
-
inline void SetOpsetVersion(const std::string &domain, int opset_version)#
Records the opset version of
domain. An emptydomainis normalised to :cpp:var:kOnnxDomain. Replaces any previous entry for the same domain.
-
inline bool HasOpsetVersion(const std::string &domain) const#
truewhen an opset version has been recorded fordomain(after normalising the empty domain to :cpp:var:kOnnxDomain).
-
inline int OpsetVersion(const std::string &domain) const#
Returns the recorded opset version of
domain, or :cpp:var:kUnknownOpsetVersionif none was recorded. An emptydomainis normalised to :cpp:var:kOnnxDomain.
-
inline const std::unordered_map<std::string, int> &Opsets() const noexcept#
Read-only access to the underlying
domain → opset_versionmap.
-
inline void SetLocalFunction(const FunctionProto *func)#
Registers a non-owning pointer to a model-local :cpp:class:
FunctionProto. The pointer must remain valid for the lifetime of the shape-inference pass. Replaces any previous entry registered under the same"<domain>:<name>"key.funcmust not benullptr.
-
inline bool HasLocalFunction(const std::string &key) const#
truewhen a model-local function is registered forkey.keyis expected to be the"<domain>:<name>"identifier of the function.
-
inline const FunctionProto *GetLocalFunction(const std::string &key) const#
Returns the registered
FunctionProtopointer forkey, ornullptrwhen none is registered.keyis expected to be the"<domain>:<name>"identifier of the function.
-
inline const std::unordered_map<std::string, const FunctionProto*> &LocalFunctions() const noexcept#
Read-only access to the underlying
"<domain>:<name>" → FunctionProto*map.
-
inline void SetCustomShapeInferenceFunction(const std::string &domain, const std::string &op_type, CustomComputeShapeFn fn)#
Registers or replaces a custom shape-inference callback for the
(domain, op_type)pair.domain == ""is normalized to :cpp:var:kOnnxDomain.
-
inline const CustomComputeShapeFn *GetCustomShapeInferenceFunction(const std::string &domain, const std::string &op_type) const#
Returns a pointer to the custom shape-inference callback registered for
(domain, op_type), ornullptrif none is registered.domain == ""is normalized to :cpp:var:kOnnxDomain.
-
inline bool RemoveCustomShapeInferenceFunction(const std::string &domain, const std::string &op_type)#
Removes the custom shape-inference callback registered for
(domain, op_type).domain == ""is normalized to :cpp:var:kOnnxDomain. Returnstruewhen an entry was removed andfalsewhen no callback matched that key.
-
inline void ClearCustomShapeInferenceFunctions()#
Removes every custom shape-inference callback.
-
inline const CustomShapeInferenceMap &CustomShapeInferenceFunctions() const noexcept#
Read-only access to all registered custom shape-inference callbacks.
-
inline bool AddConstraint(const std::string &a, const std::string &b)#
Records that two symbolic dimension names are equal. The pair is canonicalised so that
(a, b)and(b, a)are stored only once, and the trivial self-equality is dropped. Returnstruewhen a new constraint was inserted,falseotherwise (either a duplicate or a self-constraint).
-
inline bool HasConstraint(const std::string &a, const std::string &b) const#
truewhen an equality constraint betweenaandbis recorded (canonical order is applied before lookup).
-
inline const std::set<Constraint> &Constraints() const noexcept#
Read-only access to the underlying set of equality constraints. Each element is a
(lhs, rhs)pair withlhs < rhs.
-
inline bool AddLessEqualConstraint(const std::string &lhs, const std::string &rhs)#
Records that the symbolic dimension named
lhsis less-than-or-equal-to the expressionrhs. The trivial self-bound (lhs == rhs) is dropped, and empty operands are rejected (they cannot designate a valid dimension name nor a well-formed bound expression). Returnstruewhen a new constraint was inserted,falseotherwise (duplicate, self-bound, or empty operand).
-
inline bool HasLessEqualConstraint(const std::string &lhs, const std::string &rhs) const#
truewhen alhs <= rhsconstraint is recorded.lhs == rhsalways returnstrue.
-
inline const std::set<LessEqualConstraint> &LessEqualConstraints() const noexcept#
Read-only access to the underlying set of
<=constraints. Each element is an ordered(lhs, rhs)pair meaninglhs <= rhs.
-
void ComputeShapeNode(const NodeProto &node)#
Dispatches a single
NodePrototo the matching per-operatorComputeShape*function and stores the resulting output :cpp:class:OptimTensordescriptors in*this.
-
void CheckInputsAvailable(const NodeProto &node) const#
Throws
std::invalid_argumentif any non-empty input name declared bynodeis missing from*this.
-
void CheckOutputsNotAvailable(const NodeProto &node) const#
Throws
std::invalid_argumentif any non-empty output name declared bynodealready has an entry in*this.
-
void ComputeShapes(const utils::RepeatedProtoField<NodeProto> &nodes)#
Runs :cpp:func:
ComputeShapeNodeon every node ofnodesin order.
-
void ComputeShapeGraph(const GraphProto &graph)#
Seeds
*thisfrom the initializers and inputs ofgraphand then runs :cpp:func:ComputeShapeson its nodes.
-
void ComputeShapeModel(const ModelProto &model, bool prefill_with_value_info_output = false)#
Runs shape inference on
model.graph(), also recording opset versions and local functions frommodel.
-
void ApplyInferredShapesToGraph(GraphProto &graph) const#
Writes the shape and element-type descriptors stored in
*thisback intograph.
-
void ApplyInferredShapesToModel(ModelProto &model) const#
Writes the shape and element-type descriptors stored in
*thisback intomodel.graph().
-
inline void set_events_enabled(bool enabled) noexcept#
Enables or disables event logging. When disabled (the default), :cpp:func:
Set, :cpp:func:ComputeShapeNode, :cpp:func:AddConstraintand :cpp:func:AddLessEqualConstraintskip all event construction. Callset_events_enabled(true)before running shape inference if descriptor or constraint tracing is required.
-
inline bool events_enabled() const noexcept#
-
inline void set_current_subgraph(int64_t node_index, const std::string &attr_name)#
Index of the control-flow node in the parent graph currently being inferred. Set before running subgraph shape inference so that events recorded inside carry :cpp:var:
ShapeEvent::subgraph_node_indexand :cpp:var:ShapeEvent::subgraph_attr_name.-1for the top-level graph. Use :cpp:func:set_current_subgraphto update both the index and the attribute name atomically.
-
inline int64_t current_subgraph_node_index() const noexcept#
-
inline void set_current_node_index(int64_t index) noexcept#
Index of the node currently being processed, used to tag the :cpp:var:
ShapeEvent::node_indexof descriptors and events recorded during its shape-inference dispatch. Set by :cpp:func:ComputeShapesbefore each :cpp:func:ComputeShapeNodecall,-2while seeding initializers and-1while seeding graph inputs (or when no node is being processed).
-
inline int64_t current_node_index() const noexcept#
-
inline const ShapeEventLog &Events() const noexcept#
Append-only log of every tensor descriptor mutation performed through :cpp:func:
Set, every node dispatched through :cpp:func:ComputeShapeNodeand every constraint recorded through :cpp:func:AddConstraint/ :cpp:func:AddLessEqualConstraint. See :cpp:class:ShapeEventfor the captured fields.
-
inline ShapeEventLog &Events() noexcept#
-
inline void ClearEvents() noexcept#
Empties the event log without otherwise touching the context.
-
inline void set_event_callback(std::function<void(const ShapeEvent&)> callback)#
Registers a callback invoked synchronously for every newly appended :cpp:class:
ShapeEvent. Used by callers that want to stream shape inference progress while computation is still running.
-
inline void clear_event_callback() noexcept#
-
inline bool has_event_callback() const noexcept#
-
void AppendComputeNodeEvent(const std::string &op_domain, const std::string &op_type, std::vector<std::string> inputs)#
Appends a :cpp:class:
ShapeEventwith action :cpp:enumerator:ShapeEventAction::kComputeNodesummarising the shape-inference dispatch of a singleNodeProto(itsop_domain/op_typeand theinputsit consumed). Appended by :cpp:func:ComputeShapeNodefor every dispatched node when event logging is enabled.
Private Functions
-
void LogSetEvent(const std::string &name, const OptimTensor &tensor)#
Appends a :cpp:enumerator:
ShapeEventAction::kAdd/ :cpp:enumerator:ShapeEventAction::kReplaceevent fornamedescribingtensor(the descriptor about to be stored). Only called by :cpp:func:Setwhen event logging is enabled.
-
void LogConstraintEvent(ShapeEventAction action, const std::string &lhs, const std::string &rhs)#
Appends a :cpp:enumerator:
ShapeEventAction::kConstraint/ :cpp:enumerator:ShapeEventAction::kConstraintMaxevent recording the two operands of a newly inserted constraint ininputs. Only called by :cpp:func:AddConstraint/ :cpp:func:AddLessEqualConstraintwhen event logging is enabled.
-
inline void EmitEvent(const ShapeEvent &ev) const#
Private Members
-
std::unordered_map<std::string, OptimTensor> tensors_#
-
std::unordered_map<std::string, OptimSequence> sequences_#
-
std::unordered_map<std::string, const FunctionProto*> local_functions_#
-
CustomShapeInferenceMap custom_shape_inference_#
-
std::set<Constraint> constraints_#
-
std::set<LessEqualConstraint> le_constraints_#
-
std::map<SubgraphContextKey, std::shared_ptr<ShapesContext>> subgraph_contexts_#
-
ShapeEventLog events_#
-
std::function<void(const ShapeEvent&)> event_callback_#
-
bool events_enabled_ = false#
-
int64_t current_node_index_ = -1#
-
int64_t current_subgraph_node_index_ = -1#
Index of the control-flow node in the parent graph currently being inferred (see :cpp:func:
set_current_subgraph).-1for the top-level graph.
-
using ShapeEventLog = std::vector<ShapeEvent>#
-
namespace shapes
-
namespace onnx_optim