brainx-skill 1.0.6 → 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/README.md +9 -2
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/installation/lib/installer.js +4 -1
- package/manifest.json +5 -1
- package/package.json +7 -2
- 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 +1 -1
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
- package/skills/brainstate/references/collective_model_operations.md +9 -9
- package/skills/brainstate/references/extension_mechanisms.md +12 -1
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
- package/skills/brainstate/references/model-interop-and-migration.md +11 -1
- package/skills/brainstate/references/size-inference-variations.md +11 -0
- package/skills/brainstate/references/state-graph-operations.md +13 -15
- package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
- 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/brainstate/references/braintools-optimizer-reference.md +0 -133
- package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
|
@@ -1,483 +1,334 @@
|
|
|
1
|
-
#
|
|
1
|
+
# BrainState control-flow patterns
|
|
2
2
|
|
|
3
|
-
Use this reference when
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
Official source used throughout: [Control Flow](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html).
|
|
9
|
-
No other source is used in this reference.
|
|
10
|
-
|
|
11
|
-
## Imports
|
|
12
|
-
|
|
13
|
-
The tutorial imports every primitive from `brainstate.transform`:
|
|
14
|
-
|
|
15
|
-
```python
|
|
16
|
-
import jax
|
|
17
|
-
import jax.numpy as jnp
|
|
18
|
-
|
|
19
|
-
import brainstate
|
|
20
|
-
from brainstate.transform import (
|
|
21
|
-
scan,
|
|
22
|
-
checkpointed_scan,
|
|
23
|
-
for_loop,
|
|
24
|
-
checkpointed_for_loop,
|
|
25
|
-
while_loop,
|
|
26
|
-
bounded_while_loop,
|
|
27
|
-
cond,
|
|
28
|
-
switch,
|
|
29
|
-
ifelse,
|
|
30
|
-
)
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
```python
|
|
34
|
-
# Import ProgressBar
|
|
35
|
-
from brainstate.transform import ProgressBar
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
Source: [Imports and Setup](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#imports-and-setup).
|
|
3
|
+
Use this reference when loops or branches must preserve BrainState `State`
|
|
4
|
+
effects under JAX transformations, or when reverse-mode differentiation through
|
|
5
|
+
a long rollout exhausts memory. Use the root skill for `State`, `.value`,
|
|
6
|
+
Modules, gradients, and JIT fundamentals.
|
|
39
7
|
|
|
40
8
|
## Choose the primitive
|
|
41
9
|
|
|
42
|
-
|
|
|
43
|
-
|
|
44
|
-
|
|
|
45
|
-
|
|
|
46
|
-
| Per-step outputs
|
|
47
|
-
|
|
|
48
|
-
|
|
|
49
|
-
|
|
|
50
|
-
|
|
|
51
|
-
|
|
|
52
|
-
|
|
|
53
|
-
|
|
54
|
-
Sources: [scan vs for_loop](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#comparison-scan-vs-for-loop), [while_loop vs bounded_while_loop](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#comparison-while-loop-vs-bounded-while-loop), and [Conditional Control Flow summary](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#id3).
|
|
55
|
-
|
|
56
|
-
## Scans and collected outputs
|
|
57
|
-
|
|
58
|
-
### `scan`
|
|
59
|
-
|
|
60
|
-
`scan` iterates over the leading axis of a sequence, threads a carry through the
|
|
61
|
-
iterations, collects each step's output, and properly handles `State` objects.
|
|
62
|
-
|
|
63
|
-
```text
|
|
64
|
-
scan(
|
|
65
|
-
f: Callable[[Carry, X], Tuple[Carry, Y]],
|
|
66
|
-
init: Carry,
|
|
67
|
-
xs: X,
|
|
68
|
-
length: int | None = None,
|
|
69
|
-
reverse: bool = False,
|
|
70
|
-
unroll: int | bool = 1,
|
|
71
|
-
pbar: ProgressBar | int | None = None,
|
|
72
|
-
) -> Tuple[Carry, Y]
|
|
73
|
-
```
|
|
74
|
-
|
|
75
|
-
- `f` has the form `(carry, x) -> (new_carry, output)`.
|
|
76
|
-
- `length` is inferred from `xs` when omitted.
|
|
77
|
-
- `reverse=True` iterates in reverse order.
|
|
78
|
-
- `unroll=1` disables unrolling; `unroll=True` fully unrolls.
|
|
79
|
-
- `pbar` accepts a `ProgressBar` or an integer update frequency.
|
|
80
|
-
|
|
81
|
-
This source example bundles a stateful update with stacked PyTree outputs. The
|
|
82
|
-
explicit carry is unused, so it remains `None`; the mutable statistics live in
|
|
83
|
-
the Module's `ShortTermState` objects.
|
|
84
|
-
|
|
85
|
-
```python
|
|
86
|
-
class RunningStats(brainstate.nn.Module):
|
|
87
|
-
"""Maintain running mean and variance."""
|
|
88
|
-
|
|
89
|
-
def __init__(self):
|
|
90
|
-
super().__init__()
|
|
91
|
-
self.count = brainstate.ShortTermState(jnp.array(0))
|
|
92
|
-
self.mean = brainstate.ShortTermState(jnp.array(0.0))
|
|
93
|
-
self.m2 = brainstate.ShortTermState(jnp.array(0.0)) # sum of squared differences
|
|
94
|
-
|
|
95
|
-
def update(self, x):
|
|
96
|
-
"""Update statistics with new value using Welford's algorithm."""
|
|
97
|
-
self.count.value = self.count.value + 1
|
|
98
|
-
delta = x - self.mean.value
|
|
99
|
-
self.mean.value = self.mean.value + delta / self.count.value
|
|
100
|
-
delta2 = x - self.mean.value
|
|
101
|
-
self.m2.value = self.m2.value + delta * delta2
|
|
102
|
-
|
|
103
|
-
variance = self.m2.value / self.count.value
|
|
104
|
-
return {'mean': self.mean.value, 'var': variance}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
stats = RunningStats()
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
def stats_body(carry, x):
|
|
111
|
-
result = stats.update(x)
|
|
112
|
-
return carry, result
|
|
10
|
+
| API | Use when |
|
|
11
|
+
|---|---|
|
|
12
|
+
| `scan(...)` | An explicit carry must thread through recurrent steps or accumulation while per-step outputs are collected. |
|
|
13
|
+
| `checkpointed_scan(...)` | Reverse-mode differentiation through a long carried sequence makes activation memory the bottleneck. |
|
|
14
|
+
| `for_loop(...)` | Per-step outputs must be collected while iteration-to-iteration effects live in Module `State` instead of an explicit carry. |
|
|
15
|
+
| `checkpointed_for_loop(...)` | A long State-driven differentiated rollout exhausts memory and the body needs no explicit carry. |
|
|
16
|
+
| `while_loop(...)` | Iteration continues until a runtime condition becomes false and reverse-mode gradients are not required. |
|
|
17
|
+
| `bounded_while_loop(...)` | Conditional iteration needs reverse-mode gradients, an iteration safety bound, or predictable compilation. |
|
|
18
|
+
| `cond(...)` | A scalar predicate selects one of two lazily executed branches. |
|
|
19
|
+
| `switch(...)` | An integer selects one of several callables and out-of-range indices may be clamped. |
|
|
20
|
+
| `ifelse(...)` | Mutually exclusive predicates express `if`/`elif`/`else`, with a final `True` condition as the default branch. |
|
|
113
21
|
|
|
22
|
+
Source: [Control flow](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html).
|
|
114
23
|
|
|
115
|
-
|
|
116
|
-
_, history = scan(stats_body, init=None, xs=data)
|
|
117
|
-
```
|
|
24
|
+
## Run fixed-length sequences
|
|
118
25
|
|
|
119
|
-
|
|
26
|
+
Fixed-length loop transforms slice inputs along axis 0, preserve tracked State
|
|
27
|
+
updates, and stack each step's output along a new leading axis.
|
|
120
28
|
|
|
121
|
-
|
|
29
|
+
| API | Description |
|
|
30
|
+
|---|---|
|
|
31
|
+
| `scan(f, init, xs, length=None, reverse=False, unroll=1, pbar=None)` | Use when `f(carry, x)` must return `(new_carry, output)`; it returns the final carry and stacked outputs. |
|
|
32
|
+
| `for_loop(f, *xs, length=None, reverse=False, unroll=1, pbar=None)` | Use when `f(*x)` needs no explicit carry; it slices every input along axis 0 and returns stacked outputs. |
|
|
33
|
+
| `checkpointed_scan(f, init, xs, length=None, base=16, pbar=None)` | Use the `scan` contract with gradient checkpointing; it returns the same carry and output structure while rematerializing intermediate activations during the backward pass. |
|
|
34
|
+
| `checkpointed_for_loop(f, *xs, length=None, base=16, pbar=None)` | Use the `for_loop` contract with gradient checkpointing; it returns the same stacked output structure while rematerializing intermediate activations during the backward pass. |
|
|
122
35
|
|
|
123
|
-
`
|
|
124
|
-
|
|
125
|
-
along axis 0: scalar steps produce shape `(n,)`, and `(d,)` steps produce
|
|
126
|
-
`(n, d)`.
|
|
36
|
+
Use `scan` when the carry is an ordinary function value. Use `for_loop` when
|
|
37
|
+
iteration-to-iteration effects already live in Module `State`:
|
|
127
38
|
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
*xs,
|
|
132
|
-
length: Optional[int] = None,
|
|
133
|
-
reverse: bool = False,
|
|
134
|
-
unroll: int | bool = 1,
|
|
135
|
-
pbar: Optional[ProgressBar | int] = None
|
|
136
|
-
) -> Y
|
|
137
|
-
```
|
|
39
|
+
```python
|
|
40
|
+
import jax.numpy as jnp
|
|
41
|
+
import brainstate
|
|
138
42
|
|
|
139
|
-
Use State for iteration-to-iteration effects when no explicit carry is needed:
|
|
140
43
|
|
|
141
|
-
```python
|
|
142
44
|
class Accumulator(brainstate.nn.Module):
|
|
143
|
-
"""Simple accumulator that tracks total and count."""
|
|
144
|
-
|
|
145
45
|
def __init__(self):
|
|
146
46
|
super().__init__()
|
|
147
47
|
self.total = brainstate.ShortTermState(jnp.array(0.0))
|
|
148
48
|
self.count = brainstate.ShortTermState(jnp.array(0))
|
|
149
49
|
|
|
150
|
-
def
|
|
50
|
+
def update(self, x):
|
|
151
51
|
self.total.value = self.total.value + x
|
|
152
52
|
self.count.value = self.count.value + 1
|
|
153
|
-
return self.total.value / self.count.value
|
|
53
|
+
return self.total.value / self.count.value
|
|
154
54
|
|
|
155
55
|
|
|
156
|
-
|
|
56
|
+
accumulator = Accumulator()
|
|
57
|
+
averages = brainstate.transform.for_loop(
|
|
58
|
+
accumulator.update,
|
|
59
|
+
jnp.array([1.0, 2.0, 3.0, 4.0]),
|
|
60
|
+
)
|
|
157
61
|
|
|
158
|
-
|
|
159
|
-
|
|
62
|
+
assert jnp.allclose(averages, jnp.array([1.0, 1.5, 2.0, 2.5]))
|
|
63
|
+
assert accumulator.count.value == 4
|
|
160
64
|
```
|
|
161
65
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
66
|
+
**Invariant:** A scalar body result produces shape `(steps,)`; a body result of
|
|
67
|
+
shape `(d,)` produces shape `(steps, d)`. Pass `reverse=True` to traverse inputs
|
|
68
|
+
in reverse, `unroll` to control loop unrolling, and either an update frequency
|
|
69
|
+
or `ProgressBar` through `pbar` when progress reporting is required.
|
|
165
70
|
|
|
166
|
-
|
|
167
|
-
tutorial states that regular `scan` stores `O(n)` intermediate activations,
|
|
168
|
-
whereas `checkpointed_scan` stores `O(log_base(n))` checkpoints and recomputes
|
|
169
|
-
intermediate values during the backward pass. A smaller `base` saves more memory
|
|
170
|
-
but increases recomputation.
|
|
71
|
+
## Checkpoint long training rollouts
|
|
171
72
|
|
|
172
|
-
|
|
73
|
+
Checkpointed loops preserve the forward result but trade backward-pass
|
|
74
|
+
recomputation for lower activation memory, so place the checkpointed loop
|
|
75
|
+
inside the differentiated loss.
|
|
173
76
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
base: int = 16,
|
|
181
|
-
pbar: Optional[ProgressBar | int] = None,
|
|
182
|
-
) -> Tuple[Carry, Y]
|
|
183
|
-
```
|
|
77
|
+
| API | Description |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `checkpointed_for_loop(f, *xs, base=16)` | Use as a drop-in replacement for `for_loop` when a long State-driven BPTT rollout causes out-of-memory failures. |
|
|
80
|
+
| `checkpointed_scan(f, init, xs, base=16)` | Use as a drop-in replacement for `scan` when the differentiated rollout carries an explicit recurrent value. |
|
|
81
|
+
| `brainstate.transform.grad(loss_fn, grad_states, return_value=True)` | Differentiate the loss containing the checkpointed loop; it returns gradients keyed like `grad_states` and the loss from the same pass. |
|
|
82
|
+
| `brainstate.transform.jit(train_step)` | Compile the complete state initialization, differentiated rollout, and parameter update as one training step. |
|
|
184
83
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
otherwise retain every intermediate activation:
|
|
84
|
+
This training pattern keeps the source how-to's ordinary and checkpointed paths
|
|
85
|
+
adjacent so the memory strategy is a construction-time choice:
|
|
188
86
|
|
|
189
87
|
```python
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
super().__init__()
|
|
195
|
-
self.hidden_size = hidden_size
|
|
196
|
-
self.weight = brainstate.ParamState(jax.random.normal(
|
|
197
|
-
jax.random.PRNGKey(0), (hidden_size, hidden_size)
|
|
198
|
-
))
|
|
199
|
-
|
|
200
|
-
def step(self, hidden, x):
|
|
201
|
-
"""Single recurrent step."""
|
|
202
|
-
new_hidden = jnp.tanh(jnp.dot(self.weight.value, hidden) + x)
|
|
203
|
-
return new_hidden
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
# Create a cell and input sequence
|
|
207
|
-
cell = RecurrentCell(hidden_size=32)
|
|
208
|
-
sequence_length = 100
|
|
209
|
-
inputs = jax.random.normal(jax.random.PRNGKey(1), (sequence_length, 32))
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
def rnn_body(hidden, x):
|
|
213
|
-
new_hidden = cell.step(hidden, x)
|
|
214
|
-
return new_hidden, new_hidden
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
# Use checkpointed scan for memory efficiency during gradient computation
|
|
218
|
-
init_hidden = jnp.zeros(32)
|
|
219
|
-
final_hidden, all_hiddens = checkpointed_scan(
|
|
220
|
-
rnn_body,
|
|
221
|
-
init=init_hidden,
|
|
222
|
-
xs=inputs,
|
|
223
|
-
base=8 # Checkpoint every 8 steps
|
|
224
|
-
)
|
|
225
|
-
```
|
|
226
|
-
|
|
227
|
-
Source: [1.2 checkpointed_scan: Memory-Efficient Scanning](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#checkpointed-scan-memory-efficient-scanning).
|
|
228
|
-
|
|
229
|
-
### `checkpointed_for_loop`
|
|
230
|
-
|
|
231
|
-
```text
|
|
232
|
-
checkpointed_for_loop(
|
|
233
|
-
f: Callable[..., Y],
|
|
234
|
-
*xs: X,
|
|
235
|
-
length: Optional[int] = None,
|
|
236
|
-
base: int = 16,
|
|
237
|
-
pbar: Optional[ProgressBar | int] = None,
|
|
238
|
-
) -> Y
|
|
239
|
-
```
|
|
88
|
+
import brainpy
|
|
89
|
+
import brainstate
|
|
90
|
+
import braintools
|
|
91
|
+
import brainunit as u
|
|
240
92
|
|
|
241
|
-
This variant combines `for_loop`'s no-carry interface with checkpointing during
|
|
242
|
-
gradient computation:
|
|
243
93
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
"""Exponential moving average."""
|
|
247
|
-
|
|
248
|
-
def __init__(self, alpha=0.1):
|
|
94
|
+
class SNN(brainstate.nn.Module):
|
|
95
|
+
def __init__(self, n_in, n_rec, n_out):
|
|
249
96
|
super().__init__()
|
|
250
|
-
self.
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
97
|
+
self.input = brainstate.nn.Sequential(
|
|
98
|
+
brainstate.nn.Linear(
|
|
99
|
+
n_in,
|
|
100
|
+
n_rec,
|
|
101
|
+
w_init=braintools.init.KaimingNormal(unit=u.mA),
|
|
102
|
+
b_init=braintools.init.ZeroInit(unit=u.mA),
|
|
103
|
+
),
|
|
104
|
+
brainpy.state.Expon(
|
|
105
|
+
n_rec,
|
|
106
|
+
tau=5.0 * u.ms,
|
|
107
|
+
g_initializer=braintools.init.Constant(0.0 * u.mA),
|
|
108
|
+
),
|
|
109
|
+
)
|
|
110
|
+
self.recurrent = brainpy.state.LIF(
|
|
111
|
+
n_rec,
|
|
112
|
+
tau=20.0 * u.ms,
|
|
113
|
+
V_rest=0.0 * u.mV,
|
|
114
|
+
V_reset=0.0 * u.mV,
|
|
115
|
+
V_th=1.0 * u.mV,
|
|
116
|
+
spk_fun=braintools.surrogate.ReluGrad(),
|
|
117
|
+
)
|
|
118
|
+
self.readout = brainstate.nn.Linear(
|
|
119
|
+
n_rec,
|
|
120
|
+
n_out,
|
|
121
|
+
w_init=braintools.init.KaimingNormal(),
|
|
122
|
+
)
|
|
123
|
+
self.output = brainpy.state.Expon(
|
|
124
|
+
n_out,
|
|
125
|
+
tau=10.0 * u.ms,
|
|
126
|
+
g_initializer=braintools.init.Constant(0.0),
|
|
260
127
|
)
|
|
261
|
-
self.initialized.value = True
|
|
262
|
-
return self.ema.value
|
|
263
|
-
|
|
264
128
|
|
|
265
|
-
|
|
129
|
+
def update(self, spikes):
|
|
130
|
+
spikes = self.recurrent(self.input(spikes))
|
|
131
|
+
return self.output(self.readout(spikes))
|
|
266
132
|
|
|
267
|
-
# Generate noisy signal
|
|
268
|
-
signal = jnp.sin(jnp.linspace(0, 4 * jnp.pi, 200)) + 0.2 * brainstate.random.normal(size=(200,))
|
|
269
133
|
|
|
270
|
-
|
|
271
|
-
|
|
134
|
+
def make_train_step(
|
|
135
|
+
net,
|
|
136
|
+
x_data,
|
|
137
|
+
y_data,
|
|
138
|
+
batch_size,
|
|
139
|
+
*,
|
|
140
|
+
use_checkpoint=True,
|
|
141
|
+
base=16,
|
|
142
|
+
):
|
|
143
|
+
params = net.states(brainstate.ParamState)
|
|
144
|
+
optimizer = braintools.optim.Adam(lr=2e-3)
|
|
145
|
+
optimizer.register_trainable_weights(params)
|
|
146
|
+
|
|
147
|
+
def loss_fn():
|
|
148
|
+
if use_checkpoint:
|
|
149
|
+
predictions = brainstate.transform.checkpointed_for_loop(
|
|
150
|
+
net.update,
|
|
151
|
+
x_data,
|
|
152
|
+
base=base,
|
|
153
|
+
)
|
|
154
|
+
else:
|
|
155
|
+
predictions = brainstate.transform.for_loop(
|
|
156
|
+
net.update,
|
|
157
|
+
x_data,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
logits = u.math.mean(predictions, axis=0)
|
|
161
|
+
return braintools.metric.softmax_cross_entropy_with_integer_labels(
|
|
162
|
+
logits,
|
|
163
|
+
y_data,
|
|
164
|
+
).mean()
|
|
165
|
+
|
|
166
|
+
@brainstate.transform.jit
|
|
167
|
+
def train_step():
|
|
168
|
+
brainstate.nn.init_all_states(net, batch_size=batch_size)
|
|
169
|
+
grads, loss = brainstate.transform.grad(
|
|
170
|
+
loss_fn,
|
|
171
|
+
params,
|
|
172
|
+
return_value=True,
|
|
173
|
+
)()
|
|
174
|
+
optimizer.update(grads)
|
|
175
|
+
return loss
|
|
176
|
+
|
|
177
|
+
return train_step
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
with brainstate.environ.context(dt=1.0 * u.ms):
|
|
181
|
+
n_in, n_rec, n_out = 80, 8, 2
|
|
182
|
+
num_steps, batch_size = 400, 64
|
|
183
|
+
x_data = (
|
|
184
|
+
brainstate.random.rand(num_steps, batch_size, n_in)
|
|
185
|
+
< 5.0 * u.Hz * brainstate.environ.get_dt()
|
|
186
|
+
).astype(float)
|
|
187
|
+
y_data = u.math.asarray(
|
|
188
|
+
brainstate.random.rand(batch_size) < 0.5,
|
|
189
|
+
dtype=int,
|
|
190
|
+
)
|
|
191
|
+
net = SNN(n_in, n_rec, n_out)
|
|
192
|
+
train_step = make_train_step(
|
|
193
|
+
net,
|
|
194
|
+
x_data,
|
|
195
|
+
y_data,
|
|
196
|
+
batch_size=batch_size,
|
|
197
|
+
use_checkpoint=True,
|
|
198
|
+
base=16,
|
|
199
|
+
)
|
|
200
|
+
loss = train_step()
|
|
272
201
|
```
|
|
273
202
|
|
|
274
|
-
|
|
203
|
+
Use plain `for_loop` or `scan` by default. Switch only when reverse-mode
|
|
204
|
+
gradients through a long rollout make activation memory the binding constraint.
|
|
205
|
+
Tune `base` by measuring peak memory and step time: it controls checkpoint
|
|
206
|
+
granularity, so lower memory requires more backward recomputation.
|
|
275
207
|
|
|
276
|
-
|
|
208
|
+
**Invariant:** Initialize recurrent State before each rollout, keep the
|
|
209
|
+
checkpointed loop inside `loss_fn`, differentiate that loss, then JIT the whole
|
|
210
|
+
training step. Checkpointing changes the memory/compute profile, not the
|
|
211
|
+
predictions or loss contract.
|
|
277
212
|
|
|
278
|
-
|
|
213
|
+
Source: [How to train through long rollouts without exhausting memory](https://brainx.chaobrain.com/brainpy-state/brainpy-style/howto/train-long-rollouts-checkpoint.html).
|
|
279
214
|
|
|
280
|
-
|
|
215
|
+
## Run conditional iteration
|
|
281
216
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
body_fun: Callable[[T], T],
|
|
286
|
-
init_val: T
|
|
287
|
-
) -> T
|
|
288
|
-
```
|
|
217
|
+
Conditional loops preserve a fixed loop-value structure; choose the bounded
|
|
218
|
+
form when reverse-mode differentiation or an explicit iteration ceiling
|
|
219
|
+
matters.
|
|
289
220
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
221
|
+
| API | Description |
|
|
222
|
+
|---|---|
|
|
223
|
+
| `while_loop(cond_fun, body_fun, init_val)` | Use for an unknown iteration count without reverse-mode gradients; `cond_fun` must only read State, while State writes belong in `body_fun`. |
|
|
224
|
+
| `bounded_while_loop(cond_fun, body_fun, init_val, *, max_steps, base=16)` | Use when the loop needs reverse-mode differentiation or a hard upper bound; it stops when the condition is false or `max_steps` is reached. |
|
|
294
225
|
|
|
295
226
|
```python
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
def __init__(self, target):
|
|
300
|
-
super().__init__()
|
|
301
|
-
self.target = target
|
|
302
|
-
self.iterations = brainstate.ShortTermState(jnp.array(0))
|
|
303
|
-
|
|
304
|
-
def refine(self, x):
|
|
305
|
-
"""Newton's method step for computing sqrt(target)."""
|
|
306
|
-
self.iterations.value = self.iterations.value + 1
|
|
307
|
-
return 0.5 * (x + self.target / x)
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
# Compute square root of 2 using Newton's method
|
|
311
|
-
refiner = IterativeRefiner(target=2.0)
|
|
227
|
+
import jax.numpy as jnp
|
|
228
|
+
import brainstate
|
|
312
229
|
|
|
313
230
|
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
231
|
+
class Counter(brainstate.nn.Module):
|
|
232
|
+
def __init__(self):
|
|
233
|
+
super().__init__()
|
|
234
|
+
self.steps = brainstate.ShortTermState(jnp.array(0))
|
|
317
235
|
|
|
236
|
+
def increment(self, value):
|
|
237
|
+
self.steps.value = self.steps.value + 1
|
|
238
|
+
return value + 1
|
|
318
239
|
|
|
319
|
-
def body(x):
|
|
320
|
-
return refiner.refine(x)
|
|
321
240
|
|
|
241
|
+
counter = Counter()
|
|
242
|
+
result = brainstate.transform.while_loop(
|
|
243
|
+
lambda value: value < 5,
|
|
244
|
+
counter.increment,
|
|
245
|
+
jnp.array(0),
|
|
246
|
+
)
|
|
322
247
|
|
|
323
|
-
result
|
|
248
|
+
assert result == 5
|
|
249
|
+
assert counter.steps.value == 5
|
|
324
250
|
```
|
|
325
251
|
|
|
326
|
-
|
|
252
|
+
**Invariant:** `cond_fun` must not mutate State, and every body result must keep
|
|
253
|
+
the loop value's PyTree structure, shape, and dtype stable. Do not use
|
|
254
|
+
`while_loop` for reverse-mode gradients; provide `max_steps` and use
|
|
255
|
+
`bounded_while_loop`.
|
|
327
256
|
|
|
328
|
-
|
|
257
|
+
For `bounded_while_loop`, `base` controls its recursive lowering rather than
|
|
258
|
+
gradient-checkpoint spacing. Larger values compile faster but can run slightly
|
|
259
|
+
slower; smaller values compile slower but can run faster.
|
|
329
260
|
|
|
330
|
-
|
|
331
|
-
bounded_while_loop(
|
|
332
|
-
cond_fun: Callable[[T], BooleanNumeric],
|
|
333
|
-
body_fun: Callable[[T], T],
|
|
334
|
-
init_val: T,
|
|
335
|
-
*,
|
|
336
|
-
max_steps: int,
|
|
337
|
-
base: int = 16,
|
|
338
|
-
)
|
|
339
|
-
```
|
|
261
|
+
## Select conditional branches
|
|
340
262
|
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
compiling slower but running faster; compilation scales with
|
|
344
|
-
`math.ceil(math.log(max_steps, base))`.
|
|
263
|
+
Branch transforms execute only the selected callable while tracking its State
|
|
264
|
+
reads and writes.
|
|
345
265
|
|
|
346
|
-
|
|
266
|
+
| API | Description |
|
|
267
|
+
|---|---|
|
|
268
|
+
| `cond(pred, true_fun, false_fun, *operands)` | Use for two branches selected by a boolean or numeric scalar; both branches must return the same PyTree structure. |
|
|
269
|
+
| `switch(index, branches, *operands)` | Use for integer-indexed multi-way branching; it clamps the index to `[0, len(branches) - 1]`. |
|
|
270
|
+
| `ifelse(conditions, branches, *operands, check_cond=True)` | Use for mutually exclusive predicates; with checking enabled, it verifies that exactly one condition is true. |
|
|
347
271
|
|
|
348
272
|
```python
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
def cond_fn(val):
|
|
353
|
-
return val < threshold - 0.1
|
|
354
|
-
|
|
355
|
-
def body(val):
|
|
356
|
-
# Gradient of loss = (val - threshold)^2
|
|
357
|
-
grad = 2 * (val - threshold)
|
|
358
|
-
return val - lr * grad
|
|
359
|
-
|
|
360
|
-
return bounded_while_loop(cond_fn, body, x, max_steps=max_steps)
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
# Compute gradient
|
|
364
|
-
x = 0.0
|
|
365
|
-
value, grad = jax.value_and_grad(smooth_threshold)(x)
|
|
366
|
-
```
|
|
367
|
-
|
|
368
|
-
Source: [2.2 bounded_while_loop: While Loop with Maximum Steps](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#bounded-while-loop-while-loop-with-maximum-steps).
|
|
369
|
-
|
|
370
|
-
## Conditional branches
|
|
371
|
-
|
|
372
|
-
All three branch primitives track State reads and writes. The selected branch is
|
|
373
|
-
executed lazily, so put branch-specific State effects inside its callable.
|
|
374
|
-
|
|
375
|
-
### `cond`
|
|
376
|
-
|
|
377
|
-
```text
|
|
378
|
-
cond(
|
|
379
|
-
pred,
|
|
380
|
-
true_fun: Callable,
|
|
381
|
-
false_fun: Callable,
|
|
382
|
-
*operands
|
|
383
|
-
)
|
|
384
|
-
```
|
|
273
|
+
import jax.numpy as jnp
|
|
274
|
+
import brainstate
|
|
385
275
|
|
|
386
|
-
`pred` is a boolean scalar, or a numeric scalar for which non-zero means `True`.
|
|
387
|
-
Both branches must return the same PyTree structure.
|
|
388
276
|
|
|
389
|
-
```python
|
|
390
277
|
class BranchTracker(brainstate.nn.Module):
|
|
391
|
-
"""Track which branches were taken."""
|
|
392
|
-
|
|
393
278
|
def __init__(self):
|
|
394
279
|
super().__init__()
|
|
395
|
-
self.
|
|
396
|
-
self.
|
|
280
|
+
self.positive = brainstate.ShortTermState(jnp.array(0))
|
|
281
|
+
self.nonpositive = brainstate.ShortTermState(jnp.array(0))
|
|
397
282
|
|
|
398
|
-
def
|
|
399
|
-
self.
|
|
283
|
+
def double(self, x):
|
|
284
|
+
self.positive.value = self.positive.value + 1
|
|
400
285
|
return x * 2
|
|
401
286
|
|
|
402
|
-
def
|
|
403
|
-
self.
|
|
287
|
+
def halve(self, x):
|
|
288
|
+
self.nonpositive.value = self.nonpositive.value + 1
|
|
404
289
|
return x / 2
|
|
405
290
|
|
|
406
291
|
|
|
407
292
|
tracker = BranchTracker()
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
for v in values:
|
|
414
|
-
result = cond(v > 0, tracker.true_branch, tracker.false_branch, v)
|
|
415
|
-
results.append(result)
|
|
416
|
-
```
|
|
417
|
-
|
|
418
|
-
Source: [3.1 cond: Binary Conditional](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#cond-binary-conditional-if-else).
|
|
419
|
-
|
|
420
|
-
### `switch`
|
|
421
|
-
|
|
422
|
-
```text
|
|
423
|
-
switch(
|
|
424
|
-
index,
|
|
425
|
-
branches: Sequence[Callable],
|
|
426
|
-
*operands
|
|
293
|
+
result = brainstate.transform.cond(
|
|
294
|
+
jnp.array(3.0) > 0,
|
|
295
|
+
tracker.double,
|
|
296
|
+
tracker.halve,
|
|
297
|
+
jnp.array(3.0),
|
|
427
298
|
)
|
|
299
|
+
|
|
300
|
+
assert result == 6
|
|
301
|
+
assert tracker.positive.value == 1
|
|
302
|
+
assert tracker.nonpositive.value == 0
|
|
428
303
|
```
|
|
429
304
|
|
|
430
|
-
`
|
|
431
|
-
`0`; indices at or above `len(branches)` are clamped to
|
|
432
|
-
`len(branches) - 1`.
|
|
305
|
+
For `ifelse`, use a final `True` predicate to encode the default branch:
|
|
433
306
|
|
|
434
307
|
```python
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
return x * 2
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
def operation_2(x):
|
|
444
|
-
return x ** 2
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
def operation_3(x):
|
|
448
|
-
return -x
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
operations = [operation_0, operation_1, operation_2, operation_3]
|
|
452
|
-
|
|
453
|
-
x = 5.0
|
|
454
|
-
for i in range(len(operations)):
|
|
455
|
-
result = switch(i, operations, x)
|
|
308
|
+
result = brainstate.transform.ifelse(
|
|
309
|
+
[x > 10, x > 5, True],
|
|
310
|
+
[large_fn, medium_fn, small_fn],
|
|
311
|
+
x,
|
|
312
|
+
)
|
|
456
313
|
```
|
|
457
314
|
|
|
458
|
-
|
|
315
|
+
**Invariant:** Keep branch return PyTrees compatible, and put branch-specific
|
|
316
|
+
State writes inside the branch callable. Do not use Python `if`, `for`, or
|
|
317
|
+
`while` when the decision or iteration count depends on traced JAX values.
|
|
459
318
|
|
|
460
|
-
|
|
319
|
+
## Common failures
|
|
461
320
|
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
321
|
+
- Do not select a checkpointed loop for forward-only execution; its memory
|
|
322
|
+
benefit applies during gradient computation.
|
|
323
|
+
- Do not expect checkpointing to reduce memory without extra backward
|
|
324
|
+
computation.
|
|
325
|
+
- Do not mutate State from a `while_loop` condition.
|
|
326
|
+
- Do not differentiate through `while_loop` with reverse mode; use
|
|
327
|
+
`bounded_while_loop`.
|
|
328
|
+
- Do not return incompatible structures from alternative branches.
|
|
329
|
+
- Do not assume `switch` rejects an invalid index; it clamps the index.
|
|
470
330
|
|
|
471
|
-
|
|
472
|
-
and `check_cond=True` verifies that exactly one condition is true. The official
|
|
473
|
-
default-branch pattern is:
|
|
474
|
-
|
|
475
|
-
```python
|
|
476
|
-
ifelse(
|
|
477
|
-
[x > 10, x > 5, True], # last condition is always True
|
|
478
|
-
[large_fn, medium_fn, small_fn],
|
|
479
|
-
x
|
|
480
|
-
)
|
|
481
|
-
```
|
|
331
|
+
## Sources
|
|
482
332
|
|
|
483
|
-
|
|
333
|
+
- [Control flow](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html) supplies the primitive contracts, selection rules, State behavior, loop-output semantics, checkpoint tradeoff, and branch invariants.
|
|
334
|
+
- [How to train through long rollouts without exhausting memory](https://brainx.chaobrain.com/brainpy-state/brainpy-style/howto/train-long-rollouts-checkpoint.html) supplies the BPTT checkpoint placement, compiled training-step workflow, and `base` tuning application.
|