brainx-skill 1.0.10 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +6 -0
  2. package/adapters/antigravity.js +8 -0
  3. package/installation/lib/installer.js +60 -20
  4. package/installation/lib/paths.js +41 -3
  5. package/installation/lib/prompts.js +13 -7
  6. package/manifest.json +2 -1
  7. package/package.json +3 -2
  8. package/skills/braincell/SKILL.md +14 -0
  9. package/skills/brainevent/SKILL.md +1 -0
  10. package/skills/brainmass/SKILL.md +1 -1
  11. package/skills/brainpy-state/SKILL.md +7 -1
  12. package/skills/brainpy-state/references/array-creation.md +2 -2
  13. package/skills/brainpy-state/references/brainPy(legacy)/analysis.md +150 -0
  14. package/skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +373 -0
  15. package/skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +150 -0
  16. package/skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +175 -0
  17. package/skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +286 -0
  18. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +111 -0
  19. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +163 -0
  20. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +113 -0
  21. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +136 -0
  22. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +222 -0
  23. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +123 -0
  24. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +107 -0
  25. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +185 -0
  26. package/skills/brainpy-state/references/brainPy(legacy)/integrators.md +181 -0
  27. package/skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +102 -0
  28. package/skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +147 -0
  29. package/skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +159 -0
  30. package/skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +127 -0
  31. package/skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +167 -0
  32. package/skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +107 -0
  33. package/skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +186 -0
  34. package/skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +104 -0
  35. package/skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +89 -0
  36. package/skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +253 -0
  37. package/skills/brainstate/SKILL.md +14 -10
  38. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +1 -1
  39. package/skills/brainstate/references/braintools/optimizer.md +179 -0
  40. package/skills/braintrace/SKILL.md +161 -0
  41. package/skills/braintrace/references/Drtrl.md +179 -0
  42. package/skills/braintrace/references/ETP operators.md +161 -0
  43. package/skills/braintrace/references/algorithm selection.md +120 -0
  44. package/skills/braintrace/references/batching.md +150 -0
  45. package/skills/braintrace/references/compiler_internal.md +162 -0
  46. package/skills/braintrace/references/custom ETP primitives.md +200 -0
  47. package/skills/braintrace/references/custom algorithms.md +206 -0
  48. package/skills/braintrace/references/customizing_primitive_transforms.md +191 -0
  49. package/skills/braintrace/references/pp_pprop workflow.md +196 -0
  50. package/skills/braintrace/references/pre-built-braintrace-layer.md +149 -0
  51. package/skills/brainx-general-guard/SKILL.md +20 -2
  52. package/skills/brainx-install/SKILL.md +24 -21
  53. package/skills/brainstate/agents/openai.yaml +0 -4
@@ -0,0 +1,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)
@@ -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)