yobx.xshape#

NativeShapeInference#

class yobx.xshape.NativeShapeInference(verbose=0, opset=None)[source]#

Infers ONNX tensor descriptors with a persistent native ShapesContext.

TYPE uses the same native engine but exposes only element types. Unknown operators and incompatible constraints raise the native exception, including when the legacy exc=False argument is supplied. Custom inference can be registered directly on context.

add_to_constraints(dim_name: str, value: int | str | set[int | str]) → None[source]#

Registers one or several native dimension equalities.

estimate_node_flops(node)[source]#

Estimates arithmetic cost using only native descriptors and values.

evaluate_cost_with_true_inputs(feeds, cost, exc=False)[source]#

Evaluates symbolic costs against actual input dimensions.

evaluate_shape(name: str, context: dict[str, int]) → tuple[int | None, ...][source]#

Evaluates native expressions and preserves anonymous unknown dimensions.

get_constant(name, exc=True, computed_value=False, as_shape=False, **kwargs)[source]#

Returns a registered literal without evaluating Python operators.

get_debug_msg(limit=1000)[source]#

Returns a compact native inference diagnostic.

get_device(name)[source]#

Returns caller-supplied device metadata.

get_opset(name)[source]#

Returns the native domain opset.

get_rank(name)[source]#

Returns the inferred rank.

get_registered_constraints() → dict[str, set[int | str]][source]#

Returns equality constraints recorded by the native engine.

get_shape(name: str) → Tuple[int | str | None, ...][source]#

Returns native dimensions, preserving anonymous dimensions as None.

get_shape_renamed(name)[source]#

Returns dimensions as resolved by the native engine.

get_type(name)[source]#

Returns the native element type, or zero when unavailable.

has_device(name)[source]#

Returns whether optional device metadata was supplied.

has_opset(name)[source]#

Returns whether the domain has an opset.

has_rank(name)[source]#

Returns whether a native shape is available.

has_shape(name, full=False)[source]#

Returns whether a native shape is available.

has_type(name)[source]#

Returns whether a native element type is available.

property input_names#

Returns the model input names.

is_constant(name)[source]#

Returns whether a literal tensor is registered.

property main_opset#

Returns the default-domain opset.

property output_names#

Returns the model output names.

register_constraint_dimension(dim_name: str, value: int | str | set[int | str]) → None[source]#

Registers one or several native dimension equalities.

reset_types_and_shapes()[source]#

Clears inferred descriptors and native callbacks.

run_model(model, functions=None, exc=False, inference=InferenceMode.SHAPE)[source]#

Runs native inference and optionally returns per-node cost statistics.

run_node(node, exc=False, cost=True)[source]#

Infers a node natively and optionally estimates its arithmetic cost.

set_constant(name, value)[source]#

Registers a literal through native Constant inference.

set_device(name: str, device: int, **kwargs) → None[source]#

Stores optional device metadata without performing inference.

set_opset(name: str, version: int) → None[source]#

Registers a domain opset with the native engine.

set_rank(name, rank)[source]#

Seeds a rank with anonymous native dimensions.

set_shape(name, shape, exc=False, **kwargs)[source]#

Seeds a native descriptor with dimensions.

set_type(name: str, itype: int, exc: bool = True) → bool[source]#

Seeds a native descriptor with an element type.

set_value_shape(name, value, equal_to=None)[source]#

Seeds native shape-tensor values.

to_onnx()[source]#

Returns an inferred copy of the most recently processed model.

update_shapes(model)[source]#

Writes native inferred descriptors to a model or graph in place.

value_as_shape(name: str) → Tuple[int | str | None, ...] | None[source]#

Returns native shape-tensor values, or None when unavailable.

ShapeBuilder#

class yobx.xshape.ShapeBuilder[source]#

API for a class computing shapes in an ONNX model.

The main implementation is NativeShapeInference. It walks through all the nodes of an ONNX model and infers output shapes and types based on the input shapes, using symbolic expressions when the exact integer values are not known.

Symbolic expressions — When a dimension cannot be determined as a plain integer (e.g. because it depends on a dynamic input dimension), it is stored as a Python-arithmetic string expression built from the input dimension names. For instance, concatenating tensors of shapes ("batch", "seq1") and ("batch", "seq2") along axis 1 yields output shape ("batch", "seq1+seq2"). The supported operators inside a symbolic expression are +, -, *, //, % and ^ (where ^ means max). Expressions are automatically simplified by simplify_expression before being stored, so d + f - f becomes d and 2*seq//2 becomes seq. Once concrete values are available they can be resolved with evaluate_shape() or evaluate_expression.

<<<

from onnx_light import onnx
import onnx_light.onnx.helper as oh
from yobx.xshape import NativeShapeInference

TFLOAT = onnx.TensorProto.FLOAT

# Build a small model: Z = Concat(X, Y, axis=1)
model = oh.make_model(
    oh.make_graph(
        [oh.make_node("Concat", ["X", "Y"], ["Z"], axis=1)],
        "graph",
        [
            oh.make_tensor_value_info("X", TFLOAT, ["batch", "seq1"]),
            oh.make_tensor_value_info("Y", TFLOAT, ["batch", "seq2"]),
        ],
        [oh.make_tensor_value_info("Z", TFLOAT, [None, None])],
    ),
    opset_imports=[oh.make_opsetid("", 18)],
    ir_version=10,
)

builder = NativeShapeInference()
builder.run_model(model)

print("input names :", builder.input_names)
print("output names:", builder.output_names)
print("shape of Z  :", builder.get_shape("Z"))
print("type of Z   :", builder.get_type("Z"))

>>>

    input names : ['X', 'Y']
    output names: ['Z']
    shape of Z  : ('batch', 'seq1+seq2')
    type of Z   : 1

Constraint mechanism — When a broadcasting operation aligns a symbolic dimension (e.g. "d_model") with a concrete integer (e.g. 64), the concrete value is used immediately as the output dimension and the equality "d_model" = 64 is stored as a constraint. This avoids the need to backtrack through earlier nodes when the concrete value is later discovered. Constraints are inspected with get_registered_constraints() and are used internally for dimension renaming and equality checks. See Native symbolic shape inference for details.

add_to_constraints(dim_name: str, value: str | int | Set[str | int])[source]#

Adds a constraint associating a symbolic dimension name with a value or set of values.

Parameters:
  • dim_name – symbolic dimension name (e.g. "batch")

  • value – the value, name, or set of values/names to associate with that dimension

compare_with_true_inputs(inputs: Dict[str, ndarray] | List[ndarray], outputs: Dict[str, ndarray] | List[ndarray], exc: bool = True, do_shape: bool = True, do_type: bool = True) → Dict[str, Tuple[Tuple[str, int, int], ...]][source]#

Compares the shape of the outputs with what the output shapes would return.

Parameters:
  • inputs – inputs

  • outputs – outputs

  • exc – raises an exception when a discrepancy is met

  • do_type – compares types

  • do_shape – compares shapes

Returns:

list of expression, expected value, computed value

evaluate_dimension_equality_with_constraints(d1: str, *args) → bool[source]#

Tells if two dimensions are equal.

evaluate_shape(name: str, context: Dict[str, int]) → Tuple[int | None, ...][source]#

Evaluates symbolic dimensions and preserves anonymous unknown dimensions.

get_attribute(node: NodeProto, att_name: str, exc: bool = True) → AttributeProto | None[source]#

Returns an attribute for a node.

get_attribute_with_default(node: NodeProto, name: str, default_value: Any) → Any[source]#

Returns an attribute or its default value if missing.

Parameters:
  • node – node

  • name – attribute name

  • default_value – default value

Returns:

value

get_attributes_with_default(node: NodeProto, **default_values) → Dict[str, Any][source]#

Returns int or float attributes. If missing, the default value is returned if it is not None.

Parameters:
  • node – node

  • default_values – default values

get_debug_msg(limit: int = 1000) → str[source]#

Returns a string providing as much information as possible to help the developer understand why a conversion failed.

Parameters:

limit – limit the string if the model is big

Returns:

many pieces of information about the on going conversion

get_device(name: str) → int[source]#

Returns the device of result name.

Parameters:

name – result name

Returns:

rank as an integer

get_opset(name: str) → int[source]#

Returns the opset version for domain name.

Parameters:

name – domain name

Returns:

domain version or 0 if not defined

get_rank(name: str) → int[source]#

Returns the rank (number of dimensions) of result name.

Parameters:

name – result name

Returns:

rank as an integer

get_registered_constraints() → Dict[str, Set[str | int]][source]#

Returns the constraints registered so far.

Returns:

mapping from dimension name to the set of values/names it is constrained to be equal to

get_shape(name: str) → Tuple[int | str | None, ...][source]#

Returns the shape of result name as a tuple. Each dimension is an integer, a symbolic string, or None when unknown.

Parameters:

name – result name

Returns:

shape as a tuple of integers, strings, and/or None

get_shape_renamed(name: str) → Tuple[int | torch.SymInt | torch.SymFloat | TracingInt | float | str, ...][source]#

Returns the shape of result name using user-visible dimension names.

After _improves_dynamic_dimension_naming() has been called, symbolic dimension names that were given by the user (e.g. "batch", "seq_length") are substituted for the internal names (e.g. "s0", "s1"). When no renaming has been computed yet this falls back to get_shape().

Parameters:

name – result name

Returns:

shape tuple with user dimension names where available

get_type(name: str) → int[source]#

Returns the element type of result name as an ONNX integer (e.g. onnx.TensorProto.FLOAT == 1).

Parameters:

name – result name

Returns:

element type as an integer

has_device(name: str) → bool[source]#

Tells if name has a device.

has_opset(name: str) → bool[source]#

Tells if opset name is defined.

has_rank(name: str) → bool[source]#

Tells if name has a rank.

has_shape(name: str) → bool[source]#

Tells if name has a shape.

has_type(name: str) → bool[source]#

Tells if name has a type.

property input_names: List[str]#

Returns the list of input names of the model.

property output_names: List[str]#

Returns the list of output names of the model.

pretty_node(node: NodeProto | None, limit: int = 80, short: bool = True, shape: bool = False) → str[source]#

Pretty rendering for a node.

Parameters:
  • node – node to render

  • limit – to show type and shapes after the limit

  • short – do not display shape information on the left

  • shape – show shape information below

Returns:

string

register_constraint_dimension(dim_name: str, value: str | int | Set[str | int])[source]#

Registers a constraint associating a symbolic dimension name with a value. This allows to deal backward constraints after a single pass if the model.

Parameters:
  • dim_name – symbolic dimension name (e.g. "batch")

  • value – the value or set of values to associate with that dimension

set_device(name: str, device: int)[source]#

Sets the device identifier for result name.

Parameters:
  • name – result name

  • device – device identifier as an integer

set_opset(name: str, version: int)[source]#

Sets the opset version for domain name.

Parameters:
  • name – domain name

  • version – domain version

set_rank(name: str, rank: int)[source]#

Sets the rank (number of dimensions) for result name.

Parameters:
  • name – result name

  • rank – rank as an integer

set_shape(name: str, shape: Tuple[int | str | None, ...])[source]#

Sets the shape for result name.

Parameters:
  • name – result name

  • shape – integers, symbolic strings, or None for unknown dimensions

set_type(name: str, itype: int)[source]#

Sets the element type for result name.

Parameters:
  • name – result name

  • itype – element type as an ONNX integer (e.g. onnx.TensorProto.FLOAT == 1)

update_shapes(model: ModelProto)[source]#

Updates model shapes with the value stored inside this graph.

estimate_node_flops#

yobx.xshape.estimate_node_flops(node: NodeProto, shape_fn: Callable[[str], Tuple[int | str | None, ...] | None], literal_fn: Callable[[str], Tuple[int | str | None, ...] | None]) → int | str | None[source]#

Estimates the number of floating-point operations for a single ONNX node.

Returns None when required dimensions are unknown or the op_type is not covered. Symbolic dimensions produce symbolic costs. Rank-only costs remain available when individual dimensions are unknown.

Parameters:
  • node – ONNX node

  • shape_fn – callable mapping tensor name to a shape tuple containing integers, symbolic strings, or None for unknown dimensions

  • literal_fn – callable mapping tensor name → int-value tuple for 1-D integer constant tensors (shape specification tensors); used as a fallback when shape_fn cannot resolve a shape

Returns:

estimated number of FLOPs, or None

list_op_cost_formulas#

yobx.xshape.list_op_cost_formulas() → Dict[str, str][source]#

Returns a mapping from each supported ONNX op_type to the symbolic FLOPs expression produced by estimate_node_flops() on a representative test case from the ONNX backend test suite.

For every single-node model in the native wheel’s backend test inventory the static input dimensions are replaced by symbolic variables (DIM<n>) using replace_static_dimensions_by_strings(). NativeShapeInference is then run with inference=InferenceMode.COST to obtain the symbolic FLOPs expression.

Only the first passing test case per op_type is kept. Operators with no matching backend test case, or whose cost cannot be inferred symbolically, are omitted.

Returns:

{op_type: symbolic_flops_expression} sorted alphabetically.