yobx.typing#

class yobx.typing.ConvertOptionsProtocol(*args, **kwargs)[source]#

Protocol for a class giving indications on how to convert a model.

has(option_name: str, piece: object) bool[source]#

Returns true if option option_name applies to piece

class yobx.typing.DefaultConvertOptions[source]#

All options are disabled.

has(option_name: str, piece: object) bool[source]#

Returns always False.

class yobx.typing.ExportArtifactProtocol(*args, **kwargs)[source]#

Protocol for ExportArtifact.

get_proto(include_weights: bool = True) Any[source]#

Return the ONNX proto, optionally with all weights inlined.

When the export was performed with large_model=True (i.e. container is set), the raw proto has external-data placeholders instead of embedded weight tensors. Passing include_weights=True (the default) uses to_ir() to build a fully self-contained ModelProto.

Parameters:

include_weights – when True (default) embed the large initializers stored in container into the returned proto. When False return the raw proto as-is.

Returns:

ModelProto, FunctionProto, or GraphProto.

Example:

artifact = to_onnx(estimator, (X,), large_model=True)
# Fully self-contained proto (weights embedded):
proto_with_weights = artifact.get_proto(include_weights=True)
# Proto with external-data placeholders:
proto_no_weights = artifact.get_proto(include_weights=False)
classmethod load(file_path: str, load_large_initializers: bool = True) ExportArtifactProtocol[source]#

Load a saved model from file_path.

If the file references external data (i.e. the model was saved with large_model=True) an ExtendedModelContainer is created and returned in container. Otherwise the proto is loaded directly with onnx.load() and container is None.

Parameters:
  • file_path – path to the .onnx file.

  • load_large_initializers – when True (default) also load the large initializers stored alongside the model file.

Returns:

ExportArtifact with filename set to file_path.

Example:

artifact = ExportArtifact.load("model.onnx")
proto = artifact.get_proto()
save(file_path: str, all_tensors_to_one_file: bool = True)[source]#

Save the exported model to file_path.

When a ExtendedModelContainer is present (large_model=True was used during export) the model and its external weight files are saved via save(). Otherwise the proto is saved with onnx.save_model().

Parameters:
  • file_path – destination file path (including .onnx extension).

  • all_tensors_to_one_file – when saving a large model, write all external tensors into a single companion data file.

class yobx.typing.GraphBuilderExtendedProtocol(*args, **kwargs)[source]#

Extended protocol for graph builders that support opset helpers and shape/type inference for common operator patterns.

This protocol extends GraphBuilderProtocol with additional methods present on yobx.xbuilder.GraphBuilder and yobx.builder.onnxscript.OnnxScriptGraphBuilder that are useful for advanced graph construction:

  • main_opset — the opset version for the main (""/ONNX) domain.

  • op — an opset helper that allows constructing nodes with g.op.Add(x, y)-style syntax via __getattr__().

  • set_type_shape_unary_op() — propagates type and shape from an input to an output for unary operators such as Abs, Relu, etc.

get_debug_msg() str[source]#

Returns any information useful to understand where an error could come from. This message is expected to be part of any exception raised while converting a model.

Returns:

information in a string

property main_opset: int#

Returns the opset version for the main (""/ONNX) domain.

Returns:

integer opset version for domain ""

property op: OpsetProtocol#

Returns the opset helper for this graph builder.

The opset helper allows constructing ONNX nodes using attribute-access syntax. For example:

out = g.op.Relu(x)
Returns:

an OpsetProtocol-compatible object

set_type_shape_unary_op(name: str, input_name: str, itype: int | None = None) bool[source]#

Propagates type and shape from input_name to name for a unary op.

This is a convenience helper used when emitting elementwise unary operators (Abs, Exp, Relu, etc.) where the output has the same type and shape as the input.

Parameters:
  • name – output tensor name whose type/shape should be set

  • input_name – input tensor name to copy type/shape from

  • itype – override element type; if None the input’s element type is used

Returns:

True when shape information was available and set, None/falsy when it could not be determined

unique_name(prefix: str) str[source]#

Returns a unique name derived from prefix.

Parameters:

prefix – name prefix

Returns:

a name that has not been used yet in this graph

class yobx.typing.GraphBuilderPatternOptimizationProtocol(*args, **kwargs)[source]#

Protocol describing the expected API of the graph pattern optimizer.

Any class that implements this protocol can be passed as the g argument to match() and related methods. The concrete implementation is yobx.xoptim.GraphBuilderPatternOptimization.

The protocol covers all attributes and methods that pattern authors typically call on the optimizer object inside their match() implementations.

property builder: Any#

The underlying GraphBuilder instance.

do_not_turn_constant_initializers_maybe_because_of_showing(name: str) bool[source]#

Returns True when the initializer for name must not be folded into a Constant node (e.g. because it is displayed).

Parameters:

name – initializer name

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

Returns the AttributeProto named att_name on node.

Parameters:
  • nodeNodeProto

  • att_name – attribute name

  • exc – raise an exception if the attribute is missing

Returns:

AttributeProto or None

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

Returns the value of attribute name on node, or default_value if the attribute is absent.

Parameters:
  • nodeNodeProto

  • name – attribute name

  • default_value – fallback value

Returns:

attribute value or default_value

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

Returns a dict of attribute values for node, substituting default_values for any missing attributes.

Parameters:
  • nodeNodeProto

  • default_values – keyword arguments mapping attribute names to their default values

Returns:

dict of attribute name → value

get_axis(node: Any, default_axis: int | None = None) int[source]#

Returns the axis attribute of node.

Parameters:
  • nodeNodeProto

  • default_axis – default value when the attribute is absent

Returns:

axis integer

get_computed_constant(name: str, statistics: List[str] | None = None) Any[source]#

Returns the evaluated value of constant name.

Parameters:
  • name – result name

  • statistics – optional list of summary statistics to compute ("min", "max"); when given, a list of values is returned

Returns:

numpy.ndarray or a list of statistics

get_constant_or_attribute(node: Any, attribute: str, input_index: int, cvt: Callable | None = None) Any[source]#

Returns the value of an operator attribute or input depending on the opset version. Some attributes became inputs in newer opsets.

Parameters:
  • nodeNodeProto

  • attribute – attribute name (used in older opsets)

  • input_index – input index (used in newer opsets)

  • cvt – optional conversion callable applied to the result

Returns:

attribute or constant value

get_constant_scalar(name: str, broadcast: bool = False) int | float[source]#

Returns the scalar value of constant name.

Parameters:
  • name – result name

  • broadcast – accept shapes such as (1,) or (1,1)

Returns:

int, float, or complex

get_constant_shape(name: str, exc: bool = True) Tuple[int, ...] | None[source]#

Returns the shape of constant name.

Parameters:
  • name – result name

  • exc – raise an exception if the shape cannot be determined

Returns:

shape tuple, or None when exc is False

get_position(node: Any) int[source]#

Returns the position (index) of node in the graph node list.

Parameters:

node – a NodeProto

Returns:

zero-based index

get_rank(name: str) int[source]#

Returns the rank of name.

Parameters:

name – result name

Returns:

number of dimensions

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

Returns the shape constraints registered on the builder.

Returns:

mapping from constraint name to set of allowed values

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

Returns the shape of name.

Parameters:

name – result name

Returns:

tuple where each element is an int or a symbolic dimension string

get_shape_renamed(name: str) Tuple[int | str, ...][source]#

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

Parameters:

name – result name

Returns:

shape tuple with user dimension names

get_type(name: str) int[source]#

Returns the ONNX element type integer for name.

Parameters:

name – result name

Returns:

element type (e.g. TensorProto.FLOAT)

has_exact_same_constant_in_context(name: str) bool | None[source]#

Checks whether an identical constant already exists in the graph.

Parameters:

name – constant name to look up

Returns:

True/False when known, None otherwise

has_processor(processor: str) bool[source]#

Returns True when processor is in the active processor list.

Parameters:

processor – processor name, e.g. "CUDA"

has_rank(name: str) bool[source]#

Returns True when the rank of name is known.

Parameters:

name – result name

has_shape(name: str) bool[source]#

Returns True when the full shape of name is known.

Parameters:

name – result name

has_type(name: str) bool[source]#

Returns True when the element type of name is known.

Parameters:

name – result name

property input_names: List[str]#

Names of the graph inputs.

Returns:

list of input names

property inputs: List[Any]#

Graph input value infos.

Returns:

list of ValueInfoProto objects

is_constant(name: str) bool[source]#

Returns True when name is a known constant (initializer or the output of a constant-foldable node chain).

Parameters:

name – result name

is_constant_scalar(name: str, value: Any | None = None, broadcast: bool = False) bool[source]#

Returns True when name is a scalar constant.

Parameters:
  • name – result name

  • value – if not None, also check that the scalar equals this value

  • broadcast – treat shapes (1,), (1,1), … as scalar

is_output(name: str) bool[source]#

Returns True when name is a graph output.

Parameters:

name – result name

is_used(name: str) bool[source]#

Returns True when name is consumed by any node or is a graph output.

Parameters:

name – result name

is_used_by_subgraph(name: str) bool[source]#

Returns True when name is used inside a sub-graph.

Parameters:

name – result name

is_used_more_than_once(name: str) bool[source]#

Returns True when name has more than one consumer, is a graph output, or is referenced by a sub-graph.

Parameters:

name – result name

is_used_only_by(name: str, *nodes: Any) bool[source]#

Returns True when name is consumed exclusively by the given nodes.

Parameters:
  • name – result name

  • nodes – the only permitted consumers

iter_nodes() Iterator[Any][source]#

Iterates over all nodes in the graph.

Returns:

iterator of NodeProto

property main_opset: int#

Opset version for the main (""/ONNX) domain.

Returns:

integer opset version

make_initializer(name: str, value: Any, external: bool = False, msg: str = '', source: str | None = None, give_unique_name: bool = True) str[source]#

Adds a constant initializer and returns its (possibly auto-generated) name.

Parameters:
  • name – desired name (may be empty for auto-naming)

  • valuenumpy.ndarray or TensorProto value

  • external – store as external data

  • msg – optional debug message

  • source – optional source tag for debugging

  • give_unique_name – generate a unique name when name is already taken

Returns:

the registered name

make_node(op_type: str, inputs: str | List[str], outputs: int | List[str] | str = 1, domain: str = '', attributes: List[Any] | None = None, name: str | None = None, **kwargs: Any) Any[source]#

Creates an ONNX node (without adding it to the graph) and returns the NodeProto.

Parameters:
  • op_type – operator type

  • inputs – input name(s)

  • outputs – number of outputs (int), single output name (str), or list of output names

  • domain – operator domain

  • attributes – list of AttributeProto objects

  • name – node name

  • kwargs – operator attributes as Python primitives

Returns:

NodeProto

make_node_check_opset(op_type: str, inputs: str | List[str], outputs: int | List[str] | str = 1, domain: str = '', attributes: List[Any] | None = None, name: str | None = None, **kwargs: Any) Any[source]#

Like make_node() but adapts certain operators for the active opset (e.g. Squeeze/Unsqueeze axis handling changed between opset 11 and 13).

Parameters:
  • op_type – operator type

  • inputs – input name(s)

  • outputs – number of outputs (int), single output name (str), or list of output names

  • domain – operator domain (must be "" for the main domain)

  • attributes – list of AttributeProto objects

  • name – node name

  • kwargs – operator attributes as Python primitives

Returns:

NodeProto

next_node(name: str) Any[source]#

Returns the unique consumer of name. Raises if there is not exactly one consumer.

Parameters:

name – result name

Returns:

NodeProto

next_nodes(name: str) List[Any][source]#

Returns all nodes that consume name.

Parameters:

name – result name

Returns:

list of NodeProto

node_before(name: str) Any | None[source]#

Returns the node that produces output name, or None.

Parameters:

name – result name

Returns:

NodeProto or None if name is an input or initializer

property nodes: List[Any]#

Ordered list of NodeProto objects in the graph.

Returns:

list of nodes

property opsets: Dict[str, int]#

Mapping from domain name to opset version.

Returns:

dict of domain → opset version

property output_names: List[str]#

Names of the graph outputs.

Returns:

list of output names

property outputs: List[Any]#

Graph output value infos.

Returns:

list of ValueInfoProto objects

pretty_text(add_fx_graph: bool = False, recursive: bool = True) str[source]#

Returns a human-readable text rendering of the graph.

Parameters:
  • add_fx_graph – include the FX graph representation when available

  • recursive – recurse into sub-graphs

Returns:

multi-line string

property processor: str#

Target processor(s), e.g. "CPU" or "CPU,CUDA".

same_shape(a: str, b: str) bool[source]#

Returns True when a and b have the same shape, taking registered constraints into account.

Parameters:
  • a – first result name

  • b – second result name

try_infer_shape(name: str, exc: bool = False) Tuple[int | str, ...] | None[source]#

Tries to infer the shape of name.

Parameters:
  • name – result name

  • exc – raise an exception when the shape cannot be determined

Returns:

shape tuple or None

try_infer_type(name: str, exc: bool = False) int[source]#

Tries to infer the element type of name, propagating through the graph if necessary.

Parameters:
  • name – result name

  • exc – raise an exception when the type cannot be determined

Returns:

element type integer, or 0 when unknown

unique_name(prefix: str) str[source]#

Returns a name derived from prefix that has not been used yet.

Parameters:

prefix – name prefix

Returns:

unique name

property verbose: int#

Current verbosity level.

class yobx.typing.GraphBuilderProtocol(*args, **kwargs)[source]#

Protocol describing the expected API for graph builders.

Any class that implements this protocol can be used as a graph builder when converting models to ONNX format. Both yobx.xbuilder.GraphBuilder and yobx.builder.onnxscript.OnnxScriptGraphBuilder satisfy this protocol.

property convert_options: ConvertOptionsProtocol#

Returns converting options.

get_opset(domain: str, exc: bool = True) int[source]#

Returns the opset version for a specific domain.

Parameters:
  • domain – domain name

  • exc – raise an exception if missing

Returns:

version or 0 when exc is False and the domain is unknown

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

Returns the shape of name.

Parameters:

name – tensor name

Returns:

shape as a tuple where each element is an int, a str (symbolic dimension)

get_type(name: str) int[source]#

Returns the ONNX element type of name.

Parameters:

name – tensor name

Returns:

ONNX element type integer

has_name(name: str) bool[source]#

Returns True when name is a known value in this graph.

Parameters:

name – tensor name to query

has_opset(domain: str) int[source]#

Returns the opset version for a domain, or 0 if the domain is not registered.

Parameters:

domain – domain name

Returns:

opset version, or 0 if the domain is unknown

has_shape(name: str) bool[source]#

Returns True when the shape of name is known.

Parameters:

name – tensor name to query

has_type(name: str) bool | int[source]#

Returns True (or a truthy int) when the type of name is known.

Parameters:

name – tensor name to query

property input_names: List[str]#

Returns the list of input names.

make_initializer(name: str, value: Any, give_unique_name: bool = True) str[source]#

Adds a constant initializer and returns its name.

Parameters:
  • name – initializer name; may be empty to auto-generate a unique name

  • value – initializer value (numpy.ndarray, onnx.TensorProto, int, or float)

  • give_unique_name – changes the name if it is already taken, otherwise, the user should expect an exception to raised

Returns:

the final registered name

make_node(op_type: str, inputs: str | List[str], outputs: int | str | List[str] = 1, domain: str = '', attributes: List[Any] | None = None, name: str | None = None, **kwargs: Any) str | Tuple[str][source]#

Creates an ONNX node and returns its output name(s).

Parameters:
  • op_type – ONNX operator type (e.g. "Relu", "MatMul")

  • inputs – input tensor name(s)

  • outputs – number of outputs (int), a single output name (str), or a list of output names

  • domain – operator domain (default "" = standard ONNX)

  • attributes – list of onnx.AttributeProto to attach

  • name – optional node name for debugging

  • kwargs – operator attributes as Python primitives

Returns:

output name when a single output is created, otherwise a list

make_tensor_input(name: str, elem_type: int | None = None, shape: Tuple[int | str, ...] | None = None, device: int | None = None) str | List[str][source]#

Declares a graph input and returns its name.

Parameters:
  • name – tensor name

  • elem_type – ONNX element type (e.g. TensorProto.FLOAT)

  • shape – tensor shape; use a str for symbolic or unknown dimensions (e.g. "batch" or "?"), and an int for fixed-size dimensions

  • device – device identifier (optional, may be ignored by some backends)

Returns:

the registered name (same as name)

make_tensor_output(name: str | List[str], elem_type: int | None = None, shape: Tuple[int | str, ...] | None = None, indexed: bool = False, allow_untyped_output: bool = False) str | List[str][source]#

Declares a graph output and returns its name.

Parameters:
  • name – tensor name or list of names to mark as outputs

  • elem_type – ONNX element type hint

  • shape – shape hint

  • indexed – whether the name must follow an indexed naming convention

  • allow_untyped_output – allow output with no type / shape information

Returns:

the registered name or list of names

property output_names: List[str]#

Returns the list of output names.

set_opset(domain: str, version: int = 1) None[source]#

Registers a domain with its opset version.

Parameters:
  • domain – domain name

  • version – opset version

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

Sets the shape for name.

Parameters:
  • name – tensor name

  • shape – shape to assign

  • allow_zero – allow zero-sized dimensions

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

Sets the ONNX element type for name.

Parameters:
  • name – tensor name

  • itype – ONNX element type integer

to_onnx() ExportArtifactProtocol[source]#

Exports the graph and returns an ONNX proto or model container.

Returns:

a ModelProto, GraphProto, FunctionProto, or a model container object

class yobx.typing.GraphBuilderTorchProtocol(*args, **kwargs)[source]#

Protocol for graph builders that support the full torch-exporter API.

This protocol extends GraphBuilderExtendedProtocol with the additional methods and attributes used by DynamoInterpreter (the torch exporter) when translating a torch.fx graph into ONNX.

The extra surface covers:

add_dynamic_object(key: str, value: Any, name: str | None = None, dim: int | None = None, parse: bool = False, check_tokens: bool = True) None[source]#

Registers value as the dynamic dimension named key.

Parameters:
  • key – symbolic dimension name

  • valuetorch.SymInt, int, or similar

  • name – tensor input this dimension originates from

  • dim – axis of name this dimension corresponds to

  • parse – also register sub-expressions of value

  • check_tokens – verify sub-tokens are registered first

add_stat(kind: str, name: str) None[source]#

Records a conversion statistic (no-op in most implementations).

Parameters:
  • kind – statistic category

  • name – statistic name

property anyop: OpsetProtocol#

An opset helper that allows operators from any domain.

Identical to op but configured to accept unknown domains. Used by the torch exporter to emit custom-domain operators such as ai.onnx.complex.

Returns:

an OpsetProtocol-compatible object

extract_input_names_from_args(args: Any) List[str][source]#

Extracts all known tensor names from a (possibly nested) args structure.

Parameters:

args – flat or nested sequence of values; strings that are known graph names are collected

Returns:

deduplicated list of input tensor names

get_device(name: str) int[source]#

Returns the device index for tensor name.

The convention is -1 for CPU and a non-negative index for a CUDA device.

Parameters:

name – tensor name

Returns:

device index

get_input_dynamic_shape(name: str | None, input_index: int, example_shape: Any, dynamic_shapes: Any | None = None, example_value: Any | None = None) Any[source]#

Returns the dynamic shape specification for a graph input.

Parameters:
  • name – input name

  • input_index – positional index of the input

  • example_shape – concrete shape of an example input

  • dynamic_shapes – override the builder’s dynamic_shapes

  • example_value – one example tensor value

Returns:

shape tuple (mixing int for static dimensions and str for dynamic ones)

get_is_dimension(name: str, elem_type: int | None = None, shape: Any | None = None, n_outputs: int | None = None, exc: bool = True) bool[source]#

Returns True when name represents a scalar dynamic-dimension value (e.g. the result of aten.sym_size).

Parameters:
  • name – tensor name

  • elem_type – expected ONNX element type hint

  • shape – expected shape hint

  • n_outputs – number of outputs produced by the enclosing node

  • exc – raise when ambiguous

get_rank(name: str) int[source]#

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

Parameters:

name – tensor name

Returns:

non-negative integer rank

get_sequence(name: str) Dict[str, Any][source]#

Returns sequence metadata for name.

Parameters:

name – tensor name

Returns:

dictionary with keys such as "dtype", "shapes", "ranks"

get_type_known(name: str, exc: bool = False) int | None[source]#

Returns the ONNX element type inferred by torch for name, or None when unavailable.

Parameters:
  • name – tensor name

  • exc – raise an exception when the value is malformed

Returns:

ONNX element type integer or None

has_device(name: str) bool[source]#

Returns True when the device of tensor name is known.

Parameters:

name – tensor name

has_rank(name: str) bool[source]#

Returns True when the rank of tensor name is known.

Parameters:

name – tensor name

is_dynamic_shape(shape: Any, verify: bool = True, allow_none: bool = False, allow_new_dynamic_dimension: bool = False) bool[source]#

Returns True when shape contains at least one dynamic (non-integer) dimension.

Parameters:
  • shape – shape tuple to check

  • verify – verify that symbolic names are registered

  • allow_none – treat None entries as dynamic

  • allow_new_dynamic_dimension – allow unregistered symbolic dims

is_sequence(name: str) bool[source]#

Returns True when name has been registered as a tensor sequence.

Parameters:

name – tensor name

property last_added_node: Any | None#

The most recently appended ONNX node, or None when the graph is still empty.

Returns:

an NodeProto or None

make_dynamic_object(name: str, value: Any, shape_as_input: bool = False, input_name: str | None = None, axis: int | None = None) str | None[source]#

Creates and registers a dynamic dimension object.

Parameters:
  • name – name for the dynamic dimension

  • valuetorch.SymInt or similar symbolic value

  • shape_as_input – add the dimension as a scalar graph input

  • input_name – the tensor input this dimension originates from

  • axis – the axis of input_name this dimension corresponds to

Returns:

the registered name, or None

make_local_function(builder: Any, function_options: Any, optimize: bool = False, metadata_props: Dict[str, str] | None = None) Tuple[List[str], Tuple[str, str]][source]#

Converts builder into a local ONNX function and registers it.

Parameters:
  • builder – source GraphBuilder for the function body

  • function_options – controls naming, inlining, and weight handling

  • optimize – run optimizations on the function body

  • metadata_props – extra key/value metadata for the function

Returns:

(added_initializers, (domain, name))

make_new_dynamic_shape(rank: int, prefix: str = 'd') Tuple[Any, ...][source]#

Creates a dynamic shape of the given rank with fresh symbolic dimensions.

Parameters:
  • rank – number of dimensions

  • prefix – prefix for the generated dimension names

Returns:

tuple of torch.SymInt objects

make_nodes(builder: Any, input_names: List[str], output_names: List[str], prefix: str = '', function_options: Any | None = None, optimize: bool = False, force_rename_with_prefix: str | None = None) Any[source]#

Appends all nodes and initializers from builder into this graph.

Parameters:
  • builder – source GraphBuilder

  • input_names – names of the inputs that correspond to builder’s inputs in the current graph

  • output_names – desired output names in the current graph

  • prefix – prefix applied to every result name from builder when function_options is None

  • function_options – when set the sub-graph is exported as a local ONNX function

  • optimize – run optimizations on the appended sub-graph

  • force_rename_with_prefix – force this prefix regardless of function_options

Returns:

output name(s) in the current graph

make_subset_builder(input_names: List[str], name: str, domain: str, add_local_functions: bool = False) Any[source]#

Creates a reduced copy of this builder that covers only the tensors reachable from input_names.

Parameters:
  • input_names – graph inputs for the subset

  • name – local-function name for the subset

  • domain – local-function domain for the subset

  • add_local_functions – copy local functions into the subset

Returns:

new GraphBuilder instance

make_tensor_sequence_input(name: str, elem_type: Any, shape: Any, marker: str = '') str[source]#

Registers a tensor-sequence graph input and returns its name.

Parameters:
  • name – desired input name

  • elem_type – ONNX element type for the sequence elements

  • shape – shape of each element

  • marker – optional label for debugging / provenance

Returns:

the registered input name

pretty_text(add_fx_graph: bool = False, recursive: bool = True) str[source]#

Returns a human-readable multi-line description of the graph.

Parameters:
  • add_fx_graph – include the original FX graph text

  • recursive – include local functions

Returns:

formatted string

register_dynamic_objects_from_shape(shape: Any) None[source]#

Registers all dynamic-dimension objects found in shape.

Parameters:

shape – shape tuple potentially containing symbolic dimensions

register_users(name: str, users: Iterable[str]) None[source]#

Registers the consumers of tensor name (used for validation).

Parameters:
  • name – producer tensor name

  • users – iterable of consumer tensor names

set_device(name: str, device: Any, exc: bool = True, keep_this_device: bool = False) None[source]#

Records the device for tensor name.

Parameters:
  • name – tensor name

  • device – device identifier — an int index, a torch.device, or a constant name

  • exc – raise an exception on inconsistency

  • keep_this_device – overwrite an already-known device

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

Records the rank for tensor name.

Parameters:
  • name – tensor name

  • value – rank (number of dimensions)

set_sequence(name: str, dtype: Any, shapes: Any | None = None, ranks: Any | None = None, unknown: bool = False) None[source]#

Marks name as a tensor sequence.

Parameters:
  • name – tensor name

  • dtype – element type (ONNX integer or tuple of integers)

  • shapes – optional tuple of per-element shapes

  • ranks – optional tuple of per-element ranks

  • unknown – set True when sequence contents are unknown

set_shapes_types(name: Any, where: str, value: Any) None[source]#

Records a torch-side (where, value) annotation for name.

The annotation is later consulted by get_type_known() to resolve type mismatches between ONNX and torch.

Parameters:
  • name – tensor name (or a torch.fx.Node)

  • where – source label (e.g. "run_node")

  • value – annotation value (a tuple describing type / shape)

verify_dynamic_shape(shape: Any, name: str | None = None, add: bool = True) Any | None[source]#

Normalises shape, replacing symbolic dimensions with their registered string names.

Parameters:
  • shape – raw shape (may contain torch.SymInt)

  • name – tensor name for context messages

  • add – register newly encountered symbolic dims automatically

Returns:

normalised shape tuple or None if shape is None

class yobx.typing.InferenceSessionLike(*args, **kwargs)[source]#
class yobx.typing.OpsetProtocol(*args, **kwargs)[source]#

Protocol describing the API of an opset helper object.

Both Opset (used by GraphBuilder) and the internal opset helper in OnnxScriptGraphBuilder satisfy this protocol.

The primary usage pattern is attribute-access dispatch:

out = g.op.Relu(x)   # resolves via __getattr__("Relu"), then calls result

__getattr__ must return a callable that, when invoked, creates the corresponding ONNX node and returns its output name(s).

class yobx.typing.TensorLike(*args, **kwargs)[source]#