brainx-skill 1.0.3 → 1.0.6
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 +21 -63
- package/{lib → installation/lib}/installer.js +4 -4
- package/manifest.json +3 -1
- package/package.json +19 -9
- 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 +483 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +176 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +199 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +166 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +210 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +450 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +157 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +286 -0
- package/skills/brainstate/references/braintools-optimizer-reference.md +133 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +282 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +217 -0
- package/skills/brainstate/references/libraries/solver-library-with-effects.md +85 -0
- package/skills/brainstate/references/model-interop-and-migration.md +295 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +268 -0
- package/skills/brainstate/references/state-graph-operations.md +218 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +224 -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-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,483 @@
|
|
|
1
|
+
# Brainstate control-flow patterns
|
|
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).
|
|
39
|
+
|
|
40
|
+
## Choose the primitive
|
|
41
|
+
|
|
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
|
|
113
|
+
|
|
114
|
+
|
|
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
|
+
```
|
|
118
|
+
|
|
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).
|
|
120
|
+
|
|
121
|
+
### `for_loop`
|
|
122
|
+
|
|
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)`.
|
|
127
|
+
|
|
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
|
+
```
|
|
138
|
+
|
|
139
|
+
Use State for iteration-to-iteration effects when no explicit carry is needed:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
class Accumulator(brainstate.nn.Module):
|
|
143
|
+
"""Simple accumulator that tracks total and count."""
|
|
144
|
+
|
|
145
|
+
def __init__(self):
|
|
146
|
+
super().__init__()
|
|
147
|
+
self.total = brainstate.ShortTermState(jnp.array(0.0))
|
|
148
|
+
self.count = brainstate.ShortTermState(jnp.array(0))
|
|
149
|
+
|
|
150
|
+
def process(self, x):
|
|
151
|
+
self.total.value = self.total.value + x
|
|
152
|
+
self.count.value = self.count.value + 1
|
|
153
|
+
return self.total.value / self.count.value # running average
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
acc = Accumulator()
|
|
157
|
+
|
|
158
|
+
data = jnp.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
|
|
159
|
+
running_averages = for_loop(acc.process, data)
|
|
160
|
+
```
|
|
161
|
+
|
|
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
|
|
165
|
+
|
|
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.
|
|
171
|
+
|
|
172
|
+
### `checkpointed_scan`
|
|
173
|
+
|
|
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
|
+
```
|
|
184
|
+
|
|
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:
|
|
188
|
+
|
|
189
|
+
```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
|
+
```
|
|
240
|
+
|
|
241
|
+
This variant combines `for_loop`'s no-carry interface with checkpointing during
|
|
242
|
+
gradient computation:
|
|
243
|
+
|
|
244
|
+
```python
|
|
245
|
+
class ExpMovingAverage(brainstate.nn.Module):
|
|
246
|
+
"""Exponential moving average."""
|
|
247
|
+
|
|
248
|
+
def __init__(self, alpha=0.1):
|
|
249
|
+
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
|
|
260
|
+
)
|
|
261
|
+
self.initialized.value = True
|
|
262
|
+
return self.ema.value
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
ema = ExpMovingAverage(alpha=0.3)
|
|
266
|
+
|
|
267
|
+
# Generate noisy signal
|
|
268
|
+
signal = jnp.sin(jnp.linspace(0, 4 * jnp.pi, 200)) + 0.2 * brainstate.random.normal(size=(200,))
|
|
269
|
+
|
|
270
|
+
# Process with checkpointed for_loop
|
|
271
|
+
smoothed = checkpointed_for_loop(ema.update, signal, base=10)
|
|
272
|
+
```
|
|
273
|
+
|
|
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).
|
|
275
|
+
|
|
276
|
+
## Conditional iteration
|
|
277
|
+
|
|
278
|
+
### `while_loop`
|
|
279
|
+
|
|
280
|
+
`while_loop` is the stateful version of `jax.lax.while_loop`:
|
|
281
|
+
|
|
282
|
+
```text
|
|
283
|
+
while_loop(
|
|
284
|
+
cond_fun: Callable[[T], BooleanNumeric],
|
|
285
|
+
body_fun: Callable[[T], T],
|
|
286
|
+
init_val: T
|
|
287
|
+
) -> T
|
|
288
|
+
```
|
|
289
|
+
|
|
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:
|
|
294
|
+
|
|
295
|
+
```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)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def cond_f(x):
|
|
315
|
+
# Continue until error is small enough
|
|
316
|
+
return jnp.abs(x * x - refiner.target) > 1e-6
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def body(x):
|
|
320
|
+
return refiner.refine(x)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
result = while_loop(cond_f, body, init_val=1.0)
|
|
324
|
+
```
|
|
325
|
+
|
|
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).
|
|
327
|
+
|
|
328
|
+
### `bounded_while_loop`
|
|
329
|
+
|
|
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
|
+
```
|
|
340
|
+
|
|
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))`.
|
|
345
|
+
|
|
346
|
+
The tutorial demonstrates reverse-mode differentiation with this source script:
|
|
347
|
+
|
|
348
|
+
```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
|
+
```
|
|
385
|
+
|
|
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
|
+
|
|
389
|
+
```python
|
|
390
|
+
class BranchTracker(brainstate.nn.Module):
|
|
391
|
+
"""Track which branches were taken."""
|
|
392
|
+
|
|
393
|
+
def __init__(self):
|
|
394
|
+
super().__init__()
|
|
395
|
+
self.true_count = brainstate.ShortTermState(jnp.array(0))
|
|
396
|
+
self.false_count = brainstate.ShortTermState(jnp.array(0))
|
|
397
|
+
|
|
398
|
+
def true_branch(self, x):
|
|
399
|
+
self.true_count.value = self.true_count.value + 1
|
|
400
|
+
return x * 2
|
|
401
|
+
|
|
402
|
+
def false_branch(self, x):
|
|
403
|
+
self.false_count.value = self.false_count.value + 1
|
|
404
|
+
return x / 2
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
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
|
|
427
|
+
)
|
|
428
|
+
```
|
|
429
|
+
|
|
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`.
|
|
433
|
+
|
|
434
|
+
```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)
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
Source: [3.2 switch: Multi-Way Branching](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html#switch-multi-way-branching).
|
|
459
|
+
|
|
460
|
+
### `ifelse`
|
|
461
|
+
|
|
462
|
+
```text
|
|
463
|
+
ifelse(
|
|
464
|
+
conditions,
|
|
465
|
+
branches,
|
|
466
|
+
*operands,
|
|
467
|
+
check_cond: bool = True
|
|
468
|
+
)
|
|
469
|
+
```
|
|
470
|
+
|
|
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
|
+
```
|
|
482
|
+
|
|
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).
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# Brainstate transformed diagnostics
|
|
2
|
+
|
|
3
|
+
Open this first-layer reference after `skills/brainstate/SKILL.md` when runtime values, state updates, or failures must be inspected from transformed BrainState code. The skill owns the core transformation model; this reference only adds diagnostics that execute after tracing or turn value-dependent failures into data or runtime exceptions.
|
|
4
|
+
|
|
5
|
+
## Choose the diagnostic outcome
|
|
6
|
+
|
|
7
|
+
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:
|
|
8
|
+
|
|
9
|
+
| Need | Tool |
|
|
10
|
+
|---|---|
|
|
11
|
+
| Return failures for inspection | `brainstate.transform.checkify` with `check` |
|
|
12
|
+
| Raise on a bad runtime condition | `brainstate.transform.jit_error_if` |
|
|
13
|
+
| Find the primitive that first produces NaN or Inf | `brainstate.transform.debug_nan` or `debug_nan_if` |
|
|
14
|
+
| Print concrete runtime values | `jax.debug.print` |
|
|
15
|
+
| Send runtime values to Python for richer inspection | `jax.debug.callback` |
|
|
16
|
+
| Pause only when a runtime predicate is true | `brainstate.transform.breakpoint_if` |
|
|
17
|
+
|
|
18
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
19
|
+
|
|
20
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|
|
21
|
+
|
|
22
|
+
## Return inspectable errors with `checkify`
|
|
23
|
+
|
|
24
|
+
`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:
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import jax.numpy as jnp
|
|
28
|
+
import brainstate.transform as T
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def safe_log(x):
|
|
32
|
+
T.check(jnp.all(x > 0), 'x must be positive, got {}', x)
|
|
33
|
+
return jnp.log(x)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
checked = T.checkify(safe_log, errors=T.user_checks)
|
|
37
|
+
|
|
38
|
+
err, out = checked(jnp.array([1.0, 2.0]))
|
|
39
|
+
print(err.get()) # None
|
|
40
|
+
|
|
41
|
+
err, out = checked(jnp.array([-1.0, 2.0]))
|
|
42
|
+
print(err.get()) # x must be positive ...
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
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.
|
|
46
|
+
|
|
47
|
+
For failures that do not need an explicit `T.check(...)`, choose a predefined `errors` set:
|
|
48
|
+
|
|
49
|
+
| Set | Detects |
|
|
50
|
+
|---|---|
|
|
51
|
+
| `T.user_checks` | Explicit `check(...)` assertions |
|
|
52
|
+
| `T.nan_checks` | NaN values produced by any primitive |
|
|
53
|
+
| `T.float_checks` | NaN and Inf from floating-point operations |
|
|
54
|
+
| `T.div_checks` | Division by zero |
|
|
55
|
+
| `T.index_checks` | Out-of-bounds array indexing |
|
|
56
|
+
| `T.all_checks` | Every category above |
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
nan_checked = T.checkify(lambda x: jnp.log(x), errors=T.nan_checks)
|
|
60
|
+
err, _ = nan_checked(jnp.array([-1.0]))
|
|
61
|
+
print(err.get())
|
|
62
|
+
|
|
63
|
+
index_checked = T.checkify(lambda arr, i: arr[i], errors=T.index_checks)
|
|
64
|
+
err, _ = index_checked(jnp.arange(3), 10)
|
|
65
|
+
print(err.get())
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
69
|
+
|
|
70
|
+
## Raise from a compiled step with `jit_error_if`
|
|
71
|
+
|
|
72
|
+
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.
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import brainstate
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@brainstate.transform.jit
|
|
79
|
+
def reciprocal(x):
|
|
80
|
+
T.jit_error_if(
|
|
81
|
+
jnp.any(x == 0.0),
|
|
82
|
+
'reciprocal received a zero entry',
|
|
83
|
+
)
|
|
84
|
+
return 1.0 / x
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
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.
|
|
88
|
+
|
|
89
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
90
|
+
|
|
91
|
+
## Locate the first nan or inf with `debug_nan`
|
|
92
|
+
|
|
93
|
+
`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:
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
def unstable(x):
|
|
97
|
+
y = x * 1e20
|
|
98
|
+
return jnp.exp(y)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
T.debug_nan(unstable, jnp.array([10.0]))
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
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.
|
|
105
|
+
|
|
106
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
107
|
+
|
|
108
|
+
## Inspect runtime values and `State` mutations
|
|
109
|
+
|
|
110
|
+
`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:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
import jax
|
|
114
|
+
import brainstate
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class Accumulator(brainstate.nn.Module):
|
|
118
|
+
def __init__(self, size):
|
|
119
|
+
super().__init__()
|
|
120
|
+
self.total = brainstate.ShortTermState(jnp.zeros(size))
|
|
121
|
+
|
|
122
|
+
def __call__(self, x):
|
|
123
|
+
jax.debug.print('before: {s}', s=self.total.value)
|
|
124
|
+
self.total.value = self.total.value + x
|
|
125
|
+
jax.debug.print('after : {s}', s=self.total.value)
|
|
126
|
+
return self.total.value
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
acc = Accumulator(3)
|
|
130
|
+
step = brainstate.transform.jit(acc)
|
|
131
|
+
_ = step(jnp.array([1.0, 2.0, 3.0]))
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
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.
|
|
135
|
+
|
|
136
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|
|
137
|
+
|
|
138
|
+
## Send runtime values to a python callback
|
|
139
|
+
|
|
140
|
+
`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.
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
def summarize(name, value):
|
|
144
|
+
print(
|
|
145
|
+
f'[{name}] shape={value.shape} '
|
|
146
|
+
f'min={float(jnp.min(value)):.3f} '
|
|
147
|
+
f'max={float(jnp.max(value)):.3f} '
|
|
148
|
+
f'mean={float(jnp.mean(value)):.3f}'
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@brainstate.transform.jit
|
|
153
|
+
def forward(x):
|
|
154
|
+
jax.debug.callback(summarize, 'activations', x)
|
|
155
|
+
return jnp.tanh(x)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|
|
159
|
+
|
|
160
|
+
## Pause only on a bad runtime condition
|
|
161
|
+
|
|
162
|
+
`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:
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
@brainstate.transform.jit
|
|
166
|
+
def guarded(x):
|
|
167
|
+
T.breakpoint_if(jnp.any(~jnp.isfinite(x)))
|
|
168
|
+
return x * 2.0
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|
|
172
|
+
|
|
173
|
+
## Official sources
|
|
174
|
+
|
|
175
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/06_error_handling_and_checks.html
|
|
176
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/07_debugging.html
|