brainx-skill 1.0.10 → 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 +20 -2
  52. package/skills/brainx-install/SKILL.md +24 -21
  53. package/skills/brainstate/agents/openai.yaml +0 -4
@@ -0,0 +1,179 @@
1
+ # D-RTRL
2
+
3
+ Use this reference when implementing or validating the canonical
4
+ parameter-dimensional D-RTRL workflow, including sequence resets, online
5
+ gradient accumulation, and comparison with BPTT. Open `algorithm selection.md`
6
+ when deciding among estimators and `batching.md` before adding a batch axis.
7
+
8
+ ## Understand the approximation
9
+
10
+ `D_RTRL` carries parameter-dimensional eligibility traces forward while its
11
+ default diagonal recurrence drops cross-hidden terms from the
12
+ hidden-to-hidden Jacobian.
13
+
14
+ | API | Description |
15
+ |---|---|
16
+ | `braintrace.D_RTRL` | Use when parameter-shaped trace memory is feasible. It computes approximate gradients during the forward sequence without retaining the full unrolled graph. |
17
+ | `braintrace.compile(model, braintrace.D_RTRL, example_input, ...)` | Use as the normal one-call setup. It constructs the learner and compiles its ETP graph from the representative step. |
18
+ | `learner.etrace_evolve(inputs, return_outputs=...)` | Use for evaluation or a loss-free prefix. It advances hidden and eligibility State without accumulating a loss gradient. |
19
+ | `learner.etrace_grad(inputs, *targets, step_fn=..., ...)` | Use for online sequence gradients. It owns the temporal loop, accumulation, masking, and reduction. |
20
+
21
+ Trace memory scales as `O(B * |theta|)`, where `B` is batch size and `theta` is
22
+ the participating parameter set. Wide recurrent layers can therefore be
23
+ memory-intensive even though memory does not grow with sequence length.
24
+
25
+ **Guarantee:** Do not describe D-RTRL as generally identical to BPTT. Equality
26
+ depends on the configured recurrence, VJP path, and mathematical regime being
27
+ tested.
28
+
29
+ ## Follow the sequence lifecycle
30
+
31
+ Reset recurrent and eligibility State together at each independent sequence;
32
+ then let the learner drive the complete sequence and update parameters once.
33
+
34
+ | Step | Action | Important result |
35
+ |---|---|---|
36
+ | 1. Build | Compose ETP-aware recurrent and readout layers. | Participating parameter-to-hidden paths remain visible to the compiler. |
37
+ | 2. Compile | Call `braintrace.compile(...)` once with a representative input. | The learner reuses one compiled ETP graph across training epochs. |
38
+ | 3. Register | Give the optimizer the model's trainable `ParamState` collection. | Gradient keys and optimizer weights refer to the same State objects. |
39
+ | 4. Reset | Call `brainstate.nn.reset_all_states(...)` and `learner.reset_state(...)`. | Hidden State, eligibility traces, and the learner's running index start at the same boundary. |
40
+ | 5. Drive | Define a local loss that calls the learner exactly once, then call `etrace_grad()`. | The learner accumulates per-step online gradients. |
41
+ | 6. Update | Apply the returned gradients and verify descent on a deterministic task. | A lower loss checks training mechanics, not BPTT equivalence. |
42
+
43
+ ## Train a deterministic MiniGRU
44
+
45
+ Use the same small model and affine sequence task as the official pp-prop
46
+ walkthrough when comparing estimators; changing only the algorithm isolates the
47
+ trace rule.
48
+
49
+ ```python
50
+ import brainstate
51
+ import braintools
52
+ import braintrace
53
+ import jax.numpy as jnp
54
+
55
+ brainstate.random.seed(7)
56
+
57
+
58
+ class SequenceModel(brainstate.nn.Module):
59
+ def __init__(self):
60
+ super().__init__()
61
+ self.rnn = braintrace.nn.MiniGRU(in_size=1, out_size=6)
62
+ self.readout = braintrace.nn.Linear(6, 1)
63
+
64
+ def update(self, x):
65
+ return self.readout(self.rnn(x))
66
+
67
+
68
+ model = SequenceModel()
69
+ inputs = jnp.linspace(-1.0, 1.0, 12).reshape(12, 1, 1)
70
+ targets = 0.7 * inputs + 0.2
71
+
72
+ learner = braintrace.compile(
73
+ model,
74
+ braintrace.D_RTRL,
75
+ inputs[0],
76
+ batch_size=1,
77
+ )
78
+
79
+ weights = model.states(brainstate.ParamState)
80
+ optimizer = braintools.optim.SGD(lr=0.08)
81
+ optimizer.register_trainable_weights(weights)
82
+
83
+
84
+ def reset_sequence():
85
+ brainstate.nn.reset_all_states(model, batch_size=1)
86
+ learner.reset_state(batch_size=1)
87
+
88
+
89
+ def evaluate():
90
+ reset_sequence()
91
+ predictions = learner.etrace_evolve(inputs, return_outputs=True)
92
+ return jnp.mean((predictions - targets) ** 2)
93
+
94
+
95
+ def local_loss(x, target):
96
+ prediction = learner(x)
97
+ return jnp.mean((prediction - target) ** 2)
98
+
99
+
100
+ def train_epoch(_):
101
+ reset_sequence()
102
+ grads, step_losses = learner.etrace_grad(
103
+ inputs,
104
+ targets,
105
+ step_fn=local_loss,
106
+ reduction='mean',
107
+ return_value=True,
108
+ )
109
+ optimizer.update(grads)
110
+ return step_losses.mean()
111
+
112
+
113
+ initial_loss = evaluate()
114
+ training_losses = brainstate.transform.for_loop(
115
+ train_epoch,
116
+ jnp.arange(25),
117
+ )
118
+ final_loss = evaluate()
119
+
120
+ assert final_loss < initial_loss
121
+ ```
122
+
123
+ `reduction='mean'` divides by the total mask weight, which is the number of
124
+ steps when no mask is supplied. `local_loss` must call `learner` exactly once;
125
+ `etrace_grad()` owns every other part of the sequence loop.
126
+
127
+ ## Reset both State domains
128
+
129
+ The model and learner carry different temporal information, so resetting only
130
+ one invalidates independent-sequence comparisons.
131
+
132
+ | API | State reset |
133
+ |---|---|
134
+ | `brainstate.nn.reset_all_states(model, batch_size=1)` | Resets the MiniGRU hidden State. |
135
+ | `learner.reset_state(batch_size=1)` | Resets eligibility traces and the learner's running index. |
136
+
137
+ Consecutive `etrace_evolve()` or `etrace_grad()` calls otherwise continue from
138
+ the currently installed State. Preserve that continuation only when the calls
139
+ belong to one trajectory.
140
+
141
+ ## Interpret compiler participation
142
+
143
+ A parameter participates in temporal learning only when an ETP primitive marks
144
+ its path to hidden State.
145
+
146
+ | Situation | Interpretation |
147
+ |---|---|
148
+ | Recurrent weight reaches hidden State through an ETP primitive. | The compiler records a temporal relation and D-RTRL carries its eligibility trace. |
149
+ | Readout does not feed hidden State. | The parameter remains trainable but is correctly reported as non-temporal; its instantaneous gradient does not require a recurrent trace. |
150
+ | A weight reaches hidden State only through another trainable ETP weight. | The compiler excludes the upstream weight under the non-parametric-tail invariant to prevent double counting. |
151
+
152
+ Open `ETP operators.md` when a custom layer's parameter is unexpectedly absent.
153
+ Treat a documented non-temporal or excluded relation as a diagnostic, not an
154
+ optimizer failure.
155
+
156
+ ## Keep the BPTT boundary explicit
157
+
158
+ | Property | D-RTRL | BPTT |
159
+ |---|---|---|
160
+ | Gradient timing | Updates eligibility information during the forward sequence. | Backpropagates after unrolling the sequence. |
161
+ | Sequence storage | Does not retain the full unrolled graph. | Stores intermediate activations, so memory grows with sequence length. |
162
+ | Gradient claim | Uses the configured diagonal recurrence and VJP approximations. | Provides the full-sequence baseline for a matched model and loss. |
163
+
164
+ Use a reduced matched task as a BPTT oracle only when the estimator's
165
+ mathematical regime predicts equality. A descending D-RTRL loss verifies the
166
+ workflow but does not establish gradient equality.
167
+
168
+ For explicit `brainstate.nn.Map` setup, compile directly with
169
+ `braintrace.D_RTRL(mapped_model).compile_graph(batched_step)` and follow
170
+ `batching.md`; never map an already mapped model again with `vmap=True`.
171
+
172
+ ## Sources
173
+
174
+ - [RNN Online Learning](https://brainx.chaobrain.com/braintrace/tutorials/rnn_online_learning.html)
175
+ - [D-RTRL: diagonal online gradient learning](https://brainx.chaobrain.com/braintrace/tutorials/drtrl.html)
176
+
177
+ The lifecycle, approximation boundary, examples, and diagnostics above are
178
+ trimmed and reorganized from the official pages without changing their API
179
+ names or guarantees.
@@ -0,0 +1,161 @@
1
+ # ETP operators
2
+
3
+ Use this reference when prebuilt `braintrace.nn` layers cannot express a custom
4
+ layer or model and its trainable operations must participate in eligibility
5
+ trace propagation. Use only the built-in operators here; open
6
+ `custom ETP primitives.md` when none can express the computation.
7
+
8
+ ## Control parameter participation
9
+
10
+ ETP participation is selected by the operation that consumes a parameter, not
11
+ by a special parameter class.
12
+
13
+ | Operation path | Result |
14
+ |---|---|
15
+ | A `brainstate.ParamState` value is consumed by a `braintrace.*` ETP operator. | The compiler can include that parameter in eligibility-trace computation. |
16
+ | A `brainstate.ParamState` value is consumed only by an ordinary JAX operation. | The parameter is automatically excluded from ETP participation. |
17
+
18
+ ```python
19
+ import jax
20
+ import jax.numpy as jnp
21
+ import brainstate
22
+ import braintrace
23
+
24
+
25
+ class MyRNN(brainstate.nn.Module):
26
+ def __init__(self):
27
+ super().__init__()
28
+ self.w_rec = brainstate.ParamState(jnp.eye(4))
29
+ self.w_in = brainstate.ParamState(jnp.ones((3, 4)))
30
+ self.h = brainstate.ShortTermState(jnp.zeros(4))
31
+
32
+ def update(self, x):
33
+ # Ordinary matmul: w_in remains trainable but is excluded from ETP.
34
+ input_drive = x @ self.w_in.value
35
+
36
+ # ETP matmul: w_rec participates in eligibility traces.
37
+ recurrent_drive = braintrace.matmul(
38
+ self.h.value,
39
+ self.w_rec.value,
40
+ )
41
+ self.h.value = jax.nn.tanh(input_drive + recurrent_drive)
42
+ return self.h.value
43
+ ```
44
+
45
+ **Participation invariant:** Every `brainstate.ParamState` is eligible, but
46
+ only an ETP primitive marks its operation for online learning. Changing the
47
+ parameter subclass does not include or exclude it.
48
+
49
+ ## Choose an operator
50
+
51
+ Choose the operator that matches the parameterized computation; do not replace
52
+ a direct built-in operator with a custom primitive.
53
+
54
+ | API | Use and behavior |
55
+ |---|---|
56
+ | `braintrace.matmul(x, weight, bias=None)` | Use for dense matrix multiplication. It dispatches to batched or unbatched primitives from `x.ndim`. |
57
+ | `braintrace.grouped_matmul(...)` | Use for grouped or block-diagonal matrix multiplication. |
58
+ | `braintrace.embedding(...)` | Use for an ETP-aware embedding lookup whose gather weight is trainable. |
59
+ | `braintrace.einsum(...)` | Use for a two-operand Einstein contraction that is linear in the trainable weight. |
60
+ | `braintrace.element_wise(weight, *, weight_fn=None)` | Use for diagonal element-wise parameter operations such as gates, time constants, or thresholds. `weight_fn=None` is identity; otherwise provide a JAX-differentiable transform. |
61
+ | `braintrace.conv(x, kernel, bias=None, *, strides, padding, ...)` | Use for convolution through `jax.lax.conv_general_dilated` options. The input must include a batch dimension. |
62
+ | `braintrace.sparse_matmul(x, weight_data, *, sparse_mat, bias=None)` | Use when connectivity structure is sparse. `sparse_mat` supplies indices and `weight_data` contains the trainable nonzero values. |
63
+ | `braintrace.lora_matmul(x, B, A, *, alpha=1.0, bias=None)` | Use for a low-rank update with `B` shaped `(in, rank)` and `A` shaped `(rank, out)`. Only the low-rank factors are trained. |
64
+
65
+ `element_wise` is the only listed primitive whose compiler registration has
66
+ `gradient_enabled=True`. The compiler descends through it while walking from
67
+ output to hidden State, so it does not form a tail boundary for upstream ETP
68
+ weights.
69
+
70
+ ## Respect dispatch and shape contracts
71
+
72
+ Use a direct batched operator when the model already has a batch axis; this
73
+ keeps the primitive visible and its shape rule explicit.
74
+
75
+ ```python
76
+ import jax.numpy as jnp
77
+ import braintrace
78
+
79
+ weight = jnp.ones((3, 5))
80
+
81
+ single_output = braintrace.matmul(jnp.ones(3), weight)
82
+ batched_output = braintrace.matmul(jnp.ones((4, 3)), weight)
83
+
84
+ assert single_output.shape == (5,)
85
+ assert batched_output.shape == (4, 5)
86
+
87
+ kernel = jnp.ones((4, 3, 8))
88
+ conv_output = braintrace.conv(
89
+ jnp.ones((2, 16, 3)),
90
+ kernel,
91
+ strides=(1,),
92
+ padding='SAME',
93
+ dimension_numbers=('NWC', 'WIO', 'NWC'),
94
+ )
95
+ assert conv_output.shape == (2, 16, 8)
96
+ ```
97
+
98
+ `matmul` uses its unbatched primitive when `x.ndim == 1` and its batched
99
+ primitive when `x.ndim >= 2`. `conv` is the critical exception: always supply a
100
+ batch dimension.
101
+
102
+ For sparse multiplication, pass a `brainevent.DataRepresentation` such as
103
+ `brainevent.CSR` as `sparse_mat`; its `data` contains the trainable nonzero
104
+ weights.
105
+
106
+ ## Preserve physical units
107
+
108
+ Every user-facing ETP operator accepts `brainunit.Quantity` inputs by separating
109
+ mantissas and units for primitive execution and recombining the result.
110
+
111
+ ```python
112
+ import brainunit as u
113
+
114
+ x = jnp.ones((4, 3)) * u.volt
115
+ weight = jnp.ones((3, 5)) * u.siemens
116
+ bias = jnp.zeros(5) * u.amp
117
+
118
+ output = braintrace.matmul(x, weight, bias=bias)
119
+ assert u.get_unit(output) == u.amp
120
+ ```
121
+
122
+ **Unit invariant:** A bias must be dimensionally compatible with the combined
123
+ input and weight unit. Do not strip units to bypass that check.
124
+
125
+ ## Preserve compiler recognition under JAX transforms
126
+
127
+ ETP operators support `jax.jit`, `jax.grad`, `jax.vmap`, and `jax.jvp` for
128
+ ordinary numerical transformation.
129
+
130
+ | Transform | Supported result |
131
+ |---|---|
132
+ | `jax.jit(...)` | Compiles the numerical operator. |
133
+ | `jax.grad(...)` | Differentiates with respect to operator arguments. |
134
+ | `jax.vmap(...)` | Maps the numerical operator over an added axis. |
135
+ | `jax.jvp(...)` | Produces primal and forward-mode tangent outputs. |
136
+
137
+ **Compiler invariant:** Numerical compatibility does not guarantee that the ETP
138
+ compiler still recognizes the marker. A transform can decompose it into
139
+ ordinary JAX operations. Inspect the compiled ETP graph and prefer the direct
140
+ batched BrainTrace operator when recognition matters.
141
+
142
+ ## Diagnose operator failures
143
+
144
+ | Exception | Meaning |
145
+ |---|---|
146
+ | `CompilationError` | Compilation failed while discovering or constructing the ETP graph. |
147
+ | `NotSupportedError` | The requested operation or composition is unsupported. |
148
+
149
+ Open `pre-built-braintrace-layer.md` before hand-building a common layer. Open
150
+ `customizing_primitive_transforms.md` when a weight reparameterization needs
151
+ trace-aware transform hooks. Open `custom ETP primitives.md` only when the
152
+ built-in operator set cannot represent the computation.
153
+
154
+ ## Sources
155
+
156
+ - [ETP Operators & Core Types](https://brainx.chaobrain.com/braintrace/apis/concepts.html)
157
+ - [Operators for Online Learning](https://brainx.chaobrain.com/braintrace/tutorials/five_primitive_functions.html)
158
+
159
+ The participation rules, operator behaviors, shape examples, unit contract,
160
+ and transform warning above are trimmed and reorganized from the official
161
+ pages without changing their API names.
@@ -0,0 +1,120 @@
1
+ # Algorithm selection
2
+
3
+ Use this reference when choosing a BrainTrace estimator beyond the default
4
+ `D_RTRL`, expressing a learning rule with `ETraceConfig`, or selecting sequence
5
+ driver options. Use `Drtrl.md` or `pp_pprop workflow.md` for estimator-specific
6
+ training workflows; use `custom algorithms.md` only when no built-in rule or
7
+ configuration expresses the method.
8
+
9
+ ## Choose an estimator
10
+
11
+ Choose by trace representation, recurrence approximation, learning signal, and
12
+ the mathematical regime in which the estimator is valid.
13
+
14
+ | API | Use when | Essential behavior and constraint |
15
+ |---|---|---|
16
+ | `D_RTRL` | Use as the general-purpose RNN default when parameter-dimensional trace memory fits. | Uses a diagonal hidden-to-hidden Jacobian approximation. Memory is `O(B * |theta|)` and computation is `O(B * I * O)`; it is not generally gradient-equivalent to BPTT outside that approximation's assumptions. |
17
+ | `pp_prop` | Use when parameter-dimensional traces are too large, especially for large or memory-constrained SNNs. | Factorizes each eligibility trace into input and output components with exponential smoothing. Memory is `O(B * (I + O))`; an integer `decay_or_rank` controls decay and does not allocate multiple rank factors. Prefer this name over its historical alias, `ES_D_RTRL`. |
18
+ | `SnAp` | Use when the recurrent position graph is structurally sparse over the requested `n`-step neighborhood. | Retains recurrent influence entries reachable within that neighborhood. Dense recurrence saturates the neighborhood immediately and removes the method's structural advantage. |
19
+ | `UORO` | Use when an unbiased RTRL-trace estimate is required and projection variance is acceptable. | Carries a rank-one random projection of the full recurrent Jacobian, trading variance for linear carrier storage. |
20
+ | `ThreeFactor` | Use for reward-modulated learning with a user-supplied modulatory signal. | Replaces the symmetric hidden-state learning signal with that external signal. |
21
+ | `DNI` | Use to carry credit across finite online windows with learned synthetic gradients. | Uses `SyntheticGradient` as a per-hidden-group predictor; update it with `train_synthetic_gradient()`. |
22
+ | `EProp` | Use for recurrent SNNs that need kappa-filtered traces or fixed random-feedback learning signals. | Implements eligibility propagation with optional kappa filtering and random feedback. |
23
+ | `OSTLRecurrent` | Use for the OSTL with-H recurrent regime. | Keeps the recurrent Jacobian and is RTRL-exact only for block-diagonal hidden-to-hidden Jacobians. |
24
+ | `OSTLFeedforward` | Use for the OSTL without-H feedforward regime. | Drops the recurrent Jacobian and uses the input/output-factorized trace path. |
25
+
26
+ **Correctness invariant:** Treat estimator guarantees as part of algorithm
27
+ selection. Exact rules must match a BPTT oracle element-wise; approximate rules
28
+ match BPTT only in the mathematical regime documented for that rule.
29
+
30
+ ## Configure rule coordinates
31
+
32
+ Named algorithms are presets in a shared rule space; use `ETraceConfig` when
33
+ the required coordinate combination has no preset name.
34
+
35
+ | Axis | Values and selection rule |
36
+ |---|---|
37
+ | `trace_factorization` | Use `'per_param'` for parameter-dimensional traces or `'io_factorized'` for `O(I + O)` factorized traces. |
38
+ | `temporal_recursion` | Choose `'jacobian'`, `'scalar_leak'`, or `'none'`; under `'io_factorized'`, provide the `(x, f)` pair when the two sides differ. |
39
+ | `recurrence_scope` | Choose `'diagonal'` or `'coupled'`; `SnAp` uses `'sparse_n'` with `sparse_n=n`. |
40
+ | `learning_signal` | Use `'symmetric'` for the normal signal or `'random_feedback'` for fixed random feedback. |
41
+ | `trace_filter` | Use `'none'` normally or `'kappa'` for kappa-filtered traces. |
42
+ | `update_schedule` | Use the supported `'per_step'` schedule. |
43
+
44
+ The named presets occupy these coordinates:
45
+
46
+ | Preset | Non-default coordinates |
47
+ |---|---|
48
+ | `D_RTRL` | Default coordinate. |
49
+ | `pp_prop` / `ES_D_RTRL` | `trace_factorization='io_factorized'`, `decay=<decay_or_rank>`. |
50
+ | `EProp` | `trace_filter='kappa'`, `kappa=<kappa_filter_decay>`; with `feedback='random'`, also `learning_signal='random_feedback'`. |
51
+ | `OSTLRecurrent` | `recurrence_scope='coupled'`. |
52
+ | `OSTLFeedforward` | `trace_factorization='io_factorized'`, with `decay=1e-6` by default. |
53
+ | `SnAp` | `recurrence_scope='sparse_n'`, `sparse_n=n`. |
54
+
55
+ ```python
56
+ # Use different temporal recursion on the input and output sides.
57
+ learner = braintrace.compile(
58
+ model,
59
+ braintrace.ETraceConfig(
60
+ trace_factorization='io_factorized',
61
+ temporal_recursion=('scalar_leak', 'none'),
62
+ decay=(0.9, 0.0),
63
+ ),
64
+ x0,
65
+ )
66
+ ```
67
+
68
+ **Configuration invariant:** Construction rejects illegal coordinate
69
+ combinations and names the legal pairings. It also canonicalizes equivalent
70
+ rules; for example, zero decay collapses to `temporal_recursion='none'`.
71
+
72
+ ## Drive a sequence
73
+
74
+ Compile once, then let the learner own temporal iteration, State continuation,
75
+ loss masking, and gradient accumulation.
76
+
77
+ | API | Description |
78
+ |---|---|
79
+ | `braintrace.compile(model, algorithm, example_input, ...)` | Use as the one-call entry point. It constructs the selected algorithm, eagerly compiles its eligibility-trace graph from the example input, and returns the ready-to-run learner. |
80
+ | `learner.etrace_evolve(inputs, ...)` | Use for a loss-free prefix or other forward-only interval. It advances both hidden and eligibility State and leaves the final State installed. |
81
+ | `learner.etrace_grad(inputs, *step_args, step_fn=..., ...)` | Use for a training interval. It owns the temporal loop, calls `step_fn` once per step or chunk, accumulates online gradients, and optionally returns per-step values. |
82
+
83
+ ```python
84
+ learner = braintrace.compile(model, 'd_rtrl', inputs[0], batch_size=1)
85
+
86
+ def step_loss(inp, target):
87
+ prediction = learner(inp)
88
+ return braintools.metric.squared_error(prediction, target).mean()
89
+
90
+ # Advance a loss-free prefix without resetting the trajectory.
91
+ learner.etrace_evolve(inputs[:n_warmup])
92
+
93
+ grads, step_losses = learner.etrace_grad(
94
+ inputs[n_warmup:],
95
+ targets[n_warmup:],
96
+ step_fn=step_loss,
97
+ return_value=True,
98
+ )
99
+ ```
100
+
101
+ `step_fn` owns the learner call and must call `learner` exactly once per
102
+ invocation. Both drivers are continuations: they leave final State installed,
103
+ so consecutive calls compose into one trajectory and neither call implies a
104
+ reset.
105
+
106
+ | Driver option | Use and effect |
107
+ |---|---|
108
+ | `mask=...` | Use to gate loss contributions. The learner still runs at every step, so a zero-weighted prefix is equivalent to calling `etrace_evolve()` over that prefix. |
109
+ | `chunk_size=1` | Use for the normal single-step path. |
110
+ | `chunk_size=k` with `k >= 2` | Use when `step_fn` consumes `(k, ...)` windows. Set `vjp_method='multi-step'`. |
111
+ | `braintrace.compile(..., vmap=True)` | Use when compilation should own batch mapping. Call `etrace_grad()` and `etrace_evolve()` on the returned wrapper, not on `learner.module`, or the mapped lanes are bypassed. |
112
+
113
+ Open `batching.md` before adding a batch axis. Open `custom algorithms.md` when
114
+ the six configuration axes cannot express the research method.
115
+
116
+ ## Source
117
+
118
+ [Online-Learning Algorithms](https://brainx.chaobrain.com/braintrace/apis/algorithms.html).
119
+ The selection rules, coordinate values, examples, and invariants above are
120
+ condensed from the official page's prose, API tables, and code blocks.
@@ -0,0 +1,150 @@
1
+ # Batching
2
+
3
+ Use this reference when adding a batch axis to BrainTrace online learning,
4
+ choosing which API owns mapping, compiling from a batched example, or wrapping
5
+ single-step and multi-step inputs. Keep model update logic single-sample and
6
+ assign batch mapping to exactly one API.
7
+
8
+ ## Choose one mapping owner
9
+
10
+ Map-based batching keeps parameters shared while giving each batch lane an
11
+ independent copy of recurrent State.
12
+
13
+ | Path | Use when | Mapping owner |
14
+ |---|---|---|
15
+ | Explicit map | Use for the recommended path when mapping and State initialization must be visible. | Create one `brainstate.nn.Map`; construct the algorithm around it directly. |
16
+ | Compile-owned map | Use when the one-call compiler should create the wrapper. | Pass an unmapped model to `braintrace.compile(..., vmap=True)`. |
17
+ | Single stream | Use for one stream or step-by-step debugging. | Use an unmapped model and unbatched example; no API owns a batch transformation. |
18
+
19
+ **Mapping invariant:** Use exactly one mapping owner. Never pass an existing
20
+ `brainstate.nn.Map` to `braintrace.compile(..., vmap=True)` because that maps
21
+ the model twice.
22
+
23
+ ## Map and compile a batch
24
+
25
+ Create and initialize one `Map`, construct the algorithm with that mapped
26
+ model, then compile from one complete batched time step.
27
+
28
+ | API | Description |
29
+ |---|---|
30
+ | `brainstate.nn.Map(model, init_map_size=B)` | Use to replicate mutable model State across `B` lanes while sharing parameter State. |
31
+ | `mapped_model.init_all_states()` | Use before algorithm construction to initialize the independent recurrent State copies. |
32
+ | `braintrace.D_RTRL(mapped_model)` | Use to construct the selected algorithm directly around an explicitly mapped model. |
33
+ | `mapped_algo.compile_graph(example_input)` | Use once with an example shaped `(batch_size, n_in)` so the batch axis remains inside the compiled ETP graph. |
34
+
35
+ ```python
36
+ import jax.numpy as jnp
37
+ import brainstate
38
+ import braintrace
39
+
40
+
41
+ class SimpleGRU(brainstate.nn.Module):
42
+ def __init__(self, n_in, n_rec, n_out):
43
+ super().__init__()
44
+ self.rnn = braintrace.nn.GRUCell(n_in, n_rec)
45
+ self.out = braintrace.nn.Linear(n_rec, n_out)
46
+
47
+ def update(self, x):
48
+ return self.out(self.rnn(x))
49
+
50
+
51
+ model = SimpleGRU(10, 64, 5)
52
+ batch_size = 16
53
+ example_input = jnp.zeros((batch_size, 10))
54
+
55
+ mapped_model = brainstate.nn.Map(model, init_map_size=batch_size)
56
+ mapped_model.init_all_states()
57
+
58
+ mapped_algo = braintrace.D_RTRL(mapped_model)
59
+ mapped_algo.compile_graph(example_input)
60
+ ```
61
+
62
+ The mapped learner applies the wrapped single-sample update over axis 0. Its
63
+ parameters remain shared and its recurrent State remains independent across
64
+ lanes; an input shaped `(16, 10)` produces an output shaped `(16, 5)` for this
65
+ model.
66
+
67
+ ## Train over time-major batches
68
+
69
+ Keep time on axis 0 and the batch on axis 1, then let the learner's sequence
70
+ driver own the temporal scan and gradient accumulation.
71
+
72
+ | API | Description |
73
+ |---|---|
74
+ | `mapped_algo.etrace_grad(inputs, ..., step_fn=..., reduction=...)` | Use for online gradients over time-major input. It calls `step_fn` across axis 0 and returns gradient keys matching `mapped_algo.param_states`. |
75
+ | `mapped_algo.etrace_evolve(inputs, ...)` | Use for loss-free sequence evolution. It advances every mapped lane without accumulating a loss gradient. |
76
+ | `reduction='sum'` | Use when accumulated per-step gradients must not be divided by the number of steps. |
77
+
78
+ ```python
79
+ @brainstate.transform.jit
80
+ def train_step(inputs, targets):
81
+ """inputs: (n_steps, batch_size, n_in); targets: (batch_size, n_out)."""
82
+ def step_loss(inp):
83
+ prediction = mapped_algo(inp)
84
+ return jnp.mean((prediction - targets) ** 2)
85
+
86
+ return mapped_algo.etrace_grad(
87
+ inputs,
88
+ step_fn=step_loss,
89
+ reduction='sum',
90
+ )
91
+
92
+
93
+ inputs = jnp.ones((20, 16, 10))
94
+ targets = jnp.zeros((16, 5))
95
+ grads = train_step(inputs, targets)
96
+ # Register mapped_algo.param_states with the optimizer that consumes grads.
97
+ ```
98
+
99
+ `step_fn` must call `mapped_algo` exactly once. Call `etrace_grad()` and
100
+ `etrace_evolve()` on the mapped learner itself; accessing a wrapped `.module`
101
+ bypasses mapped lanes.
102
+
103
+ ## Use single-sample mode
104
+
105
+ Use an unbatched model when processing one stream or diagnosing a single step;
106
+ do not create a `Map` or request `vmap`.
107
+
108
+ ```python
109
+ single_model = SimpleGRU(10, 64, 5)
110
+ single_algo = braintrace.compile(
111
+ single_model,
112
+ braintrace.D_RTRL,
113
+ jnp.zeros(10),
114
+ )
115
+
116
+ output = single_algo(jnp.ones(10))
117
+ assert output.shape == (5,)
118
+ ```
119
+
120
+ Omitting `batch_size` keeps model State unbatched and the example input contains
121
+ only the feature axis.
122
+
123
+ ## Wrap temporal data
124
+
125
+ Use data wrappers to distinguish one forward step from an input whose first
126
+ axis is time.
127
+
128
+ | API | Description |
129
+ |---|---|
130
+ | `braintrace.SingleStepData(data)` | Use to mark `data` as one forward step. A plain array has the same single-step interpretation. |
131
+ | `braintrace.MultiStepData(sequence)` | Use to mark axis 0 as time. The algorithm scans that axis internally instead of treating the complete sequence as one step. |
132
+
133
+ ```python
134
+ one_step = braintrace.SingleStepData(jnp.ones(10))
135
+ many_steps = braintrace.MultiStepData(jnp.ones((20, 10)))
136
+ ```
137
+
138
+ For mapped data, preserve the same axis meaning: a complete time-major sequence
139
+ has shape `(n_steps, batch_size, n_in)`, and each compiled step has shape
140
+ `(batch_size, n_in)`.
141
+
142
+ Open `algorithm selection.md` when batching cost changes the estimator choice.
143
+ Open `Drtrl.md` or `pp_pprop workflow.md` for estimator-specific State reset and
144
+ training behavior.
145
+
146
+ ## Source
147
+
148
+ [Batching Strategies](https://brainx.chaobrain.com/braintrace/advanced/batching.html).
149
+ The ownership rules, workflows, shapes, and wrapper behavior above are
150
+ condensed from the official page's prose and code blocks.