brainx-skill 1.0.2 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +24 -56
  3. package/{lib → installation/lib}/installer.js +4 -4
  4. package/manifest.json +3 -1
  5. package/package.json +19 -9
  6. package/skills/brainstate/SKILL.md +399 -0
  7. package/skills/brainstate/agents/openai.yaml +4 -0
  8. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +483 -0
  9. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +176 -0
  10. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +199 -0
  11. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +166 -0
  12. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +210 -0
  13. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +450 -0
  14. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +157 -0
  15. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +286 -0
  16. package/skills/brainstate/references/braintools-optimizer-reference.md +133 -0
  17. package/skills/brainstate/references/collective_model_operations.md +195 -0
  18. package/skills/brainstate/references/extension_mechanisms.md +282 -0
  19. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -0
  20. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +217 -0
  21. package/skills/brainstate/references/libraries/solver-library-with-effects.md +85 -0
  22. package/skills/brainstate/references/model-interop-and-migration.md +295 -0
  23. package/skills/brainstate/references/simulation-environment.md +117 -0
  24. package/skills/brainstate/references/size-inference-variations.md +268 -0
  25. package/skills/brainstate/references/state-graph-operations.md +218 -0
  26. package/skills/brainstate/references/state_collections_and_utilities.md +224 -0
  27. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  28. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  29. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  30. package/skills/brainstate/scripts/resnet.py +130 -0
  31. package/skills/brainunit/SKILL.md +287 -0
  32. package/skills/brainunit/references/array-creation.md +158 -0
  33. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  34. package/skills/brainunit/references/array-mechanics.md +165 -0
  35. package/skills/brainunit/references/math-function-library.md +433 -0
  36. package/skills/brainunit/references/physical-constant-library.md +58 -0
  37. package/skills/brainunit/references/prefix-library.md +116 -0
  38. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  39. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  40. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  41. package/skills/brainx-install/SKILL.md +21 -13
  42. package/skills/brainx-install/references/compatibility-and-release-matching.md +12 -10
  43. package/skills/brainx-install/references/uninstall-and-cleanup.md +186 -0
  44. /package/{bin → installation/bin}/brainx.js +0 -0
  45. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  46. /package/{lib → installation/lib}/bundle.js +0 -0
  47. /package/{lib → installation/lib}/cli.js +0 -0
  48. /package/{lib → installation/lib}/constants.js +0 -0
  49. /package/{lib → installation/lib}/hash.js +0 -0
  50. /package/{lib → installation/lib}/paths.js +0 -0
  51. /package/{lib → installation/lib}/prompts.js +0 -0
  52. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,268 @@
1
+ # Size inference and composition
2
+
3
+ Use this reference to compose size-aware layers with `Sequential` and `.desc()`, or when stride, padding, dimensionality, pooling mode, or flatten axes make a layer's size behavior non-obvious.
4
+
5
+ ## Compose `ComplexNet` with `Sequential` and `.desc()`
6
+
7
+ Give the first layer an explicit `in_size`, then use `.desc()` wherever `Sequential` should instantiate a layer from the preceding `out_size`. Start the classifier from `self.features.out_size` so flattening and dense construction stay coupled to the feature extractor.
8
+
9
+ ```python
10
+ import brainstate
11
+ import brainstate.nn as nn
12
+
13
+
14
+ class ComplexNet(brainstate.nn.Module):
15
+ def __init__(self, in_size):
16
+ super().__init__()
17
+ self.features = nn.Sequential(
18
+ nn.Conv2d(
19
+ in_size,
20
+ out_channels=16,
21
+ kernel_size=3,
22
+ padding="SAME",
23
+ ),
24
+ nn.ReLU(),
25
+ nn.Conv2d.desc(
26
+ out_channels=32,
27
+ kernel_size=3,
28
+ stride=2,
29
+ padding="SAME",
30
+ ),
31
+ nn.ReLU(),
32
+ nn.Conv2d.desc(
33
+ out_channels=64,
34
+ kernel_size=3,
35
+ padding="SAME",
36
+ ),
37
+ nn.ReLU(),
38
+ nn.MaxPool2d.desc(
39
+ kernel_size=(2, 2),
40
+ stride=(2, 2),
41
+ channel_axis=-1,
42
+ ),
43
+ )
44
+ self.classifier = nn.Sequential(
45
+ nn.Flatten(in_size=self.features.out_size),
46
+ nn.Linear.desc(out_size=256),
47
+ nn.ReLU(),
48
+ nn.Linear.desc(out_size=10),
49
+ )
50
+
51
+ def update(self, x):
52
+ return self.classifier(self.features(x))
53
+
54
+
55
+ brainstate.random.seed(42)
56
+ net = ComplexNet(in_size=(32, 32, 3))
57
+ x_image = brainstate.random.randn(2, 32, 32, 3)
58
+ y_image = net(x_image)
59
+
60
+ assert net.features.out_size == (8, 8, 64)
61
+ assert net.classifier.layers[0].out_size == (4096,)
62
+ assert net.classifier.out_size == (10,)
63
+ assert y_image.shape == (2, 10)
64
+ ```
65
+
66
+ ## Convolution output-size behavior
67
+
68
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
69
+
70
+ The tutorial's **Convolution Parameters** rules are:
71
+
72
+ - `stride` controls the step size; pass it with the `stride` keyword. The API no longer accepts `strides`.
73
+ - `'SAME'` preserves spatial dimensions when stride is 1; `'VALID'` performs no padding.
74
+ - Explicit tuples set different values per spatial dimension.
75
+
76
+ The following source pattern bundles those rules with the exact demonstrated 28-by-28, 3-by-3-kernel outcomes:
77
+
78
+ ```python
79
+ import brainstate
80
+
81
+ x = brainstate.random.randn(1, 28, 28, 3)
82
+
83
+ configs = [
84
+ {"stride": (1, 1), "padding": "SAME", "name": "Stride 1, SAME"},
85
+ {"stride": (2, 2), "padding": "SAME", "name": "Stride 2, SAME"},
86
+ {"stride": (1, 1), "padding": "VALID", "name": "Stride 1, VALID"},
87
+ ]
88
+
89
+ for config in configs:
90
+ brainstate.random.seed(0)
91
+ conv = brainstate.nn.Conv2d(
92
+ in_size=(28, 28, 3),
93
+ out_channels=16,
94
+ kernel_size=(3, 3),
95
+ stride=config["stride"],
96
+ padding=config["padding"],
97
+ )
98
+ y = conv(x)
99
+ print(f"{config['name']:20s}: out_size={conv.out_size}, runtime={y.shape}")
100
+ ```
101
+
102
+ Expected output:
103
+
104
+ ```text
105
+ Stride 1, SAME : out_size=(28, 28, 16), runtime=(1, 28, 28, 16)
106
+ Stride 2, SAME : out_size=(14, 14, 16), runtime=(1, 14, 14, 16)
107
+ Stride 1, VALID : out_size=(26, 26, 16), runtime=(1, 26, 26, 16)
108
+ ```
109
+
110
+ These are the tutorial's exact cases: `'SAME'` with stride 2 produces 14 by 14 from this 28-by-28 input, while `'VALID'` with stride 1 and a 3-by-3 kernel produces 26 by 26. Use `stride`, not `strides`.
111
+
112
+ ### Dimensionality and layout variations
113
+
114
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
115
+
116
+ The tutorial demonstrates channels-last layouts for each convolution rank:
117
+
118
+ | Layer | Runtime input layout | Demonstrated input | Demonstrated output |
119
+ |---|---|---|---|
120
+ | `Conv1d` | `(batch, length, channels)` | `(4, 100, 3)` | `(4, 100, 16)` |
121
+ | `Conv2d` | `(batch, height, width, channels)` | `(8, 28, 28, 3)` | `(8, 28, 28, 32)` |
122
+ | `Conv3d` | `(batch, depth, height, width, channels)` | `(2, 16, 64, 64, 3)` | `(2, 16, 64, 64, 16)` |
123
+
124
+ Each case uses `'SAME'` padding and the default stride of 1:
125
+
126
+ ```python
127
+ import brainstate
128
+
129
+ brainstate.random.seed(0)
130
+
131
+ conv1d = brainstate.nn.Conv1d(
132
+ in_size=(100, 3),
133
+ out_channels=16,
134
+ kernel_size=3,
135
+ padding="SAME",
136
+ )
137
+ conv2d = brainstate.nn.Conv2d(
138
+ in_size=(28, 28, 3),
139
+ out_channels=32,
140
+ kernel_size=(3, 3),
141
+ stride=(1, 1),
142
+ padding="SAME",
143
+ )
144
+ conv3d = brainstate.nn.Conv3d(
145
+ in_size=(16, 64, 64, 3),
146
+ out_channels=16,
147
+ kernel_size=(3, 3, 3),
148
+ padding="SAME",
149
+ )
150
+
151
+ print(conv1d(brainstate.random.randn(4, 100, 3)).shape)
152
+ print(conv2d(brainstate.random.randn(8, 28, 28, 3)).shape)
153
+ print(conv3d(brainstate.random.randn(2, 16, 64, 64, 3)).shape)
154
+ ```
155
+
156
+ ## Pooling reductions and fixed targets
157
+
158
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
159
+
160
+ Official source phrase: "Pooling layers downsample feature maps, reducing spatial dimensions." `MaxPool2d` takes the maximum value in each window; `AvgPool2d` takes the average. With a 2-by-2 kernel and stride 2, both demonstrated layers reduce 28 by 28 to 14 by 14 and retain all 16 channels:
161
+
162
+ ```python
163
+ import brainstate
164
+
165
+ x = brainstate.random.randn(4, 28, 28, 16)
166
+ maxpool = brainstate.nn.MaxPool2d(
167
+ kernel_size=(2, 2),
168
+ stride=(2, 2),
169
+ )
170
+ avgpool = brainstate.nn.AvgPool2d(
171
+ kernel_size=(2, 2),
172
+ stride=(2, 2),
173
+ )
174
+
175
+ print(maxpool(x).shape) # (4, 14, 14, 16)
176
+ print(avgpool(x).shape) # (4, 14, 14, 16)
177
+ ```
178
+
179
+ The printed layer representations in the tutorial show `padding=VALID` and `channel_axis=-1` for both constructors.
180
+
181
+ Use `AdaptiveAvgPool2d` when the required spatial result is fixed rather than tied to one input resolution. The tutorial's `target_size=(7, 7)` example maps all three inputs to 7 by 7:
182
+
183
+ ```python
184
+ adaptive_pool = brainstate.nn.AdaptiveAvgPool2d(target_size=(7, 7))
185
+
186
+ inputs = [
187
+ brainstate.random.randn(1, 28, 28, 16),
188
+ brainstate.random.randn(1, 56, 56, 16),
189
+ brainstate.random.randn(1, 224, 224, 16),
190
+ ]
191
+
192
+ for x in inputs:
193
+ y = adaptive_pool(x)
194
+ print(f"Input {x.shape[1:3]} -> Output {y.shape[1:3]}")
195
+ ```
196
+
197
+ Expected output:
198
+
199
+ ```text
200
+ Input (28, 28) -> Output (7, 7)
201
+ Input (56, 56) -> Output (7, 7)
202
+ Input (224, 224) -> Output (7, 7)
203
+ ```
204
+
205
+ ### Pooling with constructor-visible size metadata
206
+
207
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
208
+
209
+ The standalone pooling examples omit `in_size` and demonstrate reduction through runtime shapes. In the tutorial's complete CNN, the final pool instead receives the preceding convolution's size so the following `Flatten` can be constructed from its result:
210
+
211
+ ```python
212
+ conv3 = brainstate.nn.Conv2d(
213
+ (8, 8, 64),
214
+ out_channels=128,
215
+ kernel_size=(3, 3),
216
+ padding="SAME",
217
+ )
218
+ pool3 = brainstate.nn.MaxPool2d(
219
+ kernel_size=(2, 2),
220
+ stride=(2, 2),
221
+ in_size=conv3.out_size,
222
+ )
223
+
224
+ print(conv3.out_size) # (8, 8, 128)
225
+ print(pool3.out_size) # (4, 4, 128)
226
+ ```
227
+
228
+ ## Flatten: runtime axes versus constructor inference
229
+
230
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
231
+
232
+ The standalone tutorial pattern flattens a batched tensor from `start_axis=1`, preserving its leading batch axis:
233
+
234
+ ```python
235
+ import brainstate
236
+
237
+ flatten_runtime = brainstate.nn.Flatten(start_axis=1)
238
+ x_conv = brainstate.random.randn(4, 7, 7, 64)
239
+ x_flat = flatten_runtime(x_conv)
240
+
241
+ print(x_conv.shape) # (4, 7, 7, 64)
242
+ print(x_flat.shape) # (4, 3136)
243
+ ```
244
+
245
+ The exact flattened feature count is `7 * 7 * 64 = 3136` per sample. The tutorial summary identifies `start_axis` and `end_axis` as the key `Flatten` parameters.
246
+
247
+ For constructor-aware composition, the complete CNN passes the final pool's result to `Flatten`. Its printed representation shows `start_axis=0`, `end_axis=-1`, and `out_size=(2048,)` for the feature shape `(4, 4, 128)`. Continue from the `conv3` / `pool3` construction above:
248
+
249
+ ```python
250
+ import jax.numpy as jnp
251
+
252
+ flatten = brainstate.nn.Flatten(in_size=pool3.out_size)
253
+ fc1 = brainstate.nn.Linear(4 * 4 * 128, (256,))
254
+
255
+ x = brainstate.random.randn(2, 8, 8, 64)
256
+ x = conv3(x)
257
+ x = jnp.maximum(0, x)
258
+ x = pool3(x)
259
+ x = flatten(x)
260
+ y = fc1(x)
261
+
262
+ print(flatten.in_size) # (4, 4, 128)
263
+ print(flatten.out_size) # (2048,)
264
+ print(x.shape) # (2, 2048)
265
+ print(y.shape) # (2, 256)
266
+ ```
267
+
268
+ This is the source's manual-composition variation: spatial feature shapes progress from `(8, 8, 128)` through `(4, 4, 128)` to `(2048,)`, and the first dense layer accepts 2048 features. Use it when explicit construction is clearer than descriptor-based composition.
@@ -0,0 +1,218 @@
1
+ # Brainstate state-graph operations
2
+
3
+ Use this reference after the core `State`, `Module`, and transform rules in
4
+ `SKILL.md`. It covers the less-frequent graph operations needed to find,
5
+ extract, split, replace, or reconstruct state while retaining BrainState's
6
+ graph structure. All examples assume an existing graph node named `model`.
7
+
8
+ The graph engine flattens object graphs of `Node`s and `State`s into "a static
9
+ structure plus a dynamic state mapping, and back." A `GraphDef` is the static
10
+ structure. Graph nodes are hoisted into an index-keyed table, so sharing and
11
+ cycles are encoded by integer index rather than duplicated.
12
+
13
+ Source URL:
14
+ https://brainx.chaobrain.com/brainstate/apis/graph.html
15
+
16
+ ## Find nodes, leaves, and states
17
+
18
+ Use traversal when the path is part of the decision. `iter_node()` yields
19
+ `(path, graph_node)` for every graph node; `iter_leaf()` yields `(path, value)`
20
+ for every leaf. The root node appears at path `()`.
21
+
22
+ ```python
23
+ for path, node in brainstate.graph.iter_node(model):
24
+ print(path, type(node).__name__)
25
+
26
+ for path, leaf in brainstate.graph.iter_leaf(model):
27
+ print(path, type(leaf).__name__)
28
+ ```
29
+
30
+ Use collection when the result should be a path-keyed mapping. `nodes()`
31
+ collects graph nodes as `FlattedDict` object(s); `states()` collects
32
+ `State` objects as `FlattedDict` object(s). Both accept optional filters.
33
+
34
+ ```python
35
+ all_nodes = brainstate.graph.nodes(model)
36
+ all_states = brainstate.graph.states(model)
37
+ param_states = brainstate.graph.states(model, brainstate.ParamState)
38
+ params, remaining = brainstate.graph.states(
39
+ model,
40
+ brainstate.ParamState,
41
+ ...,
42
+ )
43
+ ```
44
+
45
+ A predicate filter has the exact shape below. `path` is a tuple of hashable,
46
+ comparable keys and `value` is the value at that path.
47
+
48
+ ```python
49
+ def weight_path(path: tuple, value) -> bool:
50
+ return path[-1:] == ("weight",)
51
+
52
+ weight_states = brainstate.graph.states(model, weight_path)
53
+ ```
54
+
55
+ The filter DSL also accepts:
56
+
57
+ - `...` or `True`: match every value.
58
+ - `None` or `False`: match no values.
59
+ - A type: match instances of that type, or values whose `type` attribute is
60
+ that type.
61
+ - A string: match a value whose string `tag` attribute equals that string.
62
+ - A tuple or list of filters: match any enclosed filter.
63
+
64
+ Source URL:
65
+ https://brainx.chaobrain.com/brainstate/how_to/inspect_and_edit_state_graph.html
66
+
67
+ ## Extract state objects or state pytrees
68
+
69
+ Choose the extraction API by the representation required downstream:
70
+
71
+ - `states()` returns the graph's `State` objects, keyed by path.
72
+ - `treefy_states()` returns one or more treeified state mappings and no
73
+ `GraphDef`. It is the lightweight extraction for optimization or
74
+ checkpointing when reconstruction is not required.
75
+ - `pop_states()` removes and returns matching `State` objects. It is
76
+ destructive and deduplicates matches by identity.
77
+
78
+ ```python
79
+ # State objects keyed by their graph paths.
80
+ live_params = brainstate.graph.states(model, brainstate.ParamState)
81
+
82
+ # PyTree-compatible state data without carrying graph structure.
83
+ param_tree = brainstate.graph.treefy_states(model, brainstate.ParamState)
84
+ param_tree, other_tree = brainstate.graph.treefy_states(
85
+ model,
86
+ brainstate.ParamState,
87
+ ...,
88
+ )
89
+
90
+ # Destructive extraction: matching State instances are removed from model.
91
+ removed_params = brainstate.graph.pop_states(model, brainstate.ParamState)
92
+ ```
93
+
94
+ `treefy_states()` returns state trees keyed by state paths. Do not use it alone
95
+ when another process must rebuild the module; use `treefy_split()` and retain
96
+ the returned `GraphDef` instead.
97
+
98
+ Source URLs:
99
+ https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
100
+ https://brainx.chaobrain.com/brainstate/apis/graph.html
101
+
102
+ ## Split structure from state
103
+
104
+ `treefy_split()` returns `(graph_def, state_tree1, state_tree2, ...)`. Each
105
+ filter adds one state mapping in the same order; `...` is the catch-all used for
106
+ remaining states. Use this operation when reconstruction or explicit JAX state
107
+ threading requires both structure and dynamic values.
108
+
109
+ ```python
110
+ graph_def, params, other_states = brainstate.graph.treefy_split(
111
+ model,
112
+ brainstate.ParamState,
113
+ ...,
114
+ )
115
+ ```
116
+
117
+ When no partition is needed, the operation returns one state mapping:
118
+
119
+ ```python
120
+ graph_def, all_state = brainstate.graph.treefy_split(model)
121
+ ```
122
+
123
+ If only the static structure is needed, retrieve it directly:
124
+
125
+ ```python
126
+ graph_def = brainstate.graph.graphdef(model)
127
+ ```
128
+
129
+ Source URLs:
130
+ https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
131
+ https://brainx.chaobrain.com/brainstate/how_to/inspect_and_edit_state_graph.html
132
+
133
+ ## Replace state values in place
134
+
135
+ `update_states()` updates a graph node in place from one or more state mappings.
136
+ Extract the desired subset, produce a replacement mapping with the same paths,
137
+ then apply it. The documented JAX workflow maps arithmetic over the treeified
138
+ state data; the same representation can be written back with `update_states()`.
139
+
140
+ ```python
141
+ import jax
142
+ import jax.numpy as jnp
143
+
144
+ params = brainstate.graph.treefy_states(model, brainstate.ParamState)
145
+ replacement_params = jax.tree.map(jnp.zeros_like, params)
146
+ brainstate.graph.update_states(model, replacement_params)
147
+ ```
148
+
149
+ Multiple independently partitioned mappings may be applied together:
150
+
151
+ ```python
152
+ brainstate.graph.update_states(model, replacement_params, replacement_counts)
153
+ ```
154
+
155
+ This is state-value replacement, not structural replacement. `pop_states()`
156
+ removes matching states; `update_states()` updates states already located by
157
+ the supplied mapping. The assigned official pages do not document a generic
158
+ graph-node replacement API.
159
+
160
+ Source URLs:
161
+ https://brainx.chaobrain.com/brainstate/apis/graph.html
162
+ https://brainx.chaobrain.com/brainstate/how_to/inspect_and_edit_state_graph.html
163
+
164
+ ## Reconstruct the graph
165
+
166
+ Use `treefy_merge()` with the `GraphDef` and every state mapping returned by
167
+ the corresponding `treefy_split()` call. It reconstructs a new graph node;
168
+ the state mappings must be supplied in the compatible partitioning.
169
+
170
+ ```python
171
+ rebuilt_model = brainstate.graph.treefy_merge(
172
+ graph_def,
173
+ params,
174
+ other_states,
175
+ )
176
+ ```
177
+
178
+ For the lower-level, unpartitioned representation, `flatten()` returns a
179
+ `(GraphDef, NestedDict)` pair and `unflatten()` reconstructs from that pair.
180
+ The decoder materializes states, creates node shells, then fills them, so graph
181
+ sharing and cycles resolve independently of fill order.
182
+
183
+ ```python
184
+ flat_graph_def, nested_state = brainstate.graph.flatten(model)
185
+ rebuilt_model = brainstate.graph.unflatten(flat_graph_def, nested_state)
186
+ ```
187
+
188
+ For graph nodes nested inside a larger pytree, `graph_to_tree()` converts the
189
+ container to a pure pytree and `tree_to_graph()` converts a pytree of
190
+ `NodeStates` back into graph nodes. `NodeStates` is the JAX pytree wrapper that
191
+ carries a `GraphDef` and one or more state mappings.
192
+
193
+ ```python
194
+ tree_form = brainstate.graph.graph_to_tree(container_with_graph_nodes)
195
+ restored_container = brainstate.graph.tree_to_graph(tree_form)
196
+ ```
197
+
198
+ Use `split_context` and `merge_context` only when splitting or merging multiple
199
+ graph nodes that share a reference index; those context managers preserve the
200
+ shared index across the related operations. For a deep copy of one graph,
201
+ `clone()` performs split/merge while preserving shared references.
202
+
203
+ Source URL:
204
+ https://brainx.chaobrain.com/brainstate/apis/graph.html
205
+
206
+ ## Selection rules
207
+
208
+ - Need paths plus graph objects: `iter_node()`, `iter_leaf()`, `nodes()`, or
209
+ `states()`.
210
+ - Need only a parameter/state PyTree: `treefy_states()`.
211
+ - Need filtered state PyTrees and later reconstruction: `treefy_split()` plus
212
+ `treefy_merge()`.
213
+ - Need one low-level graph IR and nested state mapping: `flatten()` plus
214
+ `unflatten()`.
215
+ - Need to update an existing graph: `update_states()`.
216
+ - Need destructive removal: `pop_states()`.
217
+ - Need graph nodes to cross a larger pytree boundary: `graph_to_tree()` plus
218
+ `tree_to_graph()`.
@@ -0,0 +1,224 @@
1
+ # Brainstate state collections and utility toolkit
2
+
3
+ Use this reference for the collection-focused parts of BrainState's Utility Toolkit: managing mappings, nested configuration, dictionary conversion, immutable structured PyTrees, declarative filters, and readable PyTree containers. These utilities organize data; the core `State` and `Module` programming model remains in the parent `SKILL.md`.
4
+
5
+ Official page: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
6
+
7
+ ## Managing collections with `DictManager`
8
+
9
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
10
+
11
+ `DictManager` extends the standard mapping interface with filters, splits, combination operators, and JAX PyTree support. The page demonstrates `subset(...)` for one matching collection, `split(...)` for matching and remaining collections, and `map_values(...)` for transforming the retained values.
12
+
13
+ ```python
14
+ from brainstate.util import DictManager
15
+
16
+ modules = DictManager({
17
+ 'encoder': {'params': 32},
18
+ 'decoder': {'params': 45},
19
+ 'dropout': 0.1,
20
+ })
21
+
22
+ submods = modules.subset(dict)
23
+ dicts, remainder = modules.split(dict)
24
+ param_counts = submods.map_values(lambda layer: layer['params'])
25
+
26
+ print(submods)
27
+ print(dicts)
28
+ print(remainder)
29
+ print(param_counts)
30
+ ```
31
+
32
+ The demonstrated results retain `encoder` and `decoder` in `submods` and `dicts`, put only `dropout` in `remainder`, and produce `DictManager({'encoder': 32, 'decoder': 45})` for `param_counts`.
33
+
34
+ ## Configuration access with `DotDict`
35
+
36
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
37
+
38
+ `DotDict` lets nested dictionaries act like lightweight objects while preserving conversion back to standard dictionaries when needed.
39
+
40
+ ```python
41
+ from brainstate.util import DotDict
42
+
43
+ config = DotDict({
44
+ 'model': {
45
+ 'layers': 4,
46
+ 'hidden': 256,
47
+ },
48
+ 'training': {
49
+ 'lr': 3e-4,
50
+ 'scheduler': {'warmup_steps': 500},
51
+ },
52
+ })
53
+
54
+ print(config.model.hidden)
55
+ config.training.dropout = 0.2
56
+ round_trip = config.to_dict()
57
+ ```
58
+
59
+ The example reads `config.model.hidden` as `256`, adds `config.training.dropout`, and converts the complete nested configuration back with `to_dict()`.
60
+
61
+ ## Merge, flatten, and unflatten dictionaries
62
+
63
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
64
+
65
+ `merge_dicts` performs optional recursive merges. `flatten_dict` and `unflatten_dict` convert between nested and dotted-key representations, which the page uses for logging or CLI overrides.
66
+
67
+ ```python
68
+ from brainstate.util import flatten_dict, merge_dicts, unflatten_dict
69
+
70
+ base = {'optimizer': {'lr': 1e-3, 'beta1': 0.9}}
71
+ override = {'optimizer': {'lr': 5e-4}, 'seed': 1234}
72
+
73
+ merged = merge_dicts(base, override)
74
+ flat = flatten_dict(merged)
75
+ restored = unflatten_dict(flat)
76
+
77
+ print(merged)
78
+ print(flat)
79
+ print(restored)
80
+ ```
81
+
82
+ The recursive merge preserves `optimizer.beta1`, overrides `optimizer.lr`, and adds `seed`. The demonstrated flattened form is:
83
+
84
+ ```python
85
+ {
86
+ 'optimizer.lr': 0.0005,
87
+ 'optimizer.beta1': 0.9,
88
+ 'seed': 1234,
89
+ }
90
+ ```
91
+
92
+ `unflatten_dict(flat)` restores the nested representation.
93
+
94
+ ## Structured pytrees and frozen mappings
95
+
96
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
97
+
98
+ The `struct` submodule mirrors Flax-friendly data structures. Its `dataclass` decorator registers classes as PyTrees, while `FrozenDict` provides immutable mappings compatible with JAX transformations.
99
+
100
+ ```python
101
+ import jax
102
+ import jax.numpy as jnp
103
+ from brainstate.util import struct
104
+
105
+
106
+ @struct.dataclass
107
+ class LayerConfig:
108
+ weight: jax.Array
109
+ bias: jax.Array
110
+ name: str = struct.field(pytree_node=False, default='layer')
111
+
112
+
113
+ cfg = LayerConfig(
114
+ weight=jnp.ones((2, 2)),
115
+ bias=jnp.zeros(2),
116
+ )
117
+ cfg2 = cfg.replace(weight=jnp.full((2, 2), 3.0))
118
+ flat_leaves, _ = jax.tree_util.tree_flatten(cfg)
119
+
120
+ frozen = struct.freeze({'encoder': jnp.arange(3)})
121
+ unfrozen = struct.unfreeze(frozen)
122
+ ```
123
+
124
+ In the page's result, `cfg.replace(...)` returns a configuration whose weight is filled with `3.0`; flattening `cfg` yields array leaves with shapes `(2, 2)` and `(2,)`, so the `name` field marked `pytree_node=False` is not a dynamic leaf. `struct.freeze(...)` returns a `FrozenDict`, and `struct.unfreeze(...)` returns the ordinary dictionary again.
125
+
126
+ ## Filtering nested objects
127
+
128
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
129
+
130
+ `brainstate.util.filter` turns declarative filters into callables. The page combines tag, type, and path checks when traversing a nested object tree; each predicate is called with `(path, value)`.
131
+
132
+ ```python
133
+ from typing import Any
134
+
135
+ import jax.numpy as jnp
136
+ from brainstate.util import filter as util_filter
137
+
138
+
139
+ class Module:
140
+ def __init__(self, tag: str | None, kind: str):
141
+ self.tag = tag
142
+ self.kind = kind
143
+ self.params = jnp.arange(2)
144
+
145
+
146
+ model_tree = {
147
+ 'encoder': Module(tag='trainable', kind='linear'),
148
+ 'decoder': Module(tag='frozen', kind='linear'),
149
+ 'head': Module(tag='trainable', kind='mlp'),
150
+ }
151
+
152
+ tag_filter = util_filter.to_predicate('trainable')
153
+ type_filter = util_filter.OfType(Module)
154
+ combined = util_filter.All(
155
+ type_filter,
156
+ util_filter.WithTag('trainable'),
157
+ )
158
+
159
+
160
+ def collect(
161
+ tree: dict[str, Any],
162
+ predicate,
163
+ ) -> dict[str, Any]:
164
+ out = {}
165
+ for key, value in tree.items():
166
+ if predicate((key,), value):
167
+ out[key] = value
168
+ return out
169
+
170
+
171
+ trainable_modules = collect(model_tree, tag_filter)
172
+ both = collect(model_tree, combined)
173
+
174
+ print(tuple(trainable_modules.keys()))
175
+ print(tuple(both.keys()))
176
+ ```
177
+
178
+ Both predicates select `('encoder', 'head')` in the demonstrated tree. Use `to_predicate(...)` to normalize the tag filter, `OfType(...)` for the type check, `WithTag(...)` for tag matching, and `All(...)` to require both conditions.
179
+
180
+ ## Pretty pytree containers and tuple-path flattening
181
+
182
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
183
+
184
+ `NestedDict`, `FlattedDict`, and `PrettyList` provide readable representations plus PyTree semantics. The page uses them to explore checkpoints or log structured configurations.
185
+
186
+ ```python
187
+ import jax.numpy as jnp
188
+ from brainstate.util import NestedDict, PrettyList, flat_mapping, nest_mapping
189
+
190
+ state = NestedDict({
191
+ 'encoder': {
192
+ 'weight': jnp.ones((2, 2)),
193
+ 'bias': jnp.zeros(2),
194
+ },
195
+ 'decoder': {
196
+ 'weight': jnp.eye(2),
197
+ },
198
+ })
199
+ print(state)
200
+
201
+ flat_state = flat_mapping(state)
202
+ print(list(flat_state.keys()))
203
+
204
+ round_trip = nest_mapping(flat_state)
205
+ print(round_trip == state)
206
+
207
+ history = PrettyList([
208
+ {'loss': 0.8},
209
+ {'loss': 0.42},
210
+ ])
211
+ print(history)
212
+ ```
213
+
214
+ The displayed flat keys are tuple paths:
215
+
216
+ ```python
217
+ [
218
+ ('encoder', 'weight'),
219
+ ('encoder', 'bias'),
220
+ ('decoder', 'weight'),
221
+ ]
222
+ ```
223
+
224
+ `nest_mapping(flat_state)` round-trips to the nested mapping (`True` in the page), while `NestedDict` and `PrettyList` print their nested contents in an indented, readable form. This tuple-path representation is the one demonstrated by `flat_mapping`; the dictionary utilities section above separately demonstrates dotted-string keys from `flatten_dict`.