brainx-skill 1.0.3 → 1.0.8
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.
- package/LICENSE +1 -1
- package/README.md +29 -64
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/{lib → installation/lib}/installer.js +8 -5
- package/manifest.json +7 -1
- package/package.json +25 -10
- package/skills/braincell/SKILL.md +182 -0
- package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
- package/skills/braincell/references/channel-library.md +170 -0
- package/skills/braincell/references/ion-library.md +154 -0
- package/skills/braincell/references/mixions-for-adaptation.md +81 -0
- package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
- package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
- package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
- package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
- package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
- package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
- package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
- package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
- package/skills/braincell/references/scripts/channel_ablation.py +61 -0
- package/skills/braincell/references/scripts/fi_curve.py +68 -0
- package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
- package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
- package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
- package/skills/braincell/references/solver-library-with-effects.md +188 -0
- package/skills/brainevent/SKILL.md +268 -0
- package/skills/brainevent/references/connectivity-variants.md +312 -0
- package/skills/brainevent/references/custom-operators-cpu.md +304 -0
- package/skills/brainevent/references/custom-operators-gpu.md +468 -0
- package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
- package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
- package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
- package/skills/brainevent/references/sparse-formats.md +182 -0
- package/skills/brainevent/references/synaptic-plasticity.md +285 -0
- package/skills/brainpy-state/SKILL.md +232 -0
- package/skills/brainpy-state/references/array-creation.md +158 -0
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
- package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
- package/skills/brainpy-state/references/braintools/metric.md +152 -0
- package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
- package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
- package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
- package/skills/brainpy-state/references/component-selection.md +273 -0
- package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
- package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
- package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
- package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
- package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
- package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
- package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
- package/skills/brainpy-state/references/projection-patterns.md +125 -0
- package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
- package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
- package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
- package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
- package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
- package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
- package/skills/brainstate/SKILL.md +399 -0
- package/skills/brainstate/agents/openai.yaml +4 -0
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +293 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
- package/skills/brainstate/references/model-interop-and-migration.md +305 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +279 -0
- package/skills/brainstate/references/state-graph-operations.md +216 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
- package/skills/brainstate/scripts/integrator_rnn.py +359 -0
- package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
- package/skills/brainstate/scripts/modern_cnn.py +73 -0
- package/skills/brainstate/scripts/resnet.py +130 -0
- package/skills/brainunit/SKILL.md +287 -0
- package/skills/brainunit/references/array-creation.md +158 -0
- package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
- package/skills/brainunit/references/array-mechanics.md +165 -0
- package/skills/brainunit/references/math-function-library.md +433 -0
- package/skills/brainunit/references/physical-constant-library.md +58 -0
- package/skills/brainunit/references/prefix-library.md +116 -0
- package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
- package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
- package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
- package/skills/brainx-general-guard/SKILL.md +153 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
- package/skills/brainx-install/SKILL.md +2 -2
- package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
- /package/{bin → installation/bin}/brainx.js +0 -0
- /package/{lib → installation/lib}/adapter-transaction.js +0 -0
- /package/{lib → installation/lib}/bundle.js +0 -0
- /package/{lib → installation/lib}/cli.js +0 -0
- /package/{lib → installation/lib}/constants.js +0 -0
- /package/{lib → installation/lib}/hash.js +0 -0
- /package/{lib → installation/lib}/paths.js +0 -0
- /package/{lib → installation/lib}/prompts.js +0 -0
- /package/{lib → installation/lib}/receipt.js +0 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
# BrainState vmap expansion
|
|
2
|
+
|
|
3
|
+
Use this reference after the minimal `brainstate.transform.vmap` example in
|
|
4
|
+
`skills/brainstate/SKILL.md` when argument axes, State axes, random-key policy,
|
|
5
|
+
nested mappings, or unexpected State writes require explicit control.
|
|
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 describes `brainstate.transform.vmap` as a
|
|
13
|
+
state-aware wrapper around `jax.vmap`, but its detailed executable examples use
|
|
14
|
+
`brainstate.transform.vmap2`. Preserve that distinction; do not silently
|
|
15
|
+
substitute one API for the other.
|
|
16
|
+
|
|
17
|
+
## Selection map
|
|
18
|
+
|
|
19
|
+
| Need | Control | Key constraint |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| Map or broadcast function arguments | `in_axes` | Use an integer axis to map and `None` to share. |
|
|
22
|
+
| Place the mapped output axis | `out_axes` | Match the downstream layout explicitly. |
|
|
23
|
+
| Map with no mapped input argument | `axis_size` | Supply the size because it cannot be inferred. |
|
|
24
|
+
| Use collectives over the mapped axis | `axis_name` | The collective must use the same name. |
|
|
25
|
+
| Map mutable State but share parameters | `vmap2(..., state_in_axes=..., state_out_axes=...)` with State filters | Define both input mapping and write-back for per-instance State. |
|
|
26
|
+
| Handle a written State omitted from `state_out_axes` | `vmap2(..., unexpected_out_state_mapping=...)` | The default `'auto'` infers and scatters the mapped axis; declare State axes when a coincidental leading-size match would be ambiguous. |
|
|
27
|
+
| Choose independent or shared random draws | BrainState automatic splitting or one broadcast JAX key | Shared keys intentionally correlate mapped results. |
|
|
28
|
+
| Build a custom mapping primitive | `StatefulMapping` | Use only when `vmap` or `vmap2` cannot express the required primitive. |
|
|
29
|
+
|
|
30
|
+
The Vectorization tutorial imports the detailed mapping API and State filter as follows:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import jax
|
|
34
|
+
import jax.numpy as jnp
|
|
35
|
+
import brainstate
|
|
36
|
+
from brainstate.transform import vmap2
|
|
37
|
+
from brainstate.util.filter import OfType
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Map sweeps and broadcast fixed arguments
|
|
41
|
+
|
|
42
|
+
`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.
|
|
43
|
+
|
|
44
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-in-axes-parameter
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
def weighted_sum(x, weight):
|
|
48
|
+
"""Compute weighted sum: x * weight"""
|
|
49
|
+
return x * weight
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
vmap_weighted = vmap2(weighted_sum, in_axes=(0, None))
|
|
53
|
+
batch_x = jnp.array([1.0, 2.0, 3.0])
|
|
54
|
+
single_weight = 2.0
|
|
55
|
+
result = vmap_weighted(batch_x, single_weight)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
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.
|
|
59
|
+
|
|
60
|
+
`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.
|
|
61
|
+
|
|
62
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-out-axes-parameter
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
def create_vector(scalar):
|
|
66
|
+
return jnp.array([scalar, scalar * 2, scalar * 3])
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
vmap_axis1 = vmap2(create_vector, in_axes=0, out_axes=1)
|
|
70
|
+
result_axis1 = vmap_axis1(jnp.array([1.0, 2.0]))
|
|
71
|
+
assert result_axis1.shape == (3, 2)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
When every input is static, the mapped size cannot be inferred from an argument; supply `axis_size` explicitly.
|
|
75
|
+
|
|
76
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-axis-size-parameter
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
def generate_sequence(unused=None):
|
|
80
|
+
return jnp.arange(3)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
vmap_generate = vmap2(generate_sequence, in_axes=None, axis_size=5)
|
|
84
|
+
result = vmap_generate()
|
|
85
|
+
assert result.shape == (5, 3)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Name the mapped axis only when a collective operation needs it. The tutorial uses `axis_name='batch'` with `jax.lax.pmean`:
|
|
89
|
+
|
|
90
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-axis-name-parameter
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
def normalize_batch(x):
|
|
94
|
+
batch_mean = jax.lax.pmean(x, axis_name='batch')
|
|
95
|
+
return x - batch_mean
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
vmap_normalize = vmap2(normalize_batch, in_axes=0, axis_name='batch')
|
|
99
|
+
normalized = vmap_normalize(jnp.array([1.0, 2.0, 3.0, 4.0]))
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Map per-instance state and share parameters
|
|
103
|
+
|
|
104
|
+
`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.
|
|
105
|
+
|
|
106
|
+
Sources:
|
|
107
|
+
|
|
108
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#state-aware-parameters-state-in-axes-and-state-out-axes
|
|
109
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#state-axis-inference
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
class StatefulComputation(brainstate.nn.Module):
|
|
113
|
+
def __init__(self):
|
|
114
|
+
super().__init__()
|
|
115
|
+
self.temp = brainstate.ShortTermState(jnp.zeros(3))
|
|
116
|
+
self.param = brainstate.ParamState(jnp.array(1.0))
|
|
117
|
+
|
|
118
|
+
def __call__(self, x):
|
|
119
|
+
self.temp.value = self.temp.value + x
|
|
120
|
+
return self.temp.value * self.param.value
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
model = StatefulComputation()
|
|
124
|
+
vmap_model = vmap2(
|
|
125
|
+
model,
|
|
126
|
+
in_axes=0,
|
|
127
|
+
out_axes=0,
|
|
128
|
+
state_in_axes={0: OfType(brainstate.ShortTermState)},
|
|
129
|
+
state_out_axes={0: OfType(brainstate.ShortTermState)},
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
inputs = jnp.array([1.0, 2.0, 3.0])
|
|
133
|
+
outputs = vmap_model(inputs)
|
|
134
|
+
|
|
135
|
+
assert jnp.allclose(model.temp.value, jnp.array([1.0, 2.0, 3.0]))
|
|
136
|
+
assert model.param.value == 1.0
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
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.
|
|
140
|
+
|
|
141
|
+
### Exact parameter names
|
|
142
|
+
|
|
143
|
+
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.
|
|
144
|
+
|
|
145
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#state-aware-parameters-state-in-axes-and-state-out-axes
|
|
146
|
+
|
|
147
|
+
## Handle state writes outside `state_out_axes`
|
|
148
|
+
|
|
149
|
+
`unexpected_out_state_mapping` controls behavior when a State is written but is
|
|
150
|
+
not covered by `state_out_axes`. The current generated `vmap2` API defaults to
|
|
151
|
+
`'auto'`, which infers the output axis and scatters the write. The `'raise'`
|
|
152
|
+
policy raises `BatchAxisError`; `'warn'` and `'ignore'` scatter with or without
|
|
153
|
+
a warning. The tutorial demonstrates an explicit `'ignore'` policy with a
|
|
154
|
+
written `LongTermState` that is not listed in State-axis filters.
|
|
155
|
+
|
|
156
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-unexpected-out-state-mapping-parameter
|
|
157
|
+
|
|
158
|
+
Exact policy source: https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.transform.vmap2.html
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
temp_state = brainstate.ShortTermState(jnp.array(0.0))
|
|
162
|
+
write_state = brainstate.LongTermState(jnp.asarray(0.0))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def update_temp(x):
|
|
166
|
+
temp_state.value = temp_state.value + x
|
|
167
|
+
write_state.value = temp_state.value
|
|
168
|
+
return temp_state.value
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
vmap_ignore = vmap2(
|
|
172
|
+
update_temp,
|
|
173
|
+
in_axes=0,
|
|
174
|
+
unexpected_out_state_mapping='ignore',
|
|
175
|
+
)
|
|
176
|
+
result = vmap_ignore(jnp.array([1.0, 2.0, 3.0]))
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Declare the State axes when an unexpected read-modify-write could be mistaken
|
|
180
|
+
for per-lane State because its leading size happens to match the mapped size.
|
|
181
|
+
Do not assume that mapping only the function arguments also specifies the
|
|
182
|
+
output behavior of every State the function mutates.
|
|
183
|
+
|
|
184
|
+
## Choose independent or shared randomness
|
|
185
|
+
|
|
186
|
+
`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.
|
|
187
|
+
|
|
188
|
+
Sources:
|
|
189
|
+
|
|
190
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#automatic-key-splitting-for-randomstate
|
|
191
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html#setting-seeds
|
|
192
|
+
|
|
193
|
+
```python
|
|
194
|
+
brainstate.random.seed(42)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def sample_normal(scale):
|
|
198
|
+
return brainstate.random.normal(0.0, scale)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
vmap_sample = vmap2(sample_normal, in_axes=0)
|
|
202
|
+
scales = jnp.array([1.0, 2.0, 3.0, 4.0])
|
|
203
|
+
samples = vmap_sample(scales)
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
This is also the smallest stochastic parameter-sweep pattern: the scale is mapped, and BrainState supplies an independent key to each element.
|
|
207
|
+
|
|
208
|
+
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`.
|
|
209
|
+
|
|
210
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#controlling-random-keys-using-jax-s-random-api
|
|
211
|
+
|
|
212
|
+
```python
|
|
213
|
+
def sample_with_jax_key(key, scale):
|
|
214
|
+
return jax.random.normal(key, ()) * scale
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
vmap_shared_key = vmap2(
|
|
218
|
+
sample_with_jax_key,
|
|
219
|
+
in_axes=(None, 0),
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
shared_key = jax.random.PRNGKey(0)
|
|
223
|
+
scales = jnp.array([1.0, 2.0, 3.0, 4.0])
|
|
224
|
+
samples_shared = vmap_shared_key(shared_key, scales)
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
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.
|
|
228
|
+
|
|
229
|
+
Randomness boundary source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html#advanced-key-management
|
|
230
|
+
|
|
231
|
+
## Nest and compose mappings
|
|
232
|
+
|
|
233
|
+
Nest `vmap2` when the function must map over more than one batch dimension. Each layer owns one mapped axis.
|
|
234
|
+
|
|
235
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#nested-vmap2
|
|
236
|
+
|
|
237
|
+
```python
|
|
238
|
+
def matrix_elem_product(x, y):
|
|
239
|
+
return x * y
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
vmap_rows = vmap2(matrix_elem_product, in_axes=(0, 0))
|
|
243
|
+
vmap_matrix = vmap2(vmap_rows, in_axes=(0, 0))
|
|
244
|
+
|
|
245
|
+
matrix_a = jnp.ones((3, 4))
|
|
246
|
+
matrix_b = jnp.arange(12).reshape(3, 4)
|
|
247
|
+
result = vmap_matrix(matrix_a, matrix_b)
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
The tutorial also composes BrainState `grad`, `vmap2`, and `jit`. Map the per-example gradient first, then compile the mapped function.
|
|
251
|
+
|
|
252
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#combining-with-other-transforms
|
|
253
|
+
|
|
254
|
+
```python
|
|
255
|
+
from brainstate.transform import grad, jit
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def loss_fn(x, target):
|
|
259
|
+
pred = x ** 2
|
|
260
|
+
return jnp.sum((pred - target) ** 2)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
batched_grad = vmap2(
|
|
264
|
+
grad(loss_fn, argnums=0),
|
|
265
|
+
in_axes=(0, 0),
|
|
266
|
+
)
|
|
267
|
+
batched_grad_jit = jit(batched_grad)
|
|
268
|
+
|
|
269
|
+
batch_x = jnp.array([1.0, 2.0, 3.0])
|
|
270
|
+
batch_targets = jnp.array([2.0, 4.0, 6.0])
|
|
271
|
+
gradients = batched_grad_jit(batch_x, batch_targets)
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
## Use `StatefulMapping` only for a custom primitive
|
|
275
|
+
|
|
276
|
+
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.
|
|
277
|
+
|
|
278
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#direct-use-of-statefulmapping
|
|
279
|
+
|
|
280
|
+
```python
|
|
281
|
+
import functools
|
|
282
|
+
from brainstate.transform import StatefulMapping
|
|
283
|
+
|
|
284
|
+
counter_state = brainstate.ShortTermState(jnp.zeros(3))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def increment(delta):
|
|
288
|
+
counter_state.value = counter_state.value + delta
|
|
289
|
+
return counter_state.value
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
custom_mapping = StatefulMapping(
|
|
293
|
+
increment,
|
|
294
|
+
in_axes=0,
|
|
295
|
+
out_axes=0,
|
|
296
|
+
state_in_axes={0: OfType(brainstate.ShortTermState)},
|
|
297
|
+
state_out_axes={0: OfType(brainstate.ShortTermState)},
|
|
298
|
+
name="custom_increment",
|
|
299
|
+
mapping_fn=functools.partial(jax.vmap, spmd_axis_name=None),
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
results = custom_mapping(jnp.array([1.0, 2.0, 3.0]))
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
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.
|
|
306
|
+
|
|
307
|
+
## High-impact checks
|
|
308
|
+
|
|
309
|
+
- Match every non-`None` `in_axes` entry to an actual mapped dimension of the corresponding argument.
|
|
310
|
+
- Decide whether mutable State is shared or mapped; use `state_in_axes` and `state_out_axes` together for per-instance State write-back.
|
|
311
|
+
- Set `axis_size` when all inputs are static.
|
|
312
|
+
- Declare State axes or set an explicit policy when automatic output-axis inference would be ambiguous.
|
|
313
|
+
- Expect automatic independent `RandomState` keys; use the documented broadcast-key pattern only when shared randomness is intentional.
|
|
314
|
+
- Route direct key manipulation through the randomness reference rather than duplicating it here.
|
|
@@ -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
|
+
## Selection map
|
|
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
|
+
| Need | API | Key constraint |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| Fix the execution order of methods | `brainstate.nn.call_order` | Lower order values run first. |
|
|
14
|
+
| Call the same method on each model node | `brainstate.nn.call_all_fns`, `brainstate.nn.vmap_call_all_fns` | Filter nodes deliberately and verify the installed call signature. |
|
|
15
|
+
| Initialise state variables everywhere | `brainstate.nn.init_all_states`, `brainstate.nn.vmap_init_all_states` | Run after construction and before the first rollout. |
|
|
16
|
+
| Reset existing states everywhere | `brainstate.nn.reset_all_states`, `brainstate.nn.vmap_reset_all_states` | Reset at the intended sequence boundary, not every time step. |
|
|
17
|
+
| Restore values keyed by absolute state paths | `brainstate.nn.assign_state_values` | Inspect both returned mismatch collections. |
|
|
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.
|