graph_to_tree#
- class brainstate.graph.graph_to_tree(may_have_graph_nodes, /, *, prefix=<class 'brainstate.typing.Missing'>, split_fn=<function _default_split_fn>, map_non_graph_nodes=False, check_aliasing=True)[source]#
Convert a pytree that may contain graph nodes into a pure pytree.
Every graph node embedded in the input is replaced (by
split_fn, which defaults to wrapping it in aNodeStates) so the result is a plain pytree safe to pass through JAX transformations. Aliasing across the split nodes is collected so it can be restored later bytree_to_graph().- Parameters:
may_have_graph_nodes (Any) – A pytree whose leaves may include graph nodes (
Nodesubclasses and registered graph-node types). Passed positionally.prefix (
Any) – A prefix pytree broadcast overmay_have_graph_nodesand handed tosplit_fnper leaf. Defaults toMissing(no prefix).split_fn (
Callable[[SplitContext,tuple[TypeVar(KeyEntry),...],Any,TypeVar(Leaf)],Any]) – Called assplit_fn(ctx, keypath, prefix, leaf)for each graph node (and, whenmap_non_graph_nodesis true, for every other leaf). The default wraps the node’s split result in aNodeStates.map_non_graph_nodes (
bool) – WhenTrue, also runsplit_fnon non-graph-node leaves. Defaults toFalse.check_aliasing (
bool) – WhenTrue(default), verify that shared/aliased graph nodes are consistent withprefixand raise if not.
- Return type:
tuple[PyTree,dict[tuple[TypeVar(KeyEntry),...],int|Array|ndarray]]- Returns:
pytree_out (PyTree) – The input pytree with graph nodes replaced by
split_fnoutputs.find_states (dict) – A mapping from key-path to the
Stateobjects discovered while splitting, used to relink shared state on the way back.
See also
tree_to_graphThe inverse conversion.