brainx-skill 1.0.10 → 1.0.12
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 +6 -0
- package/adapters/antigravity.js +8 -0
- package/installation/lib/installer.js +60 -20
- package/installation/lib/paths.js +41 -3
- package/installation/lib/prompts.js +13 -7
- package/manifest.json +2 -1
- package/package.json +3 -2
- package/skills/braincell/SKILL.md +1 -1
- package/skills/braincell/references/mixions-for-adaptation.md +26 -3
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +113 -53
- package/skills/brainevent/references/synaptic-plasticity.md +74 -230
- package/skills/brainmass/SKILL.md +11 -6
- package/skills/brainmass/references/batch-transform-acceleration.md +44 -3
- package/skills/brainmass/references/modellibrary.md +11 -0
- package/skills/brainmass/references/simulator-input-monitor-api.md +98 -0
- package/skills/brainpy-state/SKILL.md +20 -6
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +52 -1
- package/skills/brainpy-state/references/brainPy(legacy)/analysis.md +150 -0
- package/skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +373 -0
- package/skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +150 -0
- package/skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +175 -0
- package/skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +286 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +111 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +163 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +113 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +136 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +222 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +123 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +107 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +185 -0
- package/skills/brainpy-state/references/brainPy(legacy)/integrators.md +181 -0
- package/skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +102 -0
- package/skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +147 -0
- package/skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +159 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +127 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +167 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +107 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +186 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +104 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +89 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +253 -0
- package/skills/brainpy-state/references/braintools/connectivity.md +206 -0
- package/skills/brainpy-state/references/braintools/input-current.md +199 -0
- package/skills/brainpy-state/references/component-selection.md +20 -5
- package/skills/brainpy-state/references/projection-patterns.md +2 -0
- package/skills/brainpy-state/references/scripts/sound_localization.py +240 -0
- package/skills/brainstate/SKILL.md +1 -1
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +8 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +57 -7
- package/skills/brainstate/references/collective_model_operations.md +26 -27
- package/skills/braintrace/SKILL.md +161 -0
- package/skills/braintrace/references/Drtrl.md +179 -0
- package/skills/braintrace/references/ETP operators.md +161 -0
- package/skills/braintrace/references/algorithm selection.md +120 -0
- package/skills/braintrace/references/batching.md +150 -0
- package/skills/braintrace/references/compiler_internal.md +162 -0
- package/skills/braintrace/references/custom ETP primitives.md +200 -0
- package/skills/braintrace/references/custom algorithms.md +206 -0
- package/skills/braintrace/references/customizing_primitive_transforms.md +191 -0
- package/skills/braintrace/references/pp_pprop workflow.md +196 -0
- package/skills/braintrace/references/pre-built-braintrace-layer.md +149 -0
- package/skills/brainx-general-guard/SKILL.md +64 -21
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# Custom algorithms
|
|
2
|
+
|
|
3
|
+
Use this reference when built-in BrainTrace algorithms cannot express a research method and the change belongs in trace storage, trace recurrence, gradient solving, or additional algorithm State. Keep model tracing, Jacobian construction, and sequence driving in the existing BrainTrace infrastructure.
|
|
4
|
+
|
|
5
|
+
## Choose an extension base
|
|
6
|
+
|
|
7
|
+
Subclass the nearest estimator engine instead of rebuilding the compiler and executor.
|
|
8
|
+
|
|
9
|
+
| API | Use when |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `ETraceAlgorithm` | Use only for a fundamentally new executor or trace representation. It owns model wrapping, graph compilation, State separation, and `running_index`; subclasses must supply trace initialization, update, and lookup behavior. |
|
|
12
|
+
| `ETraceVjpAlgorithm` | Use for a new VJP-based estimator representation. It owns the custom-VJP forward/backward bridge and delegates trace recurrence and gradient solving to protocol methods. |
|
|
13
|
+
| `ParamDimVjpAlgorithm` | Use for a D-RTRL-like estimator with one parameter-dimensional trace per weight and hidden-group relation. Memory scales with batch size and parameter count. |
|
|
14
|
+
| `IODimVjpAlgorithm` | Use for a pp-prop-like estimator with input/output-factorized traces. Memory scales with batch size and input plus output dimensions. |
|
|
15
|
+
| `RandomProjectionVjpAlgorithm` | Use for a UORO-like rank-one random-projection estimator. |
|
|
16
|
+
| `EligibilityTrace` | Use to store algorithm trace State across time; it is a `brainstate.ShortTermState` specialization. |
|
|
17
|
+
|
|
18
|
+
Use `D_RTRL` as the concrete parameter-dimensional baseline and `pp_prop` as the concrete input/output-factorized baseline. `ES_D_RTRL` is a historical alias for `pp_prop`; use `pp_prop` in new code.
|
|
19
|
+
|
|
20
|
+
## Extension workflow
|
|
21
|
+
|
|
22
|
+
| Step | Action | Important result |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| 1 | Choose the nearest base estimator. | Existing graph compilation, Jacobian execution, and State separation remain intact. |
|
|
25
|
+
| 2 | Override the smallest protocol method that expresses the new rule. | Trace dynamics and gradient readout remain separate decisions. |
|
|
26
|
+
| 3 | Compile the subclass with `braintrace.compile()`. | The custom class receives the model and returns a normal learner. |
|
|
27
|
+
| 4 | Drive sequences through `etrace_evolve()` and `etrace_grad()`. | The standard driver owns looping, masking, reduction, and State continuation. |
|
|
28
|
+
| 5 | Inspect trace values and compiler diagnostics. | Storage shapes, recurrence behavior, and parameter participation become visible. |
|
|
29
|
+
| 6 | Reset both algorithm and model State between independent sequences. | Eligibility traces, time index, and recurrent hidden State all start cleanly. |
|
|
30
|
+
|
|
31
|
+
## Protocol methods
|
|
32
|
+
|
|
33
|
+
Override only the method responsible for the behavior being changed.
|
|
34
|
+
|
|
35
|
+
| API | Description |
|
|
36
|
+
|---|---|
|
|
37
|
+
| `init_etrace_state(*args)` | Override when the algorithm needs new trace-storage shapes at compile time. |
|
|
38
|
+
| `_get_etrace_data()` | Override when custom `EligibilityTrace` State must be assembled into the recurrence input. |
|
|
39
|
+
| `_assign_etrace_data(values)` | Override with `_get_etrace_data()` when custom recurrence results must be written back to trace State. |
|
|
40
|
+
| `_update_etrace_data(...)` | Override to change the eligibility-trace recurrence, such as clipping, normalization, or a decay schedule. It returns the new trace data. |
|
|
41
|
+
| `_solve_weight_gradients(...)` | Override to change how current traces and loss-to-hidden gradients become the final gradient dictionary. |
|
|
42
|
+
| `get_etrace_of(weight)` | Use to inspect trace tensors owned by one parameter. It returns `{(weight_id, leaf_index): {trainable_input_name: trace_tensor}}`. |
|
|
43
|
+
| `reset_state(batch_size=None)` | Use between independent episodes. It zeroes eligibility traces and resets `running_index`, optionally rebroadcasting traces for a new batch size. |
|
|
44
|
+
|
|
45
|
+
The VJP protocol signatures are:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
def _update_etrace_data(
|
|
49
|
+
self,
|
|
50
|
+
running_index,
|
|
51
|
+
etrace_vals_until_t_minus_1,
|
|
52
|
+
hid2weight_jac,
|
|
53
|
+
hid2hid_jac,
|
|
54
|
+
weight_vals,
|
|
55
|
+
input_is_multi_step,
|
|
56
|
+
):
|
|
57
|
+
...
|
|
58
|
+
|
|
59
|
+
def _solve_weight_gradients(
|
|
60
|
+
self,
|
|
61
|
+
running_index,
|
|
62
|
+
etrace_h2w_at_t,
|
|
63
|
+
dl_to_hidden_groups,
|
|
64
|
+
weight_vals,
|
|
65
|
+
dl_to_nonetws_at_t,
|
|
66
|
+
dl_to_etws_at_t,
|
|
67
|
+
):
|
|
68
|
+
...
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`_solve_weight_gradients()` must return a dictionary mapping every parameter path, including ETP and non-ETP parameters, to its gradient pytree.
|
|
72
|
+
|
|
73
|
+
## Canonical custom recurrence
|
|
74
|
+
|
|
75
|
+
Delegate to the parent recurrence, then apply the custom trace rule. This preserves the parent estimator's storage, compiler, and executor contracts.
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
import jax
|
|
79
|
+
import jax.numpy as jnp
|
|
80
|
+
import braintrace
|
|
81
|
+
from braintrace._algorithm.d_rtrl import ParamDimVjpAlgorithm
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ClippedDRTRL(ParamDimVjpAlgorithm):
|
|
85
|
+
"""D-RTRL with element-wise trace clipping."""
|
|
86
|
+
|
|
87
|
+
def __init__(self, model, clip_value=1.0, **kwargs):
|
|
88
|
+
super().__init__(model, **kwargs)
|
|
89
|
+
self.clip_value = clip_value
|
|
90
|
+
|
|
91
|
+
def _update_etrace_data(
|
|
92
|
+
self,
|
|
93
|
+
running_index,
|
|
94
|
+
history,
|
|
95
|
+
hid2weight_jac,
|
|
96
|
+
hid2hid_jac,
|
|
97
|
+
weight_vals,
|
|
98
|
+
input_is_multi_step,
|
|
99
|
+
):
|
|
100
|
+
traces = super()._update_etrace_data(
|
|
101
|
+
running_index,
|
|
102
|
+
history,
|
|
103
|
+
hid2weight_jac,
|
|
104
|
+
hid2hid_jac,
|
|
105
|
+
weight_vals,
|
|
106
|
+
input_is_multi_step,
|
|
107
|
+
)
|
|
108
|
+
return jax.tree.map(
|
|
109
|
+
lambda trace: jnp.clip(
|
|
110
|
+
trace, -self.clip_value, self.clip_value
|
|
111
|
+
),
|
|
112
|
+
traces,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
model = braintrace.nn.ValinaRNNCell(in_size=10, out_size=32)
|
|
117
|
+
learner = braintrace.compile(
|
|
118
|
+
model,
|
|
119
|
+
ClippedDRTRL,
|
|
120
|
+
jnp.zeros(10),
|
|
121
|
+
clip_value=5.0,
|
|
122
|
+
)
|
|
123
|
+
outputs = learner.etrace_evolve(
|
|
124
|
+
jnp.ones((5, 10)), return_outputs=True
|
|
125
|
+
)
|
|
126
|
+
assert len(outputs) == 5
|
|
127
|
+
assert outputs[0].shape == (32,)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
**Invariant:** `_update_etrace_data()` receives the previous trace and current Jacobians and must return the trace for the current step without changing its registered pytree structure.
|
|
131
|
+
|
|
132
|
+
## Gradient-solve variations
|
|
133
|
+
|
|
134
|
+
Override `_solve_weight_gradients()` when the recurrence remains valid but the final gradient dictionary needs a transformation such as global norm clipping or per-layer scaling.
|
|
135
|
+
|
|
136
|
+
Use this pattern:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
class GradClippedDRTRL(braintrace.D_RTRL):
|
|
140
|
+
def __init__(self, model, max_norm=1.0, **kwargs):
|
|
141
|
+
super().__init__(model, **kwargs)
|
|
142
|
+
self.max_norm = max_norm
|
|
143
|
+
|
|
144
|
+
def _solve_weight_gradients(
|
|
145
|
+
self,
|
|
146
|
+
running_index,
|
|
147
|
+
etrace_h2w_at_t,
|
|
148
|
+
dl_to_hidden_groups,
|
|
149
|
+
weight_vals,
|
|
150
|
+
dl_to_nonetws_at_t,
|
|
151
|
+
dl_to_etws_at_t,
|
|
152
|
+
):
|
|
153
|
+
gradients = super()._solve_weight_gradients(
|
|
154
|
+
running_index,
|
|
155
|
+
etrace_h2w_at_t,
|
|
156
|
+
dl_to_hidden_groups,
|
|
157
|
+
weight_vals,
|
|
158
|
+
dl_to_nonetws_at_t,
|
|
159
|
+
dl_to_etws_at_t,
|
|
160
|
+
)
|
|
161
|
+
squared_norm = jax.tree.reduce(
|
|
162
|
+
lambda total, grad: total + jnp.sum(grad * grad),
|
|
163
|
+
gradients,
|
|
164
|
+
initializer=jnp.zeros((), dtype=jnp.float32),
|
|
165
|
+
)
|
|
166
|
+
norm = jnp.sqrt(squared_norm)
|
|
167
|
+
scale = jnp.minimum(1.0, self.max_norm / (norm + 1e-12))
|
|
168
|
+
return jax.tree.map(lambda grad: grad * scale, gradients)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Trace inspection and reset
|
|
172
|
+
|
|
173
|
+
Trace lookup is nested because one parameter leaf can participate in a primitive through several trainable inputs, such as `weight` and `bias`.
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
import brainstate
|
|
177
|
+
|
|
178
|
+
learner.etrace_evolve(sequence)
|
|
179
|
+
|
|
180
|
+
for path, weight in model.states(brainstate.ParamState).items():
|
|
181
|
+
groups = learner.get_etrace_of(weight)
|
|
182
|
+
for (weight_id, leaf_index), traces in groups.items():
|
|
183
|
+
for input_name, trace in traces.items():
|
|
184
|
+
print(path, weight_id, leaf_index, input_name, trace.shape)
|
|
185
|
+
|
|
186
|
+
# Independent sequence boundary: clear both trace and recurrent State.
|
|
187
|
+
learner.reset_state()
|
|
188
|
+
brainstate.nn.reset_all_states(model)
|
|
189
|
+
assert int(learner.running_index.value) == 0
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
**Invariant:** `learner.reset_state()` does not reset the model's hidden states. Call both reset operations between independent episodes. Override `reset_state()` only when the subclass carries additional State that must also be cleared.
|
|
193
|
+
|
|
194
|
+
## Execution and validation rules
|
|
195
|
+
|
|
196
|
+
- Compile the custom algorithm once for a stable model structure; do not rebuild it per step.
|
|
197
|
+
- Let `etrace_grad()` own sequence looping, accumulation, masks, and reduction. Make `step_fn` call the learner exactly once.
|
|
198
|
+
- Compare an unmodified subclass against its parent before testing the new rule.
|
|
199
|
+
- Verify trace shapes, finite values, reset-to-zero behavior, parameter-gradient keys, and parameter updates.
|
|
200
|
+
- Use a reduced BPTT oracle only in a regime where the parent estimator documents equivalence. `D_RTRL` uses a diagonal recurrent-Jacobian approximation and is not generally equal to BPTT.
|
|
201
|
+
- Do not reimplement graph tracing, hidden grouping, Jacobian calculation, or State write-back unless the research method genuinely requires a new base engine.
|
|
202
|
+
|
|
203
|
+
## Sources
|
|
204
|
+
|
|
205
|
+
- [Developing Custom Algorithms](https://brainx.chaobrain.com/braintrace/advanced/custom_algorithms.html)
|
|
206
|
+
- [Online-Learning Algorithms](https://brainx.chaobrain.com/braintrace/apis/algorithms.html)
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# Customizing primitive transforms
|
|
2
|
+
|
|
3
|
+
Use this reference when an existing ETP operation must consume a shape-preserving transformation of a stored parameter while eligibility traces and optimizer gradients remain attached to the raw parameter. Open `custom ETP primitives.md` first when adding transform hooks to a newly registered operation.
|
|
4
|
+
|
|
5
|
+
## Choose the transform hook
|
|
6
|
+
|
|
7
|
+
Use the hook owned by the operation and trainable factor; do not transform the stored `ParamState` in place.
|
|
8
|
+
|
|
9
|
+
| API | Transform hook |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `braintrace.matmul(x, weight, bias=None, *, weight_fn=None, bias_fn=None)` | Use `weight_fn` for the matrix and `bias_fn` for bias. |
|
|
12
|
+
| `braintrace.element_wise(weight, *, weight_fn=None)` | Use `weight_fn` for the element-wise parameter. |
|
|
13
|
+
| `braintrace.conv(x, kernel, bias=None, *, ..., kernel_fn=None, bias_fn=None)` | Use `kernel_fn`, not `weight_fn`, for the convolution kernel; use `bias_fn` for bias. |
|
|
14
|
+
| `braintrace.sparse_matmul(x, weight, *, sparse_mat, bias=None, weight_fn=None, bias_fn=None)` | Use `weight_fn` for stored sparse values and `bias_fn` for bias. |
|
|
15
|
+
| `braintrace.lora_matmul(x, B, A, *, alpha=1.0, bias=None, b_fn=None, a_fn=None, bias_fn=None)` | Use `b_fn` and `a_fn` for the two LoRA factors and `bias_fn` for bias. |
|
|
16
|
+
|
|
17
|
+
All hooks default to `None`, which preserves the untransformed operation.
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import jax.numpy as jnp
|
|
21
|
+
import braintrace
|
|
22
|
+
|
|
23
|
+
x = jnp.ones((4, 3))
|
|
24
|
+
weight = jnp.arange(15.0).reshape(3, 5) / 10.0
|
|
25
|
+
bias = jnp.linspace(-1.0, 1.0, 5)
|
|
26
|
+
|
|
27
|
+
output = braintrace.matmul(
|
|
28
|
+
x,
|
|
29
|
+
weight,
|
|
30
|
+
bias=bias,
|
|
31
|
+
weight_fn=jnp.tanh,
|
|
32
|
+
bias_fn=jnp.abs,
|
|
33
|
+
)
|
|
34
|
+
expected = x @ jnp.tanh(weight) + jnp.abs(bias)
|
|
35
|
+
assert jnp.allclose(output, expected)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Use hooks for masks, standardization, sign constraints, squashing, and other differentiable shape-preserving reparameterizations.
|
|
39
|
+
|
|
40
|
+
## Chain-rule placement
|
|
41
|
+
|
|
42
|
+
The forward operation uses `V = f(W_raw)`, but the trace and optimizer gradient target `W_raw`; apply the transform Jacobian exactly once inside `xy_to_dw` by differentiating the same transformed implementation with `jax.vjp`.
|
|
43
|
+
|
|
44
|
+
| ETP rule | Transform behavior |
|
|
45
|
+
|---|---|
|
|
46
|
+
| `xy_to_dw` | Differentiate through the implementation that applies the hook so `f'(W_raw)` enters once. |
|
|
47
|
+
| `dt_to_t` | Keep transform-free; it propagates an already raw-parameter trace through time. |
|
|
48
|
+
| `init_drtrl` | Keep transform-free; it allocates parameter-dimensional trace storage. |
|
|
49
|
+
| `init_pp` | Keep transform-free; it allocates output-dimensional df-trace storage. |
|
|
50
|
+
|
|
51
|
+
**Invariant:** Do not multiply by `f'(W_raw)` in both `xy_to_dw` and `dt_to_t`. That double-counts the transform Jacobian and produces incorrect online gradients.
|
|
52
|
+
|
|
53
|
+
## Add hooks to a registered primitive
|
|
54
|
+
|
|
55
|
+
Apply each hook in the implementation, expose it as a static primitive parameter, and make `xy_to_dw` differentiate that same forward computation. Do not change the other three ETP rules.
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import jax
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _scaled_matmul_impl(
|
|
62
|
+
*args,
|
|
63
|
+
scale=1.0,
|
|
64
|
+
has_bias=False,
|
|
65
|
+
weight_fn=None,
|
|
66
|
+
bias_fn=None,
|
|
67
|
+
):
|
|
68
|
+
x, weight = args[0], args[1]
|
|
69
|
+
if weight_fn is not None:
|
|
70
|
+
weight = weight_fn(weight)
|
|
71
|
+
|
|
72
|
+
output = scale * (x @ weight)
|
|
73
|
+
if has_bias:
|
|
74
|
+
bias = args[2]
|
|
75
|
+
if bias_fn is not None:
|
|
76
|
+
bias = bias_fn(bias)
|
|
77
|
+
output = output + bias
|
|
78
|
+
return output
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _scaled_xy_to_dw(
|
|
82
|
+
x,
|
|
83
|
+
hidden_dim,
|
|
84
|
+
weights,
|
|
85
|
+
*,
|
|
86
|
+
scale=1.0,
|
|
87
|
+
has_bias=False,
|
|
88
|
+
weight_fn=None,
|
|
89
|
+
bias_fn=None,
|
|
90
|
+
):
|
|
91
|
+
def forward(trainable):
|
|
92
|
+
args = [x, trainable["weight"]]
|
|
93
|
+
if has_bias:
|
|
94
|
+
args.append(trainable["bias"])
|
|
95
|
+
return _scaled_matmul_impl(
|
|
96
|
+
*args,
|
|
97
|
+
scale=scale,
|
|
98
|
+
has_bias=has_bias,
|
|
99
|
+
weight_fn=weight_fn,
|
|
100
|
+
bias_fn=bias_fn,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
_, pullback = jax.vjp(forward, weights)
|
|
104
|
+
return pullback(hidden_dim)[0]
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Register this transform-aware `xy_to_dw` with the unchanged `dt_to_t`, `init_drtrl`, and `init_pp` rules from the primitive's original contract.
|
|
108
|
+
|
|
109
|
+
**Invariant:** The implementation used by the forward primitive and the function differentiated by `xy_to_dw` must apply identical transforms and static parameters.
|
|
110
|
+
|
|
111
|
+
## Quantity behavior
|
|
112
|
+
|
|
113
|
+
User-facing wrappers split a `brainunit.Quantity` into mantissa and unit, apply the transform to the unitless mantissa, and then recombine the unit. Keep transforms shape-preserving and write them for mantissas.
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
import brainunit as u
|
|
117
|
+
|
|
118
|
+
x_quantity = jnp.ones((4, 3)) * u.volt
|
|
119
|
+
weight_quantity = jnp.ones((3, 5)) * u.siemens
|
|
120
|
+
current = braintrace.matmul(
|
|
121
|
+
x_quantity,
|
|
122
|
+
weight_quantity,
|
|
123
|
+
weight_fn=lambda value: value**2,
|
|
124
|
+
)
|
|
125
|
+
print(u.get_unit(current))
|
|
126
|
+
# A
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Fast-path gating
|
|
130
|
+
|
|
131
|
+
Closed-form D-RTRL fast paths compute derivatives with respect to the transformed value `V` and omit `f'(W_raw)`. Disable those paths whenever a transform hook is active so execution falls back to the correct VJP rule path.
|
|
132
|
+
|
|
133
|
+
| API or primitive family | Behavior |
|
|
134
|
+
|---|---|
|
|
135
|
+
| `FastPathRules(instant, recurrent, solve, applicable)` | Defines the closed-form parameter-dimensional kernel bundle and its applicability gate. |
|
|
136
|
+
| `get_fast_path_rules(primitive)` | Returns the registered fast-path bundle or `None`. |
|
|
137
|
+
| `etp_mm`, `etp_mv`, `etp_elemwise` | May provide a fast path; `applicable(eqn_params)` must return `False` when any transform hook is non-`None`. |
|
|
138
|
+
| Sparse, convolution, and LoRA primitives | Have no fast path and always use the general rule path. |
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
from braintrace._op import etp_mm_p, get_fast_path_rules
|
|
142
|
+
|
|
143
|
+
fast_path = get_fast_path_rules(etp_mm_p)
|
|
144
|
+
assert fast_path is not None
|
|
145
|
+
assert fast_path.applicable(
|
|
146
|
+
{"weight_fn": None, "bias_fn": None}
|
|
147
|
+
)
|
|
148
|
+
assert not fast_path.applicable(
|
|
149
|
+
{"weight_fn": jnp.tanh, "bias_fn": None}
|
|
150
|
+
)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
**Invariant:** A fast path is an optimization only. Its gate must fall back to the transform-aware rule path whenever the closed form omits part of the chain rule.
|
|
154
|
+
|
|
155
|
+
## Exactness validation
|
|
156
|
+
|
|
157
|
+
Validate both the forward transform and its online gradient. The development oracle compares a sequence gradient from the online algorithm with the BPTT gradient for the same model factory and loss.
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
from braintrace._algorithm.oracle import (
|
|
161
|
+
assert_param_gradients_close,
|
|
162
|
+
bptt_param_gradients,
|
|
163
|
+
online_param_gradients,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
bptt = bptt_param_gradients(model_factory, inputs)
|
|
167
|
+
online = online_param_gradients(
|
|
168
|
+
model_factory,
|
|
169
|
+
inputs,
|
|
170
|
+
algo_factory=lambda model: braintrace.D_RTRL(
|
|
171
|
+
model, vjp_method="multi-step"
|
|
172
|
+
),
|
|
173
|
+
)
|
|
174
|
+
assert_param_gradients_close(online, bptt, atol=1e-4)
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Use the private oracle for development tests, not as an application API. Choose a reduced model whose recurrent Jacobian lies in the estimator's documented exactness regime; a general D-RTRL model is not automatically BPTT-equivalent.
|
|
178
|
+
|
|
179
|
+
Check these failures explicitly:
|
|
180
|
+
|
|
181
|
+
- The hook is applied in the forward implementation but omitted from `xy_to_dw`.
|
|
182
|
+
- The transform derivative is applied again in `dt_to_t`.
|
|
183
|
+
- A convolution uses `weight_fn` instead of `kernel_fn`.
|
|
184
|
+
- A LoRA hook is attached to the wrong factor.
|
|
185
|
+
- The hook changes parameter shape.
|
|
186
|
+
- A fast path remains active while a transform hook is present.
|
|
187
|
+
- The optimizer updates a transformed copy instead of the raw `ParamState`.
|
|
188
|
+
|
|
189
|
+
## Sources
|
|
190
|
+
|
|
191
|
+
- [Customizing Parameter Transforms for ETP Operators](https://brainx.chaobrain.com/braintrace/advanced/customizing_primitive_transforms.html)
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
# pp-prop workflow
|
|
2
|
+
|
|
3
|
+
Use this reference when lower trace memory makes input/output-factorized
|
|
4
|
+
`pp_prop` preferable to D-RTRL, especially for recurrent SNN training. Open
|
|
5
|
+
`algorithm selection.md` for other estimators and `batching.md` for batching
|
|
6
|
+
ownership beyond the explicit mapped workflow shown here.
|
|
7
|
+
|
|
8
|
+
## Choose pp-prop
|
|
9
|
+
|
|
10
|
+
`pp_prop` carries input-side and output-side eligibility factors with
|
|
11
|
+
exponential smoothing instead of a parameter-dimensional trace.
|
|
12
|
+
|
|
13
|
+
| API or option | Description |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `braintrace.pp_prop` | Use for the current input/output-factorized estimator. Its trace storage is `O(B * (I + O))`, subject to the documented model and operator assumptions. |
|
|
16
|
+
| `braintrace.ES_D_RTRL` | Use only for compatibility with historical code; new code should use `braintrace.pp_prop`. |
|
|
17
|
+
| `decay_or_rank=<float>` | Use a value in `(0, 1)` to set the exponential decay directly. Larger values retain a longer history. |
|
|
18
|
+
| `decay_or_rank=<int>` | Use a positive integer to select `decay = (rank - 1) / (rank + 1)`. It does not allocate that many independently stored low-rank factors. |
|
|
19
|
+
|
|
20
|
+
The factorization discards correlations represented by an unfactorized trace.
|
|
21
|
+
Lower memory therefore does not imply BPTT-equivalent gradients, and the
|
|
22
|
+
selected `decay_or_rank` is part of the method definition that must be reported
|
|
23
|
+
with results.
|
|
24
|
+
|
|
25
|
+
## Compare with D-RTRL
|
|
26
|
+
|
|
27
|
+
Choose between the two estimators by trace representation and acceptable
|
|
28
|
+
approximation, not by treating either as a universal BPTT replacement.
|
|
29
|
+
|
|
30
|
+
| Aspect | `D_RTRL` | `pp_prop` |
|
|
31
|
+
|---|---|---|
|
|
32
|
+
| Eligibility trace | Parameter-shaped with a diagonal hidden-Jacobian approximation. | Input/output-factorized with exponential smoothing. |
|
|
33
|
+
| Trace memory | `O(B * |theta|)`. | `O(B * (I + O))`. |
|
|
34
|
+
| Main approximation | Diagonal hidden-to-hidden Jacobian structure. | Input/output factorization plus exponential smoothing. |
|
|
35
|
+
| Use when | Parameter-shaped trace memory is feasible. | Lower trace memory is required and factorization assumptions are acceptable. |
|
|
36
|
+
|
|
37
|
+
Validate either estimator against BPTT on a reduced version of the intended
|
|
38
|
+
model before relying on gradient fidelity.
|
|
39
|
+
|
|
40
|
+
## Build an ETP-aware recurrent SNN
|
|
41
|
+
|
|
42
|
+
Use ETP-aware projections for trainable parameter paths, a stateful spiking
|
|
43
|
+
neuron for recurrent dynamics, and an ETP-aware leaky readout for continuous
|
|
44
|
+
sequence outputs.
|
|
45
|
+
|
|
46
|
+
| API | Description |
|
|
47
|
+
|---|---|
|
|
48
|
+
| `braintrace.nn.Linear(...)` | Use for the input-plus-recurrent projection so its weights participate through ETP primitives. |
|
|
49
|
+
| `brainpy.state.LIF(...)` | Use for leaky integrate-and-fire dynamics; provide a differentiable surrogate spike function. |
|
|
50
|
+
| `braintrace.nn.LeakyRateReadout(...)` | Use to integrate recurrent spikes into a continuous classification output. |
|
|
51
|
+
| `brainstate.environ.context(dt=...)` | Use to scope the physical simulation time step around model construction and execution. |
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import jax.numpy as jnp
|
|
55
|
+
import brainstate
|
|
56
|
+
import braintools
|
|
57
|
+
import braintrace
|
|
58
|
+
import brainunit as u
|
|
59
|
+
import brainpy.state
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class LIF_SNN(brainstate.nn.Module):
|
|
63
|
+
def __init__(self, n_in, n_rec, n_out):
|
|
64
|
+
super().__init__()
|
|
65
|
+
self.linear = braintrace.nn.Linear(
|
|
66
|
+
n_in + n_rec,
|
|
67
|
+
n_rec,
|
|
68
|
+
w_init=braintools.init.KaimingNormal(scale=50., unit=u.mA),
|
|
69
|
+
b_init=braintools.init.ZeroInit(unit=u.mA),
|
|
70
|
+
)
|
|
71
|
+
self.neuron = brainpy.state.LIF(
|
|
72
|
+
n_rec,
|
|
73
|
+
tau=20. * u.ms,
|
|
74
|
+
R=1. * u.ohm,
|
|
75
|
+
V_th=0.1 * u.mV,
|
|
76
|
+
V_reset=0. * u.mV,
|
|
77
|
+
V_rest=0. * u.mV,
|
|
78
|
+
spk_fun=braintools.surrogate.ReluGrad(),
|
|
79
|
+
spk_reset='soft',
|
|
80
|
+
)
|
|
81
|
+
self.readout = braintrace.nn.LeakyRateReadout(
|
|
82
|
+
n_rec,
|
|
83
|
+
n_out,
|
|
84
|
+
tau=20. * u.ms,
|
|
85
|
+
w_init=braintools.init.KaimingNormal(),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def update(self, spike_input):
|
|
89
|
+
recurrent_spikes = self.neuron.get_spike()
|
|
90
|
+
projection_input = jnp.concatenate(
|
|
91
|
+
[spike_input, recurrent_spikes],
|
|
92
|
+
axis=-1,
|
|
93
|
+
)
|
|
94
|
+
self.neuron(self.linear(projection_input))
|
|
95
|
+
return self.readout(self.neuron())
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The projection weights use current units so the LIF term `I * R` is compatible
|
|
99
|
+
with the voltage-valued threshold and membrane State.
|
|
100
|
+
|
|
101
|
+
## Train a mapped spike sequence
|
|
102
|
+
|
|
103
|
+
Create one mapped model, initialize its independent recurrent State, construct
|
|
104
|
+
`pp_prop` around it directly, and compile from one complete batched time step.
|
|
105
|
+
|
|
106
|
+
| API | Description |
|
|
107
|
+
|---|---|
|
|
108
|
+
| `brainstate.nn.Map(model, init_map_size=B)` | Use once to own batch mapping and independent recurrent State across lanes. |
|
|
109
|
+
| `braintrace.pp_prop(mapped_model, decay_or_rank=...)` | Use with an explicitly mapped model; do not pass that model to `compile(..., vmap=True)`. |
|
|
110
|
+
| `learner.compile_graph(inputs[0])` | Use once with a complete step shaped `(batch_size, n_in)`. |
|
|
111
|
+
| `learner.etrace_grad(inputs, step_fn=..., has_aux=True, ...)` | Use to scan time, accumulate online gradients, and retain per-step outputs needed for a sequence prediction. |
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
n_steps, batch_size = 100, 40
|
|
115
|
+
n_in, n_rec, n_out = 50, 128, 10
|
|
116
|
+
|
|
117
|
+
labels = jnp.arange(batch_size, dtype=jnp.int32) % n_out
|
|
118
|
+
channel_class = jnp.arange(n_in) * n_out // n_in
|
|
119
|
+
active = labels[:, None] == channel_class[None, :]
|
|
120
|
+
firing_probability = jnp.where(active, 0.6, 0.0)
|
|
121
|
+
|
|
122
|
+
brainstate.random.seed(37)
|
|
123
|
+
inputs = brainstate.random.bernoulli(
|
|
124
|
+
firing_probability,
|
|
125
|
+
size=(n_steps, batch_size, n_in),
|
|
126
|
+
).astype(jnp.float32)
|
|
127
|
+
|
|
128
|
+
with brainstate.environ.context(dt=1. * u.ms):
|
|
129
|
+
model = LIF_SNN(n_in, n_rec, n_out)
|
|
130
|
+
mapped_model = brainstate.nn.Map(model, init_map_size=batch_size)
|
|
131
|
+
mapped_model.init_all_states()
|
|
132
|
+
|
|
133
|
+
learner = braintrace.pp_prop(mapped_model, decay_or_rank=0.5)
|
|
134
|
+
learner.compile_graph(inputs[0])
|
|
135
|
+
|
|
136
|
+
optimizer = braintools.optim.Adam(3e-3)
|
|
137
|
+
optimizer.register_trainable_weights(learner.param_states)
|
|
138
|
+
|
|
139
|
+
@brainstate.transform.jit
|
|
140
|
+
def train_step(sequence, targets):
|
|
141
|
+
brainstate.nn.reset_all_states(mapped_model)
|
|
142
|
+
learner.reset_state()
|
|
143
|
+
|
|
144
|
+
def step_loss(spikes):
|
|
145
|
+
output = learner(spikes)
|
|
146
|
+
loss = braintools.metric.softmax_cross_entropy_with_integer_labels(
|
|
147
|
+
output,
|
|
148
|
+
targets,
|
|
149
|
+
).mean()
|
|
150
|
+
return loss, output
|
|
151
|
+
|
|
152
|
+
grads, step_losses, outputs = learner.etrace_grad(
|
|
153
|
+
sequence,
|
|
154
|
+
step_fn=step_loss,
|
|
155
|
+
has_aux=True,
|
|
156
|
+
reduction='sum',
|
|
157
|
+
return_value=True,
|
|
158
|
+
)
|
|
159
|
+
grads = brainstate.nn.clip_grad_norm(grads, 1.0)
|
|
160
|
+
optimizer.update(grads)
|
|
161
|
+
|
|
162
|
+
predictions = jnp.argmax(jnp.sum(outputs, axis=0), axis=-1)
|
|
163
|
+
accuracy = jnp.mean(predictions == targets)
|
|
164
|
+
return step_losses.mean(), accuracy
|
|
165
|
+
|
|
166
|
+
loss, accuracy = train_step(inputs, labels)
|
|
167
|
+
assert loss.shape == ()
|
|
168
|
+
assert accuracy.shape == ()
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
`step_loss` must call `learner` exactly once. Reset model State and eligibility
|
|
172
|
+
State together before each independent spike sequence. `reduction='sum'`
|
|
173
|
+
preserves the accumulated per-step scale used by this workflow; tune the
|
|
174
|
+
learning rate for that reduction.
|
|
175
|
+
|
|
176
|
+
## Interpret checks and exclusions
|
|
177
|
+
|
|
178
|
+
Use joint loss and accuracy evidence on a reproducible task as a teaching
|
|
179
|
+
check, not a convergence guarantee. Different trace information means pp-prop
|
|
180
|
+
need not reach the same loss as D-RTRL on a matched run.
|
|
181
|
+
|
|
182
|
+
A weight that reaches hidden State only through another trainable ETP weight is
|
|
183
|
+
excluded by the compiler's non-parametric-tail invariant. This prevents double
|
|
184
|
+
counting and does not indicate an optimizer failure.
|
|
185
|
+
|
|
186
|
+
Open `ETP operators.md` when a custom SNN projection does not participate. Open
|
|
187
|
+
`pre-built-braintrace-layer.md` when selecting recurrent or readout layers.
|
|
188
|
+
|
|
189
|
+
## Sources
|
|
190
|
+
|
|
191
|
+
- [SNN Online Learning](https://brainx.chaobrain.com/braintrace/tutorials/snn_online_learning.html)
|
|
192
|
+
- [pp_prop: input/output-factorized online gradients](https://brainx.chaobrain.com/braintrace/tutorials/pp_prop.html)
|
|
193
|
+
|
|
194
|
+
The factorization rules, decay semantics, SNN workflow, and comparison above
|
|
195
|
+
are trimmed and reorganized from the official pages without changing their API
|
|
196
|
+
names or documented guarantees.
|