brainx-skill 1.0.14 → 1.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -1
- package/manifest.json +1 -1
- package/mcp-servers/codex/skills.json +1 -1
- package/package.json +1 -1
- package/skills/bio-neuro-lit/SKILL.md +4 -2
- package/skills/bio-neuro-lit/references/required-supplements.md +27 -0
- package/skills/brainx-acceleration/SKILL.md +30 -437
- package/skills/brainx-acceleration/references/audit-and-rewrite-patterns.md +326 -0
- package/skills/brainx-general-guard/SKILL.md +24 -8
- package/skills/brainx-install/SKILL.md +3 -3
- package/skills/brainx-install/references/compatibility-and-release-matching.md +28 -20
- package/skills/brainx-install/references/uninstall-and-cleanup.md +11 -4
- package/skills/brainx-modeling-loop/SKILL.md +143 -36
- package/skills/brainx-modeling-loop/agents/openai.yaml +2 -2
- package/skills/brainx-modeling-loop/references/mechanism-comparison.md +62 -0
- package/skills/brainx-modeling-loop/references/multiscale-coupling.md +16 -0
- package/skills/brainx-modeling-loop/references/paper-reproduction.md +42 -0
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +14 -14
- package/skills/brainx-modeling-loop/references/run-experiment.md +1 -1
- package/skills/brainx-modeling-loop/references/training-workflow.md +10 -8
- package/skills/brainx-visualization/SKILL.md +6 -2
- package/skills/brainx-visualization/references/neural-data-visualization.md +1 -1
- package/skills/brainx-visualization/references/statistical-and-model-visualization.md +1 -1
- package/skills/package-skills/braincell/SKILL.md +23 -14
- package/skills/package-skills/braincell/references/braintools/input-current.md +1 -1
- package/skills/package-skills/braincell/references/braintools/metric.md +72 -46
- package/skills/package-skills/braincell/references/mixions-for-adaptation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/cv-policy-reference.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/filter-function-library.md +3 -3
- package/skills/package-skills/braincell/references/multicompartment/morphology-io-loading-validation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +31 -43
- package/skills/package-skills/braincell/references/multicompartment/network-workflow.md +49 -0
- package/skills/package-skills/braincell/references/multicompartment/probe-reference.md +26 -114
- package/skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md +40 -28
- package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py +13 -17
- package/skills/package-skills/brainevent/SKILL.md +0 -3
- package/skills/package-skills/brainevent/references/synaptic-plasticity.md +1 -1
- package/skills/package-skills/brainmass/SKILL.md +5 -3
- package/skills/package-skills/brainmass/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainmass/references/braintools/data-preprocessing.md +15 -7
- package/skills/package-skills/brainmass/references/braintools/metric.md +72 -46
- package/skills/package-skills/brainmass/references/coupling-network-api.md +3 -1
- package/skills/package-skills/brainmass/references/fitting-with-objectives-api.md +6 -6
- package/skills/package-skills/brainmass/references/horn-task-training.md +9 -9
- package/skills/package-skills/brainmass/references/modellibrary.md +12 -10
- package/skills/package-skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +5 -3
- package/skills/package-skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +10 -6
- package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +3 -1
- package/skills/package-skills/brainmass/references/visualization-analysis-api.md +17 -9
- package/skills/package-skills/brainspike/SKILL.md +201 -0
- package/skills/package-skills/brainspike/references/braintools/connectivity.md +40 -0
- package/skills/package-skills/brainspike/references/braintools/data-preprocessing.md +39 -0
- package/skills/package-skills/brainspike/references/braintools/input-current.md +55 -0
- package/skills/package-skills/brainspike/references/braintools/metric.md +36 -0
- package/skills/package-skills/brainspike/references/braintools/optimizer.md +50 -0
- package/skills/package-skills/brainspike/references/braintools/parameter-initializer.md +43 -0
- package/skills/package-skills/brainspike/references/braintools/surrogate.md +40 -0
- package/skills/package-skills/brainspike/references/migration-boundary.md +38 -0
- package/skills/package-skills/brainspike/references/model-and-readout-selection.md +41 -0
- package/skills/package-skills/brainspike/references/multirate-coupling.md +31 -0
- package/skills/package-skills/brainspike/references/multiscale-composition.md +28 -0
- package/skills/package-skills/brainspike/references/native-composition.md +52 -0
- package/skills/package-skills/brainspike/references/native-delays.md +34 -0
- package/skills/package-skills/brainspike/references/native-projections.md +43 -0
- package/skills/package-skills/brainspike/references/native-training.md +36 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/devices.md +33 -33
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/divergence-and-parity.md +15 -15
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/integration-categories.md +1 -1
- package/skills/package-skills/brainspike/references/nest-compatible/model-library.md +200 -0
- package/skills/package-skills/brainspike/references/nest-compatible/network-building.md +276 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brette_et_al_2007.py +23 -26
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_alpha.py +18 -21
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_delta.py +16 -19
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +11 -12
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +10 -11
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/spatial_gaussex.py +18 -18
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/synapsecollection.py +26 -29
- package/skills/package-skills/brainspike/references/nest-compatible/synapse-and-connectivity.md +166 -0
- package/skills/package-skills/brainspike/references/nest-delay-boundaries.md +31 -0
- package/skills/package-skills/brainspike/references/nonlinear-state-sharing.md +26 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/perturbation-experiment-validity.md +2 -2
- package/skills/package-skills/brainspike/references/simulator-training.md +61 -0
- package/skills/package-skills/brainspike/references/temporal-task-training.md +36 -0
- package/skills/package-skills/brainspike/scripts/advanced_native_patterns.py +76 -0
- package/skills/package-skills/brainspike/scripts/delay_workflow.py +44 -0
- package/skills/package-skills/brainspike/scripts/delayed_cue_training.py +78 -0
- package/skills/package-skills/brainspike/scripts/lif_smoke.py +31 -0
- package/skills/package-skills/brainspike/scripts/multiscale_workflow.py +35 -0
- package/skills/package-skills/brainspike/scripts/native_ei_network.py +47 -0
- package/skills/package-skills/brainspike/scripts/native_workflows.py +77 -0
- package/skills/package-skills/brainspike/scripts/nest_boundary_workflows.py +108 -0
- package/skills/package-skills/brainspike/scripts/train_native_snn.py +65 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator.py +69 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator_two_weights.py +220 -0
- package/skills/package-skills/brainstate/SKILL.md +16 -21
- package/skills/package-skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +1 -138
- package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
- package/skills/package-skills/brainstate/references/brainstate/delay-buffers.md +45 -0
- package/skills/package-skills/brainstate/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md +6 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md +1 -1
- package/skills/package-skills/brainstate/references/braintools-optimizer-reference.md +16 -0
- package/skills/package-skills/brainstate/references/libraries/prebuilt-layer-library.md +1 -1
- package/skills/package-skills/brainstate/references/simulation-environment.md +5 -5
- package/skills/package-skills/braintrace/SKILL.md +17 -38
- package/skills/package-skills/braintrace/references/Drtrl.md +9 -26
- package/skills/package-skills/braintrace/references/algorithm selection.md +7 -12
- package/skills/package-skills/braintrace/references/batching.md +15 -35
- package/skills/package-skills/braintrace/references/compiler_internal.md +1 -1
- package/skills/package-skills/braintrace/references/custom algorithms.md +1 -2
- package/skills/package-skills/braintrace/references/customizing_primitive_transforms.md +26 -15
- package/skills/package-skills/braintrace/references/pp_pprop workflow.md +5 -139
- package/skills/package-skills/brainunit/SKILL.md +7 -2
- package/skills/package-skills/brainunit/references/array-mechanics/functional-structural-api.md +1 -1
- package/skills/package-skills/brainunit/references/math-function-library.md +2 -2
- package/skills/package-skills/brainunit/references/typing-and-runtime-validation.md +5 -2
- package/skills/package-skills/brainevent/references/scripts/102_EI_net_1996.py +0 -107
- package/skills/package-skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +0 -168
- package/skills/package-skills/brainevent/references/scripts/coba_ei_teaching.py +0 -356
- package/skills/package-skills/brainpy-state/SKILL.md +0 -247
- package/skills/package-skills/brainpy-state/references/array-creation.md +0 -158
- package/skills/package-skills/brainpy-state/references/brain-dynamics-delay-protocol.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/analysis.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +0 -373
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +0 -175
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +0 -286
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +0 -111
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -163
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -113
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -136
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -222
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -123
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -185
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/integrators.md +0 -181
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +0 -102
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +0 -159
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +0 -127
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +0 -167
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -186
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +0 -104
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +0 -89
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +0 -253
- package/skills/package-skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +0 -334
- package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +0 -206
- package/skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md +0 -79
- package/skills/package-skills/brainpy-state/references/braintools/input-current.md +0 -199
- package/skills/package-skills/brainpy-state/references/braintools/metric.md +0 -152
- package/skills/package-skills/brainpy-state/references/braintools/optimizer.md +0 -179
- package/skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md +0 -183
- package/skills/package-skills/brainpy-state/references/braintools/surrogate.md +0 -147
- package/skills/package-skills/brainpy-state/references/component-selection.md +0 -288
- package/skills/package-skills/brainpy-state/references/nest-compatible/model-library.md +0 -200
- package/skills/package-skills/brainpy-state/references/nest-compatible/nest-workflow.md +0 -156
- package/skills/package-skills/brainpy-state/references/nest-compatible/network-building.md +0 -264
- package/skills/package-skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +0 -153
- package/skills/package-skills/brainpy-state/references/projection-patterns.md +0 -127
- package/skills/package-skills/brainpy-state/references/scripts/103_COBA_2005.py +0 -86
- package/skills/package-skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +0 -181
- package/skills/package-skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +0 -156
- package/skills/package-skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +0 -111
- package/skills/package-skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -221
- package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +0 -240
- package/skills/package-skills/brainpy-state/references/scripts/training-snn.py +0 -119
package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md
DELETED
|
@@ -1,253 +0,0 @@
|
|
|
1
|
-
# Training workflows
|
|
2
|
-
|
|
3
|
-
Use this reference after selecting a legacy BrainPy trainer. It covers the
|
|
4
|
-
canonical data and execution flow for offline reservoir fitting, online recurrent
|
|
5
|
-
fitting, backpropagation through time, and a custom gradient loop. Open
|
|
6
|
-
`trainer library.md` when the trainer family is still undecided.
|
|
7
|
-
|
|
8
|
-
## Workflow selection
|
|
9
|
-
|
|
10
|
-
| Workflow | Use when | Essential order |
|
|
11
|
-
|---|---|---|
|
|
12
|
-
| Offline ridge | A readout can be solved from the complete state-target sequence. | Reset model -> warm up recurrent state -> fit `(X, Y)` -> predict held-out input. |
|
|
13
|
-
| Online RLS or FORCE | Readout parameters must update as time steps arrive. | Reset model -> warm up -> traverse paired training sequence while updating -> predict. |
|
|
14
|
-
| BPTT | Loss must differentiate through recurrent dynamics and trainable state. | Enter training mode -> construct model -> define loss and optimizer -> fit batches -> inspect metrics -> predict. |
|
|
15
|
-
| Custom backpropagation | The built-in trainer cannot express the required loss, gradient target, or update schedule. | Predict with `DSTrainer` -> differentiate selected train variables -> optimizer update inside one compiled step. |
|
|
16
|
-
|
|
17
|
-
## Shared reservoir model and data contract
|
|
18
|
-
|
|
19
|
-
Online and offline reservoir trainers consume batch-major arrays. Keep time on
|
|
20
|
-
axis 1 and features on the final axis.
|
|
21
|
-
|
|
22
|
-
```python
|
|
23
|
-
import brainpy as bp
|
|
24
|
-
import brainpy.math as bm
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
class NGRC(bp.DynamicalSystem):
|
|
28
|
-
def __init__(self, num_in, num_out):
|
|
29
|
-
super().__init__()
|
|
30
|
-
self.reservoir = bp.dyn.NVAR(
|
|
31
|
-
num_in,
|
|
32
|
-
delay=4,
|
|
33
|
-
order=2,
|
|
34
|
-
stride=5,
|
|
35
|
-
)
|
|
36
|
-
self.readout = bp.dnn.Dense(
|
|
37
|
-
self.reservoir.num_out,
|
|
38
|
-
num_out,
|
|
39
|
-
mode=bm.training_mode,
|
|
40
|
-
)
|
|
41
|
-
|
|
42
|
-
def update(self, x):
|
|
43
|
-
return self.readout(self.reservoir(x))
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
# Expected data shapes:
|
|
47
|
-
# warmup_x: (batch, warmup_time, features)
|
|
48
|
-
# train_x: (batch, train_time, features)
|
|
49
|
-
# train_y: (batch, train_time, outputs)
|
|
50
|
-
# test_x: (batch, test_time, features)
|
|
51
|
-
# test_y: (batch, test_time, outputs)
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
Create the trainable readout in training mode. Keep `X` and `Y` aligned along
|
|
55
|
-
batch and time axes; a forecast-ahead task shifts the target time window without
|
|
56
|
-
changing those axes.
|
|
57
|
-
|
|
58
|
-
## Offline ridge workflow
|
|
59
|
-
|
|
60
|
-
Use offline ridge when all reservoir states and targets can be collected before
|
|
61
|
-
solving the readout.
|
|
62
|
-
|
|
63
|
-
| API | Description |
|
|
64
|
-
|---|---|
|
|
65
|
-
| `RidgeTrainer(model, alpha=...)` | Use for the canonical closed-form ridge path; `alpha` controls Tikhonov regularization. |
|
|
66
|
-
| `trainer.predict(warmup_x)` | Use before fitting to advance delayed or recurrent state without changing fitted parameters. |
|
|
67
|
-
| `trainer.fit([train_x, train_y])` | Use to solve the readout from the complete paired sequence. |
|
|
68
|
-
| `trainer.predict(test_x)` | Use after fitting for held-out prediction. |
|
|
69
|
-
|
|
70
|
-
```python
|
|
71
|
-
with bm.environment(bm.batching_mode):
|
|
72
|
-
offline_model = NGRC(num_in=3, num_out=3)
|
|
73
|
-
|
|
74
|
-
offline_model.reset(1)
|
|
75
|
-
offline = bp.RidgeTrainer(offline_model, alpha=1e-6)
|
|
76
|
-
|
|
77
|
-
_ = offline.predict(warmup_x)
|
|
78
|
-
_ = offline.fit([train_x, train_y])
|
|
79
|
-
offline_predictions = offline.predict(test_x)
|
|
80
|
-
|
|
81
|
-
assert offline_predictions.shape == test_y.shape
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
Do not reset between warm-up and `fit()`: the warm-up exists to establish the
|
|
85
|
-
state from which the training sequence should begin. Reset explicitly before a
|
|
86
|
-
scientifically independent trial.
|
|
87
|
-
|
|
88
|
-
## Online recurrent workflow
|
|
89
|
-
|
|
90
|
-
Use online fitting when the readout should update while the training sequence is
|
|
91
|
-
processed.
|
|
92
|
-
|
|
93
|
-
| API | Description |
|
|
94
|
-
|---|---|
|
|
95
|
-
| `OnlineTrainer(model, fit_method=bp.algorithms.RLS(), dt=...)` | Use for recursive least squares with explicit algorithm state and simulation step. |
|
|
96
|
-
| `trainer.predict(warmup_x)` | Use to establish recurrent history before learning. |
|
|
97
|
-
| `trainer.fit([train_x, train_y])` | Use to update parameters incrementally across paired time steps. |
|
|
98
|
-
| `trainer.predict(test_x)` | Use to evaluate the fitted recurrent model without further fitting. |
|
|
99
|
-
|
|
100
|
-
```python
|
|
101
|
-
with bm.environment(bm.batching_mode):
|
|
102
|
-
online_model = NGRC(num_in=3, num_out=3)
|
|
103
|
-
|
|
104
|
-
online_model.reset(1)
|
|
105
|
-
online = bp.OnlineTrainer(
|
|
106
|
-
online_model,
|
|
107
|
-
fit_method=bp.algorithms.RLS(),
|
|
108
|
-
dt=0.01,
|
|
109
|
-
)
|
|
110
|
-
|
|
111
|
-
_ = online.predict(warmup_x)
|
|
112
|
-
_ = online.fit([train_x, train_y])
|
|
113
|
-
online_predictions = online.predict(test_x)
|
|
114
|
-
|
|
115
|
-
assert online_predictions.shape == test_y.shape
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
Use `ForceTrainer` when the experiment specifically requires FORCE learning.
|
|
119
|
-
Keep the same warm-up, paired-fit, and held-out-prediction lifecycle.
|
|
120
|
-
|
|
121
|
-
## BPTT workflow
|
|
122
|
-
|
|
123
|
-
Use `BPTT` when gradients must pass through the recurrent trajectory rather than
|
|
124
|
-
fit only a readout.
|
|
125
|
-
|
|
126
|
-
| API | Description |
|
|
127
|
-
|---|---|
|
|
128
|
-
| `bm.training_environment()` | Use while constructing the model so trainable layers and states receive training semantics. |
|
|
129
|
-
| `model.train_vars().unique()` | Use when the loss or optimizer needs the unique trainable-variable collection. |
|
|
130
|
-
| `BPTT(model, loss_fun=..., optimizer=...)` | Use to bind temporal simulation, differentiation, loss, and parameter updates. |
|
|
131
|
-
| `trainer.fit(train_data, num_epoch=...)` | Use with a callable or iterable yielding `(inputs, targets)` batches. |
|
|
132
|
-
| `trainer.get_hist_metric(phase='fit', metric='loss')` | Use to verify convergence after fitting. |
|
|
133
|
-
|
|
134
|
-
```python
|
|
135
|
-
import brainpy as bp
|
|
136
|
-
import brainpy.math as bm
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
dt = 0.04
|
|
140
|
-
num_step = int(1.0 / dt)
|
|
141
|
-
num_batch = 128
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
@bm.jit
|
|
145
|
-
def make_batch(mean=0.025, scale=0.01):
|
|
146
|
-
sample = bm.random.normal(size=(num_batch, 1, 1))
|
|
147
|
-
bias = mean * 2.0 * (sample - 0.5)
|
|
148
|
-
noise = bm.random.normal(size=(num_batch, num_step, 1))
|
|
149
|
-
inputs = bias + scale / dt**0.5 * noise
|
|
150
|
-
targets = bm.cumsum(inputs, axis=1)
|
|
151
|
-
return inputs, targets
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
def train_data():
|
|
155
|
-
for _ in range(100):
|
|
156
|
-
yield make_batch()
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
class RNN(bp.DynamicalSystem):
|
|
160
|
-
def __init__(self, num_in, num_hidden):
|
|
161
|
-
super().__init__()
|
|
162
|
-
self.recurrent = bp.dyn.RNNCell(
|
|
163
|
-
num_in,
|
|
164
|
-
num_hidden,
|
|
165
|
-
train_state=True,
|
|
166
|
-
)
|
|
167
|
-
self.readout = bp.dnn.Dense(num_hidden, 1)
|
|
168
|
-
|
|
169
|
-
def update(self, x):
|
|
170
|
-
return self.readout(self.recurrent(x))
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
with bm.training_environment():
|
|
174
|
-
model = RNN(num_in=1, num_hidden=100)
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
def loss_fun(predictions, targets):
|
|
178
|
-
return bp.losses.mean_squared_error(predictions, targets)
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
schedule = bp.optim.ExponentialDecay(
|
|
182
|
-
lr=0.025,
|
|
183
|
-
decay_steps=1,
|
|
184
|
-
decay_rate=0.99975,
|
|
185
|
-
)
|
|
186
|
-
optimizer = bp.optim.Adam(lr=schedule, eps=1e-1)
|
|
187
|
-
trainer = bp.BPTT(model, loss_fun=loss_fun, optimizer=optimizer)
|
|
188
|
-
|
|
189
|
-
trainer.fit(train_data, num_epoch=30)
|
|
190
|
-
loss_history = trainer.get_hist_metric(phase='fit', metric='loss')
|
|
191
|
-
|
|
192
|
-
test_x, test_y = make_batch()
|
|
193
|
-
model.reset(num_batch)
|
|
194
|
-
predictions = trainer.predict(test_x)
|
|
195
|
-
assert predictions.shape == test_y.shape
|
|
196
|
-
assert loss_history is not None
|
|
197
|
-
```
|
|
198
|
-
|
|
199
|
-
For a spiking model, keep the same BPTT lifecycle. Encode input as a batched time
|
|
200
|
-
series, pass required spike variables through `monitors`, and set
|
|
201
|
-
`loss_has_aux=True` when the loss returns metrics such as accuracy. Add spike
|
|
202
|
-
count penalties only when they express an intended training objective.
|
|
203
|
-
|
|
204
|
-
## Custom backpropagation workflow
|
|
205
|
-
|
|
206
|
-
Use a custom loop only when `BPTT` cannot express the required gradient boundary
|
|
207
|
-
or update schedule.
|
|
208
|
-
|
|
209
|
-
| API | Description |
|
|
210
|
-
|---|---|
|
|
211
|
-
| `DSTrainer(model, progress_bar=False, numpy_mon_after_run=False)` | Use to obtain the model's temporal predictions inside a custom loss. |
|
|
212
|
-
| `bm.grad(loss_fun, grad_vars=model.train_vars().unique(), has_aux=..., return_value=True)` | Use to differentiate exactly the selected legacy BrainPy train variables and return loss or auxiliary metrics. |
|
|
213
|
-
| `bp.optim.Optimizer(..., train_vars=...)` | Use to bind the same variable collection to the update rule. |
|
|
214
|
-
| `@bm.jit` | Use around the complete gradient-and-update step, not around fragmented scalar operations. |
|
|
215
|
-
|
|
216
|
-
Reset the model inside the loss when each batch represents an independent
|
|
217
|
-
trajectory. Preserve state when batches are consecutive segments of one
|
|
218
|
-
trajectory. This choice changes the modeled history and must be explicit.
|
|
219
|
-
|
|
220
|
-
## Common failures
|
|
221
|
-
|
|
222
|
-
- Do not construct a trainable readout outside the legacy training or batching
|
|
223
|
-
environment required by the model.
|
|
224
|
-
- Do not transpose trainer data to time-major form unless the configured runner
|
|
225
|
-
explicitly requires it; the canonical online and offline contract is
|
|
226
|
-
`(batch, time, feature)`.
|
|
227
|
-
- Do not skip warm-up for delayed or recurrent reservoirs.
|
|
228
|
-
- Do not reset between warm-up and fitting unless the fit sequence is intended
|
|
229
|
-
to start from a fresh state.
|
|
230
|
-
- Do not pass independent `X` and `Y` arguments to online or offline `fit()`;
|
|
231
|
-
pass one two-item list or tuple.
|
|
232
|
-
- Do not optimize every mutable variable by default. Select the unique trainable
|
|
233
|
-
variables and verify that state reset and parameter update affect the intended
|
|
234
|
-
objects.
|
|
235
|
-
- Do not replace these legacy training APIs with similarly named APIs from a
|
|
236
|
-
different BrainPy implementation.
|
|
237
|
-
|
|
238
|
-
## Routing
|
|
239
|
-
|
|
240
|
-
- Open `trainer library.md` for the complete trainer-family selection table and
|
|
241
|
-
constructor contracts.
|
|
242
|
-
- Open `loss library.md` for built-in loss selection.
|
|
243
|
-
- Open `optimizers.md` for optimizer and learning-rate-schedule selection.
|
|
244
|
-
- Open `surrogate gradients.md` when a custom hard-threshold spiking model needs
|
|
245
|
-
an explicit surrogate derivative.
|
|
246
|
-
- Open `../infrastructure/object oriented transformations and control flows.md` when a custom loop
|
|
247
|
-
needs transformed scans, loops, or object-aware gradients.
|
|
248
|
-
|
|
249
|
-
## Sources
|
|
250
|
-
|
|
251
|
-
- Training a Brain Dynamics Model: https://brainpy.readthedocs.io/quickstart/training.html
|
|
252
|
-
- Training with Online Algorithms: https://brainpy.readthedocs.io/tutorial_training/online_training.html
|
|
253
|
-
- Training with Back-propagation Algorithms: https://brainpy.readthedocs.io/tutorial_training/bp_training.html
|
|
@@ -1,334 +0,0 @@
|
|
|
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.
|