brainx-skill 1.0.9 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +6 -0
  2. package/adapters/antigravity.js +8 -0
  3. package/installation/lib/installer.js +60 -20
  4. package/installation/lib/paths.js +41 -3
  5. package/installation/lib/prompts.js +13 -7
  6. package/manifest.json +2 -1
  7. package/package.json +3 -2
  8. package/skills/braincell/SKILL.md +14 -0
  9. package/skills/brainevent/SKILL.md +1 -0
  10. package/skills/brainmass/SKILL.md +1 -1
  11. package/skills/brainpy-state/SKILL.md +7 -1
  12. package/skills/brainpy-state/references/array-creation.md +2 -2
  13. package/skills/brainpy-state/references/brainPy(legacy)/analysis.md +150 -0
  14. package/skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +373 -0
  15. package/skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +150 -0
  16. package/skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +175 -0
  17. package/skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +286 -0
  18. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +111 -0
  19. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +163 -0
  20. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +113 -0
  21. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +136 -0
  22. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +222 -0
  23. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +123 -0
  24. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +107 -0
  25. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +185 -0
  26. package/skills/brainpy-state/references/brainPy(legacy)/integrators.md +181 -0
  27. package/skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +102 -0
  28. package/skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +147 -0
  29. package/skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +159 -0
  30. package/skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +127 -0
  31. package/skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +167 -0
  32. package/skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +107 -0
  33. package/skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +186 -0
  34. package/skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +104 -0
  35. package/skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +89 -0
  36. package/skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +253 -0
  37. package/skills/brainstate/SKILL.md +14 -10
  38. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +1 -1
  39. package/skills/brainstate/references/braintools/optimizer.md +179 -0
  40. package/skills/braintrace/SKILL.md +161 -0
  41. package/skills/braintrace/references/Drtrl.md +179 -0
  42. package/skills/braintrace/references/ETP operators.md +161 -0
  43. package/skills/braintrace/references/algorithm selection.md +120 -0
  44. package/skills/braintrace/references/batching.md +150 -0
  45. package/skills/braintrace/references/compiler_internal.md +162 -0
  46. package/skills/braintrace/references/custom ETP primitives.md +200 -0
  47. package/skills/braintrace/references/custom algorithms.md +206 -0
  48. package/skills/braintrace/references/customizing_primitive_transforms.md +191 -0
  49. package/skills/braintrace/references/pp_pprop workflow.md +196 -0
  50. package/skills/braintrace/references/pre-built-braintrace-layer.md +149 -0
  51. package/skills/brainx-general-guard/SKILL.md +45 -8
  52. package/skills/brainx-install/SKILL.md +29 -23
  53. package/skills/brainstate/agents/openai.yaml +0 -4
@@ -0,0 +1,253 @@
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
@@ -3,7 +3,7 @@ name: brainstate
3
3
  description: BrainState is the central stateful execution infrastructure for BrainX modeling and simulation. Use this skill for mutable State and `.value`, ParamState and other State roles, Module graphs, environment-scoped simulations, state initialization, operational randomness, size-aware neural-network composition, state-aware jit/grad/vmap, or a BrainState training step.
4
4
  ---
5
5
 
6
- # Brainstate
6
+ # BrainState
7
7
 
8
8
  ## Purpose and boundary
9
9
 
@@ -334,13 +334,6 @@ assert input_spikes.shape == (num_steps, batch_size, num_inputs)
334
334
 
335
335
  Open `references/brainstate/randomness-and-reproducibility.md` for independent `RandomState` streams, direct key control, stochastic mapping, exact replay, or checkpointed RNG State.
336
336
 
337
- ## Script references
338
-
339
- - `scripts/integrator_rnn.py`: full stateful sequence-training workflow with a custom RNN cell, trainable initial state, optimization, compiled steps, and evaluation.
340
- - `scripts/lif_neuron_model.py`: extended combination of `HiddenState`, `ShortTermState`, and `ParamState` with explicit `.value` updates.
341
- - `scripts/modern_cnn.py`: full convolution, normalization, activation, pooling, dropout, and dense Module composition. Select it through the layer or activation branch.
342
- - `scripts/resnet.py`: residual Modules and dynamically registered child blocks.
343
-
344
337
  ## Reference routing
345
338
 
346
339
  Route by the outcome the task needs, then open only the smallest reference that owns that variant.
@@ -372,12 +365,12 @@ Route by the outcome the task needs, then open only the smallest reference that
372
365
  | Reference | Open when |
373
366
  |---|---|
374
367
  | `references/brainstate/parameter-constraints-regularization.md` | Using `nn.Param` transforms, regularizers, priors, penalties, or `nn.Const` |
375
- | `references/braintools-optimizer-reference.md` | Selecting a `braintools.optim`, Optax, SciPy, or Nevergrad optimizer or scheduler |
368
+ | `references/braintools/optimizer.md` | Selecting a `braintools.optim`, Optax, SciPy, or Nevergrad optimizer or scheduler |
376
369
  | `references/brainstate/randomness-and-reproducibility.md` | Creating independent random streams or exact stochastic replay across transforms and checkpoints |
377
370
 
378
371
  The remaining nested reference has one inbound route:
379
372
 
380
- - Only `parameter-constraints-regularization.md` may open `parameter-transforms-regularizers-catalog.md`.
373
+ - Only `references/brainstate/parameter-constraints-regularization.md` may open `references/brainstate/parameter-transforms-regularizers-catalog.md`.
381
374
 
382
375
  ### Layer libraries
383
376
 
@@ -397,3 +390,14 @@ The remaining nested reference has one inbound route:
397
390
  | `references/brainstate/brainstate-transformed-diagnostics.md` | Debugging runtime values or enforcing invariants inside transformed stateful code |
398
391
 
399
392
  Do not route to dynamics or solver references from this skill; they are outside the architecture supplied for this BrainState skill.
393
+
394
+ ## Application script examples
395
+
396
+ Open one script only when its pattern matches the task; each is a complete, runnable program.
397
+
398
+ | Script | Open when |
399
+ |---|---|
400
+ | `scripts/integrator_rnn.py` | Building a full stateful sequence-training workflow with a custom RNN cell, trainable initial state, optimization, compiled steps, and evaluation. |
401
+ | `scripts/lif_neuron_model.py` | Combining `HiddenState`, `ShortTermState`, and `ParamState` in one Module with explicit `.value` updates. |
402
+ | `scripts/modern_cnn.py` | Composing convolution, normalization, activation, pooling, dropout, and dense Modules; select it through the layer or activation branch. |
403
+ | `scripts/resnet.py` | Building residual Modules and dynamically registered child blocks. |
@@ -440,7 +440,7 @@ def train_step(x, y):
440
440
  return loss
441
441
  ```
442
442
 
443
- Return to `skills/brainstate/SKILL.md` for the general training structure. Open `references/braintools-optimizer-reference.md` only for optimizer or scheduler selection.
443
+ Return to `skills/brainstate/SKILL.md` for the general training structure. Open `references/braintools/optimizer.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
 
@@ -0,0 +1,179 @@
1
+ # Braintools optimizer selection
2
+
3
+ Use this reference after the BrainState loss, `ParamState` selection, and gradient target are correct. Select an optimizer interface and learning-rate policy without changing the Module graph or confusing gradient-step optimizers with standalone search wrappers.
4
+
5
+ ## Choose a gradient optimizer
6
+
7
+ Choose the optimizer family by training regime and resource constraint. Ordinary reverse-mode optimizers register the selected `ParamState` tree once and accept the matching gradient tree through `update(grads)`.
8
+
9
+ ### General minibatch optimizers
10
+
11
+ Use these optimizers for ordinary repeated gradient steps; establish `Adam` or `SGD` as the baseline before selecting a specialized update rule.
12
+
13
+ | API | Description |
14
+ |---|---|
15
+ | `SGD(...)` | Use for stochastic gradient descent with optional momentum and weight decay when a simple non-adaptive baseline is required. |
16
+ | `Momentum(...)` | Use for momentum updates without selecting the broader `SGD` interface. |
17
+ | `MomentumNesterov(...)` | Use when the optimization method requires Nesterov-accelerated momentum. |
18
+ | `Adam(...)` | Use as the canonical adaptive default after validating finite, nonzero gradients. |
19
+ | `AdamW(...)` | Use when the training policy requires decoupled weight decay; set `weight_decay` deliberately. |
20
+ | `Adagrad(...)` | Use when per-parameter learning rates should accumulate squared-gradient history. |
21
+ | `Adadelta(...)` | Use when the Adadelta extension of Adagrad is explicitly required. |
22
+ | `RMSprop(...)` | Use when the method should scale updates by a moving average of squared gradients. |
23
+ | `Adamax(...)` | Use when the infinity-norm Adam variant is required. |
24
+ | `Nadam(...)` | Use when combining Adam with Nesterov acceleration. |
25
+ | `RAdam(...)` | Use when rectifying adaptive learning-rate variance addresses observed early-step instability. |
26
+ | `Yogi(...)` | Use when the Yogi additive second-moment update is part of the intended method. |
27
+ | `Rprop(...)` | Use when resilient backpropagation should adapt per-parameter step sizes from gradient signs. |
28
+ | `AdaBelief(...)` | Use when adapting step size from the optimizer's belief in the gradient direction is required. |
29
+ | `Lion(...)` | Use when a sign-momentum optimizer is chosen to reduce optimizer-State memory. |
30
+ | `Novograd(...)` | Use when layer-wise gradient normalization with momentum is required. |
31
+ | `Fromage(...)` | Use only when the Free-scale Optimal Method for Adaptive Gradient method is explicitly selected. |
32
+
33
+ ### Large-scale and memory-efficient optimizers
34
+
35
+ Use these optimizers only when large-batch scaling or optimizer-State memory is an explicit constraint.
36
+
37
+ | API | Description |
38
+ |---|---|
39
+ | `Lamb(...)` | Use for layer-wise adaptive moments in an explicitly large-batch training regime. |
40
+ | `Lars(...)` | Use for layer-wise adaptive rate scaling in an explicitly large-batch training regime. |
41
+ | `Adafactor(...)` | Use when factorized second-moment estimates are needed to reduce optimizer-State memory. |
42
+ | `SM3(...)` | Use for memory-efficient adaptive updates in a large or sparse model. |
43
+
44
+ ### Wrapper and full-batch optimizers
45
+
46
+ Use these variants when the update requires an optimizer composition or a smooth full-batch objective rather than an ordinary standalone minibatch rule.
47
+
48
+ | API | Description |
49
+ |---|---|
50
+ | `Lookahead(...)` | Use when wrapping an inner Optax gradient transformation with periodic slow-weight interpolation. |
51
+ | `LBFGS(...)` | Use for a small, smooth, full-batch problem suited to limited-memory quasi-Newton updates; verify its step contract before replacing a minibatch optimizer. |
52
+
53
+ ### Custom Optax transformations
54
+
55
+ Use the bridge when no named Braintools optimizer expresses the required Optax transformation.
56
+
57
+ | API | Description |
58
+ |---|---|
59
+ | `OptaxOptimizer(tx=..., lr=...)` | Use when supplying a custom Optax transformation while preserving Braintools parameter registration, optimizer State, gradient clipping, weight decay, and scheduler integration. |
60
+
61
+ Do not switch optimizer, scheduler, and loss reduction simultaneously. Establish an `Adam` loss and gradient baseline, then vary one optimization decision.
62
+
63
+ ## Gradient-step lifecycle
64
+
65
+ Every ordinary gradient optimizer owns persistent optimizer State and mutates exactly the registered trainable State:
66
+
67
+ | API | Use and result |
68
+ |---|---|
69
+ | `model.states(brainstate.ParamState)` | Select trainable model State; `HiddenState`, `ShortTermState`, and other dynamical State remain outside the optimizer. |
70
+ | `optimizer.register_trainable_weights(params)` | Register the parameter tree and initialize optimizer State. |
71
+ | `brainstate.transform.grad(loss_fn, params, return_value=True)` | Produce a gradient tree matching `params` and the scalar loss. |
72
+ | `optimizer.update(grads)` | Apply one update to the registered parameters. |
73
+
74
+ ```python
75
+ params = net.states(brainstate.ParamState)
76
+ optimizer = braintools.optim.Adam(lr=3e-3)
77
+ optimizer.register_trainable_weights(params)
78
+
79
+ @brainstate.transform.jit
80
+ def train_step():
81
+ brainstate.nn.init_all_states(net, batch_size=batch_size)
82
+ grads, loss = brainstate.transform.grad(
83
+ loss_fn,
84
+ params,
85
+ return_value=True,
86
+ )()
87
+ optimizer.update(grads)
88
+ return loss
89
+ ```
90
+
91
+ Register the same tree passed to `grad`. Do not rebuild or re-register that tree inside every compiled step.
92
+
93
+ Use `braintools.optim.UniqueStateManager(...)` only when an arbitrary nested PyTree may contain repeated references to the same `State`; it deduplicates State identity before optimization. An ordinary `model.states(brainstate.ParamState)` collection already expresses the canonical model-owned target.
94
+
95
+ ## Learning-rate schedulers
96
+
97
+ Pass an `LRScheduler` instance as `lr=` to any gradient-based `OptaxOptimizer`. A float is treated as a constant learning rate.
98
+
99
+ | API | Description |
100
+ |---|---|
101
+ | `LRScheduler(...)` | Subclass when implementing a custom schedule; it defines attachment, stepping, current-rate access, and State serialization. |
102
+ | `StepLR(...)` | Use for staircase decay by `gamma` every `step_size` scheduler steps. |
103
+ | `MultiStepLR(...)` | Use for multiplicative decay at explicitly chosen milestones. |
104
+ | `ConstantLR(...)` | Use to multiply the base learning rate by a constant factor for a configured interval. |
105
+ | `LinearLR(...)` | Use to scale the learning rate linearly between configured factors. |
106
+ | `ExponentialLR(...)` | Use for smooth multiplicative decay by `gamma` at every scheduler step. |
107
+ | `PolynomialLR(...)` | Use when the learning rate must follow a polynomial decay. |
108
+ | `ExponentialDecayLR(...)` | Use for exponential decay with explicit step-based control. |
109
+ | `CosineAnnealingLR(...)` | Use for smooth cosine annealing from the base rate toward `eta_min`; match `T_max` to the scheduler-call cadence. |
110
+ | `CosineAnnealingWarmRestarts(...)` | Use for cosine annealing that periodically restarts its cycle. |
111
+ | `WarmupCosineSchedule(...)` | Use when one schedule must warm up first and then anneal by cosine. |
112
+ | `CyclicLR(...)` | Use to oscillate the learning rate between configured bounds. |
113
+ | `OneCycleLR(...)` | Use for a single super-convergence cycle; derive `total_steps` from the actual number of scheduler calls. |
114
+ | `ReduceLROnPlateau(...)` | Use when a validation metric should trigger decay after stalled improvement; call `step(metric=...)`. |
115
+ | `WarmupScheduler(...)` | Use to increase the learning rate linearly during a warmup phase. |
116
+ | `PiecewiseConstantSchedule(...)` | Use for step-wise transitions among explicitly configured constant rates. |
117
+ | `ChainedScheduler(...)` | Use to apply multiple scheduler transformations together. |
118
+ | `SequentialLR(...)` | Use to switch among schedulers at configured epoch milestones. |
119
+
120
+ ```python
121
+ scheduler = braintools.optim.StepLR(
122
+ base_lr=3e-3,
123
+ step_size=20,
124
+ gamma=0.5,
125
+ )
126
+ optimizer = braintools.optim.Adam(lr=scheduler)
127
+ optimizer.register_trainable_weights(params)
128
+
129
+ # After each epoch, outside the compiled step:
130
+ optimizer.lr.step()
131
+ current_lr = optimizer.lr.get_last_lr()
132
+ ```
133
+
134
+ For validation-driven scheduling, use the different call contract:
135
+
136
+ ```python
137
+ scheduler = braintools.optim.ReduceLROnPlateau(
138
+ base_lr=3e-3,
139
+ mode="min",
140
+ factor=0.5,
141
+ patience=5,
142
+ )
143
+ optimizer = braintools.optim.Adam(lr=scheduler)
144
+
145
+ # After validation:
146
+ scheduler.step(metric=float(validation_loss))
147
+ ```
148
+
149
+ Count scheduler calls explicitly. Stepping an epoch-configured schedule once per batch silently changes its effective timescale.
150
+
151
+ ## Standalone and forward-mode optimizers
152
+
153
+ These interfaces own more of the optimization operation than `update(grads)`:
154
+
155
+ | API | Description |
156
+ |---|---|
157
+ | `ScipyOptimizer(loss_fun, bounds, method=...)` | Use for a smooth bounded or constrained objective solved as one optimization problem; match sequence bounds to `loss_fun(*params)` or dict bounds to `loss_fun(**params)`, then call `minimize(n_iter=...)` to obtain a SciPy result whose `x` matches the bounds structure. |
158
+ | `NevergradOptimizer(batched_loss_fun, bounds, n_sample, ...)` | Use when gradients are unavailable or unreliable; accept candidate-stacked parameters, return one loss per candidate, and call `minimize(n_iter=...)` to obtain the best parameter structure. |
159
+ | `SOFO(model, loss_fn, ...)` | Use for a feed-forward model when sampled forward-mode second-order directions are required; register its `ParamState`s, then call `step(inputs, targets)` to compute and apply the direction and return the pre-update loss. |
160
+ | `SOFOScan(rnn_cell, loss_fn, ...)` | Use for a stateful one-step recurrent cell with `(latent, inputs) -> (new_latent, output)`; `step(inputs, targets)` propagates forward-mode tangents through the sequence and applies one update. |
161
+
162
+ `ScipyOptimizer` and `NevergradOptimizer` deliberately raise for the State-based register/update methods. Do not place either inside the canonical compiled minibatch train step.
163
+
164
+ When SciPy bounds carry BrainUnit quantities, the wrapper optimizes numeric mantissas and calls `loss_fun` without units; reconstruct any required physical quantities inside the objective. Nevergrad reattaches units to returned parameters when the corresponding bounds carry units. Apply either optimizer's returned parameters to model State explicitly.
165
+
166
+ For Nevergrad, total objective evaluations are approximately `n_iter * n_sample`. `budget=` configures Nevergrad's internal strategy but does not cap that outer evaluation count.
167
+
168
+ ## Routing and official sources
169
+
170
+ Open `references/brainstate/transformation-grad-expansion.md` for `argnums`, `grad_states`, gradient returns, and higher-order transforms; `references/brainstate/brainstate-control-flow-patterns.md` for BPTT loop choice and checkpointing through long rollouts; and `references/brainstate/parameter-constraints-regularization.md` when a trained parameter needs a valid-domain transform, penalty, or prior. Use `scripts/integrator_rnn.py` for a complete BrainState training script.
171
+
172
+ Official sources:
173
+
174
+ - `https://brainx.chaobrain.com/braintools/apis/optim.html`
175
+ - `https://brainx.chaobrain.com/braintools/optim/01_nevergrad_optimizer.html`
176
+ - `https://brainx.chaobrain.com/braintools/optim/02_scipy_optimizer.html`
177
+ - `https://brainx.chaobrain.com/braintools/optim/03_optax_getting_started.html`
178
+ - `https://brainx.chaobrain.com/braintools/optim/04_learning_rate_scheduling.html`
179
+ - `https://brainx.chaobrain.com/braintools/optim/05_advanced_optimizers.html`
@@ -0,0 +1,161 @@
1
+ ---
2
+ name: braintrace
3
+ description: BrainTrace relieves training-memory pressure in recurrent and spiking models by replacing BPTT's sequence-length-dependent graph with eligibility traces. Use this skill for memory-efficient temporal training, long sequences, BPTT out-of-memory problems, activation-memory reduction, and BrainTrace estimator selection or compilation. Do not use for general speed optimization, offline BPTT, or model dynamics.
4
+ ---
5
+
6
+ # BrainTrace
7
+
8
+ ## Purpose and boundary
9
+
10
+ Use BrainTrace when recurrent or spiking training is limited by BPTT memory. Its broad purpose is to relieve sequence-length memory pressure: it accumulates eligibility traces during the forward sequence instead of retaining the full trajectory for reverse-mode differentiation.
11
+
12
+ Online learning is the mechanism for this memory efficiency, not the routing goal. Memory becomes constant in sequence length, not constant in total: eligibility storage still depends on the batch size, participating parameters, hidden dimensions, and selected algorithm.
13
+
14
+ Follow this path:
15
+
16
+ `build with braintrace.nn -> choose a trace representation -> compile once -> inspect -> reset both State systems -> drive the sequence -> update -> verify`
17
+
18
+ Route general `State`, `Module`, transformations, and optimizer behavior to BrainState. Route neuron and synapse dynamics to BrainPy-State or BrainCell. Use ordinary BrainState training when offline BPTT is acceptable and eligibility traces are not required.
19
+
20
+ ## Underlying principle of BrainTrace
21
+
22
+ Hidden State represents the model's recurrent memory. It carries neural activity from one time step to the next.
23
+
24
+ ETP operations represent parameterized paths that need temporal credit. The operation marks participation: a parameter consumed by a BrainTrace ETP operation can receive an eligibility trace; the same parameter consumed only by an ordinary JAX operation cannot.
25
+
26
+ `ETraceGraph` represents the compiled relationship between ETP parameters and hidden-State groups. It tells the learner which parameter influences which recurrent state.
27
+
28
+ Eligibility State represents compressed gradient history. The selected algorithm updates it during each forward step, so training does not retain the unrolled sequence graph.
29
+
30
+ ## API structure overview
31
+
32
+ | API family | Responsibility |
33
+ |---|---|
34
+ | `braintrace.nn` | Prebuilt ETP-aware recurrent, linear, convolutional, sparse, and readout layers. Start here. |
35
+ | ETP operations | Mark parameterized operations in a custom layer for eligibility-trace participation. |
36
+ | `braintrace.compile()` | Discover hidden State and ETP parameter paths, build `ETraceGraph`, and return a learner. |
37
+ | `D_RTRL`, `pp_prop`, other algorithms | Define how eligibility State is represented and updated. |
38
+ | Compiled learner | Inspect compilation, reset eligibility State, execute sequences, and return online gradients. |
39
+
40
+ ## Choose the memory strategy and compile
41
+
42
+ Compile one representative time step once; the chosen algorithm determines the eligibility-memory shape and approximation.
43
+
44
+ | API | Description |
45
+ |---|---|
46
+ | `braintrace.nn.MiniGRU(...)` | Use for the canonical recurrent model; it carries hidden State and applies ETP-aware parameter operations. |
47
+ | `braintrace.nn.Linear(...)` | Use for an ETP-aware projection; the compiler treats it as non-temporal when its output does not return to hidden State. |
48
+ | `braintrace.D_RTRL` | Use as the default recurrent estimator when a parameter-shaped trace fits memory; it avoids BPTT activation storage but uses a diagonal hidden-recurrence approximation. |
49
+ | `braintrace.pp_prop` | Use when the parameter-shaped trace is too costly, especially for recurrent SNNs; it stores input/output factors and introduces a stronger factorization approximation. |
50
+ | `braintrace.compile(model, algorithm, example_step, batch_size=...)` | Use once with the real per-step shape; it initializes State, compiles parameter-to-hidden relations, and returns the learner. |
51
+ | `learner.report.show(1)` | Use immediately after compilation; it shows hidden groups, traced weights, excluded weights, and exclusion reasons. |
52
+ | `learner.show_graph()` | Use when the report needs structural confirmation; it displays the compiled parameter-to-hidden relationships. |
53
+
54
+ ```python
55
+ import brainstate
56
+ import braintrace
57
+ import jax.numpy as jnp
58
+
59
+ brainstate.random.seed(7)
60
+
61
+ class SequenceModel(brainstate.nn.Module):
62
+ def __init__(self):
63
+ super().__init__()
64
+ self.rnn = braintrace.nn.MiniGRU(in_size=1, out_size=6)
65
+ self.readout = braintrace.nn.Linear(6, 1)
66
+
67
+ def update(self, x):
68
+ return self.readout(self.rnn(x))
69
+
70
+ model = SequenceModel()
71
+ inputs = jnp.linspace(-1.0, 1.0, 12).reshape(12, 1, 1)
72
+ targets = 0.7 * inputs + 0.2
73
+
74
+ learner = braintrace.compile(
75
+ model, braintrace.D_RTRL, inputs[0], batch_size=1
76
+ )
77
+ learner.report.show(1)
78
+ learner.show_graph()
79
+ ```
80
+
81
+ Open `references/pre-built-braintrace-layer.md` when selecting another ETP-aware layer. Open `references/Drtrl.md` for D-RTRL memory, recurrence, and validation. Open `references/pp_pprop workflow.md` when parameter-shaped traces are too large or the model is a recurrent SNN. Open `references/algorithm selection.md` only when neither canonical choice fits.
82
+
83
+ ## Train and evaluate a sequence
84
+
85
+ Let the learner own the time loop and eligibility updates; reset recurrent State and eligibility State together at every independent sequence boundary.
86
+
87
+ | API | Description |
88
+ |---|---|
89
+ | `brainstate.nn.reset_all_states(model, batch_size=...)` | Use at an independent sequence boundary; it resets the model's recurrent State. |
90
+ | `learner.reset_state(batch_size=...)` | Use at the same boundary; it resets eligibility State and the learner's time index. |
91
+ | `learner.etrace_evolve(inputs, return_outputs=True)` | Use for loss-free execution or evaluation; it advances hidden and eligibility State and returns stacked outputs when requested. |
92
+ | `learner.etrace_grad(..., step_fn=..., reduction=...)` | Use for supervised online learning; it drives the sequence, accumulates per-step gradients, applies masking and reduction, and returns gradients. |
93
+ | `optimizer.update(grads)` | Use after one sequence gradient has been reduced; it updates the registered parameters. |
94
+
95
+ ```python
96
+ import braintools
97
+
98
+ weights = model.states(brainstate.ParamState)
99
+ optimizer = braintools.optim.SGD(lr=0.08)
100
+ optimizer.register_trainable_weights(weights)
101
+
102
+ def reset_sequence():
103
+ brainstate.nn.reset_all_states(model, batch_size=1)
104
+ learner.reset_state(batch_size=1)
105
+
106
+ def evaluate():
107
+ reset_sequence()
108
+ predictions = learner.etrace_evolve(inputs, return_outputs=True)
109
+ return jnp.mean((predictions - targets) ** 2)
110
+
111
+ def step_loss(x, target):
112
+ return jnp.mean((learner(x) - target) ** 2)
113
+
114
+ def train_epoch(_):
115
+ reset_sequence()
116
+ grads, step_losses = learner.etrace_grad(
117
+ inputs,
118
+ targets,
119
+ step_fn=step_loss,
120
+ reduction="mean",
121
+ return_value=True,
122
+ )
123
+ optimizer.update(grads)
124
+ return step_losses.mean()
125
+
126
+ initial_loss = evaluate()
127
+ losses = brainstate.transform.for_loop(train_epoch, jnp.arange(25))
128
+ final_loss = evaluate()
129
+
130
+ assert losses.shape == (25,)
131
+ assert final_loss < initial_loss
132
+ ```
133
+
134
+ Open `references/batching.md` before adding a batch axis or mapping wrapper; it identifies which API must own mapping. Do not wrap `etrace_grad()` or `etrace_evolve()` in another time scan, and make `step_fn` call the learner exactly once.
135
+
136
+ ## Reference routing
137
+
138
+ Escalate model construction from prebuilt layers to built-in ETP operations, then to a custom ETP primitive only when the previous level cannot express the computation.
139
+
140
+ | Reference | Open when | Contains |
141
+ |---|---|---|
142
+ | `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. |
143
+ | `references/Drtrl.md` | Using or validating parameter-shaped D-RTRL traces. | Memory scaling, recurrence, sequence resets, and the BPTT comparison boundary. |
144
+ | `references/pp_pprop workflow.md` | Parameter-shaped traces are too costly or a recurrent SNN needs factorized traces. | Input/output factorization, decay selection, SNN integration, and validation. |
145
+ | `references/algorithm selection.md` | Neither canonical memory strategy fits the estimator requirements. | Other built-in estimators, guarantees, configuration axes, and sequence-driver options. |
146
+ | `references/batching.md` | Adding a batch axis, mapped model, or multi-step wrapper. | Mapping ownership, batched compilation, State layout, and sequence-data wrappers. |
147
+ | `references/ETP operators.md` | A prebuilt layer cannot express the required parameterized operation. | Built-in ETP operations, participation rules, units, and transform behavior. |
148
+ | `references/custom ETP primitives.md` | No built-in ETP operation can express the computation. | Primitive registration, ETP rules, compiler integration, and validation. |
149
+ | `references/customizing_primitive_transforms.md` | An ETP weight needs masking, constraints, normalization, LoRA, or a bias transform. | Transform hooks and raw-parameter gradient attachment. |
150
+ | `references/custom algorithms.md` | No built-in algorithm or `ETraceConfig` expresses the research method. | Estimator bases, trace lifecycle, solve hooks, and inspection. |
151
+ | `references/compiler_internal.md` | `learner.report` and `learner.graph` cannot explain custom graph behavior. | Discovery, graph execution, control-flow policy, and low-level diagnostics. |
152
+
153
+ ## Boundaries and common failures
154
+
155
+ - Do not describe BrainTrace as constant-total-memory training. Its memory is constant only in sequence length; trace storage still scales with the selected estimator and model.
156
+ - Do not claim that an online estimator equals BPTT unless its documented mathematical regime and a reduced gradient-oracle comparison establish that result.
157
+ - Do not compile inside training or compile from a full sequence; pass one representative time step with the real batch and feature shape.
158
+ - Do not treat every excluded weight as an error. A readout that does not feed hidden State is correctly reported as non-temporal and still receives instantaneous gradients.
159
+ - Reset both recurrent State and eligibility State between independent sequences.
160
+ - Use exactly one batching owner; do not map an already mapped model again in `braintrace.compile()`.
161
+ - Use `pp_prop` in new code; `ES_D_RTRL` is its compatibility alias.