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,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.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# Compiler internals
|
|
2
|
+
|
|
3
|
+
Use this reference when `learner.report`, `learner.graph`, and compiler diagnostics cannot explain a missing or misplaced relation in a custom layer, ETP primitive, or online-learning algorithm. Keep normal model compilation on `braintrace.compile()`.
|
|
4
|
+
|
|
5
|
+
## Escalation path
|
|
6
|
+
|
|
7
|
+
Inspect public compilation results before calling lower-level compiler functions.
|
|
8
|
+
|
|
9
|
+
| API | Description |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `braintrace.compile(model, algorithm, *example_args, ...)` | Use for normal compilation. It initializes the learner, runs the compiler pipeline once, and attaches a `CompilationReport` at `learner.report`. |
|
|
12
|
+
| `learner.report.show(level)` | Use first for human-readable hidden-group, included-weight, excluded-weight, and diagnostic summaries. Use levels `0` through `2` for increasing detail. |
|
|
13
|
+
| `learner.report.counts` | Use for programmatic checks of `hidden_groups`, `etrace_weights`, `excluded_weights`, `warnings`, and `errors`. |
|
|
14
|
+
| `learner.report.graph` | Use to access the compiled `ETraceGraph` after the report identifies a structural problem. |
|
|
15
|
+
| `graph.diagnostics` | Use to filter individual `CompilationRecord` decisions by kind or severity. |
|
|
16
|
+
| `graph.explain()` | Use to print the graph diagnostics grouped by decision kind. |
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import braintrace
|
|
20
|
+
|
|
21
|
+
learner = braintrace.compile(model, braintrace.D_RTRL, example_input)
|
|
22
|
+
learner.report.show(1)
|
|
23
|
+
|
|
24
|
+
assert learner.report.counts["errors"] == 0
|
|
25
|
+
for record in learner.report.diagnostics:
|
|
26
|
+
print(record.level.name, record.kind.name, record.message)
|
|
27
|
+
|
|
28
|
+
graph = learner.report.graph
|
|
29
|
+
graph.explain()
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**Invariant:** An exclusion is not automatically a compiler failure. Read the record's `kind`, `message`, `weight_path`, `hidden_paths`, and `context` before changing the model.
|
|
33
|
+
|
|
34
|
+
## Four-stage compilation pipeline
|
|
35
|
+
|
|
36
|
+
The compiler traces a `brainstate.nn.Module` to Jaxpr, discovers recurrent state structure and ETP relations, then adds the perturbations required by online algorithms.
|
|
37
|
+
|
|
38
|
+
| Stage API | Result | Use it to inspect |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| `braintrace.extract_module_info(model, *example_args)` | `ModuleInfo` | Jaxpr equations, compiled model states, hidden and parameter classifications, and path-to-variable mappings. |
|
|
41
|
+
| `braintrace.find_hidden_groups_from_minfo(minfo)` | `(hidden_groups, hidden_path_to_group)` | Recurrent hidden states that update together and their transition Jaxprs. |
|
|
42
|
+
| `braintrace.find_hidden_param_op_relations_from_minfo(minfo, hidden_path_to_group)` | Sequence of `HiddenParamOpRelation` | Which trainable inputs pass through which ETP primitive and reach which hidden group. |
|
|
43
|
+
| `braintrace.add_hidden_perturbation_from_minfo(minfo)` | `HiddenPerturbation` | Perturbation variables used to compute hidden-to-hidden Jacobians. |
|
|
44
|
+
| `braintrace.compile_etrace_graph(model, *example_args)` | `ETraceGraph` | The complete compiled graph, including module info, hidden groups, relations, perturbations, and diagnostics. |
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
minfo = braintrace.extract_module_info(model, example_input)
|
|
48
|
+
groups, path_to_group = braintrace.find_hidden_groups_from_minfo(minfo)
|
|
49
|
+
relations = braintrace.find_hidden_param_op_relations_from_minfo(
|
|
50
|
+
minfo, path_to_group
|
|
51
|
+
)
|
|
52
|
+
perturbation = braintrace.add_hidden_perturbation_from_minfo(minfo)
|
|
53
|
+
|
|
54
|
+
graph = braintrace.compile_etrace_graph(model, example_input)
|
|
55
|
+
assert len(graph.hidden_groups) == len(groups)
|
|
56
|
+
assert len(graph.hidden_param_op_relations) == len(relations)
|
|
57
|
+
assert graph.hidden_perturb is not None
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Use the staged calls only to isolate a compiler stage. Use `compile_etrace_graph()` when a custom algorithm needs the finished low-level graph.
|
|
61
|
+
|
|
62
|
+
## Hidden-group discovery
|
|
63
|
+
|
|
64
|
+
Hidden groups represent recurrent states connected through the traced computation and compatible enough to share a transition relation.
|
|
65
|
+
|
|
66
|
+
The compiler performs these decisions in order:
|
|
67
|
+
|
|
68
|
+
1. Trace forward from each hidden-state input variable to reachable hidden-state output variables.
|
|
69
|
+
2. Merge overlapping connected components.
|
|
70
|
+
3. Separate shape-incompatible states.
|
|
71
|
+
4. Separate hidden states belonging to different sequential layers.
|
|
72
|
+
5. Build each group's transition Jaxpr.
|
|
73
|
+
|
|
74
|
+
Inspect `HiddenGroup.index`, `num_state`, `varshape`, `hidden_paths`, `transition_jaxpr`, and `transition_jaxpr_constvars` when grouping differs from the model's intended recurrent structure.
|
|
75
|
+
|
|
76
|
+
**Invariant:** A hidden group is a compiler-discovered recurrent component, not merely every `HiddenState` with the same shape.
|
|
77
|
+
|
|
78
|
+
## ETP relation discovery
|
|
79
|
+
|
|
80
|
+
An ETP relation means that a registered primitive consumes trainable input and its output reaches a compatible recurrent hidden group without crossing an unsupported trainable tail.
|
|
81
|
+
|
|
82
|
+
| Decision | Compiler behavior |
|
|
83
|
+
|---|---|
|
|
84
|
+
| Primitive identification | Checks primitive object identity in `ETP_PRIMITIVES`; names and wrappers do not determine participation. |
|
|
85
|
+
| Trainable-input discovery | Calls the primitive's registered `trainable_invars_fn` through `get_trainable_invars(primitive, eqn.params)`. |
|
|
86
|
+
| Parameter ownership | Traces every trainable Jaxpr variable backward to its originating `ParamState`, including through parameter transforms. |
|
|
87
|
+
| Hidden reachability | Runs a forward breadth-first search from the primitive output to hidden-state outputs. |
|
|
88
|
+
| Shape validation | Keeps only hidden outputs broadcast-compatible with the primitive output. |
|
|
89
|
+
| Tail validation | Excludes a weight that reaches hidden state only through another genuinely trainable ETP primitive. |
|
|
90
|
+
|
|
91
|
+
Inspect a discovered relation through `primitive`, `trainable_paths`, `x_var`, `y_var`, `hidden_groups`, `connected_hidden_paths`, and `eqn_params`.
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from braintrace._op import is_etp_primitive
|
|
95
|
+
|
|
96
|
+
for index, equation in enumerate(minfo.jaxpr.eqns):
|
|
97
|
+
if is_etp_primitive(equation.primitive):
|
|
98
|
+
in_shapes = [
|
|
99
|
+
var.aval.shape if hasattr(var, "aval") else "literal"
|
|
100
|
+
for var in equation.invars
|
|
101
|
+
]
|
|
102
|
+
out_shapes = [var.aval.shape for var in equation.outvars]
|
|
103
|
+
print(index, equation.primitive.name, in_shapes, "->", out_shapes)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Use this Jaxpr scan to distinguish "the primitive was not traced" from "the primitive was traced but its relation was excluded."
|
|
107
|
+
|
|
108
|
+
## Graph execution
|
|
109
|
+
|
|
110
|
+
The graph executor runs the compiled forward graph and produces the hidden-to-weight and hidden-to-hidden Jacobians consumed by an online-learning algorithm.
|
|
111
|
+
|
|
112
|
+
| API | Description |
|
|
113
|
+
|---|---|
|
|
114
|
+
| `ETraceGraphExecutor` | Use as the base executor when developing a custom algorithm that consumes an `ETraceGraph`. It runs the forward graph and exposes its Jacobian calculations. |
|
|
115
|
+
| `ETraceVjpGraphExecutor` | Use for algorithms in the `ETraceVjpAlgorithm` family. It provides the VJP-based executor used by the built-in estimators. |
|
|
116
|
+
|
|
117
|
+
Keep executor calls inside the algorithm lifecycle. Application code should call the compiled learner, `etrace_evolve()`, or `etrace_grad()` rather than driving the executor directly.
|
|
118
|
+
|
|
119
|
+
## Control-flow policy
|
|
120
|
+
|
|
121
|
+
`ControlFlowPolicy` controls compiler canonicalization of JAX control-flow primitives, including conditional conversion, scan unrolling, and structured scan descent.
|
|
122
|
+
|
|
123
|
+
Use it only when recurrent State must cross compiler-supported control flow. Compile a minimal example and inspect the resulting hidden groups and relations; if hidden State inside `jax.lax.scan`, `jax.lax.while_loop`, or `jax.lax.cond` remains unsupported for the chosen structure, redesign the step so the recurrent update is directly visible to the compiler.
|
|
124
|
+
|
|
125
|
+
**Invariant:** A successful JAX trace does not prove that BrainTrace discovered the intended hidden-State relation through control flow.
|
|
126
|
+
|
|
127
|
+
## Diagnostics and failure classification
|
|
128
|
+
|
|
129
|
+
`CompilationRecord` makes every inclusion, exclusion, warning, and error inspectable instead of leaving compiler decisions silent.
|
|
130
|
+
|
|
131
|
+
| Field or type | Description |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `CompilationRecord.kind` | Machine-readable `DiagnosticKind`, such as relation inclusion, non-temporal exclusion, weight-to-weight exclusion, bounded transition tail, or state mismatch. |
|
|
134
|
+
| `CompilationRecord.level` | `DiagnosticLevel.INFO`, `WARNING`, or `ERROR`. |
|
|
135
|
+
| `CompilationRecord.message` | Human-readable decision summary. |
|
|
136
|
+
| `CompilationRecord.primitive` | ETP primitive involved, when applicable. |
|
|
137
|
+
| `CompilationRecord.weight_path` | Path to the originating `ParamState`. |
|
|
138
|
+
| `CompilationRecord.hidden_paths` | Hidden-state paths reached by the candidate relation. |
|
|
139
|
+
| `CompilationRecord.context` | Group indices, path classifications, and other structured details. |
|
|
140
|
+
|
|
141
|
+
Classify common problems as follows:
|
|
142
|
+
|
|
143
|
+
| Symptom | Likely cause | Action |
|
|
144
|
+
|---|---|---|
|
|
145
|
+
| No ETP equation in the Jaxpr | The model used a regular JAX operation such as `x @ weight`. | Use the appropriate registered `braintrace` ETP operation when the parameter should participate online. |
|
|
146
|
+
| ETP equation exists but no relation | Its output does not reach a hidden state, fails shape compatibility, or crosses another trainable ETP primitive. | Read the corresponding `CompilationRecord`; do not force a valid non-temporal or weight-to-weight exclusion into the graph. |
|
|
147
|
+
| Trainable input has no owner | Backward tracing cannot reach a `ParamState`. | Preserve parameter ownership and ensure `trainable_invars_fn` identifies the correct input index. |
|
|
148
|
+
| Hidden grouping is unexpected | Connectivity, shape, or sequential-layer filtering differs from the intended architecture. | Inspect `hidden_path_to_invar`, the hidden-group paths, and each transition Jaxpr. |
|
|
149
|
+
| Hidden state appears inside JAX control flow | The structure is outside the normal direct Jaxpr path. | Consult `ControlFlowPolicy` for conditional conversion, scan unrolling, or structured scan descent; redesign unsupported stateful control flow when compilation still rejects it. |
|
|
150
|
+
|
|
151
|
+
## Low-level boundaries
|
|
152
|
+
|
|
153
|
+
- Compile with representative inputs whose batch and feature shapes match execution.
|
|
154
|
+
- Compile once per stable model structure; do not rebuild the graph inside the training loop.
|
|
155
|
+
- Declare every custom primitive's trainable-input layout instead of relying on the single-weight fallback.
|
|
156
|
+
- Keep `gradient_enabled=True` for identity-like tail primitives only; genuinely trainable weight operations form a tail boundary.
|
|
157
|
+
- Treat `braintrace._op` and `braintrace._compiler` helpers as diagnostic internals, not application-level APIs.
|
|
158
|
+
|
|
159
|
+
## Sources
|
|
160
|
+
|
|
161
|
+
- [Compiler Internals](https://brainx.chaobrain.com/braintrace/advanced/compiler_internals.html)
|
|
162
|
+
- [Compiler, Executor & Diagnostics](https://brainx.chaobrain.com/braintrace/apis/compiler.html)
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# Custom ETP primitives
|
|
2
|
+
|
|
3
|
+
Use this reference only when built-in BrainTrace ETP operations cannot express a required computation. Use parameter-transform hooks for reparameterizing an existing operation; do not register a new primitive for that case.
|
|
4
|
+
|
|
5
|
+
## Registration contract
|
|
6
|
+
|
|
7
|
+
A custom ETP primitive combines one plain JAX implementation, explicit trainable-input metadata, and four online-learning rules. Standard JAX transformation rules are derived automatically.
|
|
8
|
+
|
|
9
|
+
| API or contract | Description |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `register_primitive(name, impl, ...)` | Use to create an `ETPPrimitive` from a plain JAX implementation. Set batching, trainable-input layout, non-trainable input index, and tail behavior during registration. |
|
|
12
|
+
| `trainable_invars_fn(static_params)` | Return `{trainable_name: invar_index}` for every trainable input present under the equation's static parameters. |
|
|
13
|
+
| `x_invar_index` | Identify the non-trainable input consumed by the operation. Use `None` only when no separate input exists. |
|
|
14
|
+
| `primitive.register_etp_rules(...)` | Register all four ETP-specific rules together. |
|
|
15
|
+
| `primitive.bind(*args, **static_params)` | Invoke the primitive directly after registration. |
|
|
16
|
+
| `gradient_enabled` | Leave `False` for genuinely trainable operations. Use `True` only for identity-like tail operations whose ETP rule is a passthrough. |
|
|
17
|
+
|
|
18
|
+
**Invariant:** The names returned by `trainable_invars_fn` are the keys used by trace storage, rule dictionaries, compiler relations, and final gradient routing. Keep them stable and complete.
|
|
19
|
+
|
|
20
|
+
## Rule families
|
|
21
|
+
|
|
22
|
+
The four registries encode the two trace factorizations supported by D-RTRL and pp-prop.
|
|
23
|
+
|
|
24
|
+
| Rule | Exact callable shape | Result |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| `dt_to_t` | `dt_to_t(hidden_dim, trace, **static_params)` | Return a trace dictionary after propagating the previous trace through the hidden-to-hidden term. |
|
|
27
|
+
| `xy_to_dw` | `xy_to_dw(x, hidden_dim, weights, **static_params)` | Return a dictionary containing the instantaneous hidden-to-raw-parameter Jacobian for every trainable key. |
|
|
28
|
+
| `init_drtrl` | `init_drtrl(x_var, y_var, weight_vars, num_hidden_state)` | Return zero-filled parameter-dimensional trace storage, one leaf per trainable key. |
|
|
29
|
+
| `init_pp` | `init_pp(x_var, y_var, weight_vars, num_hidden_state)` | Return one zero-filled output-dimensional df-trace array; pp-prop manages the matching x-trace separately. |
|
|
30
|
+
|
|
31
|
+
The backing dictionaries are `ETP_RULES_DT_TO_T`, `ETP_RULES_XY_TO_DW`, `ETP_RULES_INIT_DRTRL`, and `ETP_RULES_INIT_PP`. A primitive must register both initializers to support both `D_RTRL` and `pp_prop`.
|
|
32
|
+
|
|
33
|
+
## Canonical primitive workflow
|
|
34
|
+
|
|
35
|
+
The following scaled matrix multiplication includes optional bias and exercises every part of the dict-based rule contract.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import jax
|
|
39
|
+
import jax.numpy as jnp
|
|
40
|
+
from braintrace import register_primitive
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _scaled_matmul_impl(*args, scale=1.0, has_bias=False):
|
|
44
|
+
x, weight = args[0], args[1]
|
|
45
|
+
output = scale * (x @ weight)
|
|
46
|
+
if has_bias:
|
|
47
|
+
output = output + args[2]
|
|
48
|
+
return output
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _scaled_trainable_invars(params):
|
|
52
|
+
trainable = {"weight": 1}
|
|
53
|
+
if params.get("has_bias", False):
|
|
54
|
+
trainable["bias"] = 2
|
|
55
|
+
return trainable
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
scaled_mm_p = register_primitive(
|
|
59
|
+
"etp_scaled_mm",
|
|
60
|
+
_scaled_matmul_impl,
|
|
61
|
+
batched=True,
|
|
62
|
+
trainable_invars_fn=_scaled_trainable_invars,
|
|
63
|
+
x_invar_index=0,
|
|
64
|
+
)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Register one rule for each online-learning operation:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
def _scaled_dt_to_t(
|
|
71
|
+
hidden_dim, trace, *, scale=1.0, has_bias=False
|
|
72
|
+
):
|
|
73
|
+
updated = {
|
|
74
|
+
"weight": (
|
|
75
|
+
trace["weight"]
|
|
76
|
+
* jnp.expand_dims(hidden_dim, axis=-2)
|
|
77
|
+
* scale
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
if has_bias:
|
|
81
|
+
updated["bias"] = trace["bias"] * hidden_dim
|
|
82
|
+
return updated
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _scaled_xy_to_dw(
|
|
86
|
+
x, hidden_dim, weights, *, scale=1.0, has_bias=False
|
|
87
|
+
):
|
|
88
|
+
def forward(trainable):
|
|
89
|
+
output = scale * (x @ trainable["weight"])
|
|
90
|
+
if has_bias:
|
|
91
|
+
output = output + trainable["bias"]
|
|
92
|
+
return output
|
|
93
|
+
|
|
94
|
+
_, pullback = jax.vjp(forward, weights)
|
|
95
|
+
return pullback(hidden_dim)[0]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _scaled_init_drtrl(
|
|
99
|
+
x_var, y_var, weight_vars, num_hidden_state
|
|
100
|
+
):
|
|
101
|
+
batch_size = x_var.aval.shape[0]
|
|
102
|
+
traces = {
|
|
103
|
+
"weight": jnp.zeros(
|
|
104
|
+
(
|
|
105
|
+
batch_size,
|
|
106
|
+
*weight_vars["weight"].aval.shape,
|
|
107
|
+
num_hidden_state,
|
|
108
|
+
)
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
if "bias" in weight_vars:
|
|
112
|
+
traces["bias"] = jnp.zeros(
|
|
113
|
+
(
|
|
114
|
+
batch_size,
|
|
115
|
+
*weight_vars["bias"].aval.shape,
|
|
116
|
+
num_hidden_state,
|
|
117
|
+
)
|
|
118
|
+
)
|
|
119
|
+
return traces
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _scaled_init_pp(x_var, y_var, weight_vars, num_hidden_state):
|
|
123
|
+
return jnp.zeros(
|
|
124
|
+
(*y_var.aval.shape, num_hidden_state),
|
|
125
|
+
dtype=y_var.aval.dtype,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
scaled_mm_p.register_etp_rules(
|
|
130
|
+
dt_to_t=_scaled_dt_to_t,
|
|
131
|
+
xy_to_dw=_scaled_xy_to_dw,
|
|
132
|
+
init_drtrl=_scaled_init_drtrl,
|
|
133
|
+
init_pp=_scaled_init_pp,
|
|
134
|
+
)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Bind the registered primitive and verify the forward result:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
x = jnp.ones((4, 3))
|
|
141
|
+
weight = jnp.ones((3, 5))
|
|
142
|
+
bias = jnp.full((5,), 0.1)
|
|
143
|
+
|
|
144
|
+
output = scaled_mm_p.bind(
|
|
145
|
+
x, weight, bias, scale=2.0, has_bias=True
|
|
146
|
+
)
|
|
147
|
+
expected = 2.0 * (x @ weight) + bias
|
|
148
|
+
assert output.shape == (4, 5)
|
|
149
|
+
assert jnp.allclose(output, expected)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
**Invariant:** Derive initializer shapes from the traced avals and the algorithm's trace factorization. Do not copy the example shapes into an operation with different batching, output, or parameter semantics.
|
|
153
|
+
|
|
154
|
+
## Compiler participation
|
|
155
|
+
|
|
156
|
+
`trainable_invars_fn` and `x_invar_index` make the primitive discoverable by the ETP compiler. The compiler then:
|
|
157
|
+
|
|
158
|
+
1. Identifies the primitive by object identity.
|
|
159
|
+
2. Locates every declared trainable input.
|
|
160
|
+
3. Traces each input back to its owning `ParamState` leaf.
|
|
161
|
+
4. Connects the primitive output to reachable, shape-compatible hidden groups.
|
|
162
|
+
5. Allocates algorithm-specific trace State through the registered initializer.
|
|
163
|
+
|
|
164
|
+
A primitive without `trainable_invars_fn` still supports direct binding and standard JAX transformations, and the compiler falls back to `{"weight": 1}`. Declare the layout explicitly for custom work, especially for optional or multiple trainable inputs.
|
|
165
|
+
|
|
166
|
+
Parameter participation remains operation-based:
|
|
167
|
+
|
|
168
|
+
| Goal | Operation |
|
|
169
|
+
|---|---|
|
|
170
|
+
| Include a parameter in online learning | Consume it through the registered ETP primitive. |
|
|
171
|
+
| Exclude a parameter from eligibility traces | Consume it through the corresponding regular JAX operation. |
|
|
172
|
+
|
|
173
|
+
## Tail behavior
|
|
174
|
+
|
|
175
|
+
`gradient_enabled` controls whether an ETP primitive may appear after another trainable primitive on the path to hidden State.
|
|
176
|
+
|
|
177
|
+
| Value | Use when | Compiler behavior |
|
|
178
|
+
|---|---|---|
|
|
179
|
+
| `False` | Use for normal trainable operations such as matrix multiplication, convolution, sparse multiplication, or LoRA. | Treat the primitive as a tail boundary and exclude an upstream ETP weight whose only path to hidden State crosses it. |
|
|
180
|
+
| `True` | Use only for identity-like operations such as element-wise gating parameters. | Allow an upstream relation to pass through the primitive. |
|
|
181
|
+
|
|
182
|
+
**Invariant:** Per-primitive rules cannot represent arbitrary weight-to-weight composition. Do not set `gradient_enabled=True` to silence a valid tail-boundary exclusion.
|
|
183
|
+
|
|
184
|
+
## Validation sequence
|
|
185
|
+
|
|
186
|
+
Validate a custom primitive in this order:
|
|
187
|
+
|
|
188
|
+
1. Compare `primitive.bind()` with an equivalent plain JAX forward computation.
|
|
189
|
+
2. Run `jax.jit`, `jax.grad`, `jax.vmap`, and JVP coverage appropriate to the operation.
|
|
190
|
+
3. Assert every declared trainable key appears in the four rule outputs or initializers where required.
|
|
191
|
+
4. Compile a minimal recurrent model with `D_RTRL` and inspect its included relation and trace shapes.
|
|
192
|
+
5. Compile the same model with `pp_prop` to exercise `init_pp` and factorized trace solving.
|
|
193
|
+
6. Compare online gradients with a reduced oracle in a regime where the selected estimator documents equivalence.
|
|
194
|
+
7. Test optional static layouts such as both `has_bias=False` and `has_bias=True`.
|
|
195
|
+
|
|
196
|
+
Keep user-facing quantity behavior in a wrapper that splits a `brainunit.Quantity` into mantissa and unit, applies the array operation to the mantissa, and recombines the result. Direct primitive registration alone does not define that wrapper contract.
|
|
197
|
+
|
|
198
|
+
## Sources
|
|
199
|
+
|
|
200
|
+
- [Creating Custom ETP Primitives](https://brainx.chaobrain.com/braintrace/advanced/etp_primitives.html)
|