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.
- 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 +14 -0
- package/skills/brainevent/SKILL.md +1 -0
- package/skills/brainmass/SKILL.md +1 -1
- package/skills/brainpy-state/SKILL.md +7 -1
- package/skills/brainpy-state/references/array-creation.md +2 -2
- 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/brainstate/SKILL.md +14 -10
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +1 -1
- package/skills/brainstate/references/braintools/optimizer.md +179 -0
- 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 +20 -2
- package/skills/brainx-install/SKILL.md +24 -21
- package/skills/brainstate/agents/openai.yaml +0 -4
|
@@ -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.
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# Prebuilt BrainTrace layers
|
|
2
|
+
|
|
3
|
+
Use this reference when selecting and composing the default ETP-aware
|
|
4
|
+
`braintrace.nn` layers. Prefer these layers before built-in ETP operators or a
|
|
5
|
+
custom primitive; import activation, normalization, and pooling layers from
|
|
6
|
+
their owning package instead.
|
|
7
|
+
|
|
8
|
+
## Select by parameterized operation
|
|
9
|
+
|
|
10
|
+
`braintrace.nn` mirrors the BrainState layer pattern but routes each trainable
|
|
11
|
+
forward operation through an ETP primitive, so parameters participate without
|
|
12
|
+
manual trace wiring.
|
|
13
|
+
|
|
14
|
+
| Family | Use when | ETP behavior |
|
|
15
|
+
|---|---|---|
|
|
16
|
+
| Linear maps | The layer applies dense, grouped, signed, sparse, or low-rank weights. | Uses the matching ETP matrix operation. |
|
|
17
|
+
| Embeddings | Integer indices select trainable rows. | Uses ETP-aware indexed weight access. |
|
|
18
|
+
| Convolutions | Data has one, two, or three spatial dimensions. | Uses `braintrace.conv()`. |
|
|
19
|
+
| Recurrent cells | Hidden State must update once per input step. | Uses ETP dense and element-wise operations inside the recurrence. |
|
|
20
|
+
| Readouts | Recurrent activity needs leaky continuous output dynamics. | Uses an ETP-aware projection. |
|
|
21
|
+
|
|
22
|
+
The class namespace is convenient, but the operation in the traced graph is
|
|
23
|
+
what the compiler recognizes.
|
|
24
|
+
|
|
25
|
+
## Choose a linear map
|
|
26
|
+
|
|
27
|
+
Use the representation that matches the weight structure; do not emulate a
|
|
28
|
+
specialized structure with an unrelated dense layer.
|
|
29
|
+
|
|
30
|
+
| API | Description |
|
|
31
|
+
|---|---|
|
|
32
|
+
| `braintrace.nn.Linear` | Use for a standard dense linear transformation; its weight passes through `braintrace.matmul()`. |
|
|
33
|
+
| `braintrace.nn.GroupedLinear` | Use for a block-diagonal grouped transformation backed by `braintrace.grouped_matmul()`. |
|
|
34
|
+
| `braintrace.nn.SignedWLinear` | Use for a linear layer with signed absolute weights. |
|
|
35
|
+
| `braintrace.nn.SparseLinear` | Use for a sparse weight matrix. |
|
|
36
|
+
| `braintrace.nn.LoRA` | Use for a standalone low-rank adaptation layer. |
|
|
37
|
+
|
|
38
|
+
## Choose an embedding or convolution
|
|
39
|
+
|
|
40
|
+
Use embeddings for trainable indexed lookup and choose convolution dimensionality
|
|
41
|
+
from the number of spatial axes.
|
|
42
|
+
|
|
43
|
+
| API | Description |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `braintrace.nn.Embedding` | Use for a fixed-size trainable embedding table. |
|
|
46
|
+
| `braintrace.nn.Conv1d` | Use for one-dimensional convolution. |
|
|
47
|
+
| `braintrace.nn.Conv2d` | Use for two-dimensional convolution. |
|
|
48
|
+
| `braintrace.nn.Conv3d` | Use for three-dimensional convolution. |
|
|
49
|
+
|
|
50
|
+
## Choose a recurrent cell
|
|
51
|
+
|
|
52
|
+
Recurrent layers consume one time step, update hidden State in place, and
|
|
53
|
+
return the new hidden State; `LRUCell` instead returns its projected output.
|
|
54
|
+
|
|
55
|
+
| API | Description |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `braintrace.nn.ValinaRNNCell` | Use for the package's vanilla RNN cell. Preserve the exported identifier spelling. |
|
|
58
|
+
| `braintrace.nn.GRUCell` | Use for a standard gated recurrent unit. |
|
|
59
|
+
| `braintrace.nn.MGUCell` | Use for a minimal gated recurrent unit. |
|
|
60
|
+
| `braintrace.nn.LSTMCell` | Use for a long short-term memory core. |
|
|
61
|
+
| `braintrace.nn.URLSTMCell` | Use for an update-reset LSTM core. |
|
|
62
|
+
| `braintrace.nn.MinimalRNNCell` | Use for the minimal RNN cell. |
|
|
63
|
+
| `braintrace.nn.MiniGRU` | Use for the package's minimal GRU cell. |
|
|
64
|
+
| `braintrace.nn.MiniLSTM` | Use for the package's minimal LSTM cell. |
|
|
65
|
+
| `braintrace.nn.LRUCell` | Use for a linear recurrent unit; it returns the projected output rather than the hidden State itself. |
|
|
66
|
+
|
|
67
|
+
## Choose a readout
|
|
68
|
+
|
|
69
|
+
Use the BrainTrace readout when an online recurrent model needs leaky output
|
|
70
|
+
dynamics.
|
|
71
|
+
|
|
72
|
+
| API | Description |
|
|
73
|
+
|---|---|
|
|
74
|
+
| `braintrace.nn.LeakyRateReadout` | Use for leaky readout dynamics in Real-Time Recurrent Learning. |
|
|
75
|
+
|
|
76
|
+
## Import supporting layers from their owner
|
|
77
|
+
|
|
78
|
+
Activation, normalization, and pooling layers are intentionally not
|
|
79
|
+
re-implemented in `braintrace.nn`.
|
|
80
|
+
|
|
81
|
+
| Need | Import from |
|
|
82
|
+
|---|---|
|
|
83
|
+
| Activation | `brainstate.nn` |
|
|
84
|
+
| Normalization | `brainstate.nn` |
|
|
85
|
+
| Pooling | `brainstate.nn` |
|
|
86
|
+
|
|
87
|
+
Do not import these through `braintrace.nn`. Compatibility forwarding, such as
|
|
88
|
+
`braintrace.nn.LayerNorm`, emits `DeprecationWarning` and forwards to the owning
|
|
89
|
+
package.
|
|
90
|
+
|
|
91
|
+
## Compose and compile a recurrent model
|
|
92
|
+
|
|
93
|
+
Put the recurrent cell and observable readout in one Module, compile from a
|
|
94
|
+
representative step, then use the learner's sequence driver for repeated
|
|
95
|
+
execution.
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import jax.numpy as jnp
|
|
99
|
+
import brainstate
|
|
100
|
+
import braintrace
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class TinySequenceModel(brainstate.nn.Module):
|
|
104
|
+
def __init__(self):
|
|
105
|
+
super().__init__()
|
|
106
|
+
self.rnn = braintrace.nn.MiniGRU(in_size=1, out_size=4)
|
|
107
|
+
self.readout = braintrace.nn.Linear(4, 1)
|
|
108
|
+
|
|
109
|
+
def update(self, x):
|
|
110
|
+
return self.readout(self.rnn(x))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
model = TinySequenceModel()
|
|
114
|
+
learner = braintrace.compile(
|
|
115
|
+
model,
|
|
116
|
+
braintrace.D_RTRL,
|
|
117
|
+
jnp.ones(1),
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
sequence = jnp.linspace(-1.0, 1.0, 6).reshape(6, 1)
|
|
121
|
+
brainstate.nn.reset_all_states(model)
|
|
122
|
+
learner.reset_state()
|
|
123
|
+
outputs = learner.etrace_evolve(sequence, return_outputs=True)
|
|
124
|
+
|
|
125
|
+
assert outputs.shape == (6, 1)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The recurrent weights influence hidden State and therefore need eligibility
|
|
129
|
+
traces. The final `Linear` weight remains trainable, but because its output does
|
|
130
|
+
not feed hidden State, the compiler classifies it as non-temporal and computes
|
|
131
|
+
its instantaneous gradient directly.
|
|
132
|
+
|
|
133
|
+
**Relation invariant:** A `weight -> weight -> hidden` path crosses two
|
|
134
|
+
trainable ETP operations. The compiler stops at the downstream operation and
|
|
135
|
+
does not record the upstream weight as an independent ETP relation, which
|
|
136
|
+
prevents double counting.
|
|
137
|
+
|
|
138
|
+
Open `ETP operators.md` when no prebuilt layer matches the required custom
|
|
139
|
+
block. Escalate to `custom ETP primitives.md` only when built-in ETP operations
|
|
140
|
+
cannot express it.
|
|
141
|
+
|
|
142
|
+
## Sources
|
|
143
|
+
|
|
144
|
+
- [Neural-Network Layers](https://brainx.chaobrain.com/braintrace/apis/nn.html)
|
|
145
|
+
- [Neural Network Layers for Online Learning](https://brainx.chaobrain.com/braintrace/tutorials/neural_network_layers.html)
|
|
146
|
+
|
|
147
|
+
The layer catalogue, ownership boundary, composition, and compiler relations
|
|
148
|
+
above are trimmed and reorganized from the official pages without changing
|
|
149
|
+
their API names.
|
|
@@ -5,7 +5,13 @@ description: Use first for every BrainX modeling, simulation, training, review,
|
|
|
5
5
|
|
|
6
6
|
# BrainX general guard
|
|
7
7
|
|
|
8
|
-
##
|
|
8
|
+
## Purpose and boundary
|
|
9
|
+
|
|
10
|
+
Route every BrainX modeling, simulation, training, review, debugging, or optimization task to the package skills that own it, then enforce the ecosystem-wide rules that no single package skill owns: never mine the installed packages for knowledge, write BrainX-native code, prefer high-level APIs, and transform stateful execution.
|
|
11
|
+
|
|
12
|
+
This skill supplies no modeling APIs of its own. It selects the owning skills and hands the task to them; every signature, constructor, and workflow comes from those skills and their references.
|
|
13
|
+
|
|
14
|
+
## Never inspect BrainX packages in the venv for knowledge
|
|
9
15
|
|
|
10
16
|
Treat BrainX packages in the active virtual environment only as execution dependencies, never as sources of modeling knowledge.
|
|
11
17
|
|
|
@@ -26,7 +32,7 @@ Treat BrainX packages in the active virtual environment only as execution depend
|
|
|
26
32
|
|
|
27
33
|
## Select modeling skills by represented scale
|
|
28
34
|
|
|
29
|
-
Select every row supported by the user's task. A single-scale task opens one modeling skill; a multiscale task may open two or all three.
|
|
35
|
+
Select every row supported by the user's task. A single-scale task opens one modeling skill; a multiscale task may open two or all three of the scale skills.
|
|
30
36
|
|
|
31
37
|
| The task explicitly represents | Open |
|
|
32
38
|
|---|---|
|
|
@@ -38,6 +44,18 @@ Select every row supported by the user's task. A single-scale task opens one mod
|
|
|
38
44
|
| Cellular mechanisms coupled to aggregate neural-mass dynamics | BrainCell + BrainMass |
|
|
39
45
|
| Cellular biophysics, point-neuron networks, and aggregate population dynamics interacting in one workflow | BrainCell + BrainPy-State + BrainMass |
|
|
40
46
|
|
|
47
|
+
## Also select skills by cross-cutting concern
|
|
48
|
+
|
|
49
|
+
Scale is not the only axis. Open each row whose concern the task contains, in addition to every scale skill selected above.
|
|
50
|
+
|
|
51
|
+
| The task also involves | Open |
|
|
52
|
+
|---|---|
|
|
53
|
+
| Physical quantities, units, dimensional mismatches, unit-aware math, or suspicious bare numbers | BrainUnit |
|
|
54
|
+
| Mutable State and `.value`, Module graphs, state initialization, environment scoping, or state-aware `jit`/`grad`/`vmap` | BrainState |
|
|
55
|
+
| Binary firing events, sparse or probabilistic connectivity, spike-driven postsynaptic input, or activity-dependent weight changes | BrainEvent |
|
|
56
|
+
| Eligibility-trace online learning, D-RTRL or pp-prop selection, or training a recurrent or spiking model without BPTT | BrainTrace |
|
|
57
|
+
| Installing, upgrading, pinning, migrating, or removing BrainX packages | BrainX-Install |
|
|
58
|
+
|
|
41
59
|
## Write BrainX-native code
|
|
42
60
|
|
|
43
61
|
Start from the scientific concept and use the selected BrainX skills to construct the workflow. Avoid raw NumPy or JAX unless at an explicit interoperability boundary or after verifying an API gap.
|