brainx-skill 1.0.3 → 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 (51) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +21 -63
  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 +2 -2
  42. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  43. /package/{bin → installation/bin}/brainx.js +0 -0
  44. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  45. /package/{lib → installation/lib}/bundle.js +0 -0
  46. /package/{lib → installation/lib}/cli.js +0 -0
  47. /package/{lib → installation/lib}/constants.js +0 -0
  48. /package/{lib → installation/lib}/hash.js +0 -0
  49. /package/{lib → installation/lib}/paths.js +0 -0
  50. /package/{lib → installation/lib}/prompts.js +0 -0
  51. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,286 @@
1
+ # Brainstate vmap expansion
2
+
3
+ ## Scope and source boundary
4
+
5
+ Open this reference after the minimal `brainstate.transform.vmap` example in `skills/brainstate/SKILL.md`. The vectorization tutorial describes `brainstate.transform.vmap` as a state-aware wrapper around `jax.vmap`, but its detailed executable examples use `brainstate.transform.vmap2`. Preserve that distinction when adapting a script; do not silently substitute one API for the other.
6
+
7
+ This reference covers only behavior demonstrated by these routed official tutorials:
8
+
9
+ - Vectorization: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html
10
+ - Random Number Generation: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
11
+
12
+ The Vectorization tutorial imports the detailed mapping API and State filter as follows:
13
+
14
+ ```python
15
+ import jax
16
+ import jax.numpy as jnp
17
+ import brainstate
18
+ from brainstate.transform import vmap2
19
+ from brainstate.util.filter import OfType
20
+ ```
21
+
22
+ ## Map sweeps and broadcast fixed arguments
23
+
24
+ `in_axes` controls how batch dimensions are mapped over function arguments and works identically to `jax.vmap`. Use an axis number for a swept argument and `None` for a value shared by every mapped call.
25
+
26
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-in-axes-parameter
27
+
28
+ ```python
29
+ def weighted_sum(x, weight):
30
+ """Compute weighted sum: x * weight"""
31
+ return x * weight
32
+
33
+
34
+ vmap_weighted = vmap2(weighted_sum, in_axes=(0, None))
35
+ batch_x = jnp.array([1.0, 2.0, 3.0])
36
+ single_weight = 2.0
37
+ result = vmap_weighted(batch_x, single_weight)
38
+ ```
39
+
40
+ Here `batch_x` supplies the sweep axis and `single_weight` is broadcast. To map corresponding candidates from two sweeps, use `in_axes=(0, 0)`, as in the tutorial's batched matrix/vector product.
41
+
42
+ `out_axes` controls where the mapped dimension appears in the result. Set it deliberately when downstream code expects the batch somewhere other than axis 0.
43
+
44
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-out-axes-parameter
45
+
46
+ ```python
47
+ def create_vector(scalar):
48
+ return jnp.array([scalar, scalar * 2, scalar * 3])
49
+
50
+
51
+ vmap_axis1 = vmap2(create_vector, in_axes=0, out_axes=1)
52
+ result_axis1 = vmap_axis1(jnp.array([1.0, 2.0]))
53
+ assert result_axis1.shape == (3, 2)
54
+ ```
55
+
56
+ When every input is static, the mapped size cannot be inferred from an argument; supply `axis_size` explicitly.
57
+
58
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-axis-size-parameter
59
+
60
+ ```python
61
+ def generate_sequence(unused=None):
62
+ return jnp.arange(3)
63
+
64
+
65
+ vmap_generate = vmap2(generate_sequence, in_axes=None, axis_size=5)
66
+ result = vmap_generate()
67
+ assert result.shape == (5, 3)
68
+ ```
69
+
70
+ Name the mapped axis only when a collective operation needs it. The tutorial uses `axis_name='batch'` with `jax.lax.pmean`:
71
+
72
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-axis-name-parameter
73
+
74
+ ```python
75
+ def normalize_batch(x):
76
+ batch_mean = jax.lax.pmean(x, axis_name='batch')
77
+ return x - batch_mean
78
+
79
+
80
+ vmap_normalize = vmap2(normalize_batch, in_axes=0, axis_name='batch')
81
+ normalized = vmap_normalize(jnp.array([1.0, 2.0, 3.0, 4.0]))
82
+ ```
83
+
84
+ ## Map per-instance state and share parameters
85
+
86
+ `state_in_axes` and `state_out_axes` are BrainState-specific parameters that control how `State` objects are batched. The tutorial's State Axis Inference example maps `ShortTermState` along axis 0 while leaving `ParamState` shared; use that demonstrated separation for an ensemble with per-instance mutable State and shared parameters.
87
+
88
+ Sources:
89
+
90
+ - https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#state-aware-parameters-state-in-axes-and-state-out-axes
91
+ - https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#state-axis-inference
92
+
93
+ ```python
94
+ class StatefulComputation(brainstate.nn.Module):
95
+ def __init__(self):
96
+ super().__init__()
97
+ self.temp = brainstate.ShortTermState(jnp.zeros(3))
98
+ self.param = brainstate.ParamState(jnp.array(1.0))
99
+
100
+ def __call__(self, x):
101
+ self.temp.value = self.temp.value + x
102
+ return self.temp.value * self.param.value
103
+
104
+
105
+ model = StatefulComputation()
106
+ vmap_model = vmap2(
107
+ model,
108
+ in_axes=0,
109
+ out_axes=0,
110
+ state_in_axes={0: OfType(brainstate.ShortTermState)},
111
+ state_out_axes={0: OfType(brainstate.ShortTermState)},
112
+ )
113
+
114
+ inputs = jnp.array([1.0, 2.0, 3.0])
115
+ outputs = vmap_model(inputs)
116
+
117
+ assert jnp.allclose(model.temp.value, jnp.array([1.0, 2.0, 3.0]))
118
+ assert model.param.value == 1.0
119
+ ```
120
+
121
+ This bundles the State-axis decision with the executable pattern: each mapped element owns one `temp` value, while every element reads the same scalar parameter. For an ordinary `nn.Module` with no State-axis filters, the tutorial says Module states are typically shared, or broadcast, across the batch by default.
122
+
123
+ ### Exact parameter names
124
+
125
+ Neither routed tutorial defines mapping parameters named `in_states` or `out_states`. The exact documented names in the Vectorization tutorial are `state_in_axes` and `state_out_axes`; do not present `in_states` / `out_states` as aliases without opening an official API page that defines them.
126
+
127
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#state-aware-parameters-state-in-axes-and-state-out-axes
128
+
129
+ ## Handle state writes outside `state_out_axes`
130
+
131
+ `unexpected_out_state_mapping` controls behavior when a State is written but is not covered by `state_out_axes`. The tutorial demonstrates the default `'ignore'` policy with a written `LongTermState` that is not listed in State-axis filters.
132
+
133
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-unexpected-out-state-mapping-parameter
134
+
135
+ ```python
136
+ temp_state = brainstate.ShortTermState(jnp.array(0.0))
137
+ write_state = brainstate.LongTermState(jnp.asarray(0.0))
138
+
139
+
140
+ def update_temp(x):
141
+ temp_state.value = temp_state.value + x
142
+ write_state.value = temp_state.value
143
+ return temp_state.value
144
+
145
+
146
+ vmap_ignore = vmap2(
147
+ update_temp,
148
+ in_axes=0,
149
+ unexpected_out_state_mapping='ignore',
150
+ )
151
+ result = vmap_ignore(jnp.array([1.0, 2.0, 3.0]))
152
+ ```
153
+
154
+ Treat an unexpected write as an explicit policy decision. Do not assume that mapping only the function arguments also specifies the output behavior of every State the function mutates.
155
+
156
+ ## Choose independent or shared randomness
157
+
158
+ `brainstate.transform.vmap` automatically splits keys for `brainstate.random.RandomState`, so each mapped element receives a unique random key. Seed before the mapped call when the whole experiment must be reproducible; do not manually add `RandomState` State-axis filters for this ordinary independent-sample path.
159
+
160
+ Sources:
161
+
162
+ - https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#automatic-key-splitting-for-randomstate
163
+ - https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html#setting-seeds
164
+
165
+ ```python
166
+ brainstate.random.seed(42)
167
+
168
+
169
+ def sample_normal(scale):
170
+ return brainstate.random.normal(0.0, scale)
171
+
172
+
173
+ vmap_sample = vmap2(sample_normal, in_axes=0)
174
+ scales = jnp.array([1.0, 2.0, 3.0, 4.0])
175
+ samples = vmap_sample(scales)
176
+ ```
177
+
178
+ This is also the smallest stochastic parameter-sweep pattern: the scale is mapped, and BrainState supplies an independent key to each element.
179
+
180
+ If every mapped element must reuse the same random draw, the tutorial uses the JAX random API and broadcasts one key with `in_axes=None`.
181
+
182
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#controlling-random-keys-using-jax-s-random-api
183
+
184
+ ```python
185
+ def sample_with_jax_key(key, scale):
186
+ return jax.random.normal(key, ()) * scale
187
+
188
+
189
+ vmap_shared_key = vmap2(
190
+ sample_with_jax_key,
191
+ in_axes=(None, 0),
192
+ )
193
+
194
+ shared_key = jax.random.PRNGKey(0)
195
+ scales = jnp.array([1.0, 2.0, 3.0, 4.0])
196
+ samples_shared = vmap_shared_key(shared_key, scales)
197
+ ```
198
+
199
+ Stop here for ordinary stochastic mapping. For `get_key`, `set_key`, `split_key`, custom `RandomState` streams, checkpoint restoration, or parallel key assignment, open `randomness-and-reproducibility.md`; that reference owns direct key manipulation rather than duplicating it here.
200
+
201
+ Randomness boundary source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html#advanced-key-management
202
+
203
+ ## Nest and compose mappings
204
+
205
+ Nest `vmap2` when the function must map over more than one batch dimension. Each layer owns one mapped axis.
206
+
207
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#nested-vmap2
208
+
209
+ ```python
210
+ def matrix_elem_product(x, y):
211
+ return x * y
212
+
213
+
214
+ vmap_rows = vmap2(matrix_elem_product, in_axes=(0, 0))
215
+ vmap_matrix = vmap2(vmap_rows, in_axes=(0, 0))
216
+
217
+ matrix_a = jnp.ones((3, 4))
218
+ matrix_b = jnp.arange(12).reshape(3, 4)
219
+ result = vmap_matrix(matrix_a, matrix_b)
220
+ ```
221
+
222
+ The tutorial also composes BrainState `grad`, `vmap2`, and `jit`. Map the per-example gradient first, then compile the mapped function.
223
+
224
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#combining-with-other-transforms
225
+
226
+ ```python
227
+ from brainstate.transform import grad, jit
228
+
229
+
230
+ def loss_fn(x, target):
231
+ pred = x ** 2
232
+ return jnp.sum((pred - target) ** 2)
233
+
234
+
235
+ batched_grad = vmap2(
236
+ grad(loss_fn, argnums=0),
237
+ in_axes=(0, 0),
238
+ )
239
+ batched_grad_jit = jit(batched_grad)
240
+
241
+ batch_x = jnp.array([1.0, 2.0, 3.0])
242
+ batch_targets = jnp.array([2.0, 4.0, 6.0])
243
+ gradients = batched_grad_jit(batch_x, batch_targets)
244
+ ```
245
+
246
+ ## Use `StatefulMapping` only for a custom primitive
247
+
248
+ The tutorial states that `vmap` is a thin wrapper around `StatefulMapping`, which performs State discovery, input/output axis mapping, intermediate-representation compilation, and State management. Advanced users can instantiate it directly for a custom mapping primitive.
249
+
250
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#direct-use-of-statefulmapping
251
+
252
+ ```python
253
+ import functools
254
+ from brainstate.transform import StatefulMapping
255
+
256
+ counter_state = brainstate.ShortTermState(jnp.zeros(3))
257
+
258
+
259
+ def increment(delta):
260
+ counter_state.value = counter_state.value + delta
261
+ return counter_state.value
262
+
263
+
264
+ custom_mapping = StatefulMapping(
265
+ increment,
266
+ in_axes=0,
267
+ out_axes=0,
268
+ state_in_axes={0: OfType(brainstate.ShortTermState)},
269
+ state_out_axes={0: OfType(brainstate.ShortTermState)},
270
+ name="custom_increment",
271
+ mapping_fn=functools.partial(jax.vmap, spmd_axis_name=None),
272
+ )
273
+
274
+ results = custom_mapping(jnp.array([1.0, 2.0, 3.0]))
275
+ ```
276
+
277
+ Do not infer semantics for `vmap_new_states`, `vmap2_new_states`, `map`, `pmap2`, `pmap2_new_states`, `shard_map`, or `unvmap` from their names. The routed Vectorization tutorial lists those APIs in navigation but does not teach their contracts.
278
+
279
+ ## High-impact checks
280
+
281
+ - Match every non-`None` `in_axes` entry to an actual mapped dimension of the corresponding argument.
282
+ - Decide whether mutable State is shared or mapped; use `state_in_axes` and `state_out_axes` together for per-instance State write-back.
283
+ - Set `axis_size` when all inputs are static.
284
+ - Set an explicit policy for State writes not covered by `state_out_axes`.
285
+ - Expect automatic independent `RandomState` keys; use the documented broadcast-key pattern only when shared randomness is intentional.
286
+ - Route direct key manipulation through the randomness reference rather than duplicating it here.
@@ -0,0 +1,133 @@
1
+ # Braintools optimizer selection reference
2
+
3
+ Use this reference to select a `braintools.optim` optimizer, learning-rate scheduler, Optax bridge, or external optimizer wrapper. It is a selection adapter, not a BrainState training-loop guide: return to `skills/brainstate/SKILL.md` for the canonical State-aware training structure. Advanced full-training workflows are outside the supplied router.
4
+
5
+ **Source URL:** https://brainx.chaobrain.com/braintools/optim/index.html
6
+
7
+ ## Route from the official optimization index
8
+
9
+ The index states: "Optimization guides highlight practical solvers for tuning models and experiments. Compare gradient-free Nevergrad strategies with SciPy-based routines and learn when to apply each."
10
+
11
+ Use its five routes as follows, without importing their unshown details into this reference:
12
+
13
+ | Official index route | Selection cue available on the index |
14
+ |---|---|
15
+ | Tutorial 1: `NevergradOptimizer` Tutorial | Gradient-free Nevergrad strategy |
16
+ | Tutorial 2: `ScipyOptimizer` Tutorial | SciPy-based routine |
17
+ | Tutorial 3: Getting Started with `optax` Optimizers | Optax optimizer route |
18
+ | Tutorial 4: Learning Rate Scheduling Strategies | Learning-rate scheduler selection |
19
+ | Tutorial 5: Advanced Optimizers and Techniques | Optimizer choices beyond the basic route |
20
+
21
+ **Source URL:** https://brainx.chaobrain.com/braintools/optim/index.html
22
+
23
+ ## Optimizer and state types
24
+
25
+ The index exposes the `braintools.optim` module and lists `Optimizer`, `OptaxOptimizer`, and `OptimState` before its concrete optimizer classes. For class selection, preserve the module and symbol names exactly:
26
+
27
+ ```python
28
+ import braintools.optim
29
+
30
+ optimizer_type = braintools.optim.Adam
31
+ ```
32
+
33
+ Concrete optimizer classes, in index order:
34
+
35
+ - `SGD`
36
+ - `Momentum`
37
+ - `MomentumNesterov`
38
+ - `Adam`
39
+ - `AdamW`
40
+ - `Adagrad`
41
+ - `Adadelta`
42
+ - `RMSprop`
43
+ - `Adamax`
44
+ - `Nadam`
45
+ - `RAdam`
46
+ - `Lamb`
47
+ - `Lars`
48
+ - `Lookahead`
49
+ - `Yogi`
50
+ - `LBFGS`
51
+ - `Rprop`
52
+ - `Adafactor`
53
+ - `AdaBelief`
54
+ - `Lion`
55
+ - `SM3`
56
+ - `Novograd`
57
+ - `Fromage`
58
+ - `SOFO`
59
+ - `SOFOScan`
60
+
61
+ The index does not provide constructor signatures, update semantics, or comparative algorithm guidance. Select the requested class here; do not infer arguments or substitute a training workflow from this catalog.
62
+
63
+ **Source URL:** https://brainx.chaobrain.com/braintools/optim/index.html
64
+
65
+ ## Learning-rate schedulers
66
+
67
+ The scheduler base and concrete scheduler symbols are listed together. Select the exact class first, then return to the main BrainState skill for the surrounding canonical training structure.
68
+
69
+ ```python
70
+ import braintools.optim
71
+
72
+ scheduler_type = braintools.optim.ExponentialDecayLR
73
+ ```
74
+
75
+ Scheduler classes, in index order:
76
+
77
+ - `LRScheduler`
78
+ - `StepLR`
79
+ - `MultiStepLR`
80
+ - `ConstantLR`
81
+ - `LinearLR`
82
+ - `ExponentialLR`
83
+ - `PolynomialLR`
84
+ - `ExponentialDecayLR`
85
+ - `CosineAnnealingLR`
86
+ - `CosineAnnealingWarmRestarts`
87
+ - `WarmupCosineSchedule`
88
+ - `CyclicLR`
89
+ - `OneCycleLR`
90
+ - `ReduceLROnPlateau`
91
+ - `WarmupScheduler`
92
+ - `PiecewiseConstantSchedule`
93
+ - `ChainedScheduler`
94
+ - `SequentialLR`
95
+
96
+ **Source URL:** https://brainx.chaobrain.com/braintools/optim/index.html
97
+
98
+ ## Optax bridge
99
+
100
+ The index pairs a "Getting Started with `optax` Optimizers" route with the exported `OptaxOptimizer` symbol. Select that bridge only when the task explicitly calls for the Optax route through Braintools:
101
+
102
+ ```python
103
+ import braintools.optim
104
+
105
+ optax_bridge_type = braintools.optim.OptaxOptimizer
106
+ ```
107
+
108
+ The index gives no adapter constructor or Optax transformation example, so this reference does not invent one.
109
+
110
+ **Source URL:** https://brainx.chaobrain.com/braintools/optim/index.html
111
+
112
+ ## Scipy and nevergrad wrappers
113
+
114
+ The index distinguishes "gradient-free Nevergrad strategies" from "SciPy-based routines" and lists the wrapper symbols `NevergradOptimizer` and `ScipyOptimizer`.
115
+
116
+ ```python
117
+ import braintools.optim
118
+
119
+ gradient_free_wrapper_type = braintools.optim.NevergradOptimizer
120
+ scipy_wrapper_type = braintools.optim.ScipyOptimizer
121
+ ```
122
+
123
+ - Select `NevergradOptimizer` for the index's gradient-free Nevergrad route.
124
+ - Select `ScipyOptimizer` for the index's SciPy-based route.
125
+ - Do not assume that either wrapper follows the ordinary BrainState gradient-step interface; the index does not state their call contracts.
126
+
127
+ **Source URL:** https://brainx.chaobrain.com/braintools/optim/index.html
128
+
129
+ ## Integration boundary
130
+
131
+ After choosing a symbol, route back to the main BrainState skill for its canonical State-aware training structure. Advanced full-training workflows remain outside this supplied router. Training operations are deliberately not repeated here because the optimization index supplies names and routes, not the BrainState training structure.
132
+
133
+ **Source URL:** https://brainx.chaobrain.com/braintools/optim/index.html
@@ -0,0 +1,195 @@
1
+ # Brainstate collective operations
2
+
3
+ Use this reference when one operation must initialise, reset, batch, invoke a common method on, or restore stateful objects throughout a model without manually traversing its module graph. It assumes familiarity with `brainstate.nn` modules and states and basic JAX `vmap` usage; BrainState requires `brainunit`.
4
+
5
+ ## Overview of the api
6
+
7
+ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
8
+
9
+ The official guide presents `brainstate.nn._collective_ops` through these public `brainstate.nn` utilities:
10
+
11
+ | Operation | API |
12
+ |---|---|
13
+ | Fix the execution order of methods | `brainstate.nn.call_order` |
14
+ | Call the same method on each model node | `brainstate.nn.call_all_fns`, `brainstate.nn.vmap_call_all_fns` |
15
+ | Initialise state variables everywhere | `brainstate.nn.init_all_states`, `brainstate.nn.vmap_init_all_states` |
16
+ | Reset existing states everywhere | `brainstate.nn.reset_all_states`, `brainstate.nn.vmap_reset_all_states` |
17
+ | Restore values keyed by absolute state paths | `brainstate.nn.assign_state_values` |
18
+
19
+ ## Ordering calls with `call_order`
20
+
21
+ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
22
+
23
+ By default, `call_all_fns` respects graph node order. When method interactions require explicit ordering, `call_order` attaches a `call_order` attribute to a method; lower levels run first.
24
+
25
+ ```python
26
+ import brainstate
27
+
28
+
29
+ class EncoderDecoder(brainstate.nn.Module):
30
+ def __init__(self):
31
+ super().__init__()
32
+ self.encoder = brainstate.nn.Linear((16,), (32,))
33
+ self.decoder = brainstate.nn.Linear((32,), (16,))
34
+
35
+ @brainstate.nn.call_order(0)
36
+ def init_state(self):
37
+ self.encoder.init_state()
38
+ self.decoder.init_state()
39
+
40
+ @brainstate.nn.call_order(1)
41
+ def reset_state(self):
42
+ self.encoder.reset_state()
43
+ self.decoder.reset_state()
44
+ ```
45
+
46
+ The decorators make collective utilities honour this order while visiting child modules.
47
+
48
+ ## Initialising every module
49
+
50
+ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
51
+
52
+ `init_all_states` walks the module graph and calls `init_state` on each node. Pass keyword arguments through to the lifecycle methods, exclude nodes with `node_to_exclude`, or retain the returned target for chaining.
53
+
54
+ ```python
55
+ model = brainstate.nn.Sequential(
56
+ brainstate.nn.Linear((10,), (32,)),
57
+ brainstate.nn.GELU(),
58
+ brainstate.nn.Dropout(prob=0.1),
59
+ )
60
+
61
+ brainstate.nn.init_all_states(model, batch_size=4)
62
+ brainstate.nn.init_all_states(
63
+ model,
64
+ node_to_exclude=brainstate.nn.Dropout,
65
+ )
66
+
67
+ model = brainstate.nn.init_all_states(model)
68
+ ```
69
+
70
+ ## Resetting state between sequences
71
+
72
+ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
73
+
74
+ For recurrent models, initialise once and use `reset_all_states` after a sequence to automate the reset pass across the entire module.
75
+
76
+ ```python
77
+ rnn = brainstate.nn.ValinaRNNCell(num_in=8, num_out=16)
78
+ brainstate.nn.init_all_states(rnn, batch_size=2)
79
+
80
+ # ... run inference or training for one sequence ...
81
+
82
+ brainstate.nn.reset_all_states(rnn)
83
+ ```
84
+
85
+ As with `init_all_states`, reset can exclude nodes or receive additional arguments. `call_order` still governs the pass, allowing buffers to reset before hidden states when required.
86
+
87
+ ## Batched initialisation with `vmap_*`
88
+
89
+ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
90
+
91
+ For independent ensemble or Monte-Carlo instances, the vectorised variants insert a leading axis and manage a separate random key for each copy.
92
+
93
+ ```python
94
+ policy = brainstate.nn.Sequential(
95
+ brainstate.nn.Linear((4,), (64,)),
96
+ brainstate.nn.GELU(),
97
+ brainstate.nn.Linear((64,), (2,)),
98
+ )
99
+
100
+ brainstate.nn.vmap_init_all_states(policy, axis_size=8)
101
+
102
+ # ... run the batched rollout ...
103
+
104
+ brainstate.nn.vmap_reset_all_states(policy, axis_size=8)
105
+ ```
106
+
107
+ Pass a `state_to_exclude` filter to `vmap_init_all_states` when selected states, such as statistics buffers, must remain shared. Excluded states retain their original shape across the batch.
108
+
109
+ ## Calling arbitrary methods collectively
110
+
111
+ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
112
+
113
+ `call_all_fns` is the primitive behind the init and reset helpers. It can dispatch another common method only when each participating child module implements that method. The guide illustrates the required common-method shape with `log_stats`:
114
+
115
+ ```python
116
+ import jax.numpy as jnp
117
+
118
+
119
+ class LoggingLayer(brainstate.nn.Module):
120
+ def __init__(self, size):
121
+ super().__init__()
122
+ self.linear = brainstate.nn.Linear((size,), (size,))
123
+ self.logged = []
124
+
125
+ def init_state(self):
126
+ self.linear.init_state()
127
+
128
+ def log_stats(self):
129
+ weight = self.linear.weight.value['weight']
130
+ self.logged.append(jnp.mean(weight))
131
+
132
+
133
+ net = brainstate.nn.Sequential(
134
+ LoggingLayer(size=8),
135
+ LoggingLayer(size=8),
136
+ )
137
+
138
+ brainstate.nn.init_all_states(net)
139
+ for layer in net.layers:
140
+ layer.log_stats()
141
+ ```
142
+
143
+ The page identifies `brainstate.nn.vmap_call_all_fns` as the corresponding operation for `axis_size` independent instances and says it shares the interface and filter options. It does not provide a concrete `call_all_fns` or `vmap_call_all_fns` invocation signature, so consult API help rather than inferring argument order from this guide.
144
+
145
+ ## Restoring states with `assign_state_values`
146
+
147
+ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
148
+
149
+ `assign_state_values` maps dictionary values back to state objects by absolute state path and returns mismatched keys as `(unexpected, missing)`. The guide constructs paths for dictionary-valued states by appending each inner key:
150
+
151
+ ```python
152
+ autoencoder = brainstate.nn.Sequential(
153
+ brainstate.nn.Linear((16,), (8,)),
154
+ brainstate.nn.ReLU(),
155
+ brainstate.nn.Linear((8,), (16,)),
156
+ )
157
+ brainstate.nn.init_all_states(autoencoder)
158
+
159
+ state_snapshot = {}
160
+ for path, state in autoencoder.states().items():
161
+ if isinstance(state.value, dict):
162
+ for key, value in state.value.items():
163
+ state_snapshot[path + (key,)] = value
164
+ else:
165
+ state_snapshot[path] = state.value
166
+
167
+ # ... modify weights or states ...
168
+
169
+ unexpected, missing = brainstate.nn.assign_state_values(
170
+ autoencoder,
171
+ state_snapshot,
172
+ )
173
+ if unexpected or missing:
174
+ raise ValueError(
175
+ f'checkpoint mismatch: unexpected={unexpected}, missing={missing}'
176
+ )
177
+ ```
178
+
179
+ The guide's own output reports flattened paths as unexpected and their parent state paths as missing. Therefore, the example demonstrates why both return collections must be inspected; it does not demonstrate a mismatch-free restore.
180
+
181
+ ## Putting it all together
182
+
183
+ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
184
+
185
+ The final guide example combines the earlier operations in this order: construct a `ValinaRNNCell`, call `vmap_init_all_states(..., axis_size=4)`, build the same absolute-path snapshot shown above, run a time-stepped rollout, call `vmap_reset_all_states(..., axis_size=4)`, and pass the snapshot to `assign_state_values`. It repeats the same dictionary-flattening restoration pattern and likewise produces unexpected and missing keys, so retain the mismatch check when adapting that lifecycle.
186
+
187
+ ## Best practices
188
+
189
+ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
190
+
191
+ - Call `init_all_states` once after constructing a module.
192
+ - Decorate stateful methods with `call_order` when their interaction matters.
193
+ - Use `node_to_exclude` and `state_to_exclude` filters to fine-tune traversal.
194
+ - Inspect both return values from `assign_state_values` to catch mismatched checkpoints.
195
+ - Use vmapped helpers for ensembles while accounting for the added leading axis.