UniqueStateManager#
- class braintools.optim.UniqueStateManager(pytree=None)#
Manage unique
brainstate.Stateobjects within a PyTree structure.This class flattens a PyTree with
Stateleaves to(path, leaf)pairs, removes duplicateStateobjects based on theirid(), and supports recovering the unique states back to a PyTree structure.- Parameters:
pytree (
State]) – If provided,make_unique()is called on it during construction.
Examples
>>> import jax.numpy as jnp >>> from brainstate import ParamState >>> >>> # Create a pytree with some duplicate State objects >>> state1 = ParamState(jnp.ones((2, 3))) >>> state2 = ParamState(jnp.zeros((3, 4))) >>> pytree = { ... 'layer1': {'weight': state1, 'bias': state2}, ... 'layer2': {'weight': state1, 'bias': ParamState(jnp.ones((4,)))} # duplicate ... } >>> >>> # Create manager and process the pytree >>> manager = UniqueStateManager() >>> unique_pytree = manager.make_unique(pytree) >>> print(len(manager.flattened_states)) # 3, not 4 (duplicate removed) 3 >>> >>> # Recover to pytree structure >>> recovered = manager.to_pytree()
- get_state_by_path(target_path)[source]#
Retrieve a
Stateobject by its path.- Parameters:
target_path (
Any) – The path to the desiredState.- Returns:
The
Stateobject at the given path, orNoneif not found.- Return type:
State
- make_unique(pytree)[source]#
Process a PyTree with State leaves and remove duplicates.
- Parameters:
pytree (
State]) – A PyTree whose leaves arebrainstate.Stateobjects.- Returns:
A PyTree containing only unique
Stateobjects (duplicates removed).- Return type:
State]
- merge_with(other_pytree)[source]#
Merge another PyTree into the current unique states, maintaining uniqueness.
- Parameters:
other_pytree (
State]) – Another PyTree withStateleaves to merge in.- Returns:
self, with the new unique states merged in.- Return type:
- to_pytree()[source]#
Convert the stored unique states back to a PyTree structure.
- Returns:
PyTree with the unique
Stateobjects as leaves.- Return type:
State]