yobx.typing#
- class yobx.typing.ConvertOptionsProtocol(*args, **kwargs)[source]#
Protocol for a class giving indications on how to convert a model.
- 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.containeris set), the rawprotohas external-data placeholders instead of embedded weight tensors. Passinginclude_weights=True(the default) usesto_ir()to build a fully self-containedModelProto.- Parameters:
include_weights – when
True(default) embed the large initializers stored incontainerinto the returned proto. WhenFalsereturn the raw proto as-is.- Returns:
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) anExtendedModelContaineris created and returned incontainer. Otherwise the proto is loaded directly withonnx.load()andcontainerisNone.- Parameters:
file_path – path to the
.onnxfile.load_large_initializers – when
True(default) also load the large initializers stored alongside the model file.
- Returns:
ExportArtifactwithfilenameset 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
ExtendedModelContaineris present (large_model=Truewas used during export) the model and its external weight files are saved viasave(). Otherwise the proto is saved withonnx.save_model().- Parameters:
file_path – destination file path (including
.onnxextension).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
GraphBuilderProtocolwith additional methods present onyobx.xbuilder.GraphBuilderandyobx.builder.onnxscript.OnnxScriptGraphBuilderthat are useful for advanced graph construction:main_opset— the opset version for the main (""/ONNX) domain.op— an opset helper that allows constructing nodes withg.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 asAbs,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, evaluateNodeProtoconstants using a reference runtimeas_shape – if
True, return a tuple of integers (a shape)multiple_outputs – allow the constant to have multiple outputs
- Returns:
the constant value, or
Nonewhen exc isFalseand 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
Truewhen name is a known constant in the graph.- Parameters:
name – result name
- Returns:
Trueif 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
Nonethe input’s element type is used
- Returns:
Truewhen 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
INT64tensor (or symbolic equivalent) whose contents describe the dimensions of another tensor. The method returns:A
tupleofint/ symbolic-dimension values when the shape value is fully known (e.g. a constant or a previously recordedset_value_shapecall).Nonewhen 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.GraphBuilderandyobx.builder.onnxscript.OnnxScriptGraphBuildersatisfy this protocol.Builders whose
to_onnxmethod acceptsreturn_optimize_reportcan declaresupports_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
Falseand 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, astr(symbolic dimension), orNone(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
Truewhen 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
0if the domain is unknown
- has_shape(name: str) bool[source]#
Returns
Truewhen 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
- is_sequence(name: str) bool[source]#
Returns
Truewhen 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, orfloat)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 namesdomain – operator domain (default
""= standard ONNX)attributes – list of
onnx.AttributePrototo attachname – 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
strfor symbolic or unknown dimensions (e.g."batch"or"?"), and anintfor fixed-size dimensionsdevice – 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
- 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
Truewhen 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
GraphBuilderExtendedProtocolwith the additional methods and attributes used byFxGraphInterpreter(the torch exporter) when translating atorch.fxgraph into ONNX.The extra surface covers:
Rank helpers —
has_rank(),get_rank(),set_rank().Device helpers —
has_device(),get_device(),set_device().Extended type / shape —
get_type_known(),set_shapes_types().Tensor-sequence support —
make_tensor_sequence_input().Dynamic-shape helpers —
is_dynamic_shape(),get_input_dynamic_shape(),verify_dynamic_shape(),register_dynamic_objects_from_shape(),make_dynamic_object(),add_dynamic_object(),make_new_dynamic_shape().Sub-builder / local-function support —
make_nodes(),make_local_function(),make_subset_builder().Miscellaneous —
add_stat(),pretty_text(),register_users(),extract_input_names_from_args().State attributes —
anyop,as_function,local_domain,verbose,torch,optimization_options,dynamic_shapes,dynamic_objects,dynamic_dimensions_source,nodes,outputs,opsets,initializers_dict,raise_list,was_inputs_renamed,last_added_node.
- 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 similarname – 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
opbut configured to accept unknown domains. Used by the torch exporter to emit custom-domain operators such asai.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
-1for 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_shapesexample_value – one example tensor value
- Returns:
shape tuple (mixing
intfor static dimensions andstrfor 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
Nonewhen 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
Truewhen the device of tensor name is known.- Parameters:
name – tensor name
- has_rank(name: str) bool[source]#
Returns
Truewhen 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
Truewhen 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
Noneentries as dynamicallow_new_dynamic_dimension – allow unregistered symbolic dims
- property last_added_node: Any | None#
The most recently appended ONNX node, or
Nonewhen the graph is still empty.- Returns:
an
NodeProtoorNone
- 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.SymIntor similar symbolic valueshape_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
GraphBuilderfor the function bodyfunction_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.SymIntobjects
- 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
GraphBuilderinput_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
Nonefunction_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
GraphBuilderinstance
- 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
intindex, atorch.device, or a constant nameexc – 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
Noneif shape isNone
- class yobx.typing.OpsetProtocol(*args, **kwargs)[source]#
Protocol describing the API of an opset helper object.
Both
Opset(used byGraphBuilder) and the internal opset helper inOnnxScriptGraphBuildersatisfy 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).