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_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
Nonethe input’s element type is used
- Returns:
Truewhen shape information was available and set,None/falsy when it could not be determined
- 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 isyobx.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
GraphBuilderinstance.
- do_not_turn_constant_initializers_maybe_because_of_showing(name: str) bool[source]#
Returns
Truewhen the initializer for name must not be folded into aConstantnode (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
AttributeProtonamed att_name on node.- Parameters:
node –
NodeProtoatt_name – attribute name
exc – raise an exception if the attribute is missing
- Returns:
AttributeProtoorNone
- 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:
node –
NodeProtoname – 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:
node –
NodeProtodefault_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
axisattribute of node.- Parameters:
node –
NodeProtodefault_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.ndarrayor 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:
node –
NodeProtoattribute – 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, orcomplex
- 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
Nonewhen exc isFalse
- 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
intor 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/Falsewhen known,Noneotherwise
- has_processor(processor: str) bool[source]#
Returns
Truewhen processor is in the active processor list.- Parameters:
processor – processor name, e.g.
"CUDA"
- has_rank(name: str) bool[source]#
Returns
Truewhen the rank of name is known.- Parameters:
name – result name
- has_shape(name: str) bool[source]#
Returns
Truewhen the full shape of name is known.- Parameters:
name – result name
- has_type(name: str) bool[source]#
Returns
Truewhen the element type of name is known.- Parameters:
name – result name
- property inputs: List[Any]#
Graph input value infos.
- Returns:
list of
ValueInfoProtoobjects
- is_constant(name: str) bool[source]#
Returns
Truewhen 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
Truewhen name is a scalar constant.- Parameters:
name – result name
value – if not
None, also check that the scalar equals this valuebroadcast – treat shapes
(1,),(1,1), … as scalar
- is_output(name: str) bool[source]#
Returns
Truewhen name is a graph output.- Parameters:
name – result name
- is_used(name: str) bool[source]#
Returns
Truewhen name is consumed by any node or is a graph output.- Parameters:
name – result name
- is_used_by_subgraph(name: str) bool[source]#
Returns
Truewhen name is used inside a sub-graph.- Parameters:
name – result name
- is_used_more_than_once(name: str) bool[source]#
Returns
Truewhen 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
Truewhen 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)
value –
numpy.ndarrayorTensorProtovalueexternal – 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 namesdomain – operator domain
attributes – list of
AttributeProtoobjectsname – node name
kwargs – operator attributes as Python primitives
- Returns:
- 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/Unsqueezeaxis 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 namesdomain – operator domain (must be
""for the main domain)attributes – list of
AttributeProtoobjectsname – node name
kwargs – operator attributes as Python primitives
- Returns:
- 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:
- 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:
NodeProtoorNoneif name is an input or initializer
- property opsets: Dict[str, int]#
Mapping from domain name to opset version.
- Returns:
dict of domain → opset version
- property outputs: List[Any]#
Graph output value infos.
- Returns:
list of
ValueInfoProtoobjects
- 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
- same_shape(a: str, b: str) bool[source]#
Returns
Truewhen 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
0when unknown
- 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.- 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_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, astr(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
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
- 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, orfloat)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 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 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
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: 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
- 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
GraphBuilderExtendedProtocolwith the additional methods and attributes used byDynamoInterpreter(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 —
is_sequence(),get_sequence(),set_sequence(),make_tensor_sequence_input().Dynamic-shape helpers —
is_dynamic_shape(),get_input_dynamic_shape(),get_is_dimension(),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_is_dimension(name: str, elem_type: int | None = None, shape: Any | None = None, n_outputs: int | None = None, exc: bool = True) bool[source]#
Returns
Truewhen name represents a scalar dynamic-dimension value (e.g. the result ofaten.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
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
- is_sequence(name: str) bool[source]#
Returns
Truewhen 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
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_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_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).