TensorPlay
API reference
latest (dev)
Copy
View Markdown

Latest development documentation · Updated 2026-10-08

tensorplay.export API

Functions 12

#

default_decompositions

functionFull reference ↗
tensorplay.export.default_decompositions() → Any[source]

Return the mutable table of built-in graph rewrites.

#

draft_export

functionFull reference ↗
tensorplay.export.draft_export(model: Any, *args: Any, dynamic_shapes: Any = None, **kwargs: Any) → DraftExportReport[source]

Capture a program, reporting failures instead of raising them.

On success the returned report carries the captured program, checked two ways: structural validation of the graph, and a numerical comparison of the captured program against eager execution on the example inputs. When capture fails, the report records the failure and exported_program stays None; call raise_on_failure() to surface the errors.

#

export

functionFull reference ↗
tensorplay.export.export(model: Callable[[...], Any], *args: Any, dynamic_shapes: Any = None, strict: bool = False, preserve_module_call_signature: Any = (), **kwargs: Any) → ExportedProgram[source]

Capture a callable and return an executable graph program.

Parameters:
  • model – an nn.Module or plain callable; child modules are inlined.

  • args/kwargs – example inputs binding argument defaults.

  • dynamic_shapes – dimension specification per argument (dict, sequence, ShapesCollection, or AdditionalInputs).

  • strict – reserved for callers of the strict capture contract; capture validation is identical in both modes.

  • preserve_module_call_signature – submodule paths whose call metadata is recorded in module_call_graph for module-level tooling.

#

refine_dynamic_shapes_from_suggested_fixes

functionFull reference ↗
tensorplay.export.refine_dynamic_shapes_from_suggested_fixes(message: str, dynamic_shapes: Any) → Any[source]

Apply suggested fixes (range refinements, specializations, relations).

Supported fix forms:

name = Dim('name', min=..., max=...)  # refine a range
name = 4                              # specialize to a constant
dy = dx + 1                           # tie a dim to another with a relation
dy = 2*dx                             # positive multiple of another dim

dx must name a dimension already present in dynamic_shapes or be defined by an earlier fix line.

#

register_dataclass

functionFull reference ↗
tensorplay.export.register_dataclass(cls: type[Any], *, serialized_type_name: str | None = None, return_none_fields: bool = True) → type[Any][source]

Register a dataclass as a flattenable graph value.

serialized_type_name pins the qualified name recorded in serialized artifacts; it must resolve back to cls when the program is loaded. return_none_fields keeps None-valued fields as single None leaves instead of flattening them by field.

#

unflatten

functionFull reference ↗
tensorplay.export.unflatten(module: ExportedProgram, flat_args_adapter: FlatArgsAdapter | None = None, preserve_ops: Any = ()) → UnflattenedModule[source]

Build an executable module view from an exported program.

When the capture recorded module call boundaries, the view reconstructs the original module hierarchy (attribute access and submodule calls work as in the source model). Otherwise it falls back to the flat view.

Classes 27

#

AdditionalInputs

classFull reference ↗
class tensorplay.export.AdditionalInputs[source]

Infer dynamic shape markers from representative input sets.

#

ConstantArgument

classFull reference ↗
class tensorplay.export.ConstantArgument(name: 'str', value: 'int | float | bool | str | None')[source]
#

Constraint

classFull reference ↗
class tensorplay.export.Constraint(source: Any, dim: int, name: str | None = None, min: int | None = None, max: int | None = None, warn_only: bool = False, root: str | None = None, scale: int = 1, offset: int = 0)[source]

A range restriction attached to one input dimension.

name ties the constraint to a named Dim shared across inputs (equalities are implied). root/scale/offset describe a derived dimension whose size equals scale * root_size + offset. Constraints without a name come from dim hints or static entries.

#

CustomDecompTable

classFull reference ↗
class tensorplay.export.CustomDecompTable(entries: Mapping[Any, Callable[[...], Any]] | Iterable[tuple[Any, Callable[[...], Any]]] | None = None, *, defaults: bool = True)[source]

A validated mutable mapping from graph targets to replacement callables.

Entries are keyed by graph target (callable or method name). Removing a key preserves the op from rewriting; materialize returns a plain dict for consumers that require one.

clear() → None.  Remove all items from D.
classmethod fromkeys(iterable, value=None, /)

Create a new dictionary with keys from iterable and values set to value.

materialize() → dict[Any, Callable[[...], Any]][source]

Return a plain dict of effective entries, resolving defaults.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

remove(target: Any) → Callable[[...], Any][source]

Preserve target by deleting its decomposition entry.

setdefault(key, default=None, /)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

#

CustomObjArgument

classFull reference ↗
class tensorplay.export.CustomObjArgument(name: 'str', class_fqn: 'str', fake_val: 'Any' = None)[source]
#

EqualityConstraint

classFull reference ↗
class tensorplay.export.EqualityConstraint(sites: tuple[tuple[str, int], ...], name: str | None = None)[source]

Ties several input sites to one shared dimension size.

sites lists every (input placeholder name, dim index) pair whose runtime sizes must stay equal; name is the symbolic dimension they implement when the tie comes from a shared Dim, else None.

#

ExportBackwardSignature

classFull reference ↗
class tensorplay.export.ExportBackwardSignature(gradients_to_parameters: 'dict[str, str]', gradients_to_user_inputs: 'dict[str, str]', loss_output: 'str')[source]
#

ExportedProgram

classFull reference ↗
class tensorplay.export.ExportedProgram(graph_module: GraphModule, graph_signature: ExportGraphSignature | GraphSignature, example_inputs: dict[str, ~typing.Any]=<factory>, dynamic_shapes: Any = None, module_call_graph: list[ModuleCallEntry] = <factory>, range_constraints: dict[~typing.Any, ~typing.Any]=<factory>, equality_constraints: list[EqualityConstraint] = <factory>, verifier: Any = None)[source]

A validated graph together with its state and example bindings.

buffers() → Iterator[Any][source]

Iterate over the captured module’s buffers.

static call_exported(program: ExportedProgram) → Callable[[...], Any][source]

Return a callable executing the flat contract on user arguments.

property code: str

Python source of the captured graph’s generated forward.

classmethod deserialize(artifact: Any, state_dict: Any = None, constants: Any = None, example_inputs: Any = None) → ExportedProgram[source]

Rebuild a program from serialize() artifacts.

invalidate_unlifted() → None[source]

Drop the cached unlifted module so the next call rebuilds it.

module() → GraphModule[source]

Return a self-contained module with lifted state folded back in.

The returned module takes only the user arguments: state placeholders are rewritten into attribute reads on a fresh module that owns the parameter, buffer, and constant values. The result is cached; pass rebind to drop state changes made through this program view.

parameters() → Iterator[Any][source]

Iterate over the captured module’s parameters.

run_decompositions(decomp_table: Any = None) → ExportedProgram[source]

Return a copied program after applying registered graph rewrites.

Entries map a graph target (a callable, a method name, or a target string) to a builder invoked as builder(graph, node); the builder creates the replacement nodes and returns the value users should consume. Nodes whose target has no entry are left untouched.

serialize(opset_version: Any = None, pickle_protocol: int = 4) → Any[source]

Return serialized program artifacts (JSON program + example inputs).

property state_dict: dict[str, Any]

Tensor values of the lifted parameters and persistent buffers.

property tensor_constants: dict[str, Any]

Lifted non-parameter, non-buffer tensor values.

#

ExportGraphSignature

classFull reference ↗
class tensorplay.export.ExportGraphSignature(input_specs: list[InputSpec], output_specs: list[OutputSpec])[source]

Describe lifted state, user values, mutations, and graph outputs.

property assertion_dep_token: Mapping[int, str] | None

Position of the assertion dependency token output, if present.

clone() → ExportGraphSignature[source]

Deep copy: specs and argument records are duplicated, not shared.

get_param_to_buffer() → Mapping[str, str][source]

Map parameter targets to the buffer targets holding their gradients.

Gradients are declared as GRADIENT_TO_PARAMETER outputs; a gradient for a parameter whose optimizer state lives in a buffer binds the two targets under the parameter’s FQN.

get_replace_hook(replace_inputs: bool = False)[source]

Build a rename hook suitable for graph rewriting passes.

is_buffer(name: str) → bool[source]

Whether name is a placeholder carrying a lifted buffer.

is_param(name: str) → bool[source]

Whether name is a placeholder carrying a lifted parameter.

replace_all_uses(old: str, new: str) → None[source]

Rename a graph value across every input and output spec.

#

FlatArgsAdapter

classFull reference ↗
class tensorplay.export.FlatArgsAdapter[source]

Adapt one flattened argument layout into another layout.

#

InputSpec

classFull reference ↗
class tensorplay.export.InputSpec(kind: 'InputKind', arg: 'ArgumentSpec', target: 'str | None' = None, persistent: 'bool | None' = None)[source]
#

ModuleCallEntry

classFull reference ↗
class tensorplay.export.ModuleCallEntry(fqn: 'str', signature: 'ModuleCallSignature | None' = None)[source]
#

ModuleCallSignature

classFull reference ↗
class tensorplay.export.ModuleCallSignature(inputs: 'list[ArgumentSpec]', outputs: 'list[ArgumentSpec]', in_spec: 'TreeSpec | None' = None, out_spec: 'TreeSpec | None' = None, forward_arg_names: 'list[str] | None' = None)[source]
#

OutputSpec

classFull reference ↗
class tensorplay.export.OutputSpec(kind: 'OutputKind', arg: 'ArgumentSpec', target: 'str | None' = None)[source]
#

PT2ArchiveContents

classFull reference ↗
class tensorplay.export.PT2ArchiveContents(exported_programs: 'dict[str, Any]'=<factory>, tp_runners: 'dict[str, Any]'=<factory>, extra_files: 'dict[str, Any]'=<factory>)[source]
#

ShapesCollection

classFull reference ↗
class tensorplay.export.ShapesCollection[source]

Associate shape specifications with tensor objects by identity.

#

WeightType

classFull reference ↗
class tensorplay.export.WeightType(*values)[source]

Role a packaged weight plays in the captured program.

as_integer_ratio()

Return a pair of integers, whose ratio is equal to the original int.

The ratio is in lowest terms and has a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count()

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

classmethod from_bytes(bytes, byteorder='big', *, signed=False)
imag

the imaginary part of a complex number

is_integer()

Returns True. Exists for duck type compatibility with float.is_integer.

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes(length=1, byteorder='big', *, signed=False)

Attributes 1

Exceptions 1

#

ConstraintsExceededError

exceptionFull reference ↗
exception tensorplay.export.ConstraintsExceededError[source]

A runtime input violated the declared dynamic-shape contract.

Raised by the assertions inserted into captured graphs and by export-time validation when an example input falls outside a declared range. It is a RuntimeError so callers written against plain runtime failures keep working.

On this page

Ask DeepWiki