onnx_light.onnx_optim.shape_inference#
Top-level shape-inference helpers backed by a C++ library.
This module exposes the onnx_optim shape-inference pipeline at the
ModelProto level. It mirrors the C++ helpers
ComputeShapeModel() and ApplyInferredShapesToModel()
combined into a single infer_shapes_model() entry point.
Typical usage:
from onnx_light.onnx_optim.shape_inference import infer_shapes_model
infer_shapes_model(model)
# model.graph.output[i].type and model.graph.value_info now carry
# the inferred element types and shapes.
The module is exposed as onnx_light.onnx_optim.shape_inference.
- class onnx_light.onnx_optim.shape_inference.ComputeContext(*args, **kwargs)#
Holds the in-place reuse opportunities computed for a graph, mirroring the way
ShapesContextholds inferred descriptors. Populate it withcompute_inplace_reuse_graph(consuming aShapesContext), then read the result throughreuse/node_reuse/memoryor persist it withwrite_to_metadata.- compute_inplace_reuse_graph(self, graph: onnx_light.onnx_py._onnxpyprotoop.GraphProto, ctx: onnx_light.onnx_py._onnxpyoptim.shape_inference.ShapesContext, allow_input_overwrite: bool = False, value_tags: collections.abc.Mapping[str, str] = {}, verbose: int = 0) None#
Guesses, for every node of
graph, which outputs reuse which input buffers in place, using the shapes already inferred intoctx, and stores the result in this context (replacing any previous result).By default declared graph inputs are never overwritten in place; set
allow_input_overwrite=Trueto let an input be reused like an intermediate.When
value_tagsis provided (a{name: tag}dict such as the one returned bycompute_value_and_node_tags()), released values that carry the"shape"tag are also stored inrelease_after_shape_taggedand written toonnx_light.release_after_shape_tagbywrite_to_metadata(). Whenvalue_tagsis omitted, this method reuses the last tags stored bycompute_value_and_node_tags()on the same context, if any.verboseis currently accepted for API compatibility and has no effect.
- compute_release_after_shape_tagged(self, verbose: int = 0) list[list[str]]#
Returns
release_after_shape_tagged; the optionalverboseargument is accepted for API compatibility.
- compute_value_and_node_tags(self, graph: onnx_light.onnx_py._onnxpyprotoop.GraphProto, verbose: int = 0) tuple#
- compute_value_and_node_tags(self, function: onnx_light.onnx_py._onnxpyprotoop.FunctionProto, verbose: int = 0) tuple
- compute_value_and_node_tags(self, nodes: list, verbose: int = 0) tuple
Overloaded function.
compute_value_and_node_tags(self, graph: onnx_light.onnx_py._onnxpyprotoop.GraphProto, verbose: int = 0) -> tuple
Computes semantic
shape/axes/weight/ambiguoustags for values and nodes ingraphand stores the result in this context.verboseis currently accepted for API compatibility and has no effect.compute_value_and_node_tags(self, function: onnx_light.onnx_py._onnxpyprotoop.FunctionProto, verbose: int = 0) -> tuple
Computes semantic
shape/axes/weight/ambiguoustags for values and nodes infunctionand stores the result in this context.verboseis currently accepted for API compatibility and has no effect.compute_value_and_node_tags(self, nodes: list, verbose: int = 0) -> tuple
Computes semantic
shape/axes/weight/ambiguoustags for a node list and stores the result in this context.verboseis currently accepted for API compatibility and has no effect.
- events(self) list#
Returns the append-only decision log as a list of
ComputeEvententries.
- property events_enabled#
When
True,compute_inplace_reuse_graph()appends oneComputeEventper in-place decision, release decision and shape-tagged release decision. Default isFalse.
- property memory#
The per-node memory snapshots as a list (one entry per node, same order as
graph.node). Each entry is adict[str, int | str | dict[str, int | str]]describing the live input/initializer/intermediate buffers plus the extra output allocation needed by that node.
- node_memory(self, node_index: int) dict[str, int | str | dict[str, int | str]]#
Returns the memory snapshot
dictcomputed for the node atnode_index. RaisesIndexErrorwhennode_indexis out of bounds.
- node_release_after_shape_tagged(self, node_index: int) list[str]#
Returns the list of shape-tagged releasable value names for the node at
node_index. RaisesIndexErrorwhennode_indexis out of bounds.
- node_reuse(self, node_index: int) list[onnx_light.onnx_py._onnxpyoptim.shape_inference.InPlaceReuse]#
Returns the list of
InPlaceReuseopportunities discovered for the node atnode_index. RaisesIndexErrorwhennode_indexis out of bounds.
- node_tag(self, node_index: int) str#
Returns the last tag computed for the node at
node_index. RaisesIndexErrorwhennode_indexis out of bounds.
- property node_tags#
Returns the last per-node tag list computed by
compute_value_and_node_tags().
- property release_after_shape_tagged#
The per-node shape-tagged releasable values. When
compute_inplace_reuse_graphwas called with an explicit non-emptyvalue_tagsargument (or aftercompute_value_and_node_tagspopulated this context), this is a list with one entry per node (same order asgraph.node), where each entry is a list of value names that carry the"shape"tag. Otherwise this list is itself empty.
- property reuse#
The per-node reuse opportunities as a list (one entry per node, same order as
graph.node); each entry is a list ofInPlaceReuse.
- property value_tags#
Returns the last value-tag map computed by
compute_value_and_node_tags().
- write_to_metadata(self, graph: onnx_light.onnx_py._onnxpyprotoop.GraphProto) None#
Records the computed opportunities into each node’s
metadata_propsunder the keysonnx_light.inplace_reuse,onnx_light.release_after, and (when value tags were provided tocompute_inplace_reuse_graph)onnx_light.release_after_shape_tag. TheGraphProtois mutated in place and must be the same graph passed tocompute_inplace_reuse_graph.
- class onnx_light.onnx_optim.shape_inference.ComputeEvent#
One entry in
ComputeContext.events().inplaceevents carryoutput_index/input_index/kind.releaseandrelease_shape_tagevents carryname.- property action#
ComputeEventActionvalue describing the decision kind.
- property input_index#
Input index for
inplaceevents,-1otherwise.
- property kind#
Reuse kind for
inplaceevents.
- property name#
Value name for
release/release_shape_tagevents.
- property node_index#
Node index where the decision was made.
- property output_index#
Output index for
inplaceevents,-1otherwise.
- class onnx_light.onnx_optim.shape_inference.ComputeEventAction(*values)#
Classifies decisions logged by
ComputeContextwhenevents_enabledisTrue:kInPlacefor in-place matches,kReleasefor releasable last-use values, andkReleaseShapeTagfor released values tagged"shape".- kInPlace = 0#
- kRelease = 1#
- kReleaseShapeTag = 2#
- class onnx_light.onnx_optim.shape_inference.InPlaceReuse(*args, **kwargs)#
Represents one in-place reuse opportunity for a node: the output at
output_indexreuses the buffer of the input atinput_index(both indices into the node’soutput/inputlists).kindrecords whether the input buffer has the same size as the output (kEqual) or is strictly larger (kGreater).- property input_index#
(self) -> int
- property kind#
(self) -> onnx_light.onnx_py._onnxpyoptim.shape_inference.InPlaceReuseKind
- property output_index#
(self) -> int
- class onnx_light.onnx_optim.shape_inference.InPlaceReuseKind(*values)#
Classifies how the reused input buffer compares in size with the output:
kEqualwhen the input and output share the same element type and shape (same byte size, the preferred reuse);kGreaterwhen the input buffer is strictly larger in bytes than the output.- kEqual = 0#
- kGreater = 1#
- class onnx_light.onnx_optim.shape_inference.OptimDim(*args, **kwargs)#
A single shape dimension that is either a concrete integer or a symbolic string expression.
- class onnx_light.onnx_optim.shape_inference.OptimShape(*args, **kwargs)#
Ordered, bounded-rank collection of OptimDim entries describing a tensor shape.
- class onnx_light.onnx_optim.shape_inference.OptimTensor(*args, **kwargs)#
Lightweight (non-owning) tensor descriptor with an element type and an OptimShape, optionally annotated with a value-as-shape and value bounds. The Python binding never references a buffer; only the descriptor metadata is carried.
- property dtype#
Element type as a
TensorProto.DataTypeinteger.
- set_value_as_shape(self, shape: object) None#
Tags the tensor as carrying a shape value (e.g. the
shapeinput ofReshape) and stores that shape.
- property shape#
Shape (a copy of the underlying OptimShape).
- value_as_shape(self) onnx_light.onnx_py._onnxpyoptim.shape_inference.OptimShape#
Returns the value-as-shape annotation. Raises if not set.
- class onnx_light.onnx_optim.shape_inference.ShapeEvent#
One entry of the
ShapesContext.events()log.add/replaceevents describe a tensor descriptor mutation performed throughShapesContext.setand carry the descriptorname,data_type(aTensorProto.DataTypeinteger) andshape(a list of per-dimension strings, preserving symbolic dims).compute_nodeevents summarise the shape-inference dispatch of a single node and carryop_domain,op_typeandinputsinstead.constraint/constraint_maxevents record a newly inserted symbolic-dimension constraint and carry its two operands ininputs.- property action#
kAdd,kReplace,kComputeNode,kConstraintorkConstraintMax.- Type:
ShapeEventActionmember describing the event kind
- as_dict(self) dict#
Returns the event fields as a plain Python
dict(trivially renderable as a table, serialisable, etc.).
- property data_type#
TensorProto.DataTypeinteger of the descriptor, orUNDEFINED(0) forcompute_node/constraint/constraint_maxevents.
- property inputs#
the two constraint operands. Empty otherwise.
- Type:
For
compute_nodeevents- Type:
ordered list of input names consumed by the node (matching
NodeProto.input). Forconstraint/constraint_maxevents
- property name#
Value name targeted by the mutation. Empty for
compute_node/constraint/constraint_maxevents.
- property node_index#
-1for graph inputs,-2for initializers, and the position (>= 0) of the producing / dispatched node otherwise (-1when no producing node is known).- Type:
Index of the node this event is associated with
- property op_domain#
normalised ONNX op domain of the dispatched node (default domain reported as
"ai.onnx"). Empty otherwise.- Type:
For
compute_nodeevents
- property op_type#
ONNX
op_typeof the dispatched node. Empty otherwise.- Type:
For
compute_nodeevents
- property shape#
Descriptor shape as a list of per-dimension strings (decimal integers for concrete dims, symbolic expressions otherwise). Empty for
compute_node/constraint/constraint_maxevents.
- property subgraph_attr_name#
Attribute name of the subgraph within the owning control-flow node (
"body","then_branch","else_branch", etc.). Empty for top-level-graph events.
- property subgraph_node_index#
Index of the control-flow node in the parent graph whose attribute subgraph produced this event.
-1for top-level-graph events.
- class onnx_light.onnx_optim.shape_inference.ShapeEventAction(*values)#
Action kind recorded in a
ShapeEvent.kAdd/kReplacemark tensor-descriptor mutations;kComputeNodemarks the dispatch of a single shape-inference node;kConstraint/kConstraintMaxmark newly inserted symbolic dimension constraints.- kAdd = 0#
- kComputeNode = 2#
- kConstraint = 3#
- kConstraintMax = 4#
- kReplace = 1#
- class onnx_light.onnx_optim.shape_inference.ShapesContext(*args, **kwargs)#
In/out container shared by the per-operator
ComputeShape*shape-inference functions. Holds aname -> OptimTensormap, aname -> OptimSequencemap and adomain -> opset_versionmap mirroringopset_import.- add_constraint(self, a: str, b: str) bool#
Records an equality constraint between two symbolic dimension names. The pair is canonicalised so
(a, b)and(b, a)are stored only once, anda == ais dropped. Returns True when a new constraint was inserted, False otherwise.
- add_less_equal_constraint(self, lhs: str, rhs: str) bool#
Records that the symbolic dimension
lhsis less than or equal to the dimension expressionrhs.lhs == rhsand empty operands are dropped. Returns True when a new constraint was inserted, False otherwise.
- apply_inferred_shapes_to_graph(self, graph: onnx_light.onnx_py._onnxpyprotoop.GraphProto) None#
Writes the shape and element-type descriptors stored in
selfback intograph.outputandgraph.value_info.
- apply_inferred_shapes_to_model(self, model: onnx_light.onnx_py._onnxpyprotoop.ModelProto) None#
Writes the shape and element-type descriptors stored in
selfback intomodel.graph.
- check_inputs_available(self, node: onnx_light.onnx_py._onnxpyprotoop.NodeProto) None#
Raises
ValueErrorif any non-empty input name declared bynodeis missing fromself.
- check_outputs_not_available(self, node: onnx_light.onnx_py._onnxpyprotoop.NodeProto) None#
Raises
ValueErrorif any non-empty output name declared bynodealready has an entry inself.
- compute_shape_graph(self, graph: onnx_light.onnx_py._onnxpyprotoop.GraphProto) None#
Seeds
selffrom the initializers and inputs ofgraphand then runscompute_shape_nodeon every node in topological order.
- compute_shape_model(self, model: onnx_light.onnx_py._onnxpyprotoop.ModelProto, prefill_with_value_info_output: bool = False) None#
Records every
(domain, version)pair frommodel.opset_importinselfand delegates tocompute_shape_graph. Whenprefill_with_value_info_outputis true, tensor descriptors frommodel.graph.value_infoandmodel.graph.outputare added as anchors and preferred when there is a non-conflicting choice at the end.
- compute_shape_node(self, node: onnx_light.onnx_py._onnxpyprotoop.NodeProto) None#
Dispatches a single
NodePrototo the matching per-operatorComputeShape*function and stores the resulting output tensor descriptors inself. The node’s input descriptors must already be present inself.
- constraints(self) list#
Returns the list of recorded equality constraints as
(lhs, rhs)tuples withlhs < rhs.
- custom_shape_inference_keys(self) list#
Returns registered custom callback keys as
"<domain>:<op_type>".
- events(self) list#
Returns the append-only shape-inference event log as a list of
ShapeEventinstances. Empty unlessevents_enabledwas set before running shape inference.
- property events_enabled#
When
True,setrecordsadd/replaceevents,compute_shape_noderecords acompute_nodeevent per dispatched node, andadd_constraint/add_less_equal_constraintrecordconstraint/constraint_maxevents. Default isFalsefor maximum throughput; enable only when tracing shape inference.
- get(self, name: str) onnx_light.onnx_py._onnxpyoptim.shape_inference.OptimTensor#
Returns (a copy of) the tensor descriptor stored under
name. Raises KeyError when no such entry exists.
- has_constraint(self, a: str, b: str) bool#
True when an equality constraint between
aandbwas recorded (canonical order is applied before lookup;a == aalways returns True).
- has_custom_shape_inference_function(self, domain: str, op_type: str) bool#
True when a custom callback is registered for
(domain, op_type).
- has_less_equal_constraint(self, lhs: str, rhs: str) bool#
True when a
lhs <= rhsconstraint was recorded (lhs == rhsalways returns True).
- has_subgraph_context(self, node_index: int, attr_name: str) bool#
True when a child context was retained for the subgraph
attr_nameof the control-flow node atnode_index.
- less_equal_constraints(self) list#
Returns the list of recorded
<=constraints as ordered(lhs, rhs)tuples meaninglhs <= rhs.
- opset_version(self, domain: str) int#
Returns the recorded opset version of
domain, orkUnknownOpsetVersion(-1) when none was recorded.
- remove_custom_shape_inference_function(self, domain: str, op_type: str) bool#
Removes a custom callback for
(domain, op_type). An empty domain is normalised toai.onnx. ReturnsTruewhen an entry was removed.
- set(self, name: str, tensor: onnx_light.onnx_py._onnxpyoptim.shape_inference.OptimTensor) None#
Inserts or replaces the tensor descriptor stored under
name.
- set_custom_shape_inference_function(self, domain: str, op_type: str, fn: collections.abc.Callable) None#
Registers a Python callback for
(domain, op_type). The callback receives(ctx, node)and can populate output descriptors inctx. An emptydomainis normalised toai.onnx.
- set_opset_version(self, domain: str, opset_version: int) None#
Records the opset version for
domain. An empty domain is normalised toai.onnx.
- subgraph_context(self, node_index: int, attr_name: str) onnx_light.onnx_py._onnxpyoptim.shape_inference.ShapesContext#
Returns the child
ShapesContextretained for the subgraphattr_nameof the control-flow node atnode_index. RaisesIndexErrorif absent.
- onnx_light.onnx_optim.shape_inference.infer_shapes_model(model, prefill_with_value_info_output: bool = False) None#
Runs shape inference on a
ModelProtoin place.Seeds the shape-inference context from the model’s
opset_import, graph initializers and graph inputs, runs per-operator shape inference on every node of the main graph, and writes the inferred element types and shapes back intomodel.graph.outputandmodel.graph.value_info.- Parameters:
model – A
ModelPrototo mutate in place.prefill_with_value_info_output – When
True, prefill frommodel.graph.value_infoandmodel.graph.outputand prefer these anchors when there is a non-conflicting end-state alternative.
- Raises:
ValueError – If shape inference rejects a node (for example because of an unsupported op type) or if
modelhas no graph.