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/brainstate/references/brainstate/brainstate-control-flow-patterns.md
CHANGED
|
@@ -81,144 +81,7 @@ inside the differentiated loss.
|
|
|
81
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
82
|
| `brainstate.transform.jit(train_step)` | Compile the complete state initialization, differentiated rollout, and parameter update as one training step. |
|
|
83
83
|
|
|
84
|
-
|
|
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
|
-
Choose the transform boundary from the State lifecycle, not from a goal of
|
|
209
|
-
eliminating every host loop. Put all timesteps of one logical rollout in
|
|
210
|
-
`for_loop` or `scan`. When trials must remain sequential because learned State
|
|
211
|
-
passes from trial N to trial N+1, but neural and short-term State must reset at
|
|
212
|
-
each trial boundary, compile one complete trial callable and use a small host
|
|
213
|
-
loop across trials. Do not nest the trials in another transformed loop when
|
|
214
|
-
that prevents the required selective reset.
|
|
215
|
-
|
|
216
|
-
**Invariant:** Initialize recurrent State before each rollout, keep the
|
|
217
|
-
checkpointed loop inside `loss_fn`, differentiate that loss, then JIT the whole
|
|
218
|
-
training step. Checkpointing changes the memory/compute profile, not the
|
|
219
|
-
predictions or loss contract.
|
|
220
|
-
|
|
221
|
-
Source: [How to train through long rollouts without exhausting memory](https://brainx.chaobrain.com/brainpy-state/brainpy-style/howto/train-long-rollouts-checkpoint.html).
|
|
84
|
+
Use the same loss, inputs, initial State, and parameter collection when comparing ordinary and checkpointed loops. Reset independent runtime State before each loss evaluation; compare forward loss and gradients on a short rollout before increasing sequence length. Open `brainspike` → `references/temporal-task-training.md` for a batched native spiking task with verified ordinary/checkpointed loss and gradient parity. This loop contract does not validate cross-window or outer-JIT training of a NEST Simulator.
|
|
222
85
|
|
|
223
86
|
## Run conditional iteration
|
|
224
87
|
|
package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# BrainState transformed diagnostics
|
|
2
2
|
|
|
3
|
-
Use this reference after `
|
|
3
|
+
Use this reference after `SKILL.md` when runtime values, State
|
|
4
4
|
updates, or failures must be inspected from transformed BrainState code. The
|
|
5
5
|
skill owns the core transformation model; this reference only adds diagnostics
|
|
6
6
|
that execute after tracing or turn value-dependent failures into data or
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Preserve signal history with delay buffers
|
|
2
|
+
|
|
3
|
+
Use `brainstate.nn.Delay` when a native Module needs explicit signal history. The buffer owns both stored samples and mutable bookkeeping; initialize and advance them as one registered Module.
|
|
4
|
+
|
|
5
|
+
## Write before retrieving
|
|
6
|
+
|
|
7
|
+
| API | Use |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `brainstate.nn.Delay(target_info, max_time)` | Allocate history from a shape/dtype specification and maximum physical delay under the initialization timestep. |
|
|
10
|
+
| `delay.update(value)` | Write one current sample per step before retrieval in this convention. |
|
|
11
|
+
| `delay.retrieve_at_step(step)` | Read an integer offset; step zero is the just-written sample and step `d` is `d` updates earlier. |
|
|
12
|
+
| `delay.register_entry(name, delays, indices)` / `delay.at(name)` | Register a named heterogeneous tap before initialization, then retrieve the selected per-source histories. |
|
|
13
|
+
| `brainstate.nn.init_all_states(model)` | Initialize the whole registered graph, including the buffer and write position, for an independent rollout. |
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import brainstate
|
|
17
|
+
import brainunit as u
|
|
18
|
+
import jax
|
|
19
|
+
import jax.numpy as jnp
|
|
20
|
+
|
|
21
|
+
with brainstate.environ.context(dt=0.1*u.ms):
|
|
22
|
+
history = brainstate.nn.Delay(jax.ShapeDtypeStruct((3,),jnp.bool_),0.3*u.ms)
|
|
23
|
+
history.register_entry("taps",jnp.asarray([0,2,3])*0.1*u.ms,jnp.arange(3))
|
|
24
|
+
brainstate.nn.init_all_states(history)
|
|
25
|
+
impulses = jnp.zeros((6,3),dtype=jnp.bool_).at[0].set(True)
|
|
26
|
+
def step(events):
|
|
27
|
+
history.update(events)
|
|
28
|
+
return history.at("taps")
|
|
29
|
+
delayed = brainstate.transform.for_loop(step,impulses)
|
|
30
|
+
assert jnp.array_equal(jnp.argmax(delayed,axis=0),jnp.asarray([0,2,3]))
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Initialize under the intended `dt` and keep it fixed for the rollout. Reinitialize all history and bookkeeping at independent boundaries; clearing a neural voltage or sending zeros alone does not reset a delay. Keep signal shape, dtype, and physical unit metadata stable.
|
|
34
|
+
|
|
35
|
+
Reading before `update()` changes the indexing convention by one step. Choose one order and prove it with an impulse; do not insert an unexplained `d-1` correction. A delay measured from an already completed source event also includes that event's availability convention.
|
|
36
|
+
|
|
37
|
+
Use grid-aligned integer taps for binary events. Off-grid interpolation can produce fractional values that are not binary spikes; choose a documented continuous-signal interpolation rule only when the model requires it. Quantize physical event times before the rollout and state the rounding policy.
|
|
38
|
+
|
|
39
|
+
For mapped conditions, map the history and mutable write position compatibly. Do not vmap only the stored samples while sharing a writable scalar pointer. The canonical example verifies unbatched named taps; it does not establish every mapped or interpolated configuration.
|
|
40
|
+
|
|
41
|
+
Open `brainspike` → `references/native-delays.md` for a complete delayed conductance-to-neuron path and its source, conductance-onset, voltage-onset, and reset checks.
|
|
42
|
+
|
|
43
|
+
## Source
|
|
44
|
+
|
|
45
|
+
[BrainState delay protocol](https://brainx.chaobrain.com/brainstate/tutorials/brain_dynamics/02_synaptic_delays.html). The example is executed on BrainState 0.6.0 in the declared BrainX release.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# BrainState constrained and regularized parameters
|
|
2
2
|
|
|
3
|
-
Use this reference after `
|
|
3
|
+
Use this reference after `brainstate` → `SKILL.md` has selected
|
|
4
4
|
`brainstate.nn.Param` for a value that needs a valid-domain transform, a
|
|
5
5
|
regularization penalty, a modeling prior, or fixed parameter-like storage. It
|
|
6
6
|
owns the operational workflow and common patterns. Open
|
|
@@ -20,7 +20,7 @@ Keep `brainstate.nn` parameter transforms separate from execution transforms suc
|
|
|
20
20
|
|
|
21
21
|
## Parameter contract
|
|
22
22
|
|
|
23
|
-
A `ParamState`
|
|
23
|
+
A `ParamState` holds a trainable array or PyTree. `brainstate.nn.Param` layers two orthogonal concerns on top of it: a constraint transform and a regularization term.
|
|
24
24
|
|
|
25
25
|
- `param.val` is the underlying `ParamState`; optimizers update its unconstrained array.
|
|
26
26
|
- `param.value()` applies the forward transform and returns the constrained model-space value. With the default `IdentityT`, constrained and unconstrained values coincide.
|
|
@@ -44,6 +44,7 @@ This workflow keeps optimizer targets in unconstrained `ParamState`s, reads tran
|
|
|
44
44
|
import brainstate
|
|
45
45
|
from brainstate import nn
|
|
46
46
|
import brainunit as u
|
|
47
|
+
import braintools
|
|
47
48
|
import jax.numpy as jnp
|
|
48
49
|
|
|
49
50
|
|
|
@@ -68,6 +69,8 @@ class ConstrainedLinear(nn.Module):
|
|
|
68
69
|
|
|
69
70
|
model = ConstrainedLinear(4, 2)
|
|
70
71
|
params = model.states(brainstate.ParamState)
|
|
72
|
+
optimizer = braintools.optim.SGD(lr=0.1)
|
|
73
|
+
optimizer.register_trainable_weights(params)
|
|
71
74
|
x = brainstate.random.randn(16, 4)
|
|
72
75
|
y = brainstate.random.randn(16, 2)
|
|
73
76
|
|
|
@@ -81,11 +84,10 @@ def loss_fn():
|
|
|
81
84
|
def train_step():
|
|
82
85
|
grads, loss = brainstate.transform.grad(
|
|
83
86
|
loss_fn,
|
|
84
|
-
params,
|
|
87
|
+
grad_states=params,
|
|
85
88
|
return_value=True,
|
|
86
89
|
)()
|
|
87
|
-
|
|
88
|
-
params[key].value -= 0.1 * grads[key]
|
|
90
|
+
optimizer.update(grads)
|
|
89
91
|
return loss
|
|
90
92
|
```
|
|
91
93
|
|
|
@@ -160,7 +162,7 @@ Open `parameter-transforms-regularizers-catalog.md` to select classical, structu
|
|
|
160
162
|
Official sources:
|
|
161
163
|
|
|
162
164
|
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
163
|
-
- https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
165
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
164
166
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
|
|
165
167
|
|
|
166
168
|
## Fixed values with `nn.Const`
|
|
@@ -208,6 +210,6 @@ Official sources:
|
|
|
208
210
|
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
209
211
|
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
210
212
|
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
211
|
-
- https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
213
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
212
214
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Param.html
|
|
213
215
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Const.html
|
|
@@ -100,7 +100,7 @@ Official sources:
|
|
|
100
100
|
|
|
101
101
|
Official sources:
|
|
102
102
|
|
|
103
|
-
- https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
103
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
104
104
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Regularization.html
|
|
105
105
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
|
|
106
106
|
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_regularization.py
|
|
@@ -124,7 +124,7 @@ Official sources:
|
|
|
124
124
|
|
|
125
125
|
Use the generated class page for exact axes, reduction behavior, weights, and initialization arguments; these differ by regularizer and should not be inferred from neighboring classes.
|
|
126
126
|
|
|
127
|
-
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
127
|
+
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
128
128
|
|
|
129
129
|
## Prior-distribution regularizer selection
|
|
130
130
|
|
|
@@ -146,7 +146,7 @@ Prior regularizers encode distributional assumptions for Bayesian-inspired param
|
|
|
146
146
|
| Variable selection | `SpikeAndSlabReg` |
|
|
147
147
|
| Probability simplex | `DirichletReg` |
|
|
148
148
|
|
|
149
|
-
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
149
|
+
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#prior-distribution-based-regularizations
|
|
150
150
|
|
|
151
151
|
## Interaction safeguards
|
|
152
152
|
|
|
@@ -163,7 +163,7 @@ Official source: https://brainx.chaobrain.com/brainstate/apis/nn/regularization.
|
|
|
163
163
|
## Mirror source urls
|
|
164
164
|
|
|
165
165
|
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
166
|
-
- https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
166
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
167
167
|
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
168
168
|
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
169
169
|
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_param.py
|
package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Brainstate randomness and reproducibility
|
|
2
2
|
|
|
3
|
-
Use this reference after `
|
|
3
|
+
Use this reference after `SKILL.md` for advanced randomness. It covers independent streams, stochastic transforms, key control, parallel keys, replay, and checkpointing.
|
|
4
4
|
|
|
5
5
|
The root skill owns `brainstate.random.DEFAULT` and ordinary seeding. This reference owns advanced stream and key control.
|
|
6
6
|
|
|
@@ -10,7 +10,7 @@ Use one `RandomState` per independent concern. Calls consume successive keys fro
|
|
|
10
10
|
|
|
11
11
|
| API | Description |
|
|
12
12
|
|---|---|
|
|
13
|
-
| `RandomState(
|
|
13
|
+
| `RandomState(seed_or_key=None)` | Create an independent stateful random stream from a seed or key; pass a seed positionally, as below. |
|
|
14
14
|
| `rng.seed(seed)` | Restart a custom stream from a seed. |
|
|
15
15
|
| `rng.value` | Inspect the custom stream's current key. |
|
|
16
16
|
|
|
@@ -18,8 +18,8 @@ Use one `RandomState` per independent concern. Calls consume successive keys fro
|
|
|
18
18
|
import brainstate
|
|
19
19
|
import jax.numpy as jnp
|
|
20
20
|
|
|
21
|
-
init_rng = brainstate.random.RandomState(
|
|
22
|
-
augment_rng = brainstate.random.RandomState(
|
|
21
|
+
init_rng = brainstate.random.RandomState(42)
|
|
22
|
+
augment_rng = brainstate.random.RandomState(123)
|
|
23
23
|
|
|
24
24
|
initial_weights = init_rng.randn(5)
|
|
25
25
|
augmented_values = augment_rng.randn(5)
|
|
@@ -27,6 +27,8 @@ augmented_values = augment_rng.randn(5)
|
|
|
27
27
|
assert not jnp.allclose(initial_weights, augmented_values)
|
|
28
28
|
```
|
|
29
29
|
|
|
30
|
+
Use the [generated `RandomState` constructor contract](https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.random.RandomState.html), which names `seed_or_key`; do not copy `seed=` from the module-overview example.
|
|
31
|
+
|
|
30
32
|
Do not pass a custom stream to the global `set_key(...)`. The sources document `rng.value` inspection and `rng.seed(...)` reseeding. They do not document restoring a saved custom-stream key.
|
|
31
33
|
|
|
32
34
|
## Stochastic calls under transforms
|
package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# BrainState gradient and autodiff expansion
|
|
2
2
|
|
|
3
|
-
Use this reference after `
|
|
3
|
+
Use this reference after the BrainState skill's `SKILL.md` when a task needs gradient targets beyond the canonical training step, exact `return_value`/`has_aux` destructuring, state discovery in an arbitrary function, vector- or matrix-valued sensitivities, second derivatives, or an optimizer-integrated fitting step. The parameter reference owns the choice between `ParamState` and `nn.Param`.
|
|
4
4
|
|
|
5
|
-
These three sources do not establish BrainCell solver, reset, or conductance-fitting semantics. Specialized dynamics belongs to the matching BrainCell or
|
|
5
|
+
These three sources do not establish BrainCell solver, reset, or conductance-fitting semantics. Specialized dynamics belongs to the matching BrainCell or BrainSpike skill; use this reference only for the source-supported autodiff contract around that computation.
|
|
6
6
|
|
|
7
7
|
Official sources:
|
|
8
8
|
|
|
@@ -440,7 +440,7 @@ def train_step(x, y):
|
|
|
440
440
|
return loss
|
|
441
441
|
```
|
|
442
442
|
|
|
443
|
-
Return to `
|
|
443
|
+
Return to `SKILL.md` for the general training structure. Open `references/braintools-optimizer-reference.md` only for optimizer or scheduler selection.
|
|
444
444
|
|
|
445
445
|
Official source: https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html
|
|
446
446
|
|
|
@@ -453,7 +453,7 @@ Official source: https://brainx.chaobrain.com/brainstate/tutorials/core/07_train
|
|
|
453
453
|
- Choose `jacrev` versus `jacfwd` from the documented input/output-size tradeoff, and remember that `jacobian` aliases `jacrev`.
|
|
454
454
|
- Do not assume only `ParamState` can receive gradients; any explicit `State` can be a sensitivity target.
|
|
455
455
|
- Do not assume an attached regularizer changes fitting unless its penalty is added to the scalar loss.
|
|
456
|
-
- Do not infer BrainCell integration, reset, unit, or solver semantics from these sources; route specialized dynamics to the matching BrainCell or
|
|
456
|
+
- Do not infer BrainCell integration, reset, unit, or solver semantics from these sources; route specialized dynamics to the matching BrainCell or BrainSpike skill.
|
|
457
457
|
|
|
458
458
|
## Mirror source urls
|
|
459
459
|
|
package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# BrainState vmap expansion
|
|
2
2
|
|
|
3
3
|
Use this reference after the minimal `brainstate.transform.vmap` example in
|
|
4
|
-
`
|
|
4
|
+
`SKILL.md` when argument axes, State axes, random-key policy,
|
|
5
5
|
nested mappings, or unexpected State writes require explicit control.
|
|
6
6
|
|
|
7
7
|
This reference covers only behavior demonstrated by these routed official tutorials:
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Optimizers for BrainState training
|
|
2
|
+
|
|
3
|
+
Use this reference after choosing the trainable State collection and loss. The optimizer owns the update and its auxiliary State while the model owns the parameter values.
|
|
4
|
+
|
|
5
|
+
| Need | Use |
|
|
6
|
+
|---|---|
|
|
7
|
+
| A simple gradient-step baseline | Use `braintools.optim.SGD(lr=...)`. Register the `ParamState` collection once, then call `update(grads)` with the gradient PyTree for the same collection. |
|
|
8
|
+
| Adaptive minibatch training | Use `braintools.optim.Adam(lr=...)`. Its moments are separate from model State. Include optimizer State when saving or restoring an exact training continuation. |
|
|
9
|
+
| A scheduled learning rate | Choose a scheduler from the optimization API and advance it at the documented step or epoch boundary. Check the rate sequence in a short run before training. |
|
|
10
|
+
| An existing Optax transformation | Use the documented BrainTools bridge and keep the same registered gradient and parameter PyTrees. |
|
|
11
|
+
| Standalone SciPy or Nevergrad fitting | Use the active model package's fitting workflow. These wrappers own a search over explicit candidates and use a different lifecycle from `register_trainable_weights()` and `update()`. |
|
|
12
|
+
|
|
13
|
+
Open `brainstate` → `SKILL.md` for the compiled training step. Register after constructing the model and before tracing the step. Preserve both the State paths and the nested value structure. Keep optimizer moments across training steps and start with fresh optimizer State for independent candidates.
|
|
14
|
+
|
|
15
|
+
- [BrainTools optimization API](https://brainx.chaobrain.com/braintools/apis/optim.html)
|
|
16
|
+
- [BrainState training tutorial](https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html)
|
|
@@ -130,7 +130,7 @@ feature_extractor = nn.Sequential(
|
|
|
130
130
|
)
|
|
131
131
|
```
|
|
132
132
|
|
|
133
|
-
Open `
|
|
133
|
+
Open `scripts/modern_cnn.py` for the full convolution,
|
|
134
134
|
normalization, pooling, dropout, and dense workflow.
|
|
135
135
|
|
|
136
136
|
## Official sources
|
|
@@ -12,13 +12,13 @@ Sources:
|
|
|
12
12
|
|
|
13
13
|
Put values that describe the run, rather than one Module, in `brainstate.environ`. The environment is a stack of settings:
|
|
14
14
|
|
|
15
|
-
- `set()` installs a persistent default that
|
|
16
|
-
- `context()` pushes temporary
|
|
15
|
+
- In BrainState `0.6.0`, `set()` installs a persistent default on the selected environment object. Every thread using that object sees the default until it changes or resets.
|
|
16
|
+
- `context()` pushes temporary overrides for the calling thread and restores the previous values on exit, including exceptional exit.
|
|
17
17
|
- `get(key, default=...)` searches the active context before persistent settings; it returns the value or explicit default and otherwise raises `KeyError`.
|
|
18
18
|
- Typed accessors such as `get_dt()`, `get_precision()`, and `get_platform()` enforce the corresponding setting contract.
|
|
19
19
|
- A nested context inherits its outer context and overrides only the keys it supplies.
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
Keep `EnvironmentState` outside Module graphs and State collections. A separate object has its own defaults and per-thread override stack.
|
|
22
22
|
|
|
23
23
|
Choose the narrowest lifetime:
|
|
24
24
|
|
|
@@ -27,9 +27,9 @@ Choose the narrowest lifetime:
|
|
|
27
27
|
| One simulation, training phase, evaluation phase, or step | `brainstate.environ.context(...)` |
|
|
28
28
|
| A persistent default in the selected environment | `brainstate.environ.set(...)` |
|
|
29
29
|
| The same context on every call to one Module | Use `brainstate.nn.EnvironContext(layer, **context)`; the wrapper executes the Module with the stored settings, merges optional call-specific settings, and returns the Module's result |
|
|
30
|
-
| Configuration isolated from the default environment | Create `brainstate.environ.EnvironmentState()` and pass it through every `env=` argument
|
|
30
|
+
| Configuration isolated from the default environment | Create `brainstate.environ.EnvironmentState()` and pass it through every `env=` argument so operations use that object's defaults and overrides. |
|
|
31
31
|
|
|
32
|
-
Prefer `context()` for normal simulation and training.
|
|
32
|
+
Prefer `context()` for normal simulation and training. Set a separate context inside each worker when concurrent runs need different `dt` values.
|
|
33
33
|
|
|
34
34
|
## Advanced environment configuration
|
|
35
35
|
|
|
@@ -13,9 +13,9 @@ Follow this path:
|
|
|
13
13
|
|
|
14
14
|
`build with braintrace.nn -> choose a trace representation -> compile once -> inspect -> reset both State systems -> accumulate sequence gradients -> update once -> verify`
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
Use this workflow with BrainTrace `0.2.8`, bundled by BrainX `2026.10.25`.
|
|
17
17
|
|
|
18
|
-
Route general `State`, `Module`, transformations, mapped lifecycle operations, and optimizers to BrainState. Route neuron and synapse dynamics to
|
|
18
|
+
Route general `State`, `Module`, transformations, mapped lifecycle operations, and optimizers to BrainState. Route neuron and synapse dynamics to BrainSpike or BrainCell. Use ordinary BrainState training when offline BPTT is acceptable.
|
|
19
19
|
|
|
20
20
|
## Underlying principle of BrainTrace
|
|
21
21
|
|
|
@@ -86,18 +86,17 @@ Open `references/pre-built-braintrace-layer.md` when selecting another ETP-aware
|
|
|
86
86
|
|
|
87
87
|
## Train and evaluate a sequence
|
|
88
88
|
|
|
89
|
-
|
|
89
|
+
Use the learner to drive time. Each step loss calls the learner once, and the optimizer applies the accumulated gradient after the sequence.
|
|
90
90
|
|
|
91
91
|
| API | Description |
|
|
92
92
|
|---|---|
|
|
93
93
|
| `brainstate.nn.reset_all_states(model, batch_size=...)` | Use at an independent sequence boundary to reset recurrent State. |
|
|
94
94
|
| `learner.reset_state(batch_size=...)` | Use at the same boundary to reset eligibility State and the running index. |
|
|
95
|
-
| `
|
|
96
|
-
| `
|
|
95
|
+
| `learner.etrace_grad(*sequences, step_fn=..., reduction=..., return_value=True)` | Use to advance hidden and eligibility State while accumulating online gradients and returning step losses. Choose the gradient reduction explicitly. |
|
|
96
|
+
| `learner.etrace_evolve(inputs, return_outputs=True)` | Use for evaluation or warm-up. It advances both State systems without accumulating gradients. |
|
|
97
97
|
| `optimizer.update(grads)` | Use once after the complete sequence gradient has been accumulated. |
|
|
98
98
|
|
|
99
99
|
```python
|
|
100
|
-
import jax
|
|
101
100
|
import braintools
|
|
102
101
|
|
|
103
102
|
targets = 0.7 * inputs + 0.2
|
|
@@ -115,33 +114,14 @@ def step_loss(x, target):
|
|
|
115
114
|
return jnp.mean((learner(x) - target) ** 2)
|
|
116
115
|
|
|
117
116
|
|
|
118
|
-
loss_grad = brainstate.transform.grad(
|
|
119
|
-
step_loss,
|
|
120
|
-
weights,
|
|
121
|
-
return_value=True,
|
|
122
|
-
)
|
|
123
|
-
|
|
124
|
-
|
|
125
117
|
def train_epoch(_):
|
|
126
118
|
reset_sequence()
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
step_grads, loss = loss_grad(*sample)
|
|
134
|
-
grads = jax.tree.map(
|
|
135
|
-
lambda total, value: total + value,
|
|
136
|
-
grads,
|
|
137
|
-
step_grads,
|
|
138
|
-
)
|
|
139
|
-
return grads, loss
|
|
140
|
-
|
|
141
|
-
grads, losses = brainstate.transform.scan(
|
|
142
|
-
accumulate,
|
|
143
|
-
initial_grads,
|
|
144
|
-
(inputs, targets),
|
|
119
|
+
grads, losses = learner.etrace_grad(
|
|
120
|
+
inputs,
|
|
121
|
+
targets,
|
|
122
|
+
step_fn=step_loss,
|
|
123
|
+
reduction='sum',
|
|
124
|
+
return_value=True,
|
|
145
125
|
)
|
|
146
126
|
optimizer.update(grads)
|
|
147
127
|
return losses.mean()
|
|
@@ -149,7 +129,7 @@ def train_epoch(_):
|
|
|
149
129
|
|
|
150
130
|
losses = brainstate.transform.for_loop(train_epoch, jnp.arange(5))
|
|
151
131
|
reset_sequence()
|
|
152
|
-
predictions =
|
|
132
|
+
predictions = learner.etrace_evolve(inputs, return_outputs=True)
|
|
153
133
|
|
|
154
134
|
assert losses[-1] < losses[0]
|
|
155
135
|
assert predictions.shape == targets.shape
|
|
@@ -164,14 +144,14 @@ Escalate model construction from prebuilt layers to built-in ETP operations, the
|
|
|
164
144
|
| Reference | Open when | Contains |
|
|
165
145
|
|---|---|---|
|
|
166
146
|
| `references/pre-built-braintrace-layer.md` | Selecting another ETP-aware layer or composing the default model. | Layer families, parameterized-operation choices, and BrainState-owned supporting layers. |
|
|
167
|
-
| `references/Drtrl.md` | Using or validating parameter-shaped D-RTRL traces. | Memory scaling, recurrence, sequence resets,
|
|
147
|
+
| `references/Drtrl.md` | Using or validating parameter-shaped D-RTRL traces. | Memory scaling, recurrence, sequence resets, sequence drivers, and the BPTT boundary. |
|
|
168
148
|
| `references/pp_pprop workflow.md` | Parameter-shaped traces are too costly or a recurrent SNN needs factorized traces. | Input/output factorization, SNN integration, report-window training, and validation. |
|
|
169
|
-
| `references/algorithm selection.md` | Neither canonical memory strategy fits the estimator requirements. |
|
|
170
|
-
| `references/batching.md` | Adding a batch axis, mapped model, or multi-step wrapper. | Mapping ownership, batched compilation, mapped resets, and
|
|
149
|
+
| `references/algorithm selection.md` | Neither canonical memory strategy fits the estimator requirements. | Public estimators, guarantees, and configuration options. |
|
|
150
|
+
| `references/batching.md` | Adding a batch axis, mapped model, or multi-step wrapper. | Mapping ownership, batched compilation, mapped resets, and time-major shapes. |
|
|
171
151
|
| `references/ETP operators.md` | A prebuilt layer cannot express the required parameterized operation. | Built-in ETP operations, participation rules, sparse inputs, units, and transform behavior. |
|
|
172
152
|
| `references/custom ETP primitives.md` | No built-in ETP operation can express the computation. | Primitive registration, ETP rules, compiler integration, and validation. |
|
|
173
153
|
| `references/customizing_primitive_transforms.md` | An ETP weight needs masking, constraints, normalization, LoRA, or a bias transform. | Transform hooks and raw-parameter gradient attachment. |
|
|
174
|
-
| `references/custom algorithms.md` | No built-in
|
|
154
|
+
| `references/custom algorithms.md` | No built-in algorithm expresses the research method. | Estimator bases, trace lifecycle, solve hooks, and inspection. |
|
|
175
155
|
| `references/compiler_internal.md` | Structured report fields cannot explain custom graph behavior. | Discovery, graph execution, control-flow policy, and low-level diagnostics. |
|
|
176
156
|
|
|
177
157
|
## Boundaries and common failures
|
|
@@ -182,6 +162,5 @@ Escalate model construction from prebuilt layers to built-in ETP operations, the
|
|
|
182
162
|
- Do not treat every warning or excluded candidate as a failed parameter. Inspect `etrace_weights`, `excluded_weights`, and level-2 diagnostics together.
|
|
183
163
|
- Reset both recurrent State and eligibility State between independent sequences and verify mapped shapes survive a mapped reset.
|
|
184
164
|
- Use exactly one batching owner. Prefer `braintrace.compile(..., vmap=True)` for independent per-sample State or native batched compilation when the model supports it.
|
|
185
|
-
-
|
|
186
|
-
- Do not use BrainTrace `0.2.5` sequence-driver APIs with the bundled `0.2.4` release.
|
|
165
|
+
- Update the optimizer after `etrace_grad` returns when the schedule calls for one update per sequence.
|
|
187
166
|
- Use `pp_prop` in new code; `ES_D_RTRL` is its compatibility alias.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# D-RTRL
|
|
2
2
|
|
|
3
|
-
Use this reference when implementing or validating the parameter-dimensional D-RTRL workflow
|
|
3
|
+
Use this reference when implementing or validating the parameter-dimensional D-RTRL workflow. Open `algorithm selection.md` when choosing another estimator and `batching.md` before adding a batch axis.
|
|
4
4
|
|
|
5
5
|
## Understand the approximation
|
|
6
6
|
|
|
@@ -10,8 +10,7 @@ Use this reference when implementing or validating the parameter-dimensional D-R
|
|
|
10
10
|
|---|---|
|
|
11
11
|
| `braintrace.D_RTRL` | Use when parameter-shaped trace memory is feasible; it computes approximate online gradients without retaining the full sequence graph. |
|
|
12
12
|
| `braintrace.compile(model, braintrace.D_RTRL, example_step, ...)` | Use once to initialize State, construct the learner, and compile the ETP graph from a representative step. |
|
|
13
|
-
| `
|
|
14
|
-
| `brainstate.transform.scan(body, initial_grads, sequence)` | Use to carry the summed gradient across time while the learner advances hidden and eligibility State. |
|
|
13
|
+
| `learner.etrace_grad(..., step_fn=..., reduction=...)` | Use to accumulate online gradients across one sequence. |
|
|
15
14
|
|
|
16
15
|
Trace memory scales as `O(B * |theta|)`, where `B` is batch size and `theta` is the participating parameter set. Do not describe D-RTRL as generally identical to BPTT; equality depends on the recurrence and mathematical regime being tested.
|
|
17
16
|
|
|
@@ -25,11 +24,10 @@ Reset recurrent and eligibility State together, accumulate gradients across the
|
|
|
25
24
|
| 2. Compile | Call `braintrace.compile(...)` once with one real per-step input. | The graph and State layout are reused. |
|
|
26
25
|
| 3. Inspect | Show report level 2 and inspect structured participation fields. | Intended recurrent weights are confirmed rather than inferred from warning text. |
|
|
27
26
|
| 4. Reset | Reset model State and learner State at every independent sequence. | Hidden State, eligibility traces, and running index share one boundary. |
|
|
28
|
-
| 5. Accumulate |
|
|
29
|
-
| 6. Update | Clip if needed and call the optimizer once after the
|
|
27
|
+
| 5. Accumulate | Call `etrace_grad` with one learner call per step loss. | Every time step advances online State while gradients sum across time. |
|
|
28
|
+
| 6. Update | Clip if needed and call the optimizer once after the sequence. | The printed sequence count matches the optimizer schedule. |
|
|
30
29
|
|
|
31
30
|
```python
|
|
32
|
-
import jax
|
|
33
31
|
import jax.numpy as jnp
|
|
34
32
|
import brainstate
|
|
35
33
|
import braintrace
|
|
@@ -71,25 +69,10 @@ def step_loss(x, target):
|
|
|
71
69
|
return jnp.mean((learner(x) - target) ** 2)
|
|
72
70
|
|
|
73
71
|
|
|
74
|
-
loss_grad = brainstate.transform.grad(step_loss, weights, return_value=True)
|
|
75
|
-
|
|
76
|
-
|
|
77
72
|
def train_sequence():
|
|
78
73
|
reset_sequence()
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
{key: state.value for key, state in weights.items()},
|
|
82
|
-
)
|
|
83
|
-
|
|
84
|
-
def accumulate(grads, sample):
|
|
85
|
-
step_grads, loss = loss_grad(*sample)
|
|
86
|
-
grads = jax.tree.map(lambda x, y: x + y, grads, step_grads)
|
|
87
|
-
return grads, loss
|
|
88
|
-
|
|
89
|
-
grads, losses = brainstate.transform.scan(
|
|
90
|
-
accumulate,
|
|
91
|
-
initial_grads,
|
|
92
|
-
(inputs, targets),
|
|
74
|
+
grads, losses = learner.etrace_grad(
|
|
75
|
+
inputs, targets, step_fn=step_loss, reduction='sum', return_value=True,
|
|
93
76
|
)
|
|
94
77
|
optimizer.update(grads)
|
|
95
78
|
return losses.mean()
|
|
@@ -99,7 +82,7 @@ loss = train_sequence()
|
|
|
99
82
|
assert jnp.isfinite(loss)
|
|
100
83
|
```
|
|
101
84
|
|
|
102
|
-
|
|
85
|
+
Pass a time-major `mask` to `etrace_grad` when only selected steps contribute to the loss. The learner still advances both State systems at masked steps.
|
|
103
86
|
|
|
104
87
|
## Reset both State domains
|
|
105
88
|
|
|
@@ -129,5 +112,5 @@ Use a reduced matched task as a BPTT oracle only when the estimator's documented
|
|
|
129
112
|
|
|
130
113
|
## Sources
|
|
131
114
|
|
|
132
|
-
- [
|
|
133
|
-
- [
|
|
115
|
+
- [D-RTRL tutorial](https://brainx.chaobrain.com/braintrace/tutorials/drtrl.html)
|
|
116
|
+
- [Algorithms API](https://brainx.chaobrain.com/braintrace/apis/algorithms.html)
|