brainx-skill 1.0.6 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +10 -8
  2. package/adapters/gemini.js +7 -0
  3. package/adapters/opencode.js +7 -0
  4. package/adapters/windsurf.js +7 -0
  5. package/installation/lib/installer.js +4 -1
  6. package/manifest.json +6 -1
  7. package/package.json +8 -2
  8. package/skills/braincell/SKILL.md +182 -0
  9. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  10. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +273 -0
  11. package/skills/braincell/references/channel-library.md +85 -0
  12. package/skills/braincell/references/ion-library.md +87 -0
  13. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  14. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  15. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  16. package/skills/braincell/references/multicompartment/filter-function-library.md +154 -0
  17. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  18. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  19. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  20. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +260 -0
  21. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  22. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  23. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  24. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  25. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  26. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  27. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  28. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  29. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  30. package/skills/brainevent/SKILL.md +268 -0
  31. package/skills/brainevent/references/connectivity-variants.md +312 -0
  32. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  33. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  34. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  35. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  36. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  37. package/skills/brainevent/references/sparse-formats.md +182 -0
  38. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  39. package/skills/brainmass/SKILL.md +290 -0
  40. package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
  41. package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
  42. package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  43. package/skills/brainmass/references/braintools/cogtask.md +190 -0
  44. package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
  45. package/skills/brainmass/references/braintools/metric.md +157 -0
  46. package/skills/brainmass/references/braintools/optimizer.md +187 -0
  47. package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
  48. package/skills/brainmass/references/braintools/surrogate.md +151 -0
  49. package/skills/brainmass/references/coupling-network-api.md +148 -0
  50. package/skills/brainmass/references/datasets-api.md +72 -0
  51. package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
  52. package/skills/brainmass/references/forward-observation-api.md +131 -0
  53. package/skills/brainmass/references/horn-task-training.md +199 -0
  54. package/skills/brainmass/references/modellibrary.md +104 -0
  55. package/skills/brainmass/references/noiseprocesses.md +121 -0
  56. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
  57. package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
  58. package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
  59. package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
  60. package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
  61. package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
  62. package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
  63. package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
  64. package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
  65. package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
  66. package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
  67. package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
  68. package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
  69. package/skills/brainmass/references/visualization-analysis-api.md +130 -0
  70. package/skills/brainpy-state/SKILL.md +232 -0
  71. package/skills/brainpy-state/references/array-creation.md +158 -0
  72. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  73. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  75. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  76. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  77. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  78. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  79. package/skills/brainpy-state/references/component-selection.md +273 -0
  80. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  81. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  82. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  83. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  84. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  85. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  86. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  87. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  88. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  89. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  90. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  91. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  92. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  93. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  94. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  95. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  96. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  97. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  98. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  99. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  100. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  101. package/skills/brainstate/SKILL.md +1 -1
  102. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
  103. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
  104. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
  105. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
  106. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
  107. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
  108. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
  109. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
  110. package/skills/brainstate/references/collective_model_operations.md +9 -9
  111. package/skills/brainstate/references/extension_mechanisms.md +12 -1
  112. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
  113. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
  114. package/skills/brainstate/references/model-interop-and-migration.md +11 -1
  115. package/skills/brainstate/references/size-inference-variations.md +11 -0
  116. package/skills/brainstate/references/state-graph-operations.md +13 -15
  117. package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
  118. package/skills/brainx-general-guard/SKILL.md +68 -0
  119. package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
  120. package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
@@ -1,483 +1,334 @@
1
- # Brainstate control-flow patterns
1
+ # BrainState control-flow patterns
2
2
 
3
- Use this reference when repeated or conditional execution must preserve BrainState
4
- `State` effects and compile to JAX control-flow primitives. It covers only the
5
- control-flow variants routed out of the main skill; use the main skill for the
6
- fundamentals of `State`, `.value`, Modules, and state-aware transformations.
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
- | Need | Primitive | Source-grounded selection rule |
43
- |---|---|---|
44
- | Carry plus per-step outputs | `scan` | Use when a carry must thread through iterations, especially for recurrent patterns or an explicit accumulator. |
45
- | Carry plus per-step outputs over a long differentiable sequence | `checkpointed_scan` | Use when storing all intermediate activations during gradient computation is memory-prohibitive. |
46
- | Per-step outputs without an explicit carry | `for_loop` | Use when no carry is needed, including independent items with State updates. |
47
- | No explicit carry over a long differentiable sequence | `checkpointed_for_loop` | Use when `for_loop` syntax is appropriate but backward-pass activation storage would exhaust memory. |
48
- | Truly unknown iteration count without reverse-mode gradients | `while_loop` | Use for standard while-loop semantics when the number of iterations is unknown and gradients are not being computed. |
49
- | Conditional iteration with an upper bound | `bounded_while_loop` | Use for reverse-mode differentiation, protection against infinite loops, or predictable compilation characteristics. |
50
- | Two branches | `cond` | Select one lazily evaluated branch from a boolean or numeric scalar predicate. |
51
- | Branch selected by integer index | `switch` | Select among multiple callables; the index is clamped to the valid branch range. |
52
- | Multiple predicates or an else branch | `ifelse` | Select among mutually exclusive conditions; make the last condition `True` for a default branch. |
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
- data = jnp.array([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])
116
- _, history = scan(stats_body, init=None, xs=data)
117
- ```
24
+ ## Run fixed-length sequences
118
25
 
119
- Source: [1.1 scan: Stateful Scanning with Carry](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#scan-stateful-scanning-with-carry).
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
- ### `for_loop`
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
- `for_loop` accepts variadic inputs sliced along axis 0 and internally uses
124
- `scan` with `None` as the carry. It stacks the value returned at each iteration
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
- ```text
129
- for_loop(
130
- f: Callable[..., Y],
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 process(self, x):
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 # running average
53
+ return self.total.value / self.count.value
154
54
 
155
55
 
156
- acc = Accumulator()
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
- data = jnp.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
159
- running_averages = for_loop(acc.process, data)
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
- Source: [1.3 for_loop: Simplified Loop Without Carry](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#for-loop-simplified-loop-without-carry).
163
-
164
- ## Checkpointed sequence control flow
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
- The checkpointed variants trade recomputation for backward-pass memory. The
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
- ### `checkpointed_scan`
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
- ```text
175
- checkpointed_scan(
176
- f: Callable[[Carry, X], Tuple[Carry, Y]],
177
- init: Carry,
178
- xs: X,
179
- length: Optional[int] = None,
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
- The implementation uses a hierarchical scheme in which `max_steps = base^k`
186
- for some `k`. Use it for a long recurrent computation whose gradients would
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
- class RecurrentCell(brainstate.nn.Module):
191
- """Simple recurrent cell with hidden state."""
192
-
193
- def __init__(self, hidden_size):
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
- ```python
245
- class ExpMovingAverage(brainstate.nn.Module):
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.alpha = alpha
251
- self.ema = brainstate.ShortTermState(jnp.array(0.0))
252
- self.initialized = brainstate.ShortTermState(jnp.array(False))
253
-
254
- def update(self, x):
255
- # Initialize with first value
256
- self.ema.value = jnp.where(
257
- self.initialized.value,
258
- self.alpha * x + (1 - self.alpha) * self.ema.value,
259
- x
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
- ema = ExpMovingAverage(alpha=0.3)
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
- # Process with checkpointed for_loop
271
- smoothed = checkpointed_for_loop(ema.update, signal, base=10)
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
- Source: [1.4 checkpointed_for_loop: Memory-Efficient For Loop](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#checkpointed-for-loop-memory-efficient-for-loop).
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
- ## Conditional iteration
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
- ### `while_loop`
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
- `while_loop` is the stateful version of `jax.lax.while_loop`:
215
+ ## Run conditional iteration
281
216
 
282
- ```text
283
- while_loop(
284
- cond_fun: Callable[[T], BooleanNumeric],
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
- The condition must be read-only: `cond_fun` cannot modify State. The loop value
291
- must preserve its shape and dtype. `while_loop` is not reverse-mode
292
- differentiable; select `bounded_while_loop` when reverse-mode gradients are
293
- required. State changes belong in `body_fun`, as in this source example:
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
- class IterativeRefiner(brainstate.nn.Module):
297
- """Iteratively refine an estimate using Newton's method."""
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
- def cond_f(x):
315
- # Continue until error is small enough
316
- return jnp.abs(x * x - refiner.target) > 1e-6
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 = while_loop(cond_f, body, init_val=1.0)
248
+ assert result == 5
249
+ assert counter.steps.value == 5
324
250
  ```
325
251
 
326
- Source: [2.1 while_loop: Dynamic Conditional Iteration](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#while-loop-dynamic-conditional-iteration).
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
- ### `bounded_while_loop`
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
- ```text
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
- `max_steps` bounds iteration. For `base`, the tutorial gives the tradeoff as
342
- larger values compiling faster but running slightly slower, and smaller values
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
- The tutorial demonstrates reverse-mode differentiation with this source script:
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
- def smooth_threshold(x, threshold=5.0, lr=0.5, max_steps=20):
350
- """Smoothly approach threshold using gradient descent."""
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.true_count = brainstate.ShortTermState(jnp.array(0))
396
- self.false_count = brainstate.ShortTermState(jnp.array(0))
280
+ self.positive = brainstate.ShortTermState(jnp.array(0))
281
+ self.nonpositive = brainstate.ShortTermState(jnp.array(0))
397
282
 
398
- def true_branch(self, x):
399
- self.true_count.value = self.true_count.value + 1
283
+ def double(self, x):
284
+ self.positive.value = self.positive.value + 1
400
285
  return x * 2
401
286
 
402
- def false_branch(self, x):
403
- self.false_count.value = self.false_count.value + 1
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
- # Test multiple values
410
- values = jnp.array([1.0, -2.0, 3.0, -4.0, 5.0])
411
- results = []
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
- `branches` must contain at least one callable. Negative indices are clamped to
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
- def operation_0(x):
436
- return x + 1
437
-
438
-
439
- def operation_1(x):
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
- Source: [3.2 switch: Multi-Way Branching](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#switch-multi-way-branching).
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
- ### `ifelse`
319
+ ## Common failures
461
320
 
462
- ```text
463
- ifelse(
464
- conditions,
465
- branches,
466
- *operands,
467
- check_cond: bool = True
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
- `conditions` should be mutually exclusive, `branches` must have the same length,
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
- Source: [3.3 ifelse: Multi-Condition If/Elif/Else](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#ifelse-multi-condition-if-elif-else).
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.