brainx-skill 1.0.10 → 1.0.12
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/README.md +6 -0
- package/adapters/antigravity.js +8 -0
- package/installation/lib/installer.js +60 -20
- package/installation/lib/paths.js +41 -3
- package/installation/lib/prompts.js +13 -7
- package/manifest.json +2 -1
- package/package.json +3 -2
- package/skills/braincell/SKILL.md +1 -1
- package/skills/braincell/references/mixions-for-adaptation.md +26 -3
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +113 -53
- package/skills/brainevent/references/synaptic-plasticity.md +74 -230
- package/skills/brainmass/SKILL.md +11 -6
- package/skills/brainmass/references/batch-transform-acceleration.md +44 -3
- package/skills/brainmass/references/modellibrary.md +11 -0
- package/skills/brainmass/references/simulator-input-monitor-api.md +98 -0
- package/skills/brainpy-state/SKILL.md +20 -6
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +52 -1
- package/skills/brainpy-state/references/brainPy(legacy)/analysis.md +150 -0
- package/skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +373 -0
- package/skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +150 -0
- package/skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +175 -0
- package/skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +286 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +111 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +163 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +113 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +136 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +222 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +123 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +107 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +185 -0
- package/skills/brainpy-state/references/brainPy(legacy)/integrators.md +181 -0
- package/skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +102 -0
- package/skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +147 -0
- package/skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +159 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +127 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +167 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +107 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +186 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +104 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +89 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +253 -0
- package/skills/brainpy-state/references/braintools/connectivity.md +206 -0
- package/skills/brainpy-state/references/braintools/input-current.md +199 -0
- package/skills/brainpy-state/references/component-selection.md +20 -5
- package/skills/brainpy-state/references/projection-patterns.md +2 -0
- package/skills/brainpy-state/references/scripts/sound_localization.py +240 -0
- package/skills/brainstate/SKILL.md +1 -1
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +8 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +57 -7
- package/skills/brainstate/references/collective_model_operations.md +26 -27
- package/skills/braintrace/SKILL.md +161 -0
- package/skills/braintrace/references/Drtrl.md +179 -0
- package/skills/braintrace/references/ETP operators.md +161 -0
- package/skills/braintrace/references/algorithm selection.md +120 -0
- package/skills/braintrace/references/batching.md +150 -0
- package/skills/braintrace/references/compiler_internal.md +162 -0
- package/skills/braintrace/references/custom ETP primitives.md +200 -0
- package/skills/braintrace/references/custom algorithms.md +206 -0
- package/skills/braintrace/references/customizing_primitive_transforms.md +191 -0
- package/skills/braintrace/references/pp_pprop workflow.md +196 -0
- package/skills/braintrace/references/pre-built-braintrace-layer.md +149 -0
- package/skills/brainx-general-guard/SKILL.md +64 -21
|
@@ -9,11 +9,16 @@ Choose components in dependency order so later decisions preserve earlier semant
|
|
|
9
9
|
| Step | Decide | Result |
|
|
10
10
|
|---|---|---|
|
|
11
11
|
| 1 | Which firing mechanism must the neuron reproduce? | Neuron family and required numerical resolution |
|
|
12
|
-
| 2 | Is the
|
|
13
|
-
| 3 | Which
|
|
14
|
-
| 4 |
|
|
15
|
-
| 5 |
|
|
16
|
-
| 6 |
|
|
12
|
+
| 2 | Is the drive a direct current protocol, scheduled or stochastic spike source, encoded value, or direct State injection? | BrainTools current protocol, BrainPy input generator, encoder, or input function |
|
|
13
|
+
| 3 | Which presynaptic/postsynaptic pairs exist, and does geometry or topology determine them? | Connection topology and a `ConnectionResult` when BrainTools owns pair selection |
|
|
14
|
+
| 4 | Which temporal response must a presynaptic event create? | Synaptic dynamics and the valid projection alignment |
|
|
15
|
+
| 5 | Should synaptic activity become voltage-dependent conductance or voltage-independent current? | Synaptic output, weight units, signs, and scale |
|
|
16
|
+
| 6 | Must efficacy change over recent presynaptic history? | Optional `STP` or `STD` |
|
|
17
|
+
| 7 | What tensor and temporal statistic does the loss or analysis consume? | Readout Module or explicit time reduction |
|
|
18
|
+
|
|
19
|
+
Complete steps 3 through 6 whenever a point-neuron task names recurrent excitation, mutual inhibition, or spike-driven connectivity. Use explicit synapses, outputs, communication, and projections; do not substitute a scalar mean-spike feedback `State`. If scalar population rates and rate coupling are the scientific variables, route that scale to BrainMass or open both skills for an explicit hybrid model.
|
|
20
|
+
|
|
21
|
+
When geometry, spatial distance, graph topology, Dale's principle, or compartment targeting determines the edge set, open `references/braintools/connectivity.md` and generate the `ConnectionResult` before selecting CSR, CSC, dense, generated, or fixed-degree BrainEvent storage. Let a projection communication operator own pair selection only when its documented fixed-probability or fixed-degree contract expresses the intended topology directly.
|
|
17
22
|
|
|
18
23
|
After these choices, open `references/projection-patterns.md` to choose AlignPre versus AlignPost, communication, delay integration, and projection construction form.
|
|
19
24
|
|
|
@@ -110,6 +115,16 @@ Compare firing rate, adaptation, spike onset, and stability at the intended `dt`
|
|
|
110
115
|
|
|
111
116
|
Choose the source from what is already known and where the generated input should be applied.
|
|
112
117
|
|
|
118
|
+
### Direct current protocols
|
|
119
|
+
|
|
120
|
+
Use a BrainTools current protocol when known time-varying values should enter a neuron's current argument rather than emit spikes or mutate target State.
|
|
121
|
+
|
|
122
|
+
| API family | Use when |
|
|
123
|
+
|---|---|
|
|
124
|
+
| `braintools.input` | Use for unit-aware constant sections, steps, pulses, waveforms, stochastic current processes, and composed protocols; generate a time-major array under the intended `brainstate.environ.dt`. |
|
|
125
|
+
|
|
126
|
+
Open `references/braintools/input-current.md` for API selection, composition, and the BrainPy-State rollout handoff. Generate the complete time-major current once under the rollout `dt`, pass it as an `xs` argument to `for_loop`, and apply spatial masks through unit-aware broadcasting after each sample is sliced. Do not rebuild named sections or pulses from time predicates inside the model step.
|
|
127
|
+
|
|
113
128
|
### Scheduled and autonomous spike sources
|
|
114
129
|
|
|
115
130
|
Use this family when the source owns either a prescribed event schedule or a persistent stochastic firing-rate configuration.
|
|
@@ -115,6 +115,8 @@ Use `brainstate.nn.EventFixedProb` for the canonical probabilistic sparse-spike
|
|
|
115
115
|
|
|
116
116
|
Open `references/scripts/103_COBA_2005.py` for a complete E/I COBA projection workflow. Open `references/scripts/109_fast_global_oscillation.py` when the projection uses `DeltaProj` with delayed recurrent input.
|
|
117
117
|
|
|
118
|
+
Open `references/scripts/sound_localization.py` when independent conditions require a mapped bank of heterogeneous integer event taps feeding BrainEvent fixed-fan-out communication and coincidence detectors.
|
|
119
|
+
|
|
118
120
|
## Official sources
|
|
119
121
|
|
|
120
122
|
- `https://brainx.chaobrain.com/brainpy-state/concepts/model-anatomy.html`
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""Localize sound direction from interaural spike timing.
|
|
2
|
+
|
|
3
|
+
Positive interaural time difference (ITD) means the right-ear spike arrives
|
|
4
|
+
later, so the source is on the left. Negative ITD means the source is right.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import brainevent
|
|
10
|
+
import brainpy
|
|
11
|
+
import brainstate
|
|
12
|
+
import braintools
|
|
13
|
+
import brainunit as u
|
|
14
|
+
import jax.numpy as jnp
|
|
15
|
+
import numpy as np
|
|
16
|
+
from brainstate.transform import vmap2
|
|
17
|
+
from brainstate.util import filter as util_filter
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
DT = 0.05 * u.ms
|
|
21
|
+
NUM_STEPS = 80
|
|
22
|
+
DURATION = NUM_STEPS * DT
|
|
23
|
+
SOUND_ONSET = 40 * DT
|
|
24
|
+
|
|
25
|
+
PREFERRED_DELAY_STEPS = jnp.arange(-12, 13, dtype=jnp.int32)
|
|
26
|
+
PREFERRED_ITDS = PREFERRED_DELAY_STEPS * DT
|
|
27
|
+
MAX_INTERNAL_DELAY_STEPS = 12
|
|
28
|
+
EVALUATION_ITDS = u.math.asarray(
|
|
29
|
+
[-0.53, -0.33, -0.17, -0.075, -0.05, 0.0, 0.05, 0.075, 0.17, 0.33, 0.53]
|
|
30
|
+
) * u.ms
|
|
31
|
+
|
|
32
|
+
V_REST = -60.0 * u.mV
|
|
33
|
+
V_THRESHOLD = -50.0 * u.mV
|
|
34
|
+
V_RESET = -60.0 * u.mV
|
|
35
|
+
AUDITORY_PULSE = 27.0 * u.mA
|
|
36
|
+
DETECTOR_WEIGHT = 24.0 * u.mA
|
|
37
|
+
READOUT_WEIGHT = 120.0 * u.mA
|
|
38
|
+
|
|
39
|
+
DYNAMICAL_STATE = util_filter.Any(
|
|
40
|
+
util_filter.OfType(brainstate.HiddenState),
|
|
41
|
+
util_filter.OfType(brainstate.ShortTermState),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _lif_population(size: int, tau, tau_ref):
|
|
46
|
+
return brainpy.state.LIFRef(
|
|
47
|
+
size,
|
|
48
|
+
R=1.0 * u.ohm,
|
|
49
|
+
tau=tau,
|
|
50
|
+
tau_ref=tau_ref,
|
|
51
|
+
V_rest=V_REST,
|
|
52
|
+
V_th=V_THRESHOLD,
|
|
53
|
+
V_reset=V_RESET,
|
|
54
|
+
V_initializer=braintools.init.Constant(V_REST),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class EventDelayLine(brainstate.nn.Module):
|
|
59
|
+
"""Small integer delay bank with step 0 equal to the current event."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, max_steps: int):
|
|
62
|
+
super().__init__()
|
|
63
|
+
self.max_steps = max_steps
|
|
64
|
+
|
|
65
|
+
def init_state(self):
|
|
66
|
+
self.history = brainstate.HiddenState(
|
|
67
|
+
jnp.zeros((self.max_steps + 1, 2), dtype=jnp.bool_)
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def update(self, events):
|
|
71
|
+
self.history.value = jnp.concatenate(
|
|
72
|
+
[events[None, :], self.history.value[:-1]],
|
|
73
|
+
axis=0,
|
|
74
|
+
)
|
|
75
|
+
return self.history.value
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class SoundLocalizer(brainstate.nn.Module):
|
|
79
|
+
"""Two auditory relays, a coincidence bank, and left/right readouts."""
|
|
80
|
+
|
|
81
|
+
def __init__(self):
|
|
82
|
+
super().__init__()
|
|
83
|
+
self.num_detectors = int(PREFERRED_DELAY_STEPS.shape[0])
|
|
84
|
+
self.auditory = _lif_population(2, tau=0.1 * u.ms, tau_ref=0.5 * u.ms)
|
|
85
|
+
self.detectors = _lif_population(
|
|
86
|
+
self.num_detectors,
|
|
87
|
+
tau=0.2 * u.ms,
|
|
88
|
+
tau_ref=0.5 * u.ms,
|
|
89
|
+
)
|
|
90
|
+
self.readout = _lif_population(2, tau=0.5 * u.ms, tau_ref=0.5 * u.ms)
|
|
91
|
+
|
|
92
|
+
self.ear_history = EventDelayLine(MAX_INTERNAL_DELAY_STEPS)
|
|
93
|
+
self.left_delay_steps = jnp.maximum(PREFERRED_DELAY_STEPS, 0)
|
|
94
|
+
self.right_delay_steps = jnp.maximum(-PREFERRED_DELAY_STEPS, 0)
|
|
95
|
+
|
|
96
|
+
detector_targets = jnp.concatenate(
|
|
97
|
+
[jnp.arange(self.num_detectors), jnp.arange(self.num_detectors)]
|
|
98
|
+
)[:, None]
|
|
99
|
+
self.detector_connection = brainevent.FixedNumPerPre(
|
|
100
|
+
DETECTOR_WEIGHT,
|
|
101
|
+
detector_targets,
|
|
102
|
+
shape=(2 * self.num_detectors, self.num_detectors),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
readout_targets = jnp.where(PREFERRED_DELAY_STEPS > 0, 0, 1)[:, None]
|
|
106
|
+
readout_weights = (
|
|
107
|
+
(PREFERRED_DELAY_STEPS != 0).astype(jnp.float32)[:, None]
|
|
108
|
+
* READOUT_WEIGHT
|
|
109
|
+
)
|
|
110
|
+
self.readout_connection = brainevent.FixedNumPerPre(
|
|
111
|
+
readout_weights,
|
|
112
|
+
readout_targets,
|
|
113
|
+
shape=(self.num_detectors, 2),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def update(self, t, itd_step):
|
|
117
|
+
with brainstate.environ.context(t=t):
|
|
118
|
+
arrivals = u.math.asarray(
|
|
119
|
+
[SOUND_ONSET, SOUND_ONSET + itd_step * DT]
|
|
120
|
+
)
|
|
121
|
+
ear_drive = (
|
|
122
|
+
u.math.abs(t - arrivals) < 0.25 * brainstate.environ.get_dt()
|
|
123
|
+
) * AUDITORY_PULSE
|
|
124
|
+
ear_spikes = self.auditory(ear_drive) != 0.0
|
|
125
|
+
|
|
126
|
+
history = self.ear_history.update(ear_spikes)
|
|
127
|
+
left_events = history[self.left_delay_steps, 0]
|
|
128
|
+
right_events = history[self.right_delay_steps, 1]
|
|
129
|
+
delayed_events = jnp.concatenate([left_events, right_events])
|
|
130
|
+
|
|
131
|
+
detector_current = (
|
|
132
|
+
brainevent.BinaryArray(delayed_events) @ self.detector_connection
|
|
133
|
+
)
|
|
134
|
+
detector_spikes = self.detectors(detector_current) != 0.0
|
|
135
|
+
|
|
136
|
+
readout_current = (
|
|
137
|
+
brainevent.BinaryArray(detector_spikes) @ self.readout_connection
|
|
138
|
+
)
|
|
139
|
+
readout_spikes = self.readout(readout_current) != 0.0
|
|
140
|
+
return ear_spikes, detector_spikes, readout_spikes
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def simulate_itds(itds=EVALUATION_ITDS):
|
|
144
|
+
"""Round unit-bearing ITDs to ``dt`` and evaluate independent conditions."""
|
|
145
|
+
itds = u.math.asarray(itds, unit=u.ms)
|
|
146
|
+
if itds.ndim != 1:
|
|
147
|
+
raise ValueError("itds must be a one-dimensional time quantity")
|
|
148
|
+
itd_steps = jnp.rint(
|
|
149
|
+
itds.to_decimal(u.ms) / DT.to_decimal(u.ms)
|
|
150
|
+
).astype(jnp.int32)
|
|
151
|
+
|
|
152
|
+
with brainstate.environ.context(dt=DT):
|
|
153
|
+
net = SoundLocalizer()
|
|
154
|
+
brainstate.nn.vmap_init_all_states(net, axis_size=itds.shape[0])
|
|
155
|
+
mapped_step = vmap2(
|
|
156
|
+
net.update,
|
|
157
|
+
in_axes=(None, 0),
|
|
158
|
+
out_axes=0,
|
|
159
|
+
state_in_axes={0: DYNAMICAL_STATE},
|
|
160
|
+
state_out_axes={0: DYNAMICAL_STATE},
|
|
161
|
+
unexpected_out_state_mapping="raise",
|
|
162
|
+
)
|
|
163
|
+
times = u.math.arange(0.0 * u.ms, DURATION, DT)
|
|
164
|
+
|
|
165
|
+
def step(t):
|
|
166
|
+
return mapped_step(t, itd_steps)
|
|
167
|
+
|
|
168
|
+
ear_spikes, detector_spikes, readout_spikes = (
|
|
169
|
+
brainstate.transform.for_loop(step, times)
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
return (
|
|
173
|
+
jnp.sum(ear_spikes, axis=0),
|
|
174
|
+
jnp.sum(detector_spikes, axis=0),
|
|
175
|
+
jnp.sum(readout_spikes, axis=0),
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def decode_directions(detector_counts, readout_counts):
|
|
180
|
+
"""Decode only rows supported by coincidence-detector evidence."""
|
|
181
|
+
detectors = np.asarray(detector_counts)
|
|
182
|
+
counts = np.asarray(readout_counts)
|
|
183
|
+
if np.any(detectors.sum(axis=1) == 0):
|
|
184
|
+
raise ValueError("cannot decode a condition with no detector evidence")
|
|
185
|
+
|
|
186
|
+
labels = np.full(counts.shape[0], "CENTER", dtype="<U6")
|
|
187
|
+
labels[counts[:, 0] > counts[:, 1]] = "LEFT"
|
|
188
|
+
labels[counts[:, 1] > counts[:, 0]] = "RIGHT"
|
|
189
|
+
|
|
190
|
+
ties = counts[:, 0] == counts[:, 1]
|
|
191
|
+
winning_steps = np.asarray(PREFERRED_DELAY_STEPS)[np.argmax(detectors, axis=1)]
|
|
192
|
+
if np.any(ties & (winning_steps != 0)):
|
|
193
|
+
raise ValueError("readout tie is not supported by the center detector")
|
|
194
|
+
return labels
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def assert_delay_convention():
|
|
198
|
+
"""Prove that tap 3 returns an impulse after three completed updates."""
|
|
199
|
+
with brainstate.environ.context(dt=DT):
|
|
200
|
+
delay = EventDelayLine(max_steps=3)
|
|
201
|
+
brainstate.nn.init_all_states(delay)
|
|
202
|
+
impulse = jnp.zeros((5, 2), dtype=jnp.bool_).at[0, 0].set(True)
|
|
203
|
+
history = brainstate.transform.for_loop(delay.update, impulse)
|
|
204
|
+
expected = jnp.array([False, False, False, True, False])
|
|
205
|
+
assert jnp.array_equal(history[:, 3, 0], expected)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def main():
|
|
209
|
+
assert_delay_convention()
|
|
210
|
+
ear_counts, detector_counts, readout_counts = simulate_itds()
|
|
211
|
+
directions = decode_directions(detector_counts, readout_counts)
|
|
212
|
+
evaluated = np.asarray(EVALUATION_ITDS.to_decimal(u.ms))
|
|
213
|
+
preferences = np.asarray(PREFERRED_ITDS.to_decimal(u.ms))
|
|
214
|
+
detectors = np.asarray(detector_counts)
|
|
215
|
+
readouts = np.asarray(readout_counts)
|
|
216
|
+
|
|
217
|
+
print(" ITD (ms) | detector (ms) | L/R spikes | direction")
|
|
218
|
+
print("----------+---------------+------------+----------")
|
|
219
|
+
for itd, detector_row, readout_row, direction in zip(
|
|
220
|
+
evaluated, detectors, readouts, directions
|
|
221
|
+
):
|
|
222
|
+
detector_itd = preferences[int(np.argmax(detector_row))]
|
|
223
|
+
print(
|
|
224
|
+
f"{itd:9.2f} | {detector_itd:13.2f} |"
|
|
225
|
+
f" {readout_row[0]:3d}/{readout_row[1]:<3d} | {direction}"
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
if not np.all(np.asarray(ear_counts) == 1):
|
|
229
|
+
raise RuntimeError("each auditory relay must emit exactly one spike")
|
|
230
|
+
expected = np.where(
|
|
231
|
+
evaluated < 0.0,
|
|
232
|
+
"RIGHT",
|
|
233
|
+
np.where(evaluated > 0.0, "LEFT", "CENTER"),
|
|
234
|
+
)
|
|
235
|
+
if not np.array_equal(directions, expected):
|
|
236
|
+
raise RuntimeError("direction decoding failed")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
if __name__ == "__main__":
|
|
240
|
+
main()
|
|
@@ -299,7 +299,7 @@ batched_prediction = predict_batch(x_train)
|
|
|
299
299
|
assert batched_prediction.shape == (64, 1)
|
|
300
300
|
```
|
|
301
301
|
|
|
302
|
-
This maps a function written for one example over a batch. Open the `vmap` expansion for mapped State axes, ensembles, parameter sweeps
|
|
302
|
+
This maps a function written for one example over a batch. Open the `vmap` expansion for mapped State axes, ensembles, or parameter sweeps. Use `vmap(..., in_states=..., out_states=...)` to declare specific mapped State instances; use `vmap2(..., state_in_axes=..., state_out_axes=...)` to select State by filters with configurable output-axis inference. Do not add either transform when the owning package already exposes the required batch axis.
|
|
303
303
|
|
|
304
304
|
### 6. Randomness
|
|
305
305
|
|
|
@@ -205,6 +205,14 @@ gradients through a long rollout make activation memory the binding constraint.
|
|
|
205
205
|
Tune `base` by measuring peak memory and step time: it controls checkpoint
|
|
206
206
|
granularity, so lower memory requires more backward recomputation.
|
|
207
207
|
|
|
208
|
+
Choose the transform boundary from the State lifecycle, not from a goal of
|
|
209
|
+
eliminating every host loop. Put all timesteps of one logical rollout in
|
|
210
|
+
`for_loop` or `scan`. When trials must remain sequential because learned State
|
|
211
|
+
passes from trial N to trial N+1, but neural and short-term State must reset at
|
|
212
|
+
each trial boundary, compile one complete trial callable and use a small host
|
|
213
|
+
loop across trials. Do not nest the trials in another transformed loop when
|
|
214
|
+
that prevents the required selective reset.
|
|
215
|
+
|
|
208
216
|
**Invariant:** Initialize recurrent State before each rollout, keep the
|
|
209
217
|
checkpointed loop inside `loss_fn`, differentiate that loss, then JIT the whole
|
|
210
218
|
training step. Checkpointing changes the memory/compute profile, not the
|
|
@@ -9,10 +9,7 @@ This reference covers only behavior demonstrated by these routed official tutori
|
|
|
9
9
|
- Vectorization: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html
|
|
10
10
|
- Random Number Generation: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
|
|
11
11
|
|
|
12
|
-
The Vectorization tutorial
|
|
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.
|
|
12
|
+
The Vectorization tutorial demonstrates filter-based `vmap2`; the current generated API pages define both mapping contracts. Use `vmap` when specific State instances must be declared with `in_states` and `out_states`. Use `vmap2` when State filters, automatic output-axis inference, or `unexpected_out_state_mapping` are required. Do not silently substitute one contract for the other.
|
|
16
13
|
|
|
17
14
|
## Selection map
|
|
18
15
|
|
|
@@ -22,6 +19,7 @@ substitute one API for the other.
|
|
|
22
19
|
| Place the mapped output axis | `out_axes` | Match the downstream layout explicitly. |
|
|
23
20
|
| Map with no mapped input argument | `axis_size` | Supply the size because it cannot be inferred. |
|
|
24
21
|
| Use collectives over the mapped axis | `axis_name` | The collective must use the same name. |
|
|
22
|
+
| Map explicitly named State instances | `vmap(..., in_states=..., out_states=...)` | Declare every mapped input State and written output State; undeclared batched writes raise `BatchAxisError`. |
|
|
25
23
|
| 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
24
|
| 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
25
|
| Choose independent or shared random draws | BrainState automatic splitting or one broadcast JAX key | Shared keys intentionally correlate mapped results. |
|
|
@@ -138,11 +136,59 @@ assert model.param.value == 1.0
|
|
|
138
136
|
|
|
139
137
|
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
138
|
|
|
141
|
-
|
|
139
|
+
A shared State remains unbatched and is omitted from the mapped State axis. Keep it read-only during the mapped call. Broadcasting identical values to shape `(batch, ...)` and then mapping axis 0 creates independent copies with batch-scaled storage; it does not share one State. Map a State that each lane may write, but keep an unbatched State shared only when concurrent lanes do not update it.
|
|
142
140
|
|
|
143
|
-
|
|
141
|
+
### Map a complete step inside one time loop
|
|
144
142
|
|
|
145
|
-
|
|
143
|
+
Use `vmap_init_all_states` to allocate one dynamical State lane per independent rollout, map the complete per-step transition with semantic State-role filters, then call that mapped step from one `for_loop`. The mapping owns the condition axis and the loop owns time.
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
from brainstate.util import filter as util_filter
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class Accumulator(brainstate.nn.Module):
|
|
150
|
+
def init_state(self):
|
|
151
|
+
self.total = brainstate.ShortTermState(jnp.asarray(0.0))
|
|
152
|
+
|
|
153
|
+
def update(self, value):
|
|
154
|
+
self.total.value = self.total.value + value
|
|
155
|
+
return self.total.value
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
model = Accumulator()
|
|
159
|
+
inputs = jnp.ones((5, 8)) # [time, independent condition]
|
|
160
|
+
brainstate.nn.vmap_init_all_states(model, axis_size=inputs.shape[1])
|
|
161
|
+
|
|
162
|
+
dynamical_state = util_filter.Any(
|
|
163
|
+
util_filter.OfType(brainstate.HiddenState),
|
|
164
|
+
util_filter.OfType(brainstate.ShortTermState),
|
|
165
|
+
)
|
|
166
|
+
mapped_step = vmap2(
|
|
167
|
+
model.update,
|
|
168
|
+
in_axes=0,
|
|
169
|
+
out_axes=0,
|
|
170
|
+
state_in_axes={0: dynamical_state},
|
|
171
|
+
state_out_axes={0: dynamical_state},
|
|
172
|
+
unexpected_out_state_mapping="raise",
|
|
173
|
+
)
|
|
174
|
+
outputs = brainstate.transform.for_loop(mapped_step, inputs)
|
|
175
|
+
|
|
176
|
+
assert outputs.shape == (5, 8)
|
|
177
|
+
assert jnp.allclose(outputs[-1], 5.0)
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Do not select writable State with `.ndim`, shape, or path coincidences; those properties do not identify State ownership and can map a future parameter accidentally. Every State written by `mapped_step` needs a compatible per-lane axis. In particular, a delay buffer with per-lane history cannot share a mutable scalar write pointer merely because all lanes advance in lockstep; map the complete delay State or choose a delay representation whose writable State follows one axis policy.
|
|
181
|
+
|
|
182
|
+
### Choose the State declaration contract
|
|
183
|
+
|
|
184
|
+
The generated APIs use distinct, non-alias parameter names:
|
|
185
|
+
|
|
186
|
+
| API | State input mapping | State output mapping | Undeclared batched write |
|
|
187
|
+
|---|---|---|---|
|
|
188
|
+
| `brainstate.transform.vmap` | `in_states` by State instance | `out_states` by State instance | Raises `BatchAxisError`. |
|
|
189
|
+
| `brainstate.transform.vmap2` | `state_in_axes` by State filter | `state_out_axes` by State filter | Controlled by `unexpected_out_state_mapping`; default `'auto'` infers and scatters. |
|
|
190
|
+
|
|
191
|
+
Sources: https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.transform.vmap.html and https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.transform.vmap2.html.
|
|
146
192
|
|
|
147
193
|
## Handle state writes outside `state_out_axes`
|
|
148
194
|
|
|
@@ -307,7 +353,11 @@ Do not infer semantics for `vmap_new_states`, `vmap2_new_states`, `map`, `pmap2`
|
|
|
307
353
|
## High-impact checks
|
|
308
354
|
|
|
309
355
|
- Match every non-`None` `in_axes` entry to an actual mapped dimension of the corresponding argument.
|
|
356
|
+
- Use `vmap` for State-instance declarations and `vmap2` for filter-based State-axis policies; do not mix their parameter names.
|
|
357
|
+
- Prefer an owning package's native batch or `size` axis when it already represents the independent conditions.
|
|
310
358
|
- Decide whether mutable State is shared or mapped; use `state_in_axes` and `state_out_axes` together for per-instance State write-back.
|
|
359
|
+
- Map a complete per-step transition inside one `for_loop` when the mapping owns independent conditions and the loop owns time.
|
|
360
|
+
- Select mapped State by semantic role rather than array rank, shape, or leading-size coincidence.
|
|
311
361
|
- Set `axis_size` when all inputs are static.
|
|
312
362
|
- Declare State axes or set an explicit policy when automatic output-axis inference would be ambiguous.
|
|
313
363
|
- Expect automatic independent `RandomState` keys; use the documented broadcast-key pattern only when shared randomness is intentional.
|
|
@@ -13,7 +13,7 @@ The official guide presents `brainstate.nn._collective_ops` through these public
|
|
|
13
13
|
| Fix the execution order of methods | `brainstate.nn.call_order` | Lower order values run first. |
|
|
14
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
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,
|
|
16
|
+
| Reset existing states everywhere | `brainstate.nn.reset_all_states`, `brainstate.nn.vmap_reset_all_states` | Reset at the intended sequence boundary; after vmapped reset, verify that every mapped dynamical State retains its leading lane axis. |
|
|
17
17
|
| Restore values keyed by absolute state paths | `brainstate.nn.assign_state_values` | Inspect both returned mismatch collections. |
|
|
18
18
|
|
|
19
19
|
## Ordering calls with `call_order`
|
|
@@ -84,27 +84,28 @@ brainstate.nn.reset_all_states(rnn)
|
|
|
84
84
|
|
|
85
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
86
|
|
|
87
|
-
## Batched
|
|
87
|
+
## Batched lifecycle operations with `vmap_*`
|
|
88
88
|
|
|
89
89
|
Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
|
|
90
90
|
|
|
91
|
-
|
|
91
|
+
API contract: https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.vmap_reset_all_states.html
|
|
92
92
|
|
|
93
|
-
|
|
94
|
-
policy = brainstate.nn.Sequential(
|
|
95
|
-
brainstate.nn.Linear((4,), (64,)),
|
|
96
|
-
brainstate.nn.GELU(),
|
|
97
|
-
brainstate.nn.Linear((64,), (2,)),
|
|
98
|
-
)
|
|
93
|
+
For independent ensemble or Monte-Carlo instances, `vmap_init_all_states` inserts a leading axis and manages a separate random key for each copy. Pass a `state_to_exclude` filter when selected States, such as statistics buffers, must remain shared; excluded States retain their original shape.
|
|
99
94
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
95
|
+
```python
|
|
96
|
+
rnn = brainstate.nn.ValinaRNNCell(num_in=4, num_out=8)
|
|
97
|
+
axis_size = 8
|
|
98
|
+
brainstate.nn.vmap_init_all_states(rnn, axis_size=axis_size)
|
|
99
|
+
|
|
100
|
+
hidden_shapes = {
|
|
101
|
+
path: state.value.shape
|
|
102
|
+
for path, state in rnn.states(brainstate.HiddenState).items()
|
|
103
|
+
}
|
|
104
|
+
assert hidden_shapes
|
|
105
|
+
assert all(shape[0] == axis_size for shape in hidden_shapes.values())
|
|
105
106
|
```
|
|
106
107
|
|
|
107
|
-
|
|
108
|
+
The official `vmap_reset_all_states` contract intends to reset each lane independently, but the selected Module's `reset_state` implementation must still preserve the mapped State shape. Before selecting it for repeated rollouts, capture a direct-path snapshot, run one reset outside the transformed and timed path, and compare every mapped dynamical shape before and after. If any leading lane axis changes, restore the snapshot and use `assign_state_values` for subsequent exact resets instead of `vmap_reset_all_states`.
|
|
108
109
|
|
|
109
110
|
## Calling arbitrary methods collectively
|
|
110
111
|
|
|
@@ -146,7 +147,7 @@ The page identifies `brainstate.nn.vmap_call_all_fns` as the corresponding opera
|
|
|
146
147
|
|
|
147
148
|
Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
|
|
148
149
|
|
|
149
|
-
`assign_state_values` maps
|
|
150
|
+
`assign_state_values` maps values back to State objects by absolute State path and returns mismatched keys as `(unexpected, missing)`. Keep a dictionary-valued State intact under its State path; do not append its inner keys as if they were separate States.
|
|
150
151
|
|
|
151
152
|
```python
|
|
152
153
|
autoencoder = brainstate.nn.Sequential(
|
|
@@ -156,13 +157,10 @@ autoencoder = brainstate.nn.Sequential(
|
|
|
156
157
|
)
|
|
157
158
|
brainstate.nn.init_all_states(autoencoder)
|
|
158
159
|
|
|
159
|
-
state_snapshot = {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
state_snapshot[path + (key,)] = value
|
|
164
|
-
else:
|
|
165
|
-
state_snapshot[path] = state.value
|
|
160
|
+
state_snapshot = {
|
|
161
|
+
path: state.value
|
|
162
|
+
for path, state in autoencoder.states().items()
|
|
163
|
+
}
|
|
166
164
|
|
|
167
165
|
# ... modify weights or states ...
|
|
168
166
|
|
|
@@ -172,17 +170,17 @@ unexpected, missing = brainstate.nn.assign_state_values(
|
|
|
172
170
|
)
|
|
173
171
|
if unexpected or missing:
|
|
174
172
|
raise ValueError(
|
|
175
|
-
f
|
|
173
|
+
f"checkpoint mismatch: unexpected={unexpected}, missing={missing}"
|
|
176
174
|
)
|
|
177
175
|
```
|
|
178
176
|
|
|
179
|
-
|
|
177
|
+
Capture all States when exact whole-model restoration is required. A deliberately partial snapshot reports every omitted model State in `missing`; handle that result as an explicit partial-restore policy rather than ignoring it.
|
|
180
178
|
|
|
181
179
|
## Putting it all together
|
|
182
180
|
|
|
183
181
|
Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
|
|
184
182
|
|
|
185
|
-
|
|
183
|
+
Use this order for a batched recurrent workflow: construct the model, call `vmap_init_all_states(..., axis_size=...)`, verify mapped dynamical shapes, capture all values under their existing State paths, run the transformed rollout, then either use a shape-verified `vmap_reset_all_states` or restore the exact snapshot with `assign_state_values`. Reject unexpected or missing paths before the next rollout.
|
|
186
184
|
|
|
187
185
|
## Best practices
|
|
188
186
|
|
|
@@ -192,4 +190,5 @@ Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.htm
|
|
|
192
190
|
- Decorate stateful methods with `call_order` when their interaction matters.
|
|
193
191
|
- Use `node_to_exclude` and `state_to_exclude` filters to fine-tune traversal.
|
|
194
192
|
- Inspect both return values from `assign_state_values` to catch mismatched checkpoints.
|
|
195
|
-
-
|
|
193
|
+
- Preserve dictionary-valued State under its existing absolute State path when taking a snapshot.
|
|
194
|
+
- Use vmapped helpers for ensembles while accounting for the added leading axis, and verify that reset preserves that axis for the selected Modules.
|