flatten#
- class brainstate.graph.flatten(node, /, ref_index=None, treefy_state=True)#
Flatten a graph
nodeinto a(GraphDef, NestedDict)pair.Graph nodes and
Stateobjects are hoisted into a single global index space (deduplicated by identity, so shared references and cycles collapse to one index); pytree containers are embedded inline and re-expanded per occurrence.- Parameters:
node (
Any) – The root graph node or pytree to flatten.ref_index (
RefMap|None) – An identity mapobject -> indexto accumulate into. When supplied (e.g. bysplit_context), indices are global across multiple calls so cross-object references share indices. A fresh map is used ifNone.treefy_state (
bool) – IfTruethe state mapping holdsTreefyStatevalues; ifFalseit holds the rawStateobjects.
- Returns:
The static structure and the dynamic state mapping.
- Return type:
- Raises:
TypeError – If
ref_indexis not aRefMap, or a static attribute value is not hashable.ValueError – If
nodeis not a graph node or pytree (e.g. a bareState).
Examples
>>> import brainstate >>> model = brainstate.nn.Linear(2, 3) >>> graphdef, states = brainstate.graph.flatten(model) >>> isinstance(states, brainstate.util.NestedDict) True