jax.tree.flatten(tree, is_leaf=None)#

Flattens a pytree.

Alias of jax.tree_util.tree_flatten().

The flattening order (i.e. the order of elements in the output list) is deterministic, corresponding to a left-to-right depth-first tree traversal.

  • tree (Any) – a pytree to flatten.

  • is_leaf (Callable[[Any], bool] | None) – an optionally specified function that will be called at each flattening step. It should return a boolean, with true stopping the traversal and the whole subtree being treated as a leaf, and false indicating the flattening should traverse the current object.

Return type:

tuple[list[Leaf], PyTreeDef]


A pair where the first element is a list of leaf values and the second element is a treedef representing the structure of the flattened tree.


>>> import jax
>>> vals, treedef = jax.tree.flatten([1, (2, 3), [4, 5]])
>>> vals
[1, 2, 3, 4, 5]
>>> treedef
PyTreeDef([*, (*, *), [*, *]])