yobx.typing#

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

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

available_options() → Sequence[str][source]#

Returns the list of options.

has(option_name: str, piece: object, name: str | None = None) → bool[source]#

Returns true if option option_name applies to piece

class yobx.typing.DefaultConvertOptions[source]#

All options are disabled.

available_options() → Sequence[str][source]#

Returns the list of options.

has(option_name: str, piece: object, name: str | None = None) → 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_constant(name: str, exc: bool = True, computed_value: bool = False, as_shape: bool = False, multiple_outputs: bool = False) → Any | None[source]#

Returns the constant value for name.

Parameters:
  • name – constant name

  • exc – raise an exception if the constant cannot be retrieved

  • computed_value – if True, evaluate NodeProto constants using a reference runtime

  • as_shape – if True, return a tuple of integers (a shape)

  • multiple_outputs – allow the constant to have multiple outputs

Returns:

the constant value, or None when exc is False and the value cannot be determined

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

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

Returns True when name is a known constant in the graph.

Parameters:

name – result name

Returns:

True if the result is a constant

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

value_as_shape(name: str) → Any[source]#

Returns the value of a result if it is known to represent a shape.

A shape value is a 1-D INT64 tensor (or symbolic equivalent) whose contents describe the dimensions of another tensor. The method returns:

  • A tuple of int / symbolic-dimension values when the shape value is fully known (e.g. a constant or a previously recorded set_value_shape call).

  • None when the value cannot be determined.

Parameters:

name – result name to query

Returns:

tuple of dimension values, or None

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.

Builders whose to_onnx method accepts return_optimize_report can declare supports_optimization_report = True. Converters then forward report requests without requiring inheritance from the Python GraphBuilder. The capability is optional so existing third-party builders remain valid.

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_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_shape(name: str) → ONNX_SHAPE[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), or None (unknown 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.

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

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

Parameters:

name – tensor name

make_initializer(name: str, value: Any, give_unique_name: bool = True, source: str | None = None) → 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

  • source – used to track where this initializer was added

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 tuple

make_tensor_input(name: str, elem_type: int | None = None, shape: ONNX_SHAPE | 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: ONNX_SHAPE | 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.

prefix_name_context(prefix: str) → ContextManager[None, bool | None][source]#

Context manager that scopes all unique_name() calls to prefix.

While the context is active, every name returned by unique_name() is prefixed with the joined stack of active prefixes so that tensors produced inside the block are clearly associated with their enclosing scope (e.g. a pipeline step name). Contexts may be nested; each level pushes one entry onto the stack.

Parameters:

prefix – scope prefix to push (e.g. a pipeline step name)

Returns:

a context manager; use as with g.prefix_name_context("step"): ...

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

Registers a domain with its opset version.

Parameters:
  • domain – domain name

  • version – opset version

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_shape(name: str, shape: ONNX_SHAPE, 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 FxGraphInterpreter (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

  • value – torch.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_rank(name: str) → int[source]#

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

Parameters:

name – tensor name

Returns:

non-negative integer rank

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

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

  • value – torch.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_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]#