Pytrees¶
Pytrees let transforms preserve nested tuples, lists, dictionaries, and registered application containers while differentiating the arrays inside them. Other values remain part of the structure. Custom classes may register a node type for dynamic transforms; staged programs accept the built-in portable container forms rather than arbitrary Python class registrations.
pytree ¶
Public pytree utilities.
This module exposes Advect's structured tree utilities for advanced users.
Static
dataclass
¶
Wrapper for marking values as static (non-flattened) in pytrees.
TreeDef
dataclass
¶
TreeDef(
node_type: type[Any] | None,
aux_data: Any,
children: tuple[TreeDef, ...],
num_leaves: int,
)
A structural description of a pytree.
Attributes:
-
node_type(type[Any] | None) –Container node type, or None for leaf nodes.
-
aux_data(Any) –Node-specific metadata needed to reconstruct the tree.
-
children(tuple[TreeDef, ...]) –Child TreeDefs.
-
num_leaves(int) –Total number of leaves in this subtree.
format_path ¶
register_pytree_node ¶
register_pytree_node(
cls: type[Any],
*,
flatten_fn: _FlattenFn,
unflatten_fn: _UnflattenFn,
) -> None
Register a custom pytree node type.
Parameters:
-
cls(type[Any]) –Class to register as a pytree node.
-
flatten_fn(_FlattenFn) –Function
flatten_fn(obj) -> (children, aux_data). -
unflatten_fn(_UnflattenFn) –Function
unflatten_fn(aux_data, children) -> obj.
static ¶
static(value: T) -> Static[T]
Wrap value as a static pytree node.
Static nodes have no leaves: they are preserved by tree_map and
passed through tracing/autodiff as untraceable metadata.
Examples:
tree_flatten_with_paths ¶
tree_flatten_with_paths(
tree: Any,
) -> tuple[list[TreePath], list[Any], TreeDef]
Flatten a pytree into (paths, leaves, treedef).
Paths are tuples of typed path entries describing the location of each leaf.
Dict nodes use DictKey, and sequence-like nodes use SequenceKey.
Examples:
tree_leaves ¶
tree_map ¶
$ █