Tree API¶
Nested-structure helpers with the public API of
jax.tree. Pure Python; the
only binary dependency is NumPy (no JAX, no C++ pytree). None is an
empty pytree.
Public functions and built-in walking rules are stable. Custom-type
registration (__tree_flatten__ / __tree_unflatten__ and JAX / Torch /
optree registries) is beta — see Overview.
Why this exists (and how it relates to jax.tree / dm-tree / optree):
Why tree.
anytensor.tree
¶
Nested-structure utilities with the public API of jax.tree.
Pure Python; the only binary dependency is NumPy (no JAX, no C++ pytree
extension). Walking rules follow jax.tree / jax.tree_util:
Noneis an empty pytree (zero leaves), not a leaf.flatten(tree)returns(leaves, treedef).- Dicts flatten by sorted keys;
OrderedDictkeeps insertion order. - Arrays / tensors are leaves.
str/bytes/ sets / mapping views are leaves.
Custom nodes
-
Magic flatten (beta)::
def tree_flatten(self): return children, aux
@classmethod def tree_unflatten(cls, aux, children): return cls(...)
-
Batch / unbatch (stable; same functions as :mod:
anytensor.jraphbatch/unbatch). Checked before walking children. Use AnyTensor ops so the type stays portable::@classmethod def tree_batch(cls, xs, axis=0): return cls(at.concatenate([x.values for x in xs], axis=axis))
def tree_unbatch(self, axis=0): n = int(at.shape(self.values)[axis]) ids = at.arange(n, like=self.values) return [ cls(at.take(self.values, ids[i : i + 1], axis=axis)) for i in range(n) ]
GraphsTuple implements these (offset senders/receivers). Objects
without magic unbatch along the leading axis into unit slices.
- Already-imported pytree registries (beta), looked up by type
(never imported as a side effect):
jax.tree_util,torch.utils._pytree, andoptree. Built-in containers stay on this module's path.
Public map / flatten / batch / unbatch and built-in walking
rules are stable. Flatten-style registration (item 1 and item 3) may
change.
SequenceKey
¶
DictKey
¶
GetAttrKey
¶
PyTreeDef
¶
Tree structure leftover after flattening (jax.tree_util.PyTreeDef-like).
Source code in anytensor/tree.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
flatten_up_to
¶
Flatten tree using this schema; stop at each leaf of self.
self must be a prefix of tree's structure (same as JAX). Values
at leaf positions are returned as-is — so a post-split tree of
chunk lists can be flattened with the unsplit batch's treedef.
Source code in anytensor/tree.py
flatten
¶
Flatten tree into (leaves, treedef).
import anytensor.tree as tree leaves, _ = tree.flatten((1, (2, 3))) tuple(leaves) (1, 2, 3) empty, _ = tree.flatten(None) len(empty) 0
Source code in anytensor/tree.py
unflatten
¶
leaves
¶
structure
¶
map
¶
Map f over the leaves of tree (and rest).
Subsequent trees are flattened with tree's schema via
:meth:PyTreeDef.flatten_up_to (JAX-style prefix).
import anytensor.tree as tree tree.map(lambda v: v * 2, {"b": 1, "a": [2, 3]}) {'a': [4, 6], 'b': 2} tree.map(lambda x: x + 1, None) is None True
Source code in anytensor/tree.py
flatten_with_path
¶
leaves_with_path
¶
map_with_path
¶
Like :func:map but f receives (path, *leaves).
Source code in anytensor/tree.py
all
¶
reduce
¶
Reduce leaves with function (same empty-tree error as functools.reduce).
Source code in anytensor/tree.py
batch
¶
Batch a sequence of pytrees along axis (leading axis by default).
Same function as :func:anytensor.jraph.batch. If the type defines
__tree_batch__(xs, axis=0), that method is used and children are
not walked. Otherwise leaves are concatenated with
:func:anytensor.concatenate. All-None stays None.
import numpy as np import anytensor.tree as tree tree.batch([np.array([1, 2]), np.array([3])]) array([1, 2, 3])
Source code in anytensor/tree.py
unbatch
¶
Unbatch structure along axis into unit slices.
Same function as :func:anytensor.jraph.unbatch. __tree_unbatch__(axis=0)
on the object wins (GraphsTuple yields one graph per n_node entry).
Nested containers recurse. Top-level None cannot infer a batch size.
import numpy as np import anytensor.tree as tree head, tail = tree.unbatch(np.arange(1, 3)) tuple(int(x) for x in head), tuple(int(x) for x in tail) ((1,), (2,))