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,76 @@
1
+ # Validate perturbation experiments before scaling
2
+
3
+ Open this reference when a point-neuron experiment estimates tuning or other
4
+ baseline features and then compares matched control and intervention trials. It
5
+ settles which scientific-validity gates must pass before a full causal mapping
6
+ run and how to calibrate intervention delivery without tuning the requested
7
+ outcome.
8
+
9
+ ## Separate model validity from the tested result
10
+
11
+ Freeze the hypothesis tests only after establishing that the model produces
12
+ observable baseline responses and that the intervention reaches its declared
13
+ target. Use pilot data only for these protocol checks. Do not inspect downstream
14
+ influence signs, distance profiles, feature effects, or other requested outcomes
15
+ while choosing the operating regime or intervention strength.
16
+
17
+ | Gate | Required evidence before a formal run |
18
+ |---|---|
19
+ | Baseline operating regime | Report population and subgroup firing-rate distributions, silent fractions, and trial-count windows; reject a regime whose response statistic is almost always zero or saturated. |
20
+ | Stimulus identifiability | Show that repeated unperturbed trials yield non-degenerate response vectors, adequate reliability or dynamic range, and enough supported preferences or feature values for the planned comparisons. |
21
+ | Analysis support | Construct the exact planned eligibility filters and bins on pilot data; report finite-value, unique-value, bin, target, and effective-cluster counts, and reject empty or tie-dominated contrasts. |
22
+ | Intervention delivery | Measure the paired target-neuron response in the declared dose window and compare it with the stated protocol tolerance or cited benchmark. |
23
+ | Causal pairing | Verify identical initial State and external inputs before intervention onset and zero pre-intervention response mismatches. |
24
+
25
+ Define numerical acceptance rules from the scientific question, cited protocol,
26
+ measurement resolution, and planned estimator before running the pilot. Do not
27
+ invent universal firing-rate or bin-count thresholds. Preserve the rules and all
28
+ failed gate results in the run artifacts.
29
+
30
+ ## Calibrate only the delivered intervention
31
+
32
+ When the stimulus waveform is an implementation proxy for a published
33
+ intervention, select its amplitude using target-neuron dose alone. Use a small,
34
+ predeclared candidate grid or monotone search, run matched pilot trials, and
35
+ choose according to the predeclared dose tolerance. Record every candidate,
36
+ trial count, measured target increment, uncertainty, and selection rule.
37
+
38
+ Do not select amplitude from non-target influence, suppression, feature
39
+ specificity, distance dependence, or any other reproduction outcome. If no
40
+ candidate satisfies the target-dose rule without invalidating the baseline
41
+ regime, classify the protocol as invalid and stop.
42
+
43
+ Generate each pilot's unit-aware waveform once and pass it through the same
44
+ BrainPy-State neuron and projection path used by the formal run. Measure the
45
+ executed spike increment; a requested current or pulse count is not the delivered
46
+ biological dose.
47
+
48
+ ## Freeze and scale
49
+
50
+ After all gates pass, freeze model parameters, randomization rules, target
51
+ selection, intervention, eligibility filters, estimators, uncertainty method,
52
+ and success criteria. Then start a new immutable formal run and allow its result
53
+ to be positive, negative, or inconclusive.
54
+
55
+ Keep the pilot and formal artifacts distinct. A failed pilot is protocol
56
+ development evidence, not a scientific non-reproduction. A completed formal run
57
+ with adequate observability and support may legitimately fail every requested
58
+ hypothesis.
59
+
60
+ Open `skills/package-skills/brainstate/references/paired-perturbation-execution.md` for exact
61
+ State branching, fixed-shape batching, resource gates, and execution-status
62
+ classification. Open `references/braintools/input-current.md` when constructing
63
+ the unit-aware intervention waveform.
64
+
65
+ ## Boundaries and common failures
66
+
67
+ - Treating a successfully executed but nearly silent network as an informative
68
+ null experiment.
69
+ - Estimating preferences by `argmax` when most response vectors are tied at
70
+ zero, then interpreting the tie-broken labels as tuning.
71
+ - Plotting nominal quantile bins without reporting empty bins, tied values, or
72
+ effective target counts.
73
+ - Matching the requested current waveform but failing to measure the added
74
+ target spikes or other delivered dose.
75
+ - Adjusting connectivity or intervention strength after seeing the sign of a
76
+ downstream influence statistic.
@@ -111,10 +111,12 @@ Choose projection alignment before adding a delay. Open `references/brain-dynami
111
111
 
112
112
  ## Communication boundary
113
113
 
114
- Use `brainstate.nn.EventFixedProb` for the canonical probabilistic sparse-spike connection shown in BrainPy-State tutorials. Open `skills/brainevent/SKILL.md` when the decision involves `EventLinear`, fixed-number event connectivity, sparse formats, plasticity operators, custom kernels, or dense-to-event performance conversion.
114
+ Use `brainstate.nn.EventFixedProb` for the canonical probabilistic sparse-spike connection shown in BrainPy-State tutorials. Open `skills/package-skills/brainevent/SKILL.md` when the decision involves `EventLinear`, fixed-number event connectivity, sparse formats, plasticity operators, custom kernels, or dense-to-event performance conversion.
115
115
 
116
116
  Open `references/scripts/103_COBA_2005.py` for a complete E/I COBA projection workflow. Open `references/scripts/109_fast_global_oscillation.py` when the projection uses `DeltaProj` with delayed recurrent input.
117
117
 
118
+ Open `references/scripts/sound_localization.py` when independent conditions require a mapped bank of heterogeneous integer event taps feeding BrainEvent fixed-fan-out communication and coincidence detectors.
119
+
118
120
  ## Official sources
119
121
 
120
122
  - `https://brainx.chaobrain.com/brainpy-state/concepts/model-anatomy.html`
@@ -0,0 +1,240 @@
1
+ """Localize sound direction from interaural spike timing.
2
+
3
+ Positive interaural time difference (ITD) means the right-ear spike arrives
4
+ later, so the source is on the left. Negative ITD means the source is right.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import brainevent
10
+ import brainpy
11
+ import brainstate
12
+ import braintools
13
+ import brainunit as u
14
+ import jax.numpy as jnp
15
+ import numpy as np
16
+ from brainstate.transform import vmap2
17
+ from brainstate.util import filter as util_filter
18
+
19
+
20
+ DT = 0.05 * u.ms
21
+ NUM_STEPS = 80
22
+ DURATION = NUM_STEPS * DT
23
+ SOUND_ONSET = 40 * DT
24
+
25
+ PREFERRED_DELAY_STEPS = jnp.arange(-12, 13, dtype=jnp.int32)
26
+ PREFERRED_ITDS = PREFERRED_DELAY_STEPS * DT
27
+ MAX_INTERNAL_DELAY_STEPS = 12
28
+ EVALUATION_ITDS = u.math.asarray(
29
+ [-0.53, -0.33, -0.17, -0.075, -0.05, 0.0, 0.05, 0.075, 0.17, 0.33, 0.53]
30
+ ) * u.ms
31
+
32
+ V_REST = -60.0 * u.mV
33
+ V_THRESHOLD = -50.0 * u.mV
34
+ V_RESET = -60.0 * u.mV
35
+ AUDITORY_PULSE = 27.0 * u.mA
36
+ DETECTOR_WEIGHT = 24.0 * u.mA
37
+ READOUT_WEIGHT = 120.0 * u.mA
38
+
39
+ DYNAMICAL_STATE = util_filter.Any(
40
+ util_filter.OfType(brainstate.HiddenState),
41
+ util_filter.OfType(brainstate.ShortTermState),
42
+ )
43
+
44
+
45
+ def _lif_population(size: int, tau, tau_ref):
46
+ return brainpy.state.LIFRef(
47
+ size,
48
+ R=1.0 * u.ohm,
49
+ tau=tau,
50
+ tau_ref=tau_ref,
51
+ V_rest=V_REST,
52
+ V_th=V_THRESHOLD,
53
+ V_reset=V_RESET,
54
+ V_initializer=braintools.init.Constant(V_REST),
55
+ )
56
+
57
+
58
+ class EventDelayLine(brainstate.nn.Module):
59
+ """Small integer delay bank with step 0 equal to the current event."""
60
+
61
+ def __init__(self, max_steps: int):
62
+ super().__init__()
63
+ self.max_steps = max_steps
64
+
65
+ def init_state(self):
66
+ self.history = brainstate.HiddenState(
67
+ jnp.zeros((self.max_steps + 1, 2), dtype=jnp.bool_)
68
+ )
69
+
70
+ def update(self, events):
71
+ self.history.value = jnp.concatenate(
72
+ [events[None, :], self.history.value[:-1]],
73
+ axis=0,
74
+ )
75
+ return self.history.value
76
+
77
+
78
+ class SoundLocalizer(brainstate.nn.Module):
79
+ """Two auditory relays, a coincidence bank, and left/right readouts."""
80
+
81
+ def __init__(self):
82
+ super().__init__()
83
+ self.num_detectors = int(PREFERRED_DELAY_STEPS.shape[0])
84
+ self.auditory = _lif_population(2, tau=0.1 * u.ms, tau_ref=0.5 * u.ms)
85
+ self.detectors = _lif_population(
86
+ self.num_detectors,
87
+ tau=0.2 * u.ms,
88
+ tau_ref=0.5 * u.ms,
89
+ )
90
+ self.readout = _lif_population(2, tau=0.5 * u.ms, tau_ref=0.5 * u.ms)
91
+
92
+ self.ear_history = EventDelayLine(MAX_INTERNAL_DELAY_STEPS)
93
+ self.left_delay_steps = jnp.maximum(PREFERRED_DELAY_STEPS, 0)
94
+ self.right_delay_steps = jnp.maximum(-PREFERRED_DELAY_STEPS, 0)
95
+
96
+ detector_targets = jnp.concatenate(
97
+ [jnp.arange(self.num_detectors), jnp.arange(self.num_detectors)]
98
+ )[:, None]
99
+ self.detector_connection = brainevent.FixedNumPerPre(
100
+ DETECTOR_WEIGHT,
101
+ detector_targets,
102
+ shape=(2 * self.num_detectors, self.num_detectors),
103
+ )
104
+
105
+ readout_targets = jnp.where(PREFERRED_DELAY_STEPS > 0, 0, 1)[:, None]
106
+ readout_weights = (
107
+ (PREFERRED_DELAY_STEPS != 0).astype(jnp.float32)[:, None]
108
+ * READOUT_WEIGHT
109
+ )
110
+ self.readout_connection = brainevent.FixedNumPerPre(
111
+ readout_weights,
112
+ readout_targets,
113
+ shape=(self.num_detectors, 2),
114
+ )
115
+
116
+ def update(self, t, itd_step):
117
+ with brainstate.environ.context(t=t):
118
+ arrivals = u.math.asarray(
119
+ [SOUND_ONSET, SOUND_ONSET + itd_step * DT]
120
+ )
121
+ ear_drive = (
122
+ u.math.abs(t - arrivals) < 0.25 * brainstate.environ.get_dt()
123
+ ) * AUDITORY_PULSE
124
+ ear_spikes = self.auditory(ear_drive) != 0.0
125
+
126
+ history = self.ear_history.update(ear_spikes)
127
+ left_events = history[self.left_delay_steps, 0]
128
+ right_events = history[self.right_delay_steps, 1]
129
+ delayed_events = jnp.concatenate([left_events, right_events])
130
+
131
+ detector_current = (
132
+ brainevent.BinaryArray(delayed_events) @ self.detector_connection
133
+ )
134
+ detector_spikes = self.detectors(detector_current) != 0.0
135
+
136
+ readout_current = (
137
+ brainevent.BinaryArray(detector_spikes) @ self.readout_connection
138
+ )
139
+ readout_spikes = self.readout(readout_current) != 0.0
140
+ return ear_spikes, detector_spikes, readout_spikes
141
+
142
+
143
+ def simulate_itds(itds=EVALUATION_ITDS):
144
+ """Round unit-bearing ITDs to ``dt`` and evaluate independent conditions."""
145
+ itds = u.math.asarray(itds, unit=u.ms)
146
+ if itds.ndim != 1:
147
+ raise ValueError("itds must be a one-dimensional time quantity")
148
+ itd_steps = jnp.rint(
149
+ itds.to_decimal(u.ms) / DT.to_decimal(u.ms)
150
+ ).astype(jnp.int32)
151
+
152
+ with brainstate.environ.context(dt=DT):
153
+ net = SoundLocalizer()
154
+ brainstate.nn.vmap_init_all_states(net, axis_size=itds.shape[0])
155
+ mapped_step = vmap2(
156
+ net.update,
157
+ in_axes=(None, 0),
158
+ out_axes=0,
159
+ state_in_axes={0: DYNAMICAL_STATE},
160
+ state_out_axes={0: DYNAMICAL_STATE},
161
+ unexpected_out_state_mapping="raise",
162
+ )
163
+ times = u.math.arange(0.0 * u.ms, DURATION, DT)
164
+
165
+ def step(t):
166
+ return mapped_step(t, itd_steps)
167
+
168
+ ear_spikes, detector_spikes, readout_spikes = (
169
+ brainstate.transform.for_loop(step, times)
170
+ )
171
+
172
+ return (
173
+ jnp.sum(ear_spikes, axis=0),
174
+ jnp.sum(detector_spikes, axis=0),
175
+ jnp.sum(readout_spikes, axis=0),
176
+ )
177
+
178
+
179
+ def decode_directions(detector_counts, readout_counts):
180
+ """Decode only rows supported by coincidence-detector evidence."""
181
+ detectors = np.asarray(detector_counts)
182
+ counts = np.asarray(readout_counts)
183
+ if np.any(detectors.sum(axis=1) == 0):
184
+ raise ValueError("cannot decode a condition with no detector evidence")
185
+
186
+ labels = np.full(counts.shape[0], "CENTER", dtype="<U6")
187
+ labels[counts[:, 0] > counts[:, 1]] = "LEFT"
188
+ labels[counts[:, 1] > counts[:, 0]] = "RIGHT"
189
+
190
+ ties = counts[:, 0] == counts[:, 1]
191
+ winning_steps = np.asarray(PREFERRED_DELAY_STEPS)[np.argmax(detectors, axis=1)]
192
+ if np.any(ties & (winning_steps != 0)):
193
+ raise ValueError("readout tie is not supported by the center detector")
194
+ return labels
195
+
196
+
197
+ def assert_delay_convention():
198
+ """Prove that tap 3 returns an impulse after three completed updates."""
199
+ with brainstate.environ.context(dt=DT):
200
+ delay = EventDelayLine(max_steps=3)
201
+ brainstate.nn.init_all_states(delay)
202
+ impulse = jnp.zeros((5, 2), dtype=jnp.bool_).at[0, 0].set(True)
203
+ history = brainstate.transform.for_loop(delay.update, impulse)
204
+ expected = jnp.array([False, False, False, True, False])
205
+ assert jnp.array_equal(history[:, 3, 0], expected)
206
+
207
+
208
+ def main():
209
+ assert_delay_convention()
210
+ ear_counts, detector_counts, readout_counts = simulate_itds()
211
+ directions = decode_directions(detector_counts, readout_counts)
212
+ evaluated = np.asarray(EVALUATION_ITDS.to_decimal(u.ms))
213
+ preferences = np.asarray(PREFERRED_ITDS.to_decimal(u.ms))
214
+ detectors = np.asarray(detector_counts)
215
+ readouts = np.asarray(readout_counts)
216
+
217
+ print(" ITD (ms) | detector (ms) | L/R spikes | direction")
218
+ print("----------+---------------+------------+----------")
219
+ for itd, detector_row, readout_row, direction in zip(
220
+ evaluated, detectors, readouts, directions
221
+ ):
222
+ detector_itd = preferences[int(np.argmax(detector_row))]
223
+ print(
224
+ f"{itd:9.2f} | {detector_itd:13.2f} |"
225
+ f" {readout_row[0]:3d}/{readout_row[1]:<3d} | {direction}"
226
+ )
227
+
228
+ if not np.all(np.asarray(ear_counts) == 1):
229
+ raise RuntimeError("each auditory relay must emit exactly one spike")
230
+ expected = np.where(
231
+ evaluated < 0.0,
232
+ "RIGHT",
233
+ np.where(evaluated > 0.0, "LEFT", "CENTER"),
234
+ )
235
+ if not np.array_equal(directions, expected):
236
+ raise RuntimeError("direction decoding failed")
237
+
238
+
239
+ if __name__ == "__main__":
240
+ main()
@@ -3,7 +3,7 @@ name: brainstate
3
3
  description: BrainState is the central stateful execution infrastructure for BrainX modeling and simulation. Use this skill for mutable State and `.value`, ParamState and other State roles, Module graphs, environment-scoped simulations, state initialization, operational randomness, size-aware neural-network composition, state-aware jit/grad/vmap, or a BrainState training step.
4
4
  ---
5
5
 
6
- # BrainState
6
+ # Brainstate
7
7
 
8
8
  ## Purpose and boundary
9
9
 
@@ -299,7 +299,7 @@ batched_prediction = predict_batch(x_train)
299
299
  assert batched_prediction.shape == (64, 1)
300
300
  ```
301
301
 
302
- This maps a function written for one example over a batch. Open the `vmap` expansion for mapped State axes, ensembles, parameter sweeps, or the documented `state_in_axes` / `state_out_axes` controls. The routed tutorial does not define the rough draft's `in_states` / `out_states` names.
302
+ This maps a function written for one example over a batch. Open the `vmap` expansion for mapped State axes, ensembles, or parameter sweeps. Use `vmap(..., in_states=..., out_states=...)` to declare specific mapped State instances; use `vmap2(..., state_in_axes=..., state_out_axes=...)` to select State by filters with configurable output-axis inference. Do not add either transform when the owning package already exposes the required batch axis.
303
303
 
304
304
  ### 6. Randomness
305
305
 
@@ -334,6 +334,13 @@ assert input_spikes.shape == (num_steps, batch_size, num_inputs)
334
334
 
335
335
  Open `references/brainstate/randomness-and-reproducibility.md` for independent `RandomState` streams, direct key control, stochastic mapping, exact replay, or checkpointed RNG State.
336
336
 
337
+ ## Script references
338
+
339
+ - `scripts/integrator_rnn.py`: full stateful sequence-training workflow with a custom RNN cell, trainable initial state, optimization, compiled steps, and evaluation.
340
+ - `scripts/lif_neuron_model.py`: extended combination of `HiddenState`, `ShortTermState`, and `ParamState` with explicit `.value` updates.
341
+ - `scripts/modern_cnn.py`: full convolution, normalization, activation, pooling, dropout, and dense Module composition. Select it through the layer or activation branch.
342
+ - `scripts/resnet.py`: residual Modules and dynamically registered child blocks.
343
+
337
344
  ## Reference routing
338
345
 
339
346
  Route by the outcome the task needs, then open only the smallest reference that owns that variant.
@@ -345,6 +352,7 @@ Route by the outcome the task needs, then open only the smallest reference that
345
352
  | `references/state-graph-operations.md` | Splitting, transforming, checkpointing, or reconstructing Module graphs while preserving sharing and cycles |
346
353
  | `references/state_collections_and_utilities.md` | Filtering, freezing, flattening, configuring, or inspecting supporting mappings without graph identity |
347
354
  | `references/collective_model_operations.md` | Initializing, resetting, restoring, or invoking methods across a Module graph, including vmapped lifecycle operations |
355
+ | `references/paired-perturbation-execution.md` | Running matched baseline-perturbation simulations with exact causal branching, fixed-shape chunks, progressive resource gates, and explicit execution-versus-science outcome classification |
348
356
 
349
357
  ### Simulation environment
350
358
 
@@ -365,12 +373,12 @@ Route by the outcome the task needs, then open only the smallest reference that
365
373
  | Reference | Open when |
366
374
  |---|---|
367
375
  | `references/brainstate/parameter-constraints-regularization.md` | Using `nn.Param` transforms, regularizers, priors, penalties, or `nn.Const` |
368
- | `references/braintools/optimizer.md` | Selecting a `braintools.optim`, Optax, SciPy, or Nevergrad optimizer or scheduler |
376
+ | `references/braintools-optimizer-reference.md` | Selecting a `braintools.optim`, Optax, SciPy, or Nevergrad optimizer or scheduler |
369
377
  | `references/brainstate/randomness-and-reproducibility.md` | Creating independent random streams or exact stochastic replay across transforms and checkpoints |
370
378
 
371
379
  The remaining nested reference has one inbound route:
372
380
 
373
- - Only `references/brainstate/parameter-constraints-regularization.md` may open `references/brainstate/parameter-transforms-regularizers-catalog.md`.
381
+ - Only `parameter-constraints-regularization.md` may open `parameter-transforms-regularizers-catalog.md`.
374
382
 
375
383
  ### Layer libraries
376
384
 
@@ -390,14 +398,3 @@ The remaining nested reference has one inbound route:
390
398
  | `references/brainstate/brainstate-transformed-diagnostics.md` | Debugging runtime values or enforcing invariants inside transformed stateful code |
391
399
 
392
400
  Do not route to dynamics or solver references from this skill; they are outside the architecture supplied for this BrainState skill.
393
-
394
- ## Application script examples
395
-
396
- Open one script only when its pattern matches the task; each is a complete, runnable program.
397
-
398
- | Script | Open when |
399
- |---|---|
400
- | `scripts/integrator_rnn.py` | Building a full stateful sequence-training workflow with a custom RNN cell, trainable initial state, optimization, compiled steps, and evaluation. |
401
- | `scripts/lif_neuron_model.py` | Combining `HiddenState`, `ShortTermState`, and `ParamState` in one Module with explicit `.value` updates. |
402
- | `scripts/modern_cnn.py` | Composing convolution, normalization, activation, pooling, dropout, and dense Modules; select it through the layer or activation branch. |
403
- | `scripts/resnet.py` | Building residual Modules and dynamically registered child blocks. |
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "BrainState"
3
+ short_description: "Build stateful BrainState modules and transforms"
4
+ default_prompt: "Use $brainstate to build or debug a stateful BrainState model."
@@ -205,6 +205,14 @@ gradients through a long rollout make activation memory the binding constraint.
205
205
  Tune `base` by measuring peak memory and step time: it controls checkpoint
206
206
  granularity, so lower memory requires more backward recomputation.
207
207
 
208
+ Choose the transform boundary from the State lifecycle, not from a goal of
209
+ eliminating every host loop. Put all timesteps of one logical rollout in
210
+ `for_loop` or `scan`. When trials must remain sequential because learned State
211
+ passes from trial N to trial N+1, but neural and short-term State must reset at
212
+ each trial boundary, compile one complete trial callable and use a small host
213
+ loop across trials. Do not nest the trials in another transformed loop when
214
+ that prevents the required selective reset.
215
+
208
216
  **Invariant:** Initialize recurrent State before each rollout, keep the
209
217
  checkpointed loop inside `loss_fn`, differentiate that loss, then JIT the whole
210
218
  training step. Checkpointing changes the memory/compute profile, not the
@@ -1,6 +1,6 @@
1
1
  # BrainState transformed diagnostics
2
2
 
3
- Use this reference after `skills/brainstate/SKILL.md` when runtime values, State
3
+ Use this reference after `skills/package-skills/brainstate/SKILL.md` when runtime values, State
4
4
  updates, or failures must be inspected from transformed BrainState code. The
5
5
  skill owns the core transformation model; this reference only adds diagnostics
6
6
  that execute after tracing or turn value-dependent failures into data or
@@ -1,6 +1,6 @@
1
1
  # BrainState constrained and regularized parameters
2
2
 
3
- Use this reference after `skills/brainstate/SKILL.md` has selected
3
+ Use this reference after `skills/package-skills/brainstate/SKILL.md` has selected
4
4
  `brainstate.nn.Param` for a value that needs a valid-domain transform, a
5
5
  regularization penalty, a modeling prior, or fixed parameter-like storage. It
6
6
  owns the operational workflow and common patterns. Open
@@ -1,6 +1,6 @@
1
1
  # Brainstate randomness and reproducibility
2
2
 
3
- Use this reference after `skills/brainstate/SKILL.md` for advanced randomness. It covers independent streams, stochastic transforms, key control, parallel keys, replay, and checkpointing.
3
+ Use this reference after `skills/package-skills/brainstate/SKILL.md` for advanced randomness. It covers independent streams, stochastic transforms, key control, parallel keys, replay, and checkpointing.
4
4
 
5
5
  The root skill owns `brainstate.random.DEFAULT` and ordinary seeding. This reference owns advanced stream and key control.
6
6
 
@@ -1,6 +1,6 @@
1
1
  # BrainState gradient and autodiff expansion
2
2
 
3
- Use this reference after `skills/brainstate/SKILL.md` when a task needs gradient targets beyond the main skill's minimal parameter update, exact `return_value`/`has_aux` destructuring, state discovery in an arbitrary function, vector- or matrix-valued sensitivities, second derivatives, or an optimizer-integrated fitting step. The main skill owns the canonical `ParamState` collection and manual update; the parameter reference owns the choice between `ParamState` and `nn.Param`.
3
+ Use this reference after `skills/package-skills/brainstate/SKILL.md` when a task needs gradient targets beyond the main skill's minimal parameter update, exact `return_value`/`has_aux` destructuring, state discovery in an arbitrary function, vector- or matrix-valued sensitivities, second derivatives, or an optimizer-integrated fitting step. The main skill owns the canonical `ParamState` collection and manual update; the parameter reference owns the choice between `ParamState` and `nn.Param`.
4
4
 
5
5
  These three sources do not establish BrainCell solver, reset, or conductance-fitting semantics. Specialized dynamics belongs to the matching BrainCell or BrainPy-State skill; use this reference only for the source-supported autodiff contract around that computation.
6
6
 
@@ -440,7 +440,7 @@ def train_step(x, y):
440
440
  return loss
441
441
  ```
442
442
 
443
- Return to `skills/brainstate/SKILL.md` for the general training structure. Open `references/braintools/optimizer.md` only for optimizer or scheduler selection.
443
+ Return to `skills/package-skills/brainstate/SKILL.md` for the general training structure. Open `references/braintools-optimizer-reference.md` only for optimizer or scheduler selection.
444
444
 
445
445
  Official source: https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html
446
446
 
@@ -1,7 +1,7 @@
1
1
  # BrainState vmap expansion
2
2
 
3
3
  Use this reference after the minimal `brainstate.transform.vmap` example in
4
- `skills/brainstate/SKILL.md` when argument axes, State axes, random-key policy,
4
+ `skills/package-skills/brainstate/SKILL.md` when argument axes, State axes, random-key policy,
5
5
  nested mappings, or unexpected State writes require explicit control.
6
6
 
7
7
  This reference covers only behavior demonstrated by these routed official tutorials:
@@ -9,10 +9,7 @@ This reference covers only behavior demonstrated by these routed official tutori
9
9
  - Vectorization: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html
10
10
  - Random Number Generation: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
11
11
 
12
- The Vectorization tutorial describes `brainstate.transform.vmap` as a
13
- state-aware wrapper around `jax.vmap`, but its detailed executable examples use
14
- `brainstate.transform.vmap2`. Preserve that distinction; do not silently
15
- substitute one API for the other.
12
+ The Vectorization tutorial demonstrates filter-based `vmap2`; the current generated API pages define both mapping contracts. Use `vmap` when specific State instances must be declared with `in_states` and `out_states`. Use `vmap2` when State filters, automatic output-axis inference, or `unexpected_out_state_mapping` are required. Do not silently substitute one contract for the other.
16
13
 
17
14
  ## Selection map
18
15
 
@@ -22,6 +19,7 @@ substitute one API for the other.
22
19
  | Place the mapped output axis | `out_axes` | Match the downstream layout explicitly. |
23
20
  | Map with no mapped input argument | `axis_size` | Supply the size because it cannot be inferred. |
24
21
  | Use collectives over the mapped axis | `axis_name` | The collective must use the same name. |
22
+ | Map explicitly named State instances | `vmap(..., in_states=..., out_states=...)` | Declare every mapped input State and written output State; undeclared batched writes raise `BatchAxisError`. |
25
23
  | Map mutable State but share parameters | `vmap2(..., state_in_axes=..., state_out_axes=...)` with State filters | Define both input mapping and write-back for per-instance State. |
26
24
  | Handle a written State omitted from `state_out_axes` | `vmap2(..., unexpected_out_state_mapping=...)` | The default `'auto'` infers and scatters the mapped axis; declare State axes when a coincidental leading-size match would be ambiguous. |
27
25
  | Choose independent or shared random draws | BrainState automatic splitting or one broadcast JAX key | Shared keys intentionally correlate mapped results. |
@@ -138,11 +136,59 @@ assert model.param.value == 1.0
138
136
 
139
137
  This bundles the State-axis decision with the executable pattern: each mapped element owns one `temp` value, while every element reads the same scalar parameter. For an ordinary `nn.Module` with no State-axis filters, the tutorial says Module states are typically shared, or broadcast, across the batch by default.
140
138
 
141
- ### Exact parameter names
139
+ A shared State remains unbatched and is omitted from the mapped State axis. Keep it read-only during the mapped call. Broadcasting identical values to shape `(batch, ...)` and then mapping axis 0 creates independent copies with batch-scaled storage; it does not share one State. Map a State that each lane may write, but keep an unbatched State shared only when concurrent lanes do not update it.
142
140
 
143
- Neither routed tutorial defines mapping parameters named `in_states` or `out_states`. The exact documented names in the Vectorization tutorial are `state_in_axes` and `state_out_axes`; do not present `in_states` / `out_states` as aliases without opening an official API page that defines them.
141
+ ### Map a complete step inside one time loop
144
142
 
145
- Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#state-aware-parameters-state-in-axes-and-state-out-axes
143
+ Use `vmap_init_all_states` to allocate one dynamical State lane per independent rollout, map the complete per-step transition with semantic State-role filters, then call that mapped step from one `for_loop`. The mapping owns the condition axis and the loop owns time.
144
+
145
+ ```python
146
+ from brainstate.util import filter as util_filter
147
+
148
+
149
+ class Accumulator(brainstate.nn.Module):
150
+ def init_state(self):
151
+ self.total = brainstate.ShortTermState(jnp.asarray(0.0))
152
+
153
+ def update(self, value):
154
+ self.total.value = self.total.value + value
155
+ return self.total.value
156
+
157
+
158
+ model = Accumulator()
159
+ inputs = jnp.ones((5, 8)) # [time, independent condition]
160
+ brainstate.nn.vmap_init_all_states(model, axis_size=inputs.shape[1])
161
+
162
+ dynamical_state = util_filter.Any(
163
+ util_filter.OfType(brainstate.HiddenState),
164
+ util_filter.OfType(brainstate.ShortTermState),
165
+ )
166
+ mapped_step = vmap2(
167
+ model.update,
168
+ in_axes=0,
169
+ out_axes=0,
170
+ state_in_axes={0: dynamical_state},
171
+ state_out_axes={0: dynamical_state},
172
+ unexpected_out_state_mapping="raise",
173
+ )
174
+ outputs = brainstate.transform.for_loop(mapped_step, inputs)
175
+
176
+ assert outputs.shape == (5, 8)
177
+ assert jnp.allclose(outputs[-1], 5.0)
178
+ ```
179
+
180
+ Do not select writable State with `.ndim`, shape, or path coincidences; those properties do not identify State ownership and can map a future parameter accidentally. Every State written by `mapped_step` needs a compatible per-lane axis. In particular, a delay buffer with per-lane history cannot share a mutable scalar write pointer merely because all lanes advance in lockstep; map the complete delay State or choose a delay representation whose writable State follows one axis policy.
181
+
182
+ ### Choose the State declaration contract
183
+
184
+ The generated APIs use distinct, non-alias parameter names:
185
+
186
+ | API | State input mapping | State output mapping | Undeclared batched write |
187
+ |---|---|---|---|
188
+ | `brainstate.transform.vmap` | `in_states` by State instance | `out_states` by State instance | Raises `BatchAxisError`. |
189
+ | `brainstate.transform.vmap2` | `state_in_axes` by State filter | `state_out_axes` by State filter | Controlled by `unexpected_out_state_mapping`; default `'auto'` infers and scatters. |
190
+
191
+ Sources: https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.transform.vmap.html and https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.transform.vmap2.html.
146
192
 
147
193
  ## Handle state writes outside `state_out_axes`
148
194
 
@@ -307,7 +353,11 @@ Do not infer semantics for `vmap_new_states`, `vmap2_new_states`, `map`, `pmap2`
307
353
  ## High-impact checks
308
354
 
309
355
  - Match every non-`None` `in_axes` entry to an actual mapped dimension of the corresponding argument.
356
+ - Use `vmap` for State-instance declarations and `vmap2` for filter-based State-axis policies; do not mix their parameter names.
357
+ - Prefer an owning package's native batch or `size` axis when it already represents the independent conditions.
310
358
  - Decide whether mutable State is shared or mapped; use `state_in_axes` and `state_out_axes` together for per-instance State write-back.
359
+ - Map a complete per-step transition inside one `for_loop` when the mapping owns independent conditions and the loop owns time.
360
+ - Select mapped State by semantic role rather than array rank, shape, or leading-size coincidence.
311
361
  - Set `axis_size` when all inputs are static.
312
362
  - Declare State axes or set an explicit policy when automatic output-axis inference would be ambiguous.
313
363
  - Expect automatic independent `RandomState` keys; use the documented broadcast-key pattern only when shared randomness is intentional.