brainx-skill 1.0.15 → 1.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -1
- package/manifest.json +1 -1
- package/mcp-servers/codex/skills.json +1 -1
- package/package.json +1 -1
- package/skills/bio-neuro-lit/SKILL.md +4 -2
- package/skills/bio-neuro-lit/references/required-supplements.md +27 -0
- package/skills/brainx-acceleration/SKILL.md +30 -437
- package/skills/brainx-acceleration/references/audit-and-rewrite-patterns.md +326 -0
- package/skills/brainx-general-guard/SKILL.md +24 -8
- package/skills/brainx-install/SKILL.md +3 -3
- package/skills/brainx-install/references/compatibility-and-release-matching.md +28 -20
- package/skills/brainx-install/references/uninstall-and-cleanup.md +11 -4
- package/skills/brainx-modeling-loop/SKILL.md +117 -36
- package/skills/brainx-modeling-loop/agents/openai.yaml +2 -2
- package/skills/brainx-modeling-loop/references/mechanism-comparison.md +62 -0
- package/skills/brainx-modeling-loop/references/multiscale-coupling.md +16 -0
- package/skills/brainx-modeling-loop/references/paper-reproduction.md +42 -0
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +14 -14
- package/skills/brainx-modeling-loop/references/run-experiment.md +1 -1
- package/skills/brainx-modeling-loop/references/training-workflow.md +10 -8
- package/skills/brainx-visualization/SKILL.md +6 -2
- package/skills/brainx-visualization/references/neural-data-visualization.md +1 -1
- package/skills/brainx-visualization/references/statistical-and-model-visualization.md +1 -1
- package/skills/package-skills/braincell/SKILL.md +23 -14
- package/skills/package-skills/braincell/references/braintools/input-current.md +1 -1
- package/skills/package-skills/braincell/references/braintools/metric.md +72 -46
- package/skills/package-skills/braincell/references/mixions-for-adaptation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/cv-policy-reference.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/filter-function-library.md +3 -3
- package/skills/package-skills/braincell/references/multicompartment/morphology-io-loading-validation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +31 -43
- package/skills/package-skills/braincell/references/multicompartment/network-workflow.md +49 -0
- package/skills/package-skills/braincell/references/multicompartment/probe-reference.md +26 -114
- package/skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md +40 -28
- package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py +13 -17
- package/skills/package-skills/brainevent/SKILL.md +0 -3
- package/skills/package-skills/brainevent/references/synaptic-plasticity.md +1 -1
- package/skills/package-skills/brainmass/SKILL.md +5 -3
- package/skills/package-skills/brainmass/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainmass/references/braintools/data-preprocessing.md +15 -7
- package/skills/package-skills/brainmass/references/braintools/metric.md +72 -46
- package/skills/package-skills/brainmass/references/coupling-network-api.md +3 -1
- package/skills/package-skills/brainmass/references/fitting-with-objectives-api.md +6 -6
- package/skills/package-skills/brainmass/references/horn-task-training.md +9 -9
- package/skills/package-skills/brainmass/references/modellibrary.md +12 -10
- package/skills/package-skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +5 -3
- package/skills/package-skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +10 -6
- package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +3 -1
- package/skills/package-skills/brainmass/references/visualization-analysis-api.md +17 -9
- package/skills/package-skills/brainspike/SKILL.md +201 -0
- package/skills/package-skills/brainspike/references/braintools/connectivity.md +40 -0
- package/skills/package-skills/brainspike/references/braintools/data-preprocessing.md +39 -0
- package/skills/package-skills/brainspike/references/braintools/input-current.md +55 -0
- package/skills/package-skills/brainspike/references/braintools/metric.md +36 -0
- package/skills/package-skills/brainspike/references/braintools/optimizer.md +50 -0
- package/skills/package-skills/brainspike/references/braintools/parameter-initializer.md +43 -0
- package/skills/package-skills/brainspike/references/braintools/surrogate.md +40 -0
- package/skills/package-skills/brainspike/references/migration-boundary.md +38 -0
- package/skills/package-skills/brainspike/references/model-and-readout-selection.md +41 -0
- package/skills/package-skills/brainspike/references/multirate-coupling.md +31 -0
- package/skills/package-skills/brainspike/references/multiscale-composition.md +28 -0
- package/skills/package-skills/brainspike/references/native-composition.md +52 -0
- package/skills/package-skills/brainspike/references/native-delays.md +34 -0
- package/skills/package-skills/brainspike/references/native-projections.md +43 -0
- package/skills/package-skills/brainspike/references/native-training.md +36 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/devices.md +33 -33
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/divergence-and-parity.md +15 -15
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/integration-categories.md +1 -1
- package/skills/package-skills/brainspike/references/nest-compatible/model-library.md +200 -0
- package/skills/package-skills/brainspike/references/nest-compatible/network-building.md +276 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brette_et_al_2007.py +23 -26
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_alpha.py +18 -21
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_delta.py +16 -19
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +11 -12
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +10 -11
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/spatial_gaussex.py +18 -18
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/synapsecollection.py +26 -29
- package/skills/package-skills/brainspike/references/nest-compatible/synapse-and-connectivity.md +166 -0
- package/skills/package-skills/brainspike/references/nest-delay-boundaries.md +31 -0
- package/skills/package-skills/brainspike/references/nonlinear-state-sharing.md +26 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/perturbation-experiment-validity.md +2 -2
- package/skills/package-skills/brainspike/references/simulator-training.md +61 -0
- package/skills/package-skills/brainspike/references/temporal-task-training.md +36 -0
- package/skills/package-skills/brainspike/scripts/advanced_native_patterns.py +76 -0
- package/skills/package-skills/brainspike/scripts/delay_workflow.py +44 -0
- package/skills/package-skills/brainspike/scripts/delayed_cue_training.py +78 -0
- package/skills/package-skills/brainspike/scripts/lif_smoke.py +31 -0
- package/skills/package-skills/brainspike/scripts/multiscale_workflow.py +35 -0
- package/skills/package-skills/brainspike/scripts/native_ei_network.py +47 -0
- package/skills/package-skills/brainspike/scripts/native_workflows.py +77 -0
- package/skills/package-skills/brainspike/scripts/nest_boundary_workflows.py +108 -0
- package/skills/package-skills/brainspike/scripts/train_native_snn.py +65 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator.py +69 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator_two_weights.py +220 -0
- package/skills/package-skills/brainstate/SKILL.md +16 -21
- package/skills/package-skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +1 -138
- package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
- package/skills/package-skills/brainstate/references/brainstate/delay-buffers.md +45 -0
- package/skills/package-skills/brainstate/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md +6 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md +1 -1
- package/skills/package-skills/brainstate/references/braintools-optimizer-reference.md +16 -0
- package/skills/package-skills/brainstate/references/libraries/prebuilt-layer-library.md +1 -1
- package/skills/package-skills/brainstate/references/simulation-environment.md +5 -5
- package/skills/package-skills/braintrace/SKILL.md +17 -38
- package/skills/package-skills/braintrace/references/Drtrl.md +9 -26
- package/skills/package-skills/braintrace/references/algorithm selection.md +7 -12
- package/skills/package-skills/braintrace/references/batching.md +15 -35
- package/skills/package-skills/braintrace/references/compiler_internal.md +1 -1
- package/skills/package-skills/braintrace/references/custom algorithms.md +1 -2
- package/skills/package-skills/braintrace/references/customizing_primitive_transforms.md +26 -15
- package/skills/package-skills/braintrace/references/pp_pprop workflow.md +5 -139
- package/skills/package-skills/brainunit/SKILL.md +7 -2
- package/skills/package-skills/brainunit/references/array-mechanics/functional-structural-api.md +1 -1
- package/skills/package-skills/brainunit/references/math-function-library.md +2 -2
- package/skills/package-skills/brainunit/references/typing-and-runtime-validation.md +5 -2
- package/skills/package-skills/brainevent/references/scripts/102_EI_net_1996.py +0 -107
- package/skills/package-skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +0 -168
- package/skills/package-skills/brainevent/references/scripts/coba_ei_teaching.py +0 -356
- package/skills/package-skills/brainpy-state/SKILL.md +0 -247
- package/skills/package-skills/brainpy-state/references/array-creation.md +0 -158
- package/skills/package-skills/brainpy-state/references/brain-dynamics-delay-protocol.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/analysis.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +0 -373
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +0 -175
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +0 -286
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +0 -111
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -163
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -113
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -136
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -222
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -123
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -185
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/integrators.md +0 -181
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +0 -102
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +0 -159
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +0 -127
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +0 -167
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -186
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +0 -104
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +0 -89
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +0 -253
- package/skills/package-skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +0 -334
- package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +0 -206
- package/skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md +0 -79
- package/skills/package-skills/brainpy-state/references/braintools/input-current.md +0 -199
- package/skills/package-skills/brainpy-state/references/braintools/metric.md +0 -152
- package/skills/package-skills/brainpy-state/references/braintools/optimizer.md +0 -179
- package/skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md +0 -183
- package/skills/package-skills/brainpy-state/references/braintools/surrogate.md +0 -147
- package/skills/package-skills/brainpy-state/references/component-selection.md +0 -288
- package/skills/package-skills/brainpy-state/references/nest-compatible/model-library.md +0 -200
- package/skills/package-skills/brainpy-state/references/nest-compatible/nest-workflow.md +0 -156
- package/skills/package-skills/brainpy-state/references/nest-compatible/network-building.md +0 -264
- package/skills/package-skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +0 -153
- package/skills/package-skills/brainpy-state/references/projection-patterns.md +0 -127
- package/skills/package-skills/brainpy-state/references/scripts/103_COBA_2005.py +0 -86
- package/skills/package-skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +0 -181
- package/skills/package-skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +0 -156
- package/skills/package-skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +0 -111
- package/skills/package-skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -221
- package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +0 -240
- package/skills/package-skills/brainpy-state/references/scripts/training-snn.py +0 -119
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
# BrainX Skill
|
|
6
6
|
|
|
7
|
-
[](skills/brainx-install/references/compatibility-and-release-matching.md#version-compatibility-matrix) [](LICENSE) [](https://www.npmjs.com/package/brainx-skill) [](manifest.json) [](https://github.com/chaobrain/BrainX-skill/actions/workflows/agent-skills-validation.yml) [](https://scorecard.dev/viewer/?uri=github.com/chaobrain/BrainX-skill)
|
|
8
8
|
|
|
9
9
|
[](#installation-locations)
|
|
10
10
|
|
|
@@ -14,6 +14,22 @@ make your coding agent understand the power of BrainX
|
|
|
14
14
|
|
|
15
15
|
- Node.js 18 or newer
|
|
16
16
|
- macOS, Linux, or Windows
|
|
17
|
+
|
|
18
|
+
The current examples target BrainX `2026.10.25` with Python 3.12 or newer.
|
|
19
|
+
Use the original skill snapshot and runtime to reproduce earlier evaluations.
|
|
20
|
+
|
|
21
|
+
Use the [BrainSpike skill](skills/package-skills/brainspike/SKILL.md) for point-neuron models. Install the Python distribution as `brainspikes` and import `brainspike`. The BrainX release still includes BrainPy at runtime; earlier skill snapshots retain the BrainPy-State guidance.
|
|
22
|
+
|
|
23
|
+
From the checkout, run the single-neuron CPU smoke test in an environment with
|
|
24
|
+
the pinned BrainX release:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
python skills/package-skills/brainspike/scripts/lif_smoke.py
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The test checks that a 500 pA current drives the LIF neuron to fire and that
|
|
31
|
+
100 ms of simulation produces a `(1000, 1)` spike recording.
|
|
32
|
+
|
|
17
33
|
## Install
|
|
18
34
|
|
|
19
35
|
```bash
|
package/manifest.json
CHANGED
package/package.json
CHANGED
|
@@ -11,7 +11,7 @@ Use this skill to answer a biology, neuroscience, or computational-neuroscience
|
|
|
11
11
|
|
|
12
12
|
`interpret question -> decompose terminology -> search Europe PMC -> optionally expand with Exa -> normalize, deduplicate, and rank -> deep-read selected papers -> compare evidence -> persist modeling-relevant evidence when applicable -> answer the question`
|
|
13
13
|
|
|
14
|
-
Use Europe PMC as the primary academic discovery database and the existing Full-Text Resolver as the default reader. Use Exa only to expand recall and DeepXiv only when progressive reading of a known arXiv-compatible paper is useful. Do not add generic arXiv, Semantic Scholar, Gemini, standalone OpenAlex, Zotero, Obsidian, or local-PDF workflows.
|
|
14
|
+
Use Europe PMC as the primary academic discovery database and the existing Full-Text Resolver as the default reader. Use Exa only to expand recall and DeepXiv only when progressive reading of a known arXiv-compatible paper is useful. Do not add generic arXiv, Semantic Scholar, Gemini, standalone OpenAlex, Zotero, Obsidian, or local-PDF library-management workflows.
|
|
15
15
|
|
|
16
16
|
## Underlying mental model
|
|
17
17
|
|
|
@@ -116,7 +116,9 @@ Full text is evidence depth, not a requirement for retaining a relevant paper.
|
|
|
116
116
|
}
|
|
117
117
|
```
|
|
118
118
|
|
|
119
|
-
Prefer the Full-Text Resolver for ordinary PMC and journal biology papers. Use DeepXiv mainly for computational neuroscience or ML-neuroscience papers with arXiv IDs.
|
|
119
|
+
Prefer the Full-Text Resolver for ordinary PMC and journal biology papers. Use DeepXiv mainly for computational neuroscience or ML-neuroscience papers with arXiv IDs. For an ordinary review, if the resolver returns no usable Markdown, including a PDF-only location, retain the paper's abstract and metadata, set `full_text_status` to `abstract-only`, preserve the retrieval note or source URL, and limit claims to what the abstract supports.
|
|
120
|
+
|
|
121
|
+
When reproduction requires an original supplement or source artifact absent from the reader, open `references/required-supplements.md` for targeted official retrieval, version/hash verification and inspection of source definitions. This supplements the default reader; it does not replace academic discovery or permit unsupported full-text claims.
|
|
120
122
|
|
|
121
123
|
## Extract and compare evidence
|
|
122
124
|
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Recover a required original supplement
|
|
2
|
+
|
|
3
|
+
Use this route when reproduction needs a scientific definition in an original supplement or linked source artifact that the default reader did not expose. Keep the normal Full-Text Resolver route for article reading and the ordinary abstract-only fallback for literature reviews; a failed conversion or legacy URL does not establish that a required original artifact is unavailable.
|
|
4
|
+
|
|
5
|
+
## Locate the artifact through its publication
|
|
6
|
+
|
|
7
|
+
Inspect the article's supplementary links and official publisher or repository metadata. Record the DOI/PMCID, requested publication version and exact artifact named by the source. Check whether an available reader already supports that artifact before adding a direct retrieval boundary. Do not substitute a preprint supplement for the published one without verifying and reporting the relationship.
|
|
8
|
+
|
|
9
|
+
If a linked endpoint fails, consult the provider's current distribution documentation rather than repeatedly guessing old URLs. For PMC, use the [official cloud-service documentation](https://pmc.ncbi.nlm.nih.gov/tools/pmcaws/) and its linked [dataset README](https://pmc-oa-opendata.s3.amazonaws.com/README.txt). The public dataset provides article-version metadata and supplementary objects:
|
|
10
|
+
|
|
11
|
+
| Interface | Use |
|
|
12
|
+
|---|---|
|
|
13
|
+
| Official article inventory or PMCID prefix listing | Locate available version prefixes; do not assume version 1 exists or that the largest version is the requested publication. |
|
|
14
|
+
| Article JSON metadata | Verify identifiers, publication/manuscript status and the linked `media_urls`. |
|
|
15
|
+
| Referenced supplementary media object | Retrieve the specifically required file from its advertised location; preserve its bytes and verify the metadata digest when supplied. |
|
|
16
|
+
|
|
17
|
+
Treat this as targeted access to a named primary artifact, not a second discovery engine or an assumption that every article is present in a public dataset. Preserve the failure and bound claims when no authorized official copy can be obtained.
|
|
18
|
+
|
|
19
|
+
## Verify and read the original
|
|
20
|
+
|
|
21
|
+
Save the URL, retrieval time, response status/type, file size and SHA-256 alongside the original bytes. Inspect the actual format: an HTTP success or a `.pdf` name can contain challenge HTML or an XML error. Match identifiers and title/version against official metadata; do not accept filename similarity alone as provenance.
|
|
22
|
+
|
|
23
|
+
Inspect complete relevant pages and captions. Render a PDF when extraction loses equation grouping, signs, subscripts or figure-specific settings. Record the exact page, equation, section or code location supporting each consequential definition. A main-text summary does not establish a missing supplement's formula, analysis windows, normalization set or control distribution.
|
|
24
|
+
|
|
25
|
+
## Hand off the evidence
|
|
26
|
+
|
|
27
|
+
Distinguish verified source values from unstated implementation choices and conflicts between the article, supplement and executable author code. For an active reproduction, hand these records to `brainx-modeling-loop` → `references/paper-reproduction.md` before implementation or revised analysis. Keep case-specific parameters and findings in the project evidence, not in this skill. If a decisive definition remains missing, state the unsupported claim and the evidence needed; do not fill the gap and call it verified reproduction.
|
|
@@ -3,457 +3,50 @@ name: brainx-acceleration
|
|
|
3
3
|
description: Audits and refactors BrainX/BrainState simulation code for performance using state-aware BrainState transform patterns. Use for speed, acceleration, GPU performance, batching, vectorization, parameter sweeps, many neurons/trials, compile/runtime separation, memory reduction, throughput, multi-device execution, or performance-audit requests.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
# BrainX
|
|
6
|
+
# BrainX acceleration
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
## Purpose and boundary
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
Audit or refactor BrainX simulation and training hot paths. Open `brainstate` → `SKILL.md` before a nontrivial State-aware rewrite. Keep the modeling package's orchestrator when it already expresses the scientific operation and the needed execution boundary.
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
## Underlying mental model
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
Represent populations and independent trials as array or State axes. Let BrainState control repeated execution so a compiled function can preserve mutation, randomness, and gradients. Prioritize correctness, State and RNG safety, shape stability, warm runtime, memory, then device scale.
|
|
15
15
|
|
|
16
|
-
##
|
|
16
|
+
## Diagnose and rewrite
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
1. Inventory the hot call sites. Record loop axes and trip counts, inputs and outputs, State reads and writes, RNG policy, transform boundaries, host transfers, and connectivity representation.
|
|
19
|
+
2. Rank by measured impact, semantic risk, and confidence. Identify a small deterministic baseline before changing execution. Open `references/audit-and-rewrite-patterns.md` for search patterns, bottleneck classification, transform compositions, and an audit report template.
|
|
20
|
+
3. Rewrite one axis or compilation boundary at a time. Keep units, update order, sparse or event connectivity, and stable shapes, dtypes, and PyTrees. Use BrainState transforms for State effects. Use raw JAX transforms for pure array functions with explicit inputs and outputs. Keep host preprocessing and I/O outside transforms.
|
|
21
|
+
4. Map only independent lanes. Declare which State is shared read-only, mapped, written back, or discarded. Split or advance random streams deliberately across lanes and time.
|
|
22
|
+
5. Compile the largest stable unit that owns the repeated work. Keep transform construction outside hot loops and benchmark already-fused or I/O-bound work before rewriting it.
|
|
19
23
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
## Core mental model
|
|
23
|
-
|
|
24
|
-
Convert this:
|
|
25
|
-
|
|
26
|
-
```text
|
|
27
|
-
Python controls loops and mutable objects; arrays are small operations inside the loop.
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
into this:
|
|
31
|
-
|
|
32
|
-
```text
|
|
33
|
-
Arrays/states represent populations; BrainState transforms control repeated execution.
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
Axis map:
|
|
37
|
-
|
|
38
|
-
| Axis | Meaning | Slow NumPy/Python pattern | BrainState rewrite target |
|
|
39
|
-
|---|---|---|---|
|
|
40
|
-
| `N` | neurons, synapses, features, compartments | loop over scalar cells/synapses | population-shaped arrays + `jnp` ops inside `jit` |
|
|
41
|
-
| `T` | time/recurrent steps | Python loop calling `step` | `scan`, `for_loop`, `while_loop`; usually wrapped by `jit` |
|
|
42
|
-
| `B` | batch, trials, stimuli, subjects | loop over examples/trials | `vmap` or explicitly batched state |
|
|
43
|
-
| `E` | ensemble, parameter sweep, initial conditions, seeds | loop over model copies/configs | `vmap` with mapped states/parameters/RNG |
|
|
44
|
-
| `P` | trainable parameters/sensitivities | finite differences/manual perturbation loops | `grad`, `value_and_grad`, `jacrev`, `jacfwd` over args or `ParamState` |
|
|
45
|
-
| `D` | devices | multiprocessing/manual sharding | `pmap2`, `shard_map`, explicit sharding after single-device cleanup |
|
|
46
|
-
|
|
47
|
-
## Non-negotiable rules
|
|
48
|
-
|
|
49
|
-
- Use `brainstate.transform.*` for stateful BrainState code. Use raw `jax.*` transforms only for pure functions with explicit array inputs/outputs and no BrainState state writes.
|
|
50
|
-
- Use `jax.numpy as jnp` in transformed numerical paths. Keep `numpy as np` only for host preprocessing, file I/O, offline analysis, or static setup outside transforms.
|
|
51
|
-
- Mutable simulation quantities belong in explicit `State`, `ParamState`, or BrainState random-stream objects. Do not hide changing transformed values in ordinary Python attributes.
|
|
52
|
-
- Hot-path shapes, dtypes, and PyTree structure must be stable. Use masks, padding, bucketing, or static config instead of runtime shape creation.
|
|
53
|
-
- Do not automatically densify sparse/event/structured connectivity. First choose the right mathematical representation, then transform it.
|
|
54
|
-
- Do not claim acceleration from the first call. Separate compile time from warm execution time.
|
|
55
|
-
- Prefer small reviewable diffs with tiny deterministic equivalence tests.
|
|
56
|
-
|
|
57
|
-
## Investigation protocol
|
|
58
|
-
|
|
59
|
-
### 1. Build a hot-path inventory
|
|
60
|
-
|
|
61
|
-
For each candidate function (`step`, `update`, `forward`, `run`, `simulate`, `loss`, `train_step`, data/RNG helper), record:
|
|
62
|
-
|
|
63
|
-
```text
|
|
64
|
-
function/call site:
|
|
65
|
-
inputs: shapes, dtypes, axis meanings
|
|
66
|
-
states read: State/ParamState/RandomState, shapes, shared or per-trial
|
|
67
|
-
states written: State/ParamState/RandomState, shapes, shared or per-trial
|
|
68
|
-
loops: axis, trip count, nested axes
|
|
69
|
-
current transforms: none / raw jax / brainstate.transform
|
|
70
|
-
outputs: full history vs summary metrics
|
|
71
|
-
RNG: source, key/stream split policy, per-step/per-trial independence
|
|
72
|
-
shape changes: yes/no, cause
|
|
73
|
-
host interaction: print/log/float/item/np.asarray/callbacks
|
|
74
|
-
connectivity: dense/sparse/event/structured
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
Use searches as a first pass, then read the code before editing:
|
|
78
|
-
|
|
79
|
-
```bash
|
|
80
|
-
rg -n "import numpy|np\." .
|
|
81
|
-
rg -n "for .*range|while " .
|
|
82
|
-
rg -n "\.append\(|np\.array\(|np\.stack\(|jnp\.stack\(|concatenate\(" .
|
|
83
|
-
rg -n "jax\.jit|jax\.grad|jax\.vmap|brainstate\.transform" .
|
|
84
|
-
rg -n "\.value\s*=|\[[^\]]+\]\s*=" .
|
|
85
|
-
rg -n "random|np\.random|jax\.random|RandomState|split_key|seed" .
|
|
86
|
-
rg -n "finite|epsilon|eps|perturb|theta_plus|theta_minus|jacobian|hessian" .
|
|
87
|
-
rg -n "\.item\(|float\(|int\(|bool\(|np\.asarray|print\(|logging\." .
|
|
88
|
-
rg -n "jit\(|grad\(|vmap\(|scan\(" .
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
### 2. Classify every inefficient pattern
|
|
92
|
-
|
|
93
|
-
Use these labels in audit notes and patch comments when useful.
|
|
94
|
-
|
|
95
|
-
| Label | Evidence | Why slow/risky | Rewrite target |
|
|
96
|
-
|---|---|---|---|
|
|
97
|
-
| `loop-N-scalar` | `for i in range(N)` updates neuron/synapse scalars | Python overhead; no fused population kernel | array-shaped state + `jnp.where`/broadcast/scatter/sparse ops under `jit` |
|
|
98
|
-
| `object-neurons` | list/dict of neuron/synapse objects updated one by one | compiler sees Python objects, not arrays | one population/module with state arrays shaped `[N,...]` |
|
|
99
|
-
| `loop-T-python` | Python loop calls `step(x[t])` | dispatch per step; no compiled recurrent loop | `scan`, `for_loop`, or `while_loop` inside `jit` |
|
|
100
|
-
| `dynamic-list-history` | append outputs/states then stack | dynamic Python accumulation; memory waste | `scan` outputs or summary carry |
|
|
101
|
-
| `memory-T-full-history` | stores all `V[t]`/state when only rates/loss needed | unnecessary memory; worse autodiff storage | carry summary; record sparse snapshots; `checkpointed_scan` for differentiable long runs |
|
|
102
|
-
| `loop-B-python` | loop over trials/batch/stimuli | serial Python batch | `vmap` or batched state |
|
|
103
|
-
| `loop-E-sweep` | loop over seeds/configs/model copies | serial ensemble sweep | `vmap` with leading `[E,...]` state/param/RNG axes |
|
|
104
|
-
| `loop-P-finite-diff` | `eps`, `theta_plus`, `theta_minus`, perturb each param | O(P) or O(2P) simulations; noisy gradients | `grad`/`value_and_grad` over args or `ParamState` |
|
|
105
|
-
| `raw-jax-stateful` | `jax.jit/grad/vmap` wraps BrainState module/state writes | state updates may be lost or mishandled | `brainstate.transform.*` or explicit split/pass/return/merge |
|
|
106
|
-
| `np-in-transform` | `np.*` in code used by `jit/grad/vmap/scan` | host execution, tracer conversion, frozen constants | replace with `jnp.*` or move outside transform |
|
|
107
|
-
| `python-control-array` | Python `if/while/bool/int/float` depends on array value | tracer errors or host sync | `jnp.where`, `cond`, `while_loop`, `for_loop`, masks |
|
|
108
|
-
| `wrong-jit-boundary` | jitting tiny helpers, or making jitted functions inside loops | compile overhead; poor fusion | jit largest stable unit: `run`, `loss`, `train_step` |
|
|
109
|
-
| `transform-inside-loop` | `jit(...)`, `vmap(...)`, `grad(...)` constructed repeatedly | repeated tracing/compilation | define transforms once at module/init scope |
|
|
110
|
-
| `dynamic-shape` | shape depends on data/spikes/runtime length | recompilation or unsupported traced shape | static config, padding, masks, bucketing |
|
|
111
|
-
| `hidden-mutable-attr` | ordinary attrs mutated in transformed method | untracked state semantics | `State`/`ParamState`/explicit return value |
|
|
112
|
-
| `state-vmap-ambiguous` | `vmap` over stateful model without explicit state-axis decision | shared vs independent state bugs | set/verify `state_in_axes`, `state_out_axes`, unexpected state policy |
|
|
113
|
-
| `rng-reuse` | same key/seed reused across trials/time; `np.random` in hot path | correlated trials; unreproducible behavior | BrainState random streams or explicit split; map RNG axis under `vmap` |
|
|
114
|
-
| `host-sync` | `print`, `.item()`, `float(x)`, `np.asarray(x)` in hot loop | device-host synchronization | aggregate metrics; log outside compiled loop; debug-only callbacks |
|
|
115
|
-
| `accidental-densify` | converts sparse/event connectivity to dense `[N,N]` | memory/bandwidth blow-up | preserve sparse/event/structured representation |
|
|
116
|
-
| `already-fused` | large `jnp` matmul/conv/reduction already dominates | transforms may not help much | benchmark first; avoid churn |
|
|
117
|
-
|
|
118
|
-
### 3. Rank findings before rewriting
|
|
119
|
-
|
|
120
|
-
Score each finding:
|
|
121
|
-
|
|
122
|
-
```text
|
|
123
|
-
impact = loop trip count × work per iteration × call frequency
|
|
124
|
-
risk = state/RNG/gradient/memory semantic risk
|
|
125
|
-
confidence = evidence quality + shape clarity + API certainty
|
|
126
|
-
```
|
|
127
|
-
|
|
128
|
-
Rewrite high-impact, high-confidence items first. Do not refactor low-impact style issues unless they block a larger transform.
|
|
129
|
-
|
|
130
|
-
## Rewrite playbook
|
|
131
|
-
|
|
132
|
-
### A. Population axis `N`: scalar/object loop -> array state
|
|
133
|
-
|
|
134
|
-
Bad:
|
|
135
|
-
|
|
136
|
-
```python
|
|
137
|
-
for i in range(num_neurons):
|
|
138
|
-
v[i] += dt * (-v[i] + i_ext[i]) / tau[i]
|
|
139
|
-
if v[i] > threshold[i]:
|
|
140
|
-
spike[i] = 1
|
|
141
|
-
v[i] = reset[i]
|
|
142
|
-
```
|
|
143
|
-
|
|
144
|
-
Good shape pattern:
|
|
145
|
-
|
|
146
|
-
```python
|
|
147
|
-
v_new = V.value + dt * (-V.value + i_ext) / tau
|
|
148
|
-
spike = v_new > threshold
|
|
149
|
-
V.value = jnp.where(spike, reset, v_new)
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
Use `jnp.where`/masks for elementwise conditional reset. Use `.at[]` scatter or segment/sparse/event operations when updates are indexed. Avoid Python object-per-neuron design in hot paths.
|
|
153
|
-
|
|
154
|
-
### B. Time axis `T`: Python simulation loop -> transformed control flow
|
|
155
|
-
|
|
156
|
-
Bad:
|
|
157
|
-
|
|
158
|
-
```python
|
|
159
|
-
ys = []
|
|
160
|
-
for t in range(T):
|
|
161
|
-
ys.append(step(xs[t]))
|
|
162
|
-
y = jnp.stack(ys)
|
|
163
|
-
```
|
|
164
|
-
|
|
165
|
-
Good full-history pattern:
|
|
166
|
-
|
|
167
|
-
```python
|
|
168
|
-
def body(carry, x_t):
|
|
169
|
-
y_t = net(x_t) # may read/write BrainState State
|
|
170
|
-
return carry, y_t
|
|
171
|
-
|
|
172
|
-
@brainstate.transform.jit
|
|
173
|
-
def run(xs_T):
|
|
174
|
-
_, ys_T = brainstate.transform.scan(body, None, xs_T)
|
|
175
|
-
return ys_T
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
Good summary-only pattern:
|
|
179
|
-
|
|
180
|
-
```python
|
|
181
|
-
def body(summary, x_t):
|
|
182
|
-
y_t = net(x_t)
|
|
183
|
-
summary = summary + metric(y_t)
|
|
184
|
-
return summary, None
|
|
185
|
-
```
|
|
186
|
-
|
|
187
|
-
Use `checkpointed_scan` when differentiating through long `T` and activation/state storage dominates memory. Before applying exact control-flow APIs, read `references/brainstate/brainstate-control-flow-patterns.md` if present.
|
|
188
|
-
|
|
189
|
-
### C. Batch/trial axis `B`: Python batch loop -> `vmap` or batched state
|
|
190
|
-
|
|
191
|
-
Bad:
|
|
192
|
-
|
|
193
|
-
```python
|
|
194
|
-
outs = []
|
|
195
|
-
for b in range(B):
|
|
196
|
-
outs.append(run_one(xs_B[b]))
|
|
197
|
-
outs = jnp.stack(outs)
|
|
198
|
-
```
|
|
199
|
-
|
|
200
|
-
Good pattern:
|
|
201
|
-
|
|
202
|
-
```python
|
|
203
|
-
run_batch = brainstate.transform.jit(
|
|
204
|
-
brainstate.transform.vmap(run_one, in_axes=0, out_axes=0)
|
|
205
|
-
)
|
|
206
|
-
outs = run_batch(xs_B)
|
|
207
|
-
```
|
|
208
|
-
|
|
209
|
-
Before rewriting, decide for every state:
|
|
210
|
-
|
|
211
|
-
```text
|
|
212
|
-
shared across B? parameters, shared read-only config, global constants
|
|
213
|
-
independent per B? membrane voltage, refractory state, synaptic traces, trial RNG, optimizer-free simulation state
|
|
214
|
-
written back? final per-trial state, shared aggregate, or discarded temporary?
|
|
215
|
-
```
|
|
216
|
-
|
|
217
|
-
If independent state is required, use BrainState `vmap` state-axis controls such as `state_in_axes`/`state_out_axes` according to the local API. Read `references/brainstate/transformation-vmap-expansion.md` before editing exact arguments.
|
|
218
|
-
|
|
219
|
-
### D. Ensemble/sweep axis `E`: serial model copies -> mapped states/params
|
|
220
|
-
|
|
221
|
-
Bad:
|
|
222
|
-
|
|
223
|
-
```python
|
|
224
|
-
for e in range(E):
|
|
225
|
-
set_params(params[e])
|
|
226
|
-
results.append(run(inputs, seed=e))
|
|
227
|
-
```
|
|
228
|
-
|
|
229
|
-
Good shape intent:
|
|
230
|
-
|
|
231
|
-
```text
|
|
232
|
-
params/state/RNG: [E, ...]
|
|
233
|
-
inputs: [E, T, ...] or shared [T, ...]
|
|
234
|
-
outputs: [E, T, ...] or [E, summary]
|
|
235
|
-
```
|
|
236
|
-
|
|
237
|
-
Good transform intent:
|
|
238
|
-
|
|
239
|
-
```python
|
|
240
|
-
run_ensemble = brainstate.transform.jit(
|
|
241
|
-
brainstate.transform.vmap(
|
|
242
|
-
run_one_model,
|
|
243
|
-
in_axes=..., out_axes=...,
|
|
244
|
-
state_in_axes=..., state_out_axes=...,
|
|
245
|
-
)
|
|
246
|
-
)
|
|
247
|
-
```
|
|
248
|
-
|
|
249
|
-
Use this for parameter sweeps, random initial conditions, seeds, lesions, perturbations, and independent circuit replicas. Verify memory: mapping `E` full histories can be huge.
|
|
250
|
-
|
|
251
|
-
### E. Parameter axis `P`: manual gradients -> `grad`
|
|
252
|
-
|
|
253
|
-
Bad finite differences:
|
|
254
|
-
|
|
255
|
-
```python
|
|
256
|
-
for i in range(num_params):
|
|
257
|
-
theta_p = theta.at[i].add(eps)
|
|
258
|
-
theta_m = theta.at[i].add(-eps)
|
|
259
|
-
g = (loss(theta_p) - loss(theta_m)) / (2 * eps)
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
Good training intent:
|
|
263
|
-
|
|
264
|
-
```python
|
|
265
|
-
params = model.states(brainstate.ParamState)
|
|
266
|
-
|
|
267
|
-
def loss_fn(x, target):
|
|
268
|
-
pred = run(x)
|
|
269
|
-
return jnp.mean((pred - target) ** 2)
|
|
270
|
-
|
|
271
|
-
grad_fn = brainstate.transform.grad(loss_fn, grad_states=params, return_value=True)
|
|
272
|
-
|
|
273
|
-
@brainstate.transform.jit
|
|
274
|
-
def train_step(x, target):
|
|
275
|
-
grads, loss = grad_fn(x, target)
|
|
276
|
-
optimizer.update(grads)
|
|
277
|
-
return loss
|
|
278
|
-
```
|
|
279
|
-
|
|
280
|
-
Use `grad(loss_over_batch)` for normal batch training. Use `vmap(grad(single_loss))` only for per-sample gradients, influence functions, uncertainty, or diagnostics; it can be memory-heavy. Read `references/brainstate/transformation-grad-expansion.md` before exact state/argument gradient edits.
|
|
281
|
-
|
|
282
|
-
### F. JIT boundary: compile the largest stable unit
|
|
283
|
-
|
|
284
|
-
Prefer:
|
|
285
|
-
|
|
286
|
-
```python
|
|
287
|
-
@brainstate.transform.jit
|
|
288
|
-
def train_step(batch):
|
|
289
|
-
loss = ...
|
|
290
|
-
grads = ...
|
|
291
|
-
optimizer.update(grads)
|
|
292
|
-
return loss, metrics
|
|
293
|
-
```
|
|
294
|
-
|
|
295
|
-
Avoid:
|
|
296
|
-
|
|
297
|
-
```python
|
|
298
|
-
for t in range(T):
|
|
299
|
-
y = brainstate.transform.jit(tiny_op)(x[t])
|
|
300
|
-
```
|
|
301
|
-
|
|
302
|
-
Common good boundaries:
|
|
303
|
-
|
|
304
|
-
```text
|
|
305
|
-
step if called many times and shape-stable
|
|
306
|
-
run when it contains scan/control flow
|
|
307
|
-
loss_fn when repeatedly evaluated
|
|
308
|
-
train_step best boundary for training: forward + loss + grad + optimizer update
|
|
309
|
-
```
|
|
310
|
-
|
|
311
|
-
Read `references/brainstate/transformation-jit-expansion.md` before changing static args, diagnosing recompilation, or replacing raw `jax.jit` around stateful code.
|
|
312
|
-
|
|
313
|
-
### G. Composition patterns
|
|
314
|
-
|
|
315
|
-
Use these as intent patterns, then adapt to local BrainState API:
|
|
316
|
-
|
|
317
|
-
```text
|
|
318
|
-
single trial over time: jit(scan(step))
|
|
319
|
-
batch of independent trials: jit(vmap(run_one_trial))
|
|
320
|
-
time loop with batched state: jit(scan(vmapped_step_or_batched_step))
|
|
321
|
-
ensemble of models: jit(vmap(run_one_model, mapped states))
|
|
322
|
-
normal training: jit(train_step using grad(loss_over_batch))
|
|
323
|
-
per-sample gradients: jit(vmap(grad(single_sample_loss)))
|
|
324
|
-
long differentiable sequence: jit(checkpointed_scan(step))
|
|
325
|
-
multi-device batch/ensemble/shard: pmap2/shard_map after single-device cleanup
|
|
326
|
-
```
|
|
327
|
-
|
|
328
|
-
Axis order matters. Choose the order that preserves state semantics and minimizes memory. For example, `vmap(scan(step))` creates independent trials with independent recurrent state; `scan(vmap(step))` uses a time loop whose step is already batched.
|
|
329
|
-
|
|
330
|
-
### H. Randomness
|
|
331
|
-
|
|
332
|
-
Tiny RNG block: use one reproducible root seed or stream, then split/fold/map independent randomness for trials, parameter sweeps, stochastic dynamics, dropout/noise, and transformed execution. Route deeper seed/key restoration details to `references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md`.
|
|
333
|
-
|
|
334
|
-
Bad:
|
|
335
|
-
|
|
336
|
-
```python
|
|
337
|
-
for b in range(B):
|
|
338
|
-
y = run_one(xs[b], key) # same key reused
|
|
339
|
-
```
|
|
340
|
-
|
|
341
|
-
Good intent:
|
|
342
|
-
|
|
343
|
-
```text
|
|
344
|
-
one reproducible root seed/stream
|
|
345
|
-
split/fold/map independent keys for B/E/trials
|
|
346
|
-
split or advance per time step when stochastic dynamics require it
|
|
347
|
-
store RNG in BrainState-compatible state/stream if transformed code mutates it
|
|
348
|
-
```
|
|
349
|
-
|
|
350
|
-
Under `vmap`, verify each mapped element receives independent randomness. RNG correctness is part of validation, not a style preference.
|
|
351
|
-
|
|
352
|
-
### I. Multi-device `D`
|
|
353
|
-
|
|
354
|
-
Use `pmap2`, `shard_map`, or explicit sharding only after the single-device program is already transform-friendly. Good candidates: large independent trials, large ensembles, or explicit population/connectivity shards. Bad candidates: tiny Python-bound loops, logging-heavy code, shape-changing workloads, or dense memory blow-ups.
|
|
355
|
-
|
|
356
|
-
## Implementation sequence for Codex-style agents
|
|
357
|
-
|
|
358
|
-
1. **Do not rewrite immediately.** First produce an inventory and pattern table.
|
|
359
|
-
2. **Pick the highest-impact axis.** Usually `T`, then `N`, then `B/E`, then `P`, then `D`.
|
|
360
|
-
3. **Read reference markdowns only for transforms you will actually use.** Do not load all references by default.
|
|
361
|
-
4. **Write or identify a tiny deterministic test before refactoring.** Include final state checks, not only outputs.
|
|
362
|
-
5. **Refactor one semantic unit at a time.** Keep public APIs stable unless the user asks for deeper redesign.
|
|
363
|
-
6. **Preserve exact state ownership.** When changing `vmap`, explicitly document which states are shared, mapped, written back, or discarded.
|
|
364
|
-
7. **Preserve RNG semantics or intentionally improve them.** Document seed/key splitting.
|
|
365
|
-
8. **Avoid cosmetic churn.** Do not convert low-impact host setup code from `np` to `jnp` unless it enters transforms.
|
|
366
|
-
9. **Benchmark warm execution only after correctness.** Include compile time separately if measured.
|
|
367
|
-
10. **Leave API assumptions visible.** If BrainState syntax is uncertain, mark it and point to the needed reference markdown/test.
|
|
368
|
-
|
|
369
|
-
## Validation gates
|
|
370
|
-
|
|
371
|
-
A rewrite is not done until these are addressed:
|
|
372
|
-
|
|
373
|
-
| Gate | Required check |
|
|
24
|
+
| Bottleneck | Prefer |
|
|
374
25
|
|---|---|
|
|
375
|
-
|
|
|
376
|
-
|
|
|
377
|
-
|
|
|
378
|
-
|
|
|
379
|
-
|
|
|
380
|
-
|
|
|
381
|
-
| Memory | full-history vs summary scan choice justified; no accidental dense `[N,N]` blow-up |
|
|
382
|
-
| State under `vmap` | shared vs independent state documented and tested |
|
|
383
|
-
| Host sync | no print/item/float/np.asarray in hot path except debug-only code |
|
|
384
|
-
|
|
385
|
-
## When not to transform
|
|
386
|
-
|
|
387
|
-
Be realistic. A transform may not help when:
|
|
388
|
-
|
|
389
|
-
- the workload is tiny and compile overhead dominates;
|
|
390
|
-
- the hot path is already a large fused `jnp`/XLA operation;
|
|
391
|
-
- runtime shapes genuinely change each call and cannot be bucketed/masked;
|
|
392
|
-
- performance is limited by memory bandwidth or sparse representation choices;
|
|
393
|
-
- I/O, logging, plotting, or Python data loading dominates;
|
|
394
|
-
- the proposed rewrite would densify a sparse/event model;
|
|
395
|
-
- state/RNG semantics are not understood well enough to preserve correctness.
|
|
396
|
-
|
|
397
|
-
In these cases, report the bottleneck and propose a safer benchmark or representation change instead of forcing `jit`/`vmap`.
|
|
398
|
-
|
|
399
|
-
## Required response format when using this skill
|
|
26
|
+
| Python loop over neurons, features, or compartments | Population-shaped State and array or event operations. |
|
|
27
|
+
| Python time loop | `brainstate.transform.for_loop` for input-to-output steps, or `scan` when the body carries an explicit value. Keep only required history. |
|
|
28
|
+
| Independent trials or parameter sweeps | Native batching when provided by the model, or a State-aware mapped rollout with explicit State and RNG axes. |
|
|
29
|
+
| Parameter perturbation loops | State-aware `grad` for a differentiable objective. Keep per-example gradients for tasks that need them. |
|
|
30
|
+
| Long differentiable rollout | Checkpoint the rollout when activation storage dominates. |
|
|
31
|
+
| Multi-device workload | Establish an efficient single-device baseline before using `pmap2`, `shard_map`, or explicit sharding. |
|
|
400
32
|
|
|
401
|
-
|
|
402
|
-
## BrainX acceleration audit
|
|
33
|
+
## Validate and benchmark
|
|
403
34
|
|
|
404
|
-
|
|
405
|
-
|---|---|---|---|---|---|---|---|
|
|
406
|
-
| ... | `loop-T-python` | `for t ... step(...)` | T | High | Medium | `scan` inside `jit` | High |
|
|
407
|
-
|
|
408
|
-
## Patch / rewrite plan
|
|
409
|
-
|
|
410
|
-
[Small concrete diff or code blocks. State which reference markdown was used for exact transform semantics. State API assumptions if any.]
|
|
411
|
-
|
|
412
|
-
## Validation plan
|
|
413
|
-
|
|
414
|
-
[Old/new tiny test, final-state check, RNG check, shape/recompile check, gradient check if training, warm timing method.]
|
|
415
|
-
|
|
416
|
-
## Remaining risks
|
|
417
|
-
|
|
418
|
-
[State sharing, RNG independence, sparse/dense memory, dynamic shapes, numerical differences, unresolved API questions.]
|
|
419
|
-
```
|
|
420
|
-
|
|
421
|
-
If the user asks for an actual code rewrite, include the patch. If the user asks only for an audit, do not rewrite yet; provide the table and prioritized plan.
|
|
35
|
+
Compare baseline and rewritten outputs, final State, units, and shapes on the same small input with stated tolerances. Check mapped State isolation, repeatable seeds, independent random draws, and gradient or optimizer updates where applicable. Confirm sparse connectivity and required outputs remain intact. Separate compile time from synchronized warm timing, and inspect memory and host transfers.
|
|
422
36
|
|
|
37
|
+
For an audit, report the bottleneck evidence, affected axis, impact, risk, proposed rewrite, and validation. For a requested rewrite, apply the smallest patch and report actual parity and timing. Keep a measured baseline when the rewrite would change scientific behavior or increase resource use without a measured benefit.
|
|
423
38
|
|
|
424
39
|
## Reference routing
|
|
425
40
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
This skill owns local transform and randomness references for the exact semantics it audits:
|
|
429
|
-
|
|
430
|
-
```text
|
|
431
|
-
brainx-acceleration-audit/
|
|
432
|
-
├── brainstate/
|
|
433
|
-
│ ├── brainstate-control-flow-patterns.md
|
|
434
|
-
│ ├── transformation-jit-expansion.md
|
|
435
|
-
│ ├── transformation-vmap-expansion.md
|
|
436
|
-
│ └── transformation-grad-expansion.md
|
|
437
|
-
└── brainstate-randomness-reproducibility/
|
|
438
|
-
└── randomness-and-reproducibility.md
|
|
439
|
-
└── advanced-randomness.md
|
|
440
|
-
```
|
|
441
|
-
|
|
442
|
-
### First-layer routes
|
|
443
|
-
|
|
444
|
-
| Route | Open when |
|
|
41
|
+
| Reference | Open when |
|
|
445
42
|
|---|---|
|
|
446
|
-
| `
|
|
447
|
-
| `
|
|
448
|
-
| `
|
|
449
|
-
| `
|
|
450
|
-
| `
|
|
451
|
-
| `
|
|
452
|
-
|
|
453
|
-
### Nested randomness
|
|
454
|
-
|
|
455
|
-
The acceleration skill and its transform references route only to the local randomness parent. That parent alone may select `skills/brainx-acceleration-audit/references/brainstate-randomness-reproducibility/advanced-randomness.md` for advanced stream, mapped-key, or restoration behavior. Do not route directly to the advanced child.
|
|
43
|
+
| `references/audit-and-rewrite-patterns.md` | Classifying a suspected hot path, selecting among axis compositions, or drafting an acceleration audit. |
|
|
44
|
+
| `brainstate` → `references/brainstate/transformation-jit-expansion.md` | Choosing compilation boundaries, static arguments, timing, or diagnosing recompiles. |
|
|
45
|
+
| `brainstate` → `references/brainstate/transformation-vmap-expansion.md` | Mapping independent trial, ensemble, State, or RNG axes. |
|
|
46
|
+
| `brainstate` → `references/brainstate/transformation-grad-expansion.md` | Differentiating parameters or explicit inputs, or replacing finite differences. |
|
|
47
|
+
| `brainstate` → `references/brainstate/brainstate-control-flow-patterns.md` | Selecting a transformed time loop, branch, or checkpointing pattern. |
|
|
48
|
+
| `brainstate` → `references/brainstate/randomness-and-reproducibility.md` | Controlling stream independence, restoration, or reproducible replay. |
|
|
456
49
|
|
|
457
|
-
##
|
|
50
|
+
## Boundaries and common failures
|
|
458
51
|
|
|
459
|
-
|
|
52
|
+
Resolve State and RNG ownership before changing transforms. Keep a known-correct non-transformed path for tiny workloads, irreducibly dynamic shapes, or code dominated by I/O and logging when a transform offers little benefit. Address representation and memory bandwidth before batching a workload that would densify or materialize an unnecessary full history.
|