brainx-skill 1.0.11 → 1.0.13

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 (198) hide show
  1. package/README.md +4 -0
  2. package/installation/lib/bundle.js +51 -13
  3. package/manifest.json +2 -0
  4. package/mcp-servers/codex/README.md +62 -0
  5. package/mcp-servers/codex/UPSTREAM.md +20 -0
  6. package/mcp-servers/codex/server.mjs +140 -0
  7. package/mcp-servers/codex/skills.json +10 -0
  8. package/mcp-servers/codex/system-prompt.md +62 -0
  9. package/mcp-servers/codex/test/fixtures/fake-codex.mjs +6 -0
  10. package/mcp-servers/codex/test/server.test.mjs +88 -0
  11. package/package.json +6 -9
  12. package/skills/brainx-acceleration/SKILL.md +459 -0
  13. package/skills/brainx-general-guard/SKILL.md +67 -37
  14. package/skills/brainx-install/SKILL.md +21 -24
  15. package/skills/brainx-modeling-loop/SKILL.md +268 -0
  16. package/skills/brainx-modeling-loop/agents/openai.yaml +4 -0
  17. package/skills/brainx-modeling-loop/references/monitor-experiment.md +49 -0
  18. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow/scripts/fitting_hh_neuron.py +254 -0
  19. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +232 -0
  20. package/skills/brainx-modeling-loop/references/run-experiment.md +179 -0
  21. package/skills/brainx-modeling-loop/references/training-workflow.md +270 -0
  22. package/skills/{braincell → package-skills/braincell}/SKILL.md +3 -16
  23. package/skills/{braincell → package-skills/braincell}/references/mixions-for-adaptation.md +26 -3
  24. package/skills/{braincell → package-skills/braincell}/references/multicompartment/multicompartment-cell-workflow.md +2 -2
  25. package/skills/package-skills/braincell/references/scripts/fitting_hh_neuron.py +254 -0
  26. package/skills/package-skills/braincell/references/scripts/spike_frequency_adaptation.py +135 -0
  27. package/skills/{brainevent → package-skills/brainevent}/SKILL.md +0 -1
  28. package/skills/package-skills/brainevent/references/synaptic-plasticity.md +129 -0
  29. package/skills/{brainmass → package-skills/brainmass}/SKILL.md +10 -5
  30. package/skills/{brainmass → package-skills/brainmass}/references/batch-transform-acceleration.md +44 -3
  31. package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-constraints-regularization.md +1 -1
  32. package/skills/{brainmass → package-skills/brainmass}/references/coupling-network-api.md +121 -3
  33. package/skills/{brainmass → package-skills/brainmass}/references/modellibrary.md +90 -1
  34. package/skills/package-skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +188 -0
  35. package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +98 -0
  36. package/skills/{brainmass → package-skills/brainmass}/references/visualization-analysis-api.md +6 -6
  37. package/skills/{brainpy-state → package-skills/brainpy-state}/SKILL.md +17 -8
  38. package/skills/{brainpy-state → package-skills/brainpy-state}/references/brain-dynamics-delay-protocol.md +52 -1
  39. package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +206 -0
  40. package/skills/package-skills/brainpy-state/references/braintools/input-current.md +199 -0
  41. package/skills/{brainpy-state → package-skills/brainpy-state}/references/component-selection.md +20 -5
  42. package/skills/package-skills/brainpy-state/references/perturbation-experiment-validity.md +76 -0
  43. package/skills/{brainpy-state → package-skills/brainpy-state}/references/projection-patterns.md +3 -1
  44. package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +240 -0
  45. package/skills/{brainstate → package-skills/brainstate}/SKILL.md +12 -15
  46. package/skills/package-skills/brainstate/agents/openai.yaml +4 -0
  47. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-control-flow-patterns.md +8 -0
  48. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  49. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-constraints-regularization.md +1 -1
  50. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/randomness-and-reproducibility.md +1 -1
  51. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-grad-expansion.md +2 -2
  52. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-vmap-expansion.md +58 -8
  53. package/skills/{brainstate → package-skills/brainstate}/references/collective_model_operations.md +26 -27
  54. package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-layer-library.md +1 -1
  55. package/skills/package-skills/brainstate/references/paired-perturbation-execution.md +113 -0
  56. package/skills/package-skills/braintrace/SKILL.md +187 -0
  57. package/skills/package-skills/braintrace/references/Drtrl.md +133 -0
  58. package/skills/{braintrace → package-skills/braintrace}/references/ETP operators.md +31 -4
  59. package/skills/package-skills/braintrace/references/algorithm selection.md +64 -0
  60. package/skills/package-skills/braintrace/references/batching.md +140 -0
  61. package/skills/{braintrace → package-skills/braintrace}/references/compiler_internal.md +2 -2
  62. package/skills/{braintrace → package-skills/braintrace}/references/custom algorithms.md +8 -10
  63. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +179 -0
  64. package/skills/{braintrace → package-skills/braintrace}/references/pre-built-braintrace-layer.md +2 -2
  65. package/skills/{brainpy-state → package-skills/brainunit}/references/array-creation.md +2 -2
  66. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +0 -75
  67. package/skills/brainevent/references/synaptic-plasticity.md +0 -285
  68. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +0 -130
  69. package/skills/brainstate/references/braintools/optimizer.md +0 -179
  70. package/skills/braintrace/SKILL.md +0 -161
  71. package/skills/braintrace/references/Drtrl.md +0 -179
  72. package/skills/braintrace/references/algorithm selection.md +0 -120
  73. package/skills/braintrace/references/batching.md +0 -150
  74. package/skills/braintrace/references/pp_pprop workflow.md +0 -196
  75. /package/skills/{braincell → package-skills/braincell}/references/area-scaled-hh-pattern.md +0 -0
  76. /package/skills/{braincell → package-skills/braincell}/references/braincell-custom-ion-channel-authoring.md +0 -0
  77. /package/skills/{braincell → package-skills/braincell}/references/channel-library.md +0 -0
  78. /package/skills/{braincell → package-skills/braincell}/references/ion-library.md +0 -0
  79. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/braincell-manual-morphology-construction.md +0 -0
  80. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/cv-policy-reference.md +0 -0
  81. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/filter-function-library.md +0 -0
  82. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/morphology-io-loading-validation.md +0 -0
  83. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/probe-reference.md +0 -0
  84. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/topology-building-and-visualization.md +0 -0
  85. /package/skills/{braincell → package-skills/braincell}/references/scripts/calcium_channel_gating.py +0 -0
  86. /package/skills/{braincell → package-skills/braincell}/references/scripts/cell_multicompartment_reference.py +0 -0
  87. /package/skills/{braincell → package-skills/braincell}/references/scripts/channel_ablation.py +0 -0
  88. /package/skills/{braincell → package-skills/braincell}/references/scripts/fi_curve.py +0 -0
  89. /package/skills/{braincell → package-skills/braincell}/references/scripts/hh_neuron_basics.py +0 -0
  90. /package/skills/{braincell → package-skills/braincell}/references/scripts/t_current_rebound.py +0 -0
  91. /package/skills/{braincell → package-skills/braincell}/references/scripts/thalamic_neurons.py +0 -0
  92. /package/skills/{braincell → package-skills/braincell}/references/solver-library-with-effects.md +0 -0
  93. /package/skills/{brainevent → package-skills/brainevent}/references/connectivity-variants.md +0 -0
  94. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-cpu.md +0 -0
  95. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-gpu.md +0 -0
  96. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/102_EI_net_1996.py +0 -0
  97. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/204_joglekar_2018_propagation.py +0 -0
  98. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/coba_ei_teaching.py +0 -0
  99. /package/skills/{brainevent → package-skills/brainevent}/references/sparse-formats.md +0 -0
  100. /package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  101. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/cogtask.md +0 -0
  102. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/data-preprocessing.md +0 -0
  103. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/metric.md +0 -0
  104. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/optimizer.md +0 -0
  105. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/parameter-initializer.md +0 -0
  106. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/surrogate.md +0 -0
  107. /package/skills/{brainmass → package-skills/brainmass}/references/datasets-api.md +0 -0
  108. /package/skills/{brainmass → package-skills/brainmass}/references/fitting-with-objectives-api.md +0 -0
  109. /package/skills/{brainmass → package-skills/brainmass}/references/forward-observation-api.md +0 -0
  110. /package/skills/{brainmass → package-skills/brainmass}/references/horn-task-training.md +0 -0
  111. /package/skills/{brainmass → package-skills/brainmass}/references/noiseprocesses.md +0 -0
  112. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/eeg-fitting-with-gradients.py +0 -0
  113. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/gradient-free-fitting.py +0 -0
  114. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/hopf-bifurcation-single-node.py +0 -0
  115. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/horn-cognitive-task-training.py +0 -0
  116. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/jansen-rit-eeg-proxy.py +0 -0
  117. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/kuramoto-synchronization.py +0 -0
  118. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/linear-baseline-node.py +0 -0
  119. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/resting-state-meg-whole-brain-pipeline.py +0 -0
  120. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/seizure-epileptor-case-study.py +0 -0
  121. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wilson-cowan-ei-dynamics.py +0 -0
  122. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-decision-making.py +0 -0
  123. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-dmf-resting-state.py +0 -0
  124. /package/skills/{brainunit → package-skills/brainpy-state}/references/array-creation.md +0 -0
  125. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/analysis.md +0 -0
  126. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/brainpy legacy workflow.md +0 -0
  127. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -0
  128. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/connecting neurons.md +0 -0
  129. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/customize neuron and synpase.md +0 -0
  130. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Input generation.md +0 -0
  131. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -0
  132. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -0
  133. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -0
  134. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -0
  135. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -0
  136. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/delays.md +0 -0
  137. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -0
  138. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/integrators.md +0 -0
  139. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/route activity through connectivity.md +0 -0
  140. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synaptic projections.md +0 -0
  141. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synpase properties.md +0 -0
  142. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/loss library.md +0 -0
  143. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/optimizers.md +0 -0
  144. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/parameter initializers.md +0 -0
  145. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -0
  146. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/surrogate gradients.md +0 -0
  147. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainer library.md +0 -0
  148. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainingworkflows.md +0 -0
  149. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/brainstate-control-flow-patterns.md +0 -0
  150. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/data-preprocessing.md +0 -0
  151. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/metric.md +0 -0
  152. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/optimizer.md +0 -0
  153. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/parameter-initializer.md +0 -0
  154. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/surrogate.md +0 -0
  155. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/devices.md +0 -0
  156. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/divergence-and-parity.md +0 -0
  157. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/integration-categories.md +0 -0
  158. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/model-library.md +0 -0
  159. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/nest-workflow.md +0 -0
  160. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/network-building.md +0 -0
  161. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brette_et_al_2007.py +0 -0
  162. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_alpha.py +0 -0
  163. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_delta.py +0 -0
  164. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +0 -0
  165. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +0 -0
  166. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/spatial_gaussex.py +0 -0
  167. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/synapsecollection.py +0 -0
  168. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/synapse-and-connectivity.md +0 -0
  169. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/103_COBA_2005.py +0 -0
  170. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/106_COBA_HH_2007.py +0 -0
  171. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/107_gamma_oscillation_1996.py +0 -0
  172. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/109_fast_global_oscillation.py +0 -0
  173. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -0
  174. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/training-snn.py +0 -0
  175. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  176. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-jit-expansion.md +0 -0
  177. /package/skills/{brainstate → package-skills/brainstate}/references/extension_mechanisms.md +0 -0
  178. /package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-activation-library.md +0 -0
  179. /package/skills/{brainstate → package-skills/brainstate}/references/model-interop-and-migration.md +0 -0
  180. /package/skills/{brainstate → package-skills/brainstate}/references/simulation-environment.md +0 -0
  181. /package/skills/{brainstate → package-skills/brainstate}/references/size-inference-variations.md +0 -0
  182. /package/skills/{brainstate → package-skills/brainstate}/references/state-graph-operations.md +0 -0
  183. /package/skills/{brainstate → package-skills/brainstate}/references/state_collections_and_utilities.md +0 -0
  184. /package/skills/{brainstate → package-skills/brainstate}/scripts/integrator_rnn.py +0 -0
  185. /package/skills/{brainstate → package-skills/brainstate}/scripts/lif_neuron_model.py +0 -0
  186. /package/skills/{brainstate → package-skills/brainstate}/scripts/modern_cnn.py +0 -0
  187. /package/skills/{brainstate → package-skills/brainstate}/scripts/resnet.py +0 -0
  188. /package/skills/{braintrace → package-skills/braintrace}/references/custom ETP primitives.md +0 -0
  189. /package/skills/{braintrace → package-skills/braintrace}/references/customizing_primitive_transforms.md +0 -0
  190. /package/skills/{brainunit → package-skills/brainunit}/SKILL.md +0 -0
  191. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics/functional-structural-api.md +0 -0
  192. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics.md +0 -0
  193. /package/skills/{brainunit → package-skills/brainunit}/references/math-function-library.md +0 -0
  194. /package/skills/{brainunit → package-skills/brainunit}/references/physical-constant-library.md +0 -0
  195. /package/skills/{brainunit → package-skills/brainunit}/references/prefix-library.md +0 -0
  196. /package/skills/{brainunit → package-skills/brainunit}/references/quantity-inspection-and-conversion.md +0 -0
  197. /package/skills/{brainunit → package-skills/brainunit}/references/typing-and-runtime-validation.md +0 -0
  198. /package/skills/{brainunit → package-skills/brainunit}/references/unit-structure-and-definition.md +0 -0
@@ -0,0 +1,64 @@
1
+ # Algorithm selection
2
+
3
+ Use this reference when choosing a BrainTrace `0.2.4` estimator beyond the default `D_RTRL`. Use `Drtrl.md` or `pp_pprop workflow.md` for the two canonical training workflows; open `custom algorithms.md` only when no built-in class expresses the method.
4
+
5
+ ## Choose an estimator
6
+
7
+ Choose by trace representation, recurrence approximation, learning signal, and supported mathematical regime.
8
+
9
+ | API | Use when | Essential behavior and constraint |
10
+ |---|---|---|
11
+ | `D_RTRL` | Use as the general RNN default when parameter-dimensional trace memory fits. | Carries parameter-shaped traces with a diagonal hidden-recurrence approximation. |
12
+ | `pp_prop` | Use when parameter-shaped traces are too large, especially for SNNs. | Factorizes each trace into input and output components with exponential smoothing; `ES_D_RTRL` is its compatibility alias. |
13
+ | `EProp` | Use for recurrent SNNs that need kappa-filtered traces or fixed random-feedback learning signals. | Select feedback and filter decay through constructor options. |
14
+ | `OSTLRecurrent` | Use for the OSTL with-H recurrent regime. | Retains recurrent influence according to the implemented OSTL rule. |
15
+ | `OSTLFeedforward` | Use for the OSTL without-H feedforward regime. | Uses an input/output-factorized path and omits recurrent influence. |
16
+ | `OTPE` | Use for deep SNNs requiring the implemented online temporal-processing estimator. | Requires `leak`; select full or approximate mode explicitly. |
17
+ | `OTTT` | Use for very large SNNs using the implemented presynaptic trace rule. | Requires `leak`; report the selected mode. |
18
+ | `OSTTP` | Use for target-projection learning with supplied per-layer feedback matrices. | Requires `B_list`; declare target timing. |
19
+
20
+ `SnAp`, `UORO`, `ThreeFactor`, `DNI`, `SyntheticGradient`, and `ETraceConfig` are not public BrainTrace `0.2.4` APIs. Do not select them from newer documentation when targeting BrainX `v2026.7.9`.
21
+
22
+ ## Compile the chosen algorithm
23
+
24
+ `braintrace.compile` is the shared entry point; options are forwarded to the selected algorithm constructor.
25
+
26
+ | API or option | Description |
27
+ |---|---|
28
+ | `braintrace.compile(model, algorithm, example_step, ...)` | Use once to initialize State, build the graph, and return a learner. |
29
+ | `vjp_method='single-step'` | Use for the normal per-step learning signal. |
30
+ | `vjp_method='multi-step'` | Use only when the algorithm and `MultiStepData` workflow require a recent-window learning signal. |
31
+ | `fast_solve=True` | Use the estimator's fast supported solve path; disable only for a documented incompatibility or comparison. |
32
+ | `trace_dtype=...` | Use when a supported estimator should store eligibility traces in a selected dtype. |
33
+ | `decay_or_rank=...` | Supply for `pp_prop`; use a float decay in `(0, 1)` or a positive integer rank parameterization. |
34
+
35
+ ```python
36
+ learner = braintrace.compile(
37
+ model,
38
+ braintrace.pp_prop,
39
+ example_step,
40
+ batch_size=batch_size,
41
+ vmap=True,
42
+ decay_or_rank=0.95,
43
+ vjp_method='single-step',
44
+ )
45
+ learner.module.report.show(2)
46
+ ```
47
+
48
+ ## Drive the sequence in `0.2.4`
49
+
50
+ BrainTrace `0.2.4` advances hidden and eligibility State on every learner call; BrainState owns the explicit temporal carry and gradient accumulation.
51
+
52
+ | API | Description |
53
+ |---|---|
54
+ | `brainstate.transform.grad(step_loss, weights, ...)` | Use around one learner call to obtain the current online gradient. |
55
+ | `brainstate.transform.scan(...)` | Use when an explicit gradient carry must sum across time. |
56
+ | `braintrace.SingleStepData(data)` | Use to mark one current input; a plain array is equivalent. |
57
+ | `braintrace.MultiStepData(sequence)` | Use when one learner call intentionally consumes a multi-step window. |
58
+
59
+ Do not use `etrace_grad`, `etrace_evolve`, `SequenceDriverMixin`, or `ETraceVmap`; they start in BrainTrace `0.2.5`. Open `batching.md` for mapped and native-batch reset patterns.
60
+
61
+ ## Sources
62
+
63
+ - [BrainTrace `v0.2.4` algorithms API source](https://github.com/chaobrain/braintrace/blob/v0.2.4/docs/apis/algorithms.rst)
64
+ - [BrainTrace `v0.2.4` public API](https://github.com/chaobrain/braintrace/blob/v0.2.4/braintrace/__init__.py)
@@ -0,0 +1,140 @@
1
+ # Batching
2
+
3
+ Use this reference when adding a batch axis to BrainTrace `0.2.4`, selecting native batched execution or independent mapped lanes, resetting mapped State, or scanning time-major data.
4
+
5
+ ## Choose one batching owner
6
+
7
+ | Path | Use when | Owner and constraint |
8
+ |---|---|---|
9
+ | Compile-owned vmap | Use when each example needs independent recurrent and eligibility State. | Pass the unwrapped model to `braintrace.compile(..., batch_size=B, vmap=True)` once. |
10
+ | Native batch | Use when the model and ETP operators accept a leading batch axis directly. | Pass `batch_size=B` and a batched example to `compile(..., vmap=False)`. |
11
+ | Explicit mapping | Use only when compile-owned vmap cannot express the State construction. | Follow the official `vmap_new_states` plus `brainstate.nn.Vmap` pattern and verify reset shapes. |
12
+ | Single stream | Use for one unbatched trajectory. | Omit `batch_size` and `vmap`. |
13
+
14
+ Use exactly one owner. Do not pass an already mapped model to `compile(..., vmap=True)`.
15
+
16
+ ## Compile independent lanes
17
+
18
+ Compile-owned vmap creates per-lane State and returns a `brainstate.nn.Vmap`; its `.module` is the underlying BrainTrace learner.
19
+
20
+ | API | Description |
21
+ |---|---|
22
+ | `braintrace.compile(model, algorithm, example_step, batch_size=B, vmap=True, ...)` | Use with `example_step.shape == (B, features)`; compilation strips axis 0 to build one lane and creates mapped State across `B` lanes. |
23
+ | `mapped_learner.module.report` | Use for compilation diagnostics; the report belongs to the underlying learner. |
24
+ | `mapped_learner.states('new')` | Use to select the mapped State collection for a lane-preserving reset. |
25
+ | `brainstate.transform.vmap(in_states=mapped_states)` | Use to map reset over exactly the State created by compile-owned vmap. |
26
+
27
+ ```python
28
+ import jax
29
+ import jax.numpy as jnp
30
+ import brainstate
31
+ import braintrace
32
+
33
+
34
+ class SimpleGRU(brainstate.nn.Module):
35
+ def __init__(self, n_in, n_rec, n_out):
36
+ super().__init__()
37
+ self.rnn = braintrace.nn.GRUCell(n_in, n_rec)
38
+ self.out = braintrace.nn.Linear(n_rec, n_out)
39
+
40
+ def update(self, x):
41
+ return self.out(self.rnn(x))
42
+
43
+
44
+ batch_size = 16
45
+ example_step = jnp.zeros((batch_size, 10))
46
+ model = SimpleGRU(10, 64, 5)
47
+
48
+ mapped_learner = braintrace.compile(
49
+ model,
50
+ braintrace.D_RTRL,
51
+ example_step,
52
+ batch_size=batch_size,
53
+ vmap=True,
54
+ )
55
+ algorithm = mapped_learner.module
56
+ algorithm.report.show(2)
57
+
58
+ mapped_states = mapped_learner.states('new')
59
+
60
+
61
+ @brainstate.transform.vmap(in_states=mapped_states)
62
+ def reset_sequence():
63
+ brainstate.nn.reset_all_states(mapped_learner)
64
+ ```
65
+
66
+ Capture the shapes of mapped dynamical State before and after the first reset. If any leading lane axis changes, follow BrainState's collective-operations reference and restore an exact snapshot instead of continuing with the broken reset.
67
+
68
+ ## Compile a native batch
69
+
70
+ Use native batching when the model's one-step call already consumes `(B, features)` and initializes State with `batch_size=B`.
71
+
72
+ ```python
73
+ learner = braintrace.compile(
74
+ SimpleGRU(10, 64, 5),
75
+ braintrace.D_RTRL,
76
+ jnp.zeros((16, 10)),
77
+ batch_size=16,
78
+ )
79
+ ```
80
+
81
+ Reset native batched execution with `brainstate.nn.reset_all_states(model, batch_size=16)` and `learner.reset_state(batch_size=16)`. Prefer the compile-owned vmap path when State constructors or custom cells do not implement native batch initialization consistently.
82
+
83
+ ## Accumulate time-major gradients
84
+
85
+ Keep time on axis 0 and batch on axis 1. The scan owns time; compilation owns batch.
86
+
87
+ ```python
88
+ weights = model.states(brainstate.ParamState)
89
+
90
+
91
+ def step_loss(inp, target, mask):
92
+ prediction = mapped_learner(inp)
93
+ loss = jnp.mean((prediction - target) ** 2)
94
+ return loss * mask, prediction
95
+
96
+
97
+ step_grad = brainstate.transform.grad(
98
+ step_loss,
99
+ weights,
100
+ has_aux=True,
101
+ return_value=True,
102
+ )
103
+
104
+
105
+ def accumulate(grads, sample):
106
+ current, loss, prediction = step_grad(*sample)
107
+ grads = jax.tree.map(lambda total, value: total + value, grads, current)
108
+ return grads, (loss, prediction)
109
+
110
+
111
+ initial_grads = jax.tree.map(
112
+ jnp.zeros_like,
113
+ {key: state.value for key, state in weights.items()},
114
+ )
115
+ grads, (losses, outputs) = brainstate.transform.scan(
116
+ accumulate,
117
+ initial_grads,
118
+ (inputs, targets, loss_mask),
119
+ )
120
+ optimizer.update(grads)
121
+ ```
122
+
123
+ Every step must call the learner exactly once, including masked cue and delay steps. A zero mask suppresses the learning signal; it does not suppress recurrent or eligibility-State evolution.
124
+
125
+ ## Use sequence-data wrappers
126
+
127
+ | API | Description |
128
+ |---|---|
129
+ | `braintrace.SingleStepData(data)` | Use to mark `data` as one step; a plain array has the same interpretation. |
130
+ | `braintrace.MultiStepData(sequence)` | Use when one learner call should consume axis 0 as a multi-step window. |
131
+
132
+ Do not use `MultiStepData` as a substitute for the explicit scan when the workflow needs per-step masks, outputs, losses, or a gradient sum followed by one optimizer update.
133
+
134
+ Open `Drtrl.md` or `pp_pprop workflow.md` for estimator-specific training. Open `skills/package-skills/brainstate/references/collective_model_operations.md` when an explicit mapped lifecycle is unavoidable.
135
+
136
+ ## Sources
137
+
138
+ - [BrainTrace `v0.2.4` compile modes](https://github.com/chaobrain/braintrace/blob/v0.2.4/examples/tests/test_compile_modes.py)
139
+ - [BrainTrace `v0.2.4` mapped batching example](https://github.com/chaobrain/braintrace/blob/v0.2.4/examples/pp_prop/05-batching-vmap.py)
140
+ - [BrainTrace `v0.2.4` native batching example](https://github.com/chaobrain/braintrace/blob/v0.2.4/examples/pp_prop/06-batching-batched.py)
@@ -19,7 +19,7 @@ Inspect public compilation results before calling lower-level compiler functions
19
19
  import braintrace
20
20
 
21
21
  learner = braintrace.compile(model, braintrace.D_RTRL, example_input)
22
- learner.report.show(1)
22
+ learner.report.show(2)
23
23
 
24
24
  assert learner.report.counts["errors"] == 0
25
25
  for record in learner.report.diagnostics:
@@ -114,7 +114,7 @@ The graph executor runs the compiled forward graph and produces the hidden-to-we
114
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
115
  | `ETraceVjpGraphExecutor` | Use for algorithms in the `ETraceVjpAlgorithm` family. It provides the VJP-based executor used by the built-in estimators. |
116
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.
117
+ Keep executor calls inside the algorithm lifecycle. Application code should call the compiled learner inside a BrainState loop or scan rather than driving the executor directly. In BrainTrace `0.2.4`, use `brainstate.transform.grad` around one learner call and carry accumulated gradients through `brainstate.transform.scan`; sequence-driver methods begin in `0.2.5`.
118
118
 
119
119
  ## Control-flow policy
120
120
 
@@ -12,7 +12,6 @@ Subclass the nearest estimator engine instead of rebuilding the compiler and exe
12
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
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
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
15
  | `EligibilityTrace` | Use to store algorithm trace State across time; it is a `brainstate.ShortTermState` specialization. |
17
16
 
18
17
  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.
@@ -24,7 +23,7 @@ Use `D_RTRL` as the concrete parameter-dimensional baseline and `pp_prop` as the
24
23
  | 1 | Choose the nearest base estimator. | Existing graph compilation, Jacobian execution, and State separation remain intact. |
25
24
  | 2 | Override the smallest protocol method that expresses the new rule. | Trace dynamics and gradient readout remain separate decisions. |
26
25
  | 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. |
26
+ | 4 | Drive one learner call per step inside a BrainState loop or gradient-carrying scan. | BrainTrace updates eligibility State while BrainState owns temporal control and accumulation. |
28
27
  | 5 | Inspect trace values and compiler diagnostics. | Storage shapes, recurrence behavior, and parameter participation become visible. |
29
28
  | 6 | Reset both algorithm and model State between independent sequences. | Eligibility traces, time index, and recurrent hidden State all start cleanly. |
30
29
 
@@ -78,10 +77,7 @@ Delegate to the parent recurrence, then apply the custom trace rule. This preser
78
77
  import jax
79
78
  import jax.numpy as jnp
80
79
  import braintrace
81
- from braintrace._algorithm.d_rtrl import ParamDimVjpAlgorithm
82
-
83
-
84
- class ClippedDRTRL(ParamDimVjpAlgorithm):
80
+ class ClippedDRTRL(braintrace.ParamDimVjpAlgorithm):
85
81
  """D-RTRL with element-wise trace clipping."""
86
82
 
87
83
  def __init__(self, model, clip_value=1.0, **kwargs):
@@ -120,8 +116,9 @@ learner = braintrace.compile(
120
116
  jnp.zeros(10),
121
117
  clip_value=5.0,
122
118
  )
123
- outputs = learner.etrace_evolve(
124
- jnp.ones((5, 10)), return_outputs=True
119
+ outputs = brainstate.transform.for_loop(
120
+ learner,
121
+ jnp.ones((5, 10)),
125
122
  )
126
123
  assert len(outputs) == 5
127
124
  assert outputs[0].shape == (32,)
@@ -175,7 +172,7 @@ Trace lookup is nested because one parameter leaf can participate in a primitive
175
172
  ```python
176
173
  import brainstate
177
174
 
178
- learner.etrace_evolve(sequence)
175
+ brainstate.transform.for_loop(learner, sequence)
179
176
 
180
177
  for path, weight in model.states(brainstate.ParamState).items():
181
178
  groups = learner.get_etrace_of(weight)
@@ -194,11 +191,12 @@ assert int(learner.running_index.value) == 0
194
191
  ## Execution and validation rules
195
192
 
196
193
  - 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.
194
+ - Differentiate exactly one learner call per step and use `brainstate.transform.scan` when gradients must be accumulated across a sequence. Apply the optimizer after the scan.
198
195
  - Compare an unmodified subclass against its parent before testing the new rule.
199
196
  - Verify trace shapes, finite values, reset-to-zero behavior, parameter-gradient keys, and parameter updates.
200
197
  - 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
198
  - Do not reimplement graph tracing, hidden grouping, Jacobian calculation, or State write-back unless the research method genuinely requires a new base engine.
199
+ - This reference targets BrainTrace `0.2.4`; do not use sequence-driver methods introduced in `0.2.5`.
202
200
 
203
201
  ## Sources
204
202
 
@@ -0,0 +1,179 @@
1
+ # pp-prop workflow
2
+
3
+ Use this reference when input/output-factorized `pp_prop` is preferable to D-RTRL, especially for recurrent SNNs and silent-delay tasks. Open `batching.md` for batching ownership and `ETP operators.md` when a custom projection does not participate.
4
+
5
+ ## Choose pp-prop
6
+
7
+ `pp_prop` carries input-side and output-side eligibility factors with exponential smoothing instead of a parameter-dimensional trace.
8
+
9
+ | API or option | Description |
10
+ |---|---|
11
+ | `braintrace.pp_prop` | Use when factorized `O(B * (I + O))` trace storage is preferable to parameter-shaped storage. |
12
+ | `braintrace.ES_D_RTRL` | Use only for compatibility with historical code; prefer `pp_prop`. |
13
+ | `decay_or_rank=<float>` | Use a value in `(0, 1)` to set exponential decay directly; larger values retain longer history. |
14
+ | `decay_or_rank=<int>` | Use a positive integer to select `decay = (rank - 1) / (rank + 1)`; it does not allocate that many stored factors. |
15
+
16
+ Factorization discards correlations present in an unfactorized trace. Report `decay_or_rank` with results and validate the estimator against BPTT on a reduced matched model when gradient fidelity matters.
17
+
18
+ ## Build an ETP-aware recurrent SNN
19
+
20
+ Use ETP-aware projections for trainable parameter paths, stateful BrainPy-State neurons for dynamics, and an ETP-aware leaky readout for continuous outputs.
21
+
22
+ | API | Description |
23
+ |---|---|
24
+ | `braintrace.nn.Linear(...)` | Use for an input-plus-recurrent projection whose weights participate through ETP primitives. |
25
+ | `braintrace.sparse_matmul(x, weight_data, sparse_mat=...)` | Use for fixed sparse recurrent structure; pass raw numeric/bool spikes as `x` and a BrainEvent `DataRepresentation` as `sparse_mat`. |
26
+ | `brainpy.state.LIF(...)` | Use for leaky integrate-and-fire dynamics with a differentiable surrogate spike function. |
27
+ | `braintrace.nn.LeakyRateReadout(...)` | Use to integrate recurrent spikes into a continuous task output. |
28
+ | `brainstate.environ.context(dt=...)` | Use to scope the physical simulation step around construction and execution. |
29
+
30
+ ```python
31
+ import brainpy.state
32
+ import brainstate
33
+ import braintrace
34
+ import braintools
35
+ import brainunit as u
36
+
37
+
38
+ class LIF_SNN(brainstate.nn.Module):
39
+ def __init__(self, n_in, n_rec, n_out):
40
+ super().__init__()
41
+ self.linear = braintrace.nn.Linear(
42
+ n_in + n_rec,
43
+ n_rec,
44
+ w_init=braintools.init.KaimingNormal(scale=50., unit=u.mA),
45
+ b_init=braintools.init.ZeroInit(unit=u.mA),
46
+ )
47
+ self.neuron = brainpy.state.LIF(
48
+ n_rec,
49
+ tau=20. * u.ms,
50
+ R=1. * u.ohm,
51
+ V_th=0.1 * u.mV,
52
+ V_reset=0. * u.mV,
53
+ V_rest=0. * u.mV,
54
+ spk_fun=braintools.surrogate.ReluGrad(),
55
+ spk_reset='soft',
56
+ )
57
+ self.readout = braintrace.nn.LeakyRateReadout(
58
+ n_rec,
59
+ n_out,
60
+ tau=20. * u.ms,
61
+ w_init=braintools.init.KaimingNormal(),
62
+ )
63
+
64
+ def update(self, x):
65
+ previous = self.neuron.get_spike()
66
+ current = self.linear(u.math.concatenate([x, previous], axis=-1))
67
+ return self.readout(self.neuron(current))
68
+ ```
69
+
70
+ The projection uses current units so `I * R` is voltage-compatible with membrane State and threshold.
71
+
72
+ ## Train a batched spike sequence
73
+
74
+ Compile one-step behavior with per-sample mapped State, reset both State domains, accumulate masked step gradients through a scan, and update once per sequence.
75
+
76
+ | API | Description |
77
+ |---|---|
78
+ | `braintrace.compile(..., braintrace.pp_prop, batch_size=B, vmap=True, decay_or_rank=...)` | Use to create independent recurrent and trace State for each batch lane. |
79
+ | `brainstate.transform.grad(step_loss, weights, has_aux=True, return_value=True)` | Use around one learner call to return the online gradient, masked loss, and output. |
80
+ | `brainstate.transform.scan(...)` | Use to advance every time step and carry the summed gradient. |
81
+ | `brainstate.nn.clip_grad_norm(...)` | Use after accumulation when gradient clipping is required. |
82
+
83
+ ```python
84
+ import jax
85
+ import jax.numpy as jnp
86
+
87
+ n_steps, batch_size = 60, 16
88
+ n_in, n_rec, n_out = 2, 48, 2
89
+ inputs = jnp.zeros((n_steps, batch_size, n_in))
90
+ labels = jnp.arange(batch_size, dtype=jnp.int32) % n_out
91
+ loss_mask = jnp.concatenate([jnp.zeros(50), jnp.ones(10)])
92
+
93
+ with brainstate.environ.context(dt=1. * u.ms):
94
+ model = LIF_SNN(n_in, n_rec, n_out)
95
+ learner = braintrace.compile(
96
+ model,
97
+ braintrace.pp_prop,
98
+ inputs[0],
99
+ batch_size=batch_size,
100
+ vmap=True,
101
+ decay_or_rank=0.9,
102
+ )
103
+ algorithm = learner.module
104
+ algorithm.report.show(2)
105
+ assert algorithm.report.counts['errors'] == 0
106
+
107
+ weights = model.states(brainstate.ParamState)
108
+ optimizer = braintools.optim.Adam(lr=2e-3)
109
+ optimizer.register_trainable_weights(weights)
110
+
111
+ mapped_states = learner.states('new')
112
+
113
+ @brainstate.transform.vmap(in_states=mapped_states)
114
+ def reset_sequence():
115
+ brainstate.nn.reset_all_states(learner)
116
+
117
+ def step_loss(cue, mask):
118
+ output = learner(cue)
119
+ loss = braintools.metric.softmax_cross_entropy_with_integer_labels(
120
+ output,
121
+ labels,
122
+ ).mean()
123
+ return loss * mask, output
124
+
125
+ step_grad = brainstate.transform.grad(
126
+ step_loss,
127
+ weights,
128
+ has_aux=True,
129
+ return_value=True,
130
+ )
131
+
132
+ def train_sequence():
133
+ reset_sequence()
134
+ initial_grads = jax.tree.map(
135
+ jnp.zeros_like,
136
+ {key: state.value for key, state in weights.items()},
137
+ )
138
+
139
+ def accumulate(grads, sample):
140
+ current, loss, output = step_grad(*sample)
141
+ grads = jax.tree.map(lambda x, y: x + y, grads, current)
142
+ return grads, (loss, output)
143
+
144
+ grads, (losses, outputs) = brainstate.transform.scan(
145
+ accumulate,
146
+ initial_grads,
147
+ (inputs, loss_mask),
148
+ )
149
+ optimizer.update(brainstate.nn.clip_grad_norm(grads, 1.0))
150
+ return losses.sum() / loss_mask.sum(), outputs
151
+ ```
152
+
153
+ `step_loss` calls the learner on every cue, delay, and report step. The zero mask removes the loss signal before the report window without freezing hidden or eligibility State. Do not put `optimizer.update()` inside the scan unless the intended experiment explicitly uses per-timestep parameter changes and reports that schedule.
154
+
155
+ ## Validate silent-delay memory
156
+
157
+ A lower training loss does not prove that the first cue survived the delay; use a control that changes the claimed memory variable while preserving the evaluation path.
158
+
159
+ | Check | Required evidence |
160
+ |---|---|
161
+ | Silent interval | Assert that cue input is exactly zero during the declared delay. |
162
+ | Frozen evaluation | Fix evaluation trials, seeds, masks, and metrics before viewing the trained result. |
163
+ | First-cue ablation | Replace or permute only the first cue and rerun the same mapped rollout; accuracy should fall materially relative to intact trials. |
164
+ | Robustness | Prefer held-out stochastic cue realizations or a nearby longer delay when the task permits them. |
165
+ | Schedule | Report sequences and optimizer updates separately; one scan followed by one update means one optimizer update per sequence. |
166
+
167
+ For a deterministic two-cue task with only four combinations, first-cue ablation is the minimum discriminating control. Perfect accuracy on the same four training combinations is insufficient by itself.
168
+
169
+ ## Interpret compiler diagnostics
170
+
171
+ Use `algorithm.report.show(2)` and structured fields together. A parameter may have a rejected unbatched candidate and an included batched relation in the same report. Require zero errors and check that the intended recurrent path appears in `etrace_weights`; do not classify it from warning text alone.
172
+
173
+ Open `compiler_internal.md` only when structured report records cannot explain the relation. Open `ETP operators.md` for sparse input and structure contracts.
174
+
175
+ ## Sources
176
+
177
+ - [BrainTrace `v0.2.4` pp-prop tutorial](https://github.com/chaobrain/braintrace/blob/v0.2.4/docs/tutorials/pp_prop.md)
178
+ - [BrainTrace `v0.2.4` delayed-match example](https://github.com/chaobrain/braintrace/blob/v0.2.4/examples/pp_prop/02-neurons-alif-dms.py)
179
+ - [BrainTrace `v0.2.4` working-memory example](https://github.com/chaobrain/braintrace/blob/v0.2.4/examples/pp_prop/03-neurons-gif-working-memory.py)
@@ -91,7 +91,7 @@ package.
91
91
  ## Compose and compile a recurrent model
92
92
 
93
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
94
+ representative step, then call the learner from a BrainState loop for repeated
95
95
  execution.
96
96
 
97
97
  ```python
@@ -120,7 +120,7 @@ learner = braintrace.compile(
120
120
  sequence = jnp.linspace(-1.0, 1.0, 6).reshape(6, 1)
121
121
  brainstate.nn.reset_all_states(model)
122
122
  learner.reset_state()
123
- outputs = learner.etrace_evolve(sequence, return_outputs=True)
123
+ outputs = brainstate.transform.for_loop(learner, sequence)
124
124
 
125
125
  assert outputs.shape == (6, 1)
126
126
  ```
@@ -143,9 +143,9 @@ import jax.numpy as jnp
143
143
 
144
144
  ## Routing
145
145
 
146
- `array_split()` appears on the tutorial page, but it is a structural operation; route it to `skills/brainunit/references/array-mechanics.md`.
146
+ `array_split()` appears on the tutorial page, but it is a structural operation; route it to `array-mechanics.md`.
147
147
 
148
- Backend extraction and `as_numpy()` belong in `skills/brainunit/references/array-mechanics.md` because they cross an existing array boundary rather than create a scientific quantity from source values.
148
+ Backend extraction and `as_numpy()` belong in `array-mechanics.md` because they cross an existing array boundary rather than create a scientific quantity from source values.
149
149
 
150
150
  ## Cross-family gotchas
151
151
 
@@ -1,75 +0,0 @@
1
- """
2
- Reference script mirrored from:
3
- https://brainx.chaobrain.com/braincell/examples/spike_frequency_adaptation.html
4
-
5
- Purpose:
6
- Advanced single-cell mechanism script. Use when the task asks for spike-frequency adaptation, calcium-dependent afterhyperpolarization, dynamic calcium, `MixIons(k, ca)`, or AHP/KCa currents.
7
-
8
- Use this when:
9
- - The task asks for adaptation or calcium-dependent afterhyperpolarization in a point neuron.
10
- - The agent needs dynamic calcium plus `MixIons(self.k, self.ca)` for AHP/KCa currents.
11
-
12
- Do not use this when:
13
- - The task only needs the minimal HH Na/K/leak current-clamp pattern.
14
- """
15
-
16
- import brainstate
17
- import braintools
18
- import brainunit as u
19
- import numpy as np
20
- import matplotlib.pyplot as plt
21
- import braincell
22
-
23
-
24
- class AdaptingCell(braincell.SingleCompartment):
25
- """A thalamic-relay-style cell with Ca-activated K (AHP) current."""
26
- def __init__(self, size, solver='ind_exp_euler'):
27
- super().__init__(size, V_initializer=braintools.init.Constant(-65. * u.mV),
28
- V_th=20. * u.mV, solver=solver)
29
- self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)
30
- self.na.add(INa=braincell.channel.Na_Ba2002(size, V_sh=-30 * u.mV))
31
- self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV)
32
- self.k.add(IKL=braincell.channel.K_Leak(size, g_max=0.01 * (u.mS / u.cm ** 2)))
33
- self.k.add(IDR=braincell.channel.KDR_Ba2002(size, V_sh=-30. * u.mV, q10=2.0, temp=u.celsius2kelvin(16.)))
34
- # Dynamic calcium is an ODE state used by calcium channels and AHP coupling.
35
- self.ca = braincell.ion.CalciumDetailed(size, C_rest=5e-5 * u.mM,
36
- tau=10. * u.ms, d=0.5 * u.um)
37
- self.ca.add(ICaL=braincell.channel.CaL_IS2008(size, g_max=0.5 * (u.mS / u.cm ** 2)))
38
- self.ca.add(ICaN=braincell.channel.CaN_IS2008(size, g_max=0.5 * (u.mS / u.cm ** 2)))
39
- self.ca.add(ICaT=braincell.channel.CaT_HM1992(size, g_max=2.1 * (u.mS / u.cm ** 2)))
40
- self.ca.add(ICaHT=braincell.channel.CaHT_HM1992(size, g_max=3.0 * (u.mS / u.cm ** 2)))
41
- # AHP current depends on both potassium reversal and calcium concentration.
42
- self.kca = braincell.MixIons(self.k, self.ca)
43
- self.kca.add(IAHP=braincell.channel.AHP_De1994(size, g_max=0.3 * (u.mS / u.cm ** 2)))
44
- self.IL = braincell.channel.IL(size, g_max=0.0075 * (u.mS / u.cm ** 2), E=-70 * u.mV)
45
-
46
-
47
- cell = AdaptingCell(1)
48
- cell.init_state()
49
-
50
- I = 2. * u.uA / u.cm ** 2
51
-
52
-
53
- def step(t):
54
- with brainstate.environ.context(t=t):
55
- cell.update(I)
56
- return cell.V.value, cell.spike.value
57
-
58
-
59
- with brainstate.environ.context(dt=0.01 * u.ms):
60
- times = u.math.arange(0. * u.ms, 500. * u.ms, brainstate.environ.get_dt())
61
- vs, spikes = brainstate.transform.for_loop(step, times)
62
-
63
- spike_times = np.asarray(times[u.math.squeeze(spikes) > 0] / u.ms)
64
- isi = np.diff(spike_times)
65
- print('number of spikes:', spike_times.size)
66
- print('first ISIs (ms):', np.round(isi[:6], 2).tolist())
67
-
68
- fig, axs = plt.subplots(2, 1, figsize=(8, 5))
69
- axs[0].plot(times / u.ms, u.math.squeeze(vs) / u.mV, linewidth=0.8)
70
- axs[0].set_xlabel('Time (ms)'); axs[0].set_ylabel('V (mV)')
71
- axs[0].set_title('Membrane potential under sustained drive')
72
- axs[1].plot(np.arange(1, isi.size + 1), isi, 'o-')
73
- axs[1].set_xlabel('Inter-spike interval index'); axs[1].set_ylabel('ISI (ms)')
74
- axs[1].set_title('ISIs lengthen over time (adaptation)')
75
- plt.tight_layout(); plt.show()