brainx-skill 1.0.3 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +29 -64
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/{lib → installation/lib}/installer.js +8 -5
- package/manifest.json +7 -1
- package/package.json +25 -10
- package/skills/braincell/SKILL.md +182 -0
- package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
- package/skills/braincell/references/channel-library.md +170 -0
- package/skills/braincell/references/ion-library.md +154 -0
- package/skills/braincell/references/mixions-for-adaptation.md +81 -0
- package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
- package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
- package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
- package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
- package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
- package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
- package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
- package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
- package/skills/braincell/references/scripts/channel_ablation.py +61 -0
- package/skills/braincell/references/scripts/fi_curve.py +68 -0
- package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
- package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
- package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
- package/skills/braincell/references/solver-library-with-effects.md +188 -0
- package/skills/brainevent/SKILL.md +268 -0
- package/skills/brainevent/references/connectivity-variants.md +312 -0
- package/skills/brainevent/references/custom-operators-cpu.md +304 -0
- package/skills/brainevent/references/custom-operators-gpu.md +468 -0
- package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
- package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
- package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
- package/skills/brainevent/references/sparse-formats.md +182 -0
- package/skills/brainevent/references/synaptic-plasticity.md +285 -0
- package/skills/brainpy-state/SKILL.md +232 -0
- package/skills/brainpy-state/references/array-creation.md +158 -0
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
- package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
- package/skills/brainpy-state/references/braintools/metric.md +152 -0
- package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
- package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
- package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
- package/skills/brainpy-state/references/component-selection.md +273 -0
- package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
- package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
- package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
- package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
- package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
- package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
- package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
- package/skills/brainpy-state/references/projection-patterns.md +125 -0
- package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
- package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
- package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
- package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
- package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
- package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
- package/skills/brainstate/SKILL.md +399 -0
- package/skills/brainstate/agents/openai.yaml +4 -0
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +293 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
- package/skills/brainstate/references/model-interop-and-migration.md +305 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +279 -0
- package/skills/brainstate/references/state-graph-operations.md +216 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
- package/skills/brainstate/scripts/integrator_rnn.py +359 -0
- package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
- package/skills/brainstate/scripts/modern_cnn.py +73 -0
- package/skills/brainstate/scripts/resnet.py +130 -0
- package/skills/brainunit/SKILL.md +287 -0
- package/skills/brainunit/references/array-creation.md +158 -0
- package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
- package/skills/brainunit/references/array-mechanics.md +165 -0
- package/skills/brainunit/references/math-function-library.md +433 -0
- package/skills/brainunit/references/physical-constant-library.md +58 -0
- package/skills/brainunit/references/prefix-library.md +116 -0
- package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
- package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
- package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
- package/skills/brainx-general-guard/SKILL.md +153 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
- package/skills/brainx-install/SKILL.md +2 -2
- package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
- /package/{bin → installation/bin}/brainx.js +0 -0
- /package/{lib → installation/lib}/adapter-transaction.js +0 -0
- /package/{lib → installation/lib}/bundle.js +0 -0
- /package/{lib → installation/lib}/cli.js +0 -0
- /package/{lib → installation/lib}/constants.js +0 -0
- /package/{lib → installation/lib}/hash.js +0 -0
- /package/{lib → installation/lib}/paths.js +0 -0
- /package/{lib → installation/lib}/prompts.js +0 -0
- /package/{lib → installation/lib}/receipt.js +0 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
# BrainState control-flow patterns
|
|
2
|
+
|
|
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.
|
|
7
|
+
|
|
8
|
+
## Choose the primitive
|
|
9
|
+
|
|
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. |
|
|
21
|
+
|
|
22
|
+
Source: [Control flow](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html).
|
|
23
|
+
|
|
24
|
+
## Run fixed-length sequences
|
|
25
|
+
|
|
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.
|
|
28
|
+
|
|
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. |
|
|
35
|
+
|
|
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`:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import jax.numpy as jnp
|
|
41
|
+
import brainstate
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Accumulator(brainstate.nn.Module):
|
|
45
|
+
def __init__(self):
|
|
46
|
+
super().__init__()
|
|
47
|
+
self.total = brainstate.ShortTermState(jnp.array(0.0))
|
|
48
|
+
self.count = brainstate.ShortTermState(jnp.array(0))
|
|
49
|
+
|
|
50
|
+
def update(self, x):
|
|
51
|
+
self.total.value = self.total.value + x
|
|
52
|
+
self.count.value = self.count.value + 1
|
|
53
|
+
return self.total.value / self.count.value
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
accumulator = Accumulator()
|
|
57
|
+
averages = brainstate.transform.for_loop(
|
|
58
|
+
accumulator.update,
|
|
59
|
+
jnp.array([1.0, 2.0, 3.0, 4.0]),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
assert jnp.allclose(averages, jnp.array([1.0, 1.5, 2.0, 2.5]))
|
|
63
|
+
assert accumulator.count.value == 4
|
|
64
|
+
```
|
|
65
|
+
|
|
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.
|
|
70
|
+
|
|
71
|
+
## Checkpoint long training rollouts
|
|
72
|
+
|
|
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.
|
|
76
|
+
|
|
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. |
|
|
83
|
+
|
|
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:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import brainpy
|
|
89
|
+
import brainstate
|
|
90
|
+
import braintools
|
|
91
|
+
import brainunit as u
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class SNN(brainstate.nn.Module):
|
|
95
|
+
def __init__(self, n_in, n_rec, n_out):
|
|
96
|
+
super().__init__()
|
|
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),
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
def update(self, spikes):
|
|
130
|
+
spikes = self.recurrent(self.input(spikes))
|
|
131
|
+
return self.output(self.readout(spikes))
|
|
132
|
+
|
|
133
|
+
|
|
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()
|
|
201
|
+
```
|
|
202
|
+
|
|
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.
|
|
207
|
+
|
|
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.
|
|
212
|
+
|
|
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).
|
|
214
|
+
|
|
215
|
+
## Run conditional iteration
|
|
216
|
+
|
|
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.
|
|
220
|
+
|
|
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. |
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
import jax.numpy as jnp
|
|
228
|
+
import brainstate
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class Counter(brainstate.nn.Module):
|
|
232
|
+
def __init__(self):
|
|
233
|
+
super().__init__()
|
|
234
|
+
self.steps = brainstate.ShortTermState(jnp.array(0))
|
|
235
|
+
|
|
236
|
+
def increment(self, value):
|
|
237
|
+
self.steps.value = self.steps.value + 1
|
|
238
|
+
return value + 1
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
counter = Counter()
|
|
242
|
+
result = brainstate.transform.while_loop(
|
|
243
|
+
lambda value: value < 5,
|
|
244
|
+
counter.increment,
|
|
245
|
+
jnp.array(0),
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
assert result == 5
|
|
249
|
+
assert counter.steps.value == 5
|
|
250
|
+
```
|
|
251
|
+
|
|
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`.
|
|
256
|
+
|
|
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.
|
|
260
|
+
|
|
261
|
+
## Select conditional branches
|
|
262
|
+
|
|
263
|
+
Branch transforms execute only the selected callable while tracking its State
|
|
264
|
+
reads and writes.
|
|
265
|
+
|
|
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. |
|
|
271
|
+
|
|
272
|
+
```python
|
|
273
|
+
import jax.numpy as jnp
|
|
274
|
+
import brainstate
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class BranchTracker(brainstate.nn.Module):
|
|
278
|
+
def __init__(self):
|
|
279
|
+
super().__init__()
|
|
280
|
+
self.positive = brainstate.ShortTermState(jnp.array(0))
|
|
281
|
+
self.nonpositive = brainstate.ShortTermState(jnp.array(0))
|
|
282
|
+
|
|
283
|
+
def double(self, x):
|
|
284
|
+
self.positive.value = self.positive.value + 1
|
|
285
|
+
return x * 2
|
|
286
|
+
|
|
287
|
+
def halve(self, x):
|
|
288
|
+
self.nonpositive.value = self.nonpositive.value + 1
|
|
289
|
+
return x / 2
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
tracker = BranchTracker()
|
|
293
|
+
result = brainstate.transform.cond(
|
|
294
|
+
jnp.array(3.0) > 0,
|
|
295
|
+
tracker.double,
|
|
296
|
+
tracker.halve,
|
|
297
|
+
jnp.array(3.0),
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
assert result == 6
|
|
301
|
+
assert tracker.positive.value == 1
|
|
302
|
+
assert tracker.nonpositive.value == 0
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
For `ifelse`, use a final `True` predicate to encode the default branch:
|
|
306
|
+
|
|
307
|
+
```python
|
|
308
|
+
result = brainstate.transform.ifelse(
|
|
309
|
+
[x > 10, x > 5, True],
|
|
310
|
+
[large_fn, medium_fn, small_fn],
|
|
311
|
+
x,
|
|
312
|
+
)
|
|
313
|
+
```
|
|
314
|
+
|
|
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.
|
|
318
|
+
|
|
319
|
+
## Common failures
|
|
320
|
+
|
|
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.
|
|
330
|
+
|
|
331
|
+
## Sources
|
|
332
|
+
|
|
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.
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# BrainState transformed diagnostics
|
|
2
|
+
|
|
3
|
+
Use this reference after `skills/brainstate/SKILL.md` when runtime values, State
|
|
4
|
+
updates, or failures must be inspected from transformed BrainState code. The
|
|
5
|
+
skill owns the core transformation model; this reference only adds diagnostics
|
|
6
|
+
that execute after tracing or turn value-dependent failures into data or
|
|
7
|
+
runtime exceptions.
|
|
8
|
+
|
|
9
|
+
## Choose the diagnostic outcome
|
|
10
|
+
|
|
11
|
+
Inside a compiled `jit` function, ordinary Python `assert` and `if` statements that depend on array values do not work because those values are abstract tracers at trace time. A plain `print(x)` also runs only at trace time and shows a tracer rather than the runtime value. Select the tool by what the caller needs:
|
|
12
|
+
|
|
13
|
+
| Need | Tool |
|
|
14
|
+
|---|---|
|
|
15
|
+
| Return failures for inspection | `brainstate.transform.checkify` with `check` |
|
|
16
|
+
| Raise on a bad runtime condition | `brainstate.transform.jit_error_if` |
|
|
17
|
+
| Find the primitive that first produces NaN or Inf | `brainstate.transform.debug_nan` or `debug_nan_if` |
|
|
18
|
+
| Print concrete runtime values | `jax.debug.print` |
|
|
19
|
+
| Send runtime values to Python for richer inspection | `jax.debug.callback` |
|
|
20
|
+
| Pause only when a runtime predicate is true | `brainstate.transform.breakpoint_if` |
|
|
21
|
+
|
|
22
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
23
|
+
|
|
24
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|
|
25
|
+
|
|
26
|
+
## Return inspectable errors with `checkify`
|
|
27
|
+
|
|
28
|
+
`checkify` transforms a function so that it returns an `(error, result)` pair instead of raising. The error object is inert until inspected: `error.get()` returns `None` if every check passed or the failure message otherwise. Bundle an explicit value condition with its checked function:
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
import jax.numpy as jnp
|
|
32
|
+
import brainstate.transform as T
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def safe_log(x):
|
|
36
|
+
T.check(jnp.all(x > 0), 'x must be positive, got {}', x)
|
|
37
|
+
return jnp.log(x)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
checked = T.checkify(safe_log, errors=T.user_checks)
|
|
41
|
+
|
|
42
|
+
err, out = checked(jnp.array([1.0, 2.0]))
|
|
43
|
+
print(err.get()) # None
|
|
44
|
+
|
|
45
|
+
err, out = checked(jnp.array([-1.0, 2.0]))
|
|
46
|
+
print(err.get()) # x must be positive ...
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Call `T.check_error(err)` at an outer boundary to turn a captured error back into an exception; it raises when the error is set and otherwise does nothing.
|
|
50
|
+
|
|
51
|
+
For failures that do not need an explicit `T.check(...)`, choose a predefined `errors` set:
|
|
52
|
+
|
|
53
|
+
| Set | Detects |
|
|
54
|
+
|---|---|
|
|
55
|
+
| `T.user_checks` | Explicit `check(...)` assertions |
|
|
56
|
+
| `T.nan_checks` | NaN values produced by any primitive |
|
|
57
|
+
| `T.float_checks` | NaN and Inf from floating-point operations |
|
|
58
|
+
| `T.div_checks` | Division by zero |
|
|
59
|
+
| `T.index_checks` | Out-of-bounds array indexing |
|
|
60
|
+
| `T.all_checks` | Every category above |
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
nan_checked = T.checkify(lambda x: jnp.log(x), errors=T.nan_checks)
|
|
64
|
+
err, _ = nan_checked(jnp.array([-1.0]))
|
|
65
|
+
print(err.get())
|
|
66
|
+
|
|
67
|
+
index_checked = T.checkify(lambda arr, i: arr[i], errors=T.index_checks)
|
|
68
|
+
err, _ = index_checked(jnp.arange(3), 10)
|
|
69
|
+
print(err.get())
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
73
|
+
|
|
74
|
+
## Raise from a compiled step with `jit_error_if`
|
|
75
|
+
|
|
76
|
+
Use `jit_error_if(pred, msg)` when a bad runtime condition should fail loudly rather than be threaded outward as an error object. It raises when `pred` is true inside `brainstate.transform.jit`, making it the documented guard for a training or simulation step precondition.
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
import brainstate
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@brainstate.transform.jit
|
|
83
|
+
def reciprocal(x):
|
|
84
|
+
T.jit_error_if(
|
|
85
|
+
jnp.any(x == 0.0),
|
|
86
|
+
'reciprocal received a zero entry',
|
|
87
|
+
)
|
|
88
|
+
return 1.0 / x
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
If any entry is zero at runtime, the call raises with the supplied message instead of returning `inf`. The tutorial states that the check compiles to a cheap conditional and is safe to leave in production steps.
|
|
92
|
+
|
|
93
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
94
|
+
|
|
95
|
+
## Locate the first nan or inf with `debug_nan`
|
|
96
|
+
|
|
97
|
+
`debug_nan(fn, *args)` runs `fn` with NaN/Inf detection enabled and raises as soon as a non-finite value appears, naming the offending primitive. Keep the tested computation and the detector together:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
def unstable(x):
|
|
101
|
+
y = x * 1e20
|
|
102
|
+
return jnp.exp(y)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
T.debug_nan(unstable, jnp.array([10.0]))
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Use `T.debug_nan_if(has_nan, fn, *args)` when an upstream flag already suspects trouble and the somewhat costly detection should run only conditionally.
|
|
109
|
+
|
|
110
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
111
|
+
|
|
112
|
+
## Inspect runtime values and `State` mutations
|
|
113
|
+
|
|
114
|
+
`jax.debug.print` defers printing until runtime, so each execution prints concrete values rather than trace-time tracers. It can observe real `State` values on both sides of a mutation:
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
import jax
|
|
118
|
+
import brainstate
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class Accumulator(brainstate.nn.Module):
|
|
122
|
+
def __init__(self, size):
|
|
123
|
+
super().__init__()
|
|
124
|
+
self.total = brainstate.ShortTermState(jnp.zeros(size))
|
|
125
|
+
|
|
126
|
+
def __call__(self, x):
|
|
127
|
+
jax.debug.print('before: {s}', s=self.total.value)
|
|
128
|
+
self.total.value = self.total.value + x
|
|
129
|
+
jax.debug.print('after : {s}', s=self.total.value)
|
|
130
|
+
return self.total.value
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
acc = Accumulator(3)
|
|
134
|
+
step = brainstate.transform.jit(acc)
|
|
135
|
+
_ = step(jnp.array([1.0, 2.0, 3.0]))
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The same runtime print is documented inside `grad` and `vmap`: in a loss function it fires during the forward pass, and under `vmap` it runs once per batch element. Use `{name}` placeholders with keyword arguments as shown above.
|
|
139
|
+
|
|
140
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|
|
141
|
+
|
|
142
|
+
## Send runtime values to a python callback
|
|
143
|
+
|
|
144
|
+
`jax.debug.callback` passes runtime values to an arbitrary Python function for inspection such as shapes and summary statistics. The callback must not return a value used by the computation.
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
def summarize(name, value):
|
|
148
|
+
print(
|
|
149
|
+
f'[{name}] shape={value.shape} '
|
|
150
|
+
f'min={float(jnp.min(value)):.3f} '
|
|
151
|
+
f'max={float(jnp.max(value)):.3f} '
|
|
152
|
+
f'mean={float(jnp.mean(value)):.3f}'
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@brainstate.transform.jit
|
|
157
|
+
def forward(x):
|
|
158
|
+
jax.debug.callback(summarize, 'activations', x)
|
|
159
|
+
return jnp.tanh(x)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|
|
163
|
+
|
|
164
|
+
## Pause only on a bad runtime condition
|
|
165
|
+
|
|
166
|
+
`breakpoint_if(pred)` enters JAX's interactive debugger only when `pred` is true at runtime. Use it to halt on a rare condition without stopping every iteration:
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
@brainstate.transform.jit
|
|
170
|
+
def guarded(x):
|
|
171
|
+
T.breakpoint_if(jnp.any(~jnp.isfinite(x)))
|
|
172
|
+
return x * 2.0
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|
|
176
|
+
|
|
177
|
+
## Official sources
|
|
178
|
+
|
|
179
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
180
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|