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
|
@@ -41,7 +41,7 @@ candidate satisfies the target-dose rule without invalidating the baseline
|
|
|
41
41
|
regime, classify the protocol as invalid and stop.
|
|
42
42
|
|
|
43
43
|
Generate each pilot's unit-aware waveform once and pass it through the same
|
|
44
|
-
|
|
44
|
+
BrainSpike neuron and projection path used by the formal run. Measure the
|
|
45
45
|
executed spike increment; a requested current or pulse count is not the delivered
|
|
46
46
|
biological dose.
|
|
47
47
|
|
|
@@ -57,7 +57,7 @@ development evidence, not a scientific non-reproduction. A completed formal run
|
|
|
57
57
|
with adequate observability and support may legitimately fail every requested
|
|
58
58
|
hypothesis.
|
|
59
59
|
|
|
60
|
-
Open `
|
|
60
|
+
Open `brainstate` → `references/paired-perturbation-execution.md` for exact
|
|
61
61
|
State branching, fixed-shape batching, resource gates, and execution-status
|
|
62
62
|
classification. Open `references/braintools/input-current.md` when constructing
|
|
63
63
|
the unit-aware intervention waveform.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# Train through the NEST Simulator
|
|
2
|
+
|
|
3
|
+
Use this version-specific path to optimize a continuous membrane-voltage objective directly through `Simulator.simulate()` in BrainSpikes 0.2.0. The forward model remains a NEST-created network; no native-neuron substitute or external learned surrogate replaces it.
|
|
4
|
+
|
|
5
|
+
## Keep the objective boundary pure
|
|
6
|
+
|
|
7
|
+
Construct the same deterministic topology inside each objective evaluation, supply the candidate physical weight/current, call `simulate()` for a fresh rollout, and reduce the recorded voltage after an explicit unit conversion. No simulator or transient State escapes the objective.
|
|
8
|
+
|
|
9
|
+
| API | Use |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `Simulator.create()` / `connect(..., weight=theta*scale, comm=...)` | Construct the fixed NEST topology with a differentiable numeric candidate and explicit physical scale. Keep connection rules, spike times, and delay fixed. |
|
|
12
|
+
| `Simulator.simulate(duration)` | Execute the complete independent NEST rollout for each loss evaluation. |
|
|
13
|
+
| `SimulationResult.trace(meter, "V_m")` | Supply the continuous observable used in the verified loss; preserve units until the declared comparison boundary. |
|
|
14
|
+
| `jax.value_and_grad(objective)` | Differentiate a pure candidate-to-loss function whose temporary State is entirely local. This is not permission to wrap persistent mutable BrainState graphs with raw JAX. |
|
|
15
|
+
| `brainstate.ParamState` and `braintools.optim.Adam` | Store the candidate and apply matching gradients between complete Simulator evaluations. |
|
|
16
|
+
|
|
17
|
+
Open `scripts/train_nest_simulator.py` for the runnable objective, finite-difference comparison, and optimizer. From this skill root run:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
python scripts/train_nest_simulator.py --comm dense
|
|
21
|
+
python scripts/train_nest_simulator.py --comm sparse
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The canonical fixture uses `spike_generator → iaf_psc_alpha`, a fixed three-spike source, `0.1 ms` timestep/delay, a multimeter, and a `5 ms` rollout. A dimensionless candidate scales a `100 pA` connection weight. The target is a synthetic voltage trace at weight `1.7`; Adam starts at `0.4` and updates the actual Simulator input weight for 100 independent rollouts.
|
|
25
|
+
|
|
26
|
+
Open `references/braintools/metric.md` for observation units and loss reduction, and `references/braintools/optimizer.md` for candidate registration and update ownership.
|
|
27
|
+
|
|
28
|
+
## Interpret the measured result
|
|
29
|
+
|
|
30
|
+
In the pinned Docker image, dense and sparse both recover `1.6985590956`, while mean voltage-trace loss falls from `1.4608960822` to `1.7947458e-6`. At the initial candidate, autodiff gives `-2.2475324342` and centered finite differences give `-2.2475324340`. A separate external-current gradient also agrees with finite differences. Repeated independent rollouts are identical.
|
|
31
|
+
|
|
32
|
+
This establishes differentiable NEST Simulator weight fitting for the tested continuous objective. It does not establish every model, plasticity rule, recurrent spike path, or scientific parameter identifiability.
|
|
33
|
+
|
|
34
|
+
## Check whether multiple weights are distinguishable
|
|
35
|
+
|
|
36
|
+
Choose training spike times that give separate weights different voltage responses. Fit from several preset starts, check each normalized loss gradient against centered differences away from convergence, and check a changed spike schedule only after fitting. Verify subthreshold voltage and zero spikes if the comparison assumes no threshold resets.
|
|
37
|
+
|
|
38
|
+
Use `jax.jacrev` on the fresh candidate-to-voltage function to form the sample-by-weight Jacobian in physical weight coordinates. Inspect the singular values and the ratio of smallest to largest. A near-zero singular value can permit low voltage error with poor weight recovery. If the Jacobian is well conditioned at the probe and recovery still fails, check optimizer convergence and scaling; local sensitivity does not prove global identifiability.
|
|
39
|
+
|
|
40
|
+
Open `scripts/train_nest_simulator_two_weights.py` for the tested dense, subthreshold two-input fixture. The same-timing control also matches synapse model and delay. In this additive model, equal total weights give identical voltage despite different splits, and the Jacobian is numerically rank one. Only the sum is identifiable under that control.
|
|
41
|
+
|
|
42
|
+
## Respect the observed boundaries
|
|
43
|
+
|
|
44
|
+
- Keep host-side graph construction outside an outer JIT. The tested multi-spike `spike_generator` performs host time-order validation that raises `TracerBoolConversionError` if the entire builder is outer-jitted. The canonical optimizer therefore runs on the host while Simulator owns its rollout execution.
|
|
45
|
+
- Do not infer spike-loss learning from voltage-loss learning. The recorded hard spike-count control emits three spikes yet has zero gradient with respect to external current in the tested configuration. Use `references/native-training.md` for the verified surrogate-gradient recurrent SNN path.
|
|
46
|
+
- Rebuild the same topology for each independent candidate here. This does not establish differentiable `SynapseCollection.set()` on an existing compiled Simulator, or a reusable fully compiled training step. The separate `window_voltage` fixture in `scripts/nest_boundary_workflows.py` does preserve the tested gradient through two local `cont(5 ms)` calls: final voltage and weight gradient match a single `simulate(10 ms)` run. All source spikes occur in the first window, so the nonzero final gradient crosses that boundary.
|
|
47
|
+
- Keep sparse connectivity structure fixed. The experiment differentiates weights, not discrete connection choices or spike times.
|
|
48
|
+
|
|
49
|
+
## Fit a hard spike count without gradients
|
|
50
|
+
|
|
51
|
+
The hard-count control still has zero autodiff gradient. `fit_hard_count()` in `scripts/nest_boundary_workflows.py` instead uses `braintools.optim.ScipyOptimizer(..., method="Powell")` with a bounded scalar external-current candidate. It finds five recorded spikes and zero count error in the tested 20 ms fixture. The candidate scales `100 pA` and lies in `[5,20]`.
|
|
52
|
+
|
|
53
|
+
This is derivative-free fitting, not surrogate-gradient learning. A count objective has plateaus and does not identify a unique physical current; a successful scalar fixture does not establish robust high-dimensional spike-time fitting. Use native surrogate training when temporal gradient credit is required.
|
|
54
|
+
|
|
55
|
+
## Evidence and public contracts
|
|
56
|
+
|
|
57
|
+
The repository-maintained Docker receipt and full log record the immutable image, versions, code hashes, positive controls, and negative controls. Reproduce the installed skill's fitting path through its bundled script.
|
|
58
|
+
|
|
59
|
+
- [Simulator lifecycle and recording](https://brainx.chaobrain.com/brainspike/apis/generated/brainspike.network.Simulator.html)
|
|
60
|
+
- [iaf_psc_alpha parameters and update contract](https://brainx.chaobrain.com/brainspike/apis/generated/brainspike.iaf_psc_alpha.html)
|
|
61
|
+
- [JAX reverse-mode Jacobian](https://docs.jax.dev/en/latest/_autosummary/jax.jacrev.html)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Train a masked temporal report
|
|
2
|
+
|
|
3
|
+
A temporal task advances hidden State through cue, silent delay, and report phases; a report mask removes loss outside the scoring window without freezing the model. A dynamic readout is part of the model's retained memory, not merely a final plotting operation.
|
|
4
|
+
|
|
5
|
+
## Keep trials and time distinct
|
|
6
|
+
|
|
7
|
+
| API | Use |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `DelayedCueSNN` in `scripts/delayed_cue_training.py` | Compose an ETP-aware input projection, native BrainSpike LIF population, and leaky trainable readout. |
|
|
10
|
+
| `braintrace.nn.LeakyRateReadout(..., tau=...)` | Use a readout with explicit temporal State when accumulated activity is part of the task. |
|
|
11
|
+
| `brainstate.nn.reset_all_states(model, batch_size=B)` | Reset independent trial State while preserving parameters; the example trains with four lanes and evaluates with two. |
|
|
12
|
+
| `brainstate.transform.for_loop(model, inputs)` | Advance every time step of `(time,batch,feature)` inputs. |
|
|
13
|
+
| `brainstate.transform.checkpointed_for_loop(model, inputs, base=4)` | Trade recomputation for activation memory inside the differentiated native loss; verify against the ordinary loop first. |
|
|
14
|
+
|
|
15
|
+
Run the complete canonical task from this skill root:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
python scripts/delayed_cue_training.py
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The fixture supplies cue amplitude for 5 steps, then zero external input for 15 steps at `dt=1 ms`. Only the final 5 steps contribute loss. Average per-output error first, multiply by the `(time,)` report mask broadcast over trials, and divide by the number of scored time-trial pairs. Do not average masked zeros over all time unless that scaling is intentional. Validate that the mask has positive support before using another protocol.
|
|
22
|
+
|
|
23
|
+
Initialize once, reset runtime State inside every loss, differentiate only `ParamState`, register optimizer State once, and apply one update after the sequence. The checkpointed loop belongs inside that differentiated loss. It does not eliminate membrane or readout State, nor does it turn BPTT into an online estimator.
|
|
24
|
+
|
|
25
|
+
## Verify the temporal claim
|
|
26
|
+
|
|
27
|
+
The Docker regression checks exact silent input, mask invariance outside the report window, finite nonzero input-projection/readout gradients, and ordinary/checkpointed loss and gradient parity on the same graph. Training lowers loss from approximately `0.424` to `0.0201`. Two fixed held-out cue amplitudes classify correctly; cue ablation reduces accuracy to 50 percent.
|
|
28
|
+
|
|
29
|
+
These tiny deterministic fixtures validate task mechanics and retained cue information in the complete graph. They do not prove population-only memory, scientific generalization, robustness over many trials, or a memory/performance benchmark. The leaky readout itself can retain the cue. Freeze evaluation trials and add matched state interventions before making a mechanism-specific claim.
|
|
30
|
+
|
|
31
|
+
Open `references/model-and-readout-selection.md` for instantaneous, dynamic, and windowed readouts. Open `brainstate` → `references/brainstate/brainstate-control-flow-patterns.md` for other loop/carry/checkpoint choices. Open `references/native-training.md` for the separately verified pp-prop workflow; this checkpointed task uses BPTT and does not validate an arbitrary pp-prop task integration.
|
|
32
|
+
|
|
33
|
+
## Sources
|
|
34
|
+
|
|
35
|
+
- [BrainTrace readout layers](https://brainx.chaobrain.com/braintrace/apis/nn.html)
|
|
36
|
+
- [BrainState control flow](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Conditional nonlinear State sharing and conservative two-clock exchange."""
|
|
2
|
+
import brainspike
|
|
3
|
+
import brainstate
|
|
4
|
+
import brainmass
|
|
5
|
+
import brainunit as u
|
|
6
|
+
from native_workflows import LIF
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class SaturatingSynapse(brainspike.Synapse):
|
|
10
|
+
"""Exact constant-drive step for dr/dt=alpha*s*(1-r)-beta*r."""
|
|
11
|
+
def __init__(self,shape,alpha=1/u.ms,beta=.2/u.ms):
|
|
12
|
+
super().__init__(shape)
|
|
13
|
+
self.state_shape=(shape,) if isinstance(shape,int) else tuple(shape)
|
|
14
|
+
self.alpha,self.beta=alpha,beta
|
|
15
|
+
|
|
16
|
+
def init_state(self,batch_size=None,**kwargs):
|
|
17
|
+
shape=self.state_shape if batch_size is None else (batch_size,*self.state_shape)
|
|
18
|
+
self.r=brainstate.HiddenState(u.math.zeros(shape))
|
|
19
|
+
|
|
20
|
+
def reset_state(self,batch_size=None,**kwargs):
|
|
21
|
+
shape=self.state_shape if batch_size is None else (batch_size,*self.state_shape)
|
|
22
|
+
self.r.value=u.math.zeros(shape)
|
|
23
|
+
|
|
24
|
+
def update(self,events):
|
|
25
|
+
rate=self.alpha*events+self.beta
|
|
26
|
+
equilibrium=self.alpha*events/rate
|
|
27
|
+
self.r.value=equilibrium+(self.r.value-equilibrium)*u.math.exp(-brainstate.environ.get_dt()*rate)
|
|
28
|
+
return self.r.value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class MultirateCoupling(brainstate.nn.Module):
|
|
32
|
+
def __init__(self,fine_dt=.1*u.ms,ratio=5,gain=.2):
|
|
33
|
+
super().__init__()
|
|
34
|
+
if not isinstance(ratio,int) or ratio<1:
|
|
35
|
+
raise ValueError("ratio must be a positive integer")
|
|
36
|
+
self.fine_dt,self.ratio,self.gain=fine_dt,ratio,gain
|
|
37
|
+
self.coarse_dt=ratio*fine_dt
|
|
38
|
+
self.point=LIF(1)
|
|
39
|
+
self.mass=brainmass.HopfStep(in_size=1,a=-.25,w=.3)
|
|
40
|
+
|
|
41
|
+
def init_state(self,**kwargs):
|
|
42
|
+
self.rate=brainstate.ShortTermState(u.math.zeros(1)*u.Hz)
|
|
43
|
+
self.held=brainstate.ShortTermState(u.math.zeros(1))
|
|
44
|
+
self.events=brainstate.ShortTermState(u.math.zeros((self.ratio,1)))
|
|
45
|
+
self.end_time=brainstate.ShortTermState(0.*u.ms)
|
|
46
|
+
|
|
47
|
+
def update(self,start):
|
|
48
|
+
held=self.mass.x.value
|
|
49
|
+
self.held.value=held
|
|
50
|
+
def fine_step(i):
|
|
51
|
+
with brainstate.environ.context(dt=self.fine_dt,t=start+i*self.fine_dt):
|
|
52
|
+
return self.point(.5*u.nA+self.gain*held*.05*u.nA)
|
|
53
|
+
events=brainstate.transform.for_loop(fine_step,u.math.arange(self.ratio))
|
|
54
|
+
self.events.value=events
|
|
55
|
+
self.rate.value=(events.sum(axis=0)/self.coarse_dt).in_unit(u.Hz)
|
|
56
|
+
self.end_time.value=(start+self.coarse_dt).in_unit(u.ms)
|
|
57
|
+
with brainstate.environ.context(dt=self.coarse_dt,t=self.end_time.value):
|
|
58
|
+
self.mass.update(x_inp=self.gain*self.rate.value/(1000*u.Hz),y_inp=0.)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def run_multirate(ratio=5,gain=.2,duration=20*u.ms,fine_dt=.1*u.ms):
|
|
62
|
+
brainstate.environ.set(precision=64)
|
|
63
|
+
brainstate.random.seed(7)
|
|
64
|
+
model=MultirateCoupling(fine_dt=fine_dt,ratio=ratio,gain=gain)
|
|
65
|
+
result=brainmass.Simulator(model,dt=model.coarse_dt).run(
|
|
66
|
+
duration,inputs=lambda i,t:t,monitors={
|
|
67
|
+
"point":lambda m:m.point.V.value,"mass":lambda m:m.mass.x.value,
|
|
68
|
+
"held":lambda m:m.held.value,"events":lambda m:m.events.value,
|
|
69
|
+
"rate":lambda m:m.rate.value,"end_time":lambda m:m.end_time.value,
|
|
70
|
+
})
|
|
71
|
+
return model,result
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if __name__=="__main__":
|
|
75
|
+
_,result=run_multirate()
|
|
76
|
+
print("fine events",result["events"].shape,"final mass",result["mass"][-1])
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Grid-aligned native delay taps, independent of retired BrainPy projections."""
|
|
2
|
+
import brainevent
|
|
3
|
+
import brainstate
|
|
4
|
+
import brainunit as u
|
|
5
|
+
import jax
|
|
6
|
+
import jax.numpy as jnp
|
|
7
|
+
from native_workflows import LIF, ExponentialConductance
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DelayBank(brainstate.nn.Module):
|
|
11
|
+
def __init__(self):
|
|
12
|
+
super().__init__()
|
|
13
|
+
dt = brainstate.environ.get_dt()
|
|
14
|
+
self.history = brainstate.nn.Delay(jax.ShapeDtypeStruct((3,),jnp.bool_), 3*dt)
|
|
15
|
+
self.history.register_entry("axonal",jnp.asarray([0,2,3])*dt,jnp.arange(3))
|
|
16
|
+
|
|
17
|
+
def update(self, spikes):
|
|
18
|
+
self.history.update(spikes)
|
|
19
|
+
return self.history.at("axonal")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DelayedProjection(brainstate.nn.Module):
|
|
23
|
+
"""External binary events -> named taps -> conductance -> native point neuron."""
|
|
24
|
+
def __init__(self):
|
|
25
|
+
super().__init__()
|
|
26
|
+
self.bank = DelayBank()
|
|
27
|
+
self.synapse = ExponentialConductance(1)
|
|
28
|
+
self.post = LIF(1)
|
|
29
|
+
self.weights = jnp.asarray([[.5],[.7],[.9]])*u.nS
|
|
30
|
+
|
|
31
|
+
def update(self,spikes):
|
|
32
|
+
delayed = self.bank(spikes)
|
|
33
|
+
increment = brainevent.BinaryArray(delayed) @ self.weights
|
|
34
|
+
conductance = self.synapse(increment)
|
|
35
|
+
self.post(conductance*(0*u.mV-self.post.V.value))
|
|
36
|
+
return {"events":delayed,"conductance":conductance,"voltage":self.post.V.value}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
if __name__ == "__main__":
|
|
40
|
+
brainstate.environ.set(dt=0.1*u.ms)
|
|
41
|
+
bank = DelayBank()
|
|
42
|
+
brainstate.nn.init_all_states(bank)
|
|
43
|
+
impulses = jnp.zeros((6,3),dtype=jnp.bool_).at[0].set(True)
|
|
44
|
+
print(brainstate.transform.for_loop(bank,impulses))
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Batched cue -> silent delay -> masked report, with checkpointed BPTT."""
|
|
2
|
+
import json
|
|
3
|
+
import brainstate
|
|
4
|
+
import braintrace
|
|
5
|
+
import braintools
|
|
6
|
+
import brainunit as u
|
|
7
|
+
from native_workflows import LIF
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DelayedCueSNN(brainstate.nn.Module):
|
|
11
|
+
def __init__(self,size=8):
|
|
12
|
+
super().__init__()
|
|
13
|
+
self.drive = braintrace.nn.Linear(1,size,w_init=braintools.init.Constant(0.6),b_init=braintools.init.ZeroInit())
|
|
14
|
+
self.neuron = LIF(size)
|
|
15
|
+
self.readout = braintrace.nn.LeakyRateReadout(size,1,tau=10*u.ms,w_init=braintools.init.XavierNormal())
|
|
16
|
+
|
|
17
|
+
def update(self,x):
|
|
18
|
+
return self.readout(self.neuron(self.drive(x)*u.nA))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def trials(cues):
|
|
22
|
+
inputs = u.math.zeros((20,len(cues),1))
|
|
23
|
+
inputs = inputs.at[:5,:,0].set(cues)
|
|
24
|
+
mask = u.math.concatenate((u.math.zeros(15),u.math.ones(5)))
|
|
25
|
+
targets = u.math.where(cues[:,None]<1.,-0.5,0.5)
|
|
26
|
+
return inputs,targets,mask
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def masked_loss(outputs,targets,mask):
|
|
30
|
+
per_trial = u.math.mean((outputs-targets)**2,axis=-1)
|
|
31
|
+
return u.math.sum(per_trial*mask[:,None])/(u.math.sum(mask)*outputs.shape[1])
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def sequence_loss(model,inputs,targets,mask,checkpointed=False):
|
|
35
|
+
brainstate.nn.reset_all_states(model,batch_size=inputs.shape[1])
|
|
36
|
+
if checkpointed:
|
|
37
|
+
outputs = brainstate.transform.checkpointed_for_loop(model,inputs,base=4)
|
|
38
|
+
else:
|
|
39
|
+
outputs = brainstate.transform.for_loop(model,inputs)
|
|
40
|
+
return masked_loss(outputs,targets,mask)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def train(epochs=120):
|
|
44
|
+
brainstate.environ.set(precision=64,dt=1*u.ms)
|
|
45
|
+
brainstate.random.seed(7)
|
|
46
|
+
inputs,targets,mask = trials(u.math.asarray([0.6,0.8,1.2,1.4]))
|
|
47
|
+
model = DelayedCueSNN()
|
|
48
|
+
brainstate.nn.init_all_states(model,batch_size=4)
|
|
49
|
+
params = model.states(brainstate.ParamState)
|
|
50
|
+
loss = lambda: sequence_loss(model,inputs,targets,mask,checkpointed=True)
|
|
51
|
+
initial = float(loss())
|
|
52
|
+
optimizer = braintools.optim.Adam(lr=0.02)
|
|
53
|
+
optimizer.register_trainable_weights(params)
|
|
54
|
+
gradient = brainstate.transform.grad(loss,params,return_value=True)
|
|
55
|
+
@brainstate.transform.jit
|
|
56
|
+
def step():
|
|
57
|
+
grads,value = gradient()
|
|
58
|
+
optimizer.update(grads)
|
|
59
|
+
return value
|
|
60
|
+
for _ in range(epochs):step()
|
|
61
|
+
final = float(loss())
|
|
62
|
+
held_inputs,held_targets,held_mask = trials(u.math.asarray([0.7,1.3]))
|
|
63
|
+
def evaluate(xs):
|
|
64
|
+
brainstate.nn.reset_all_states(model,batch_size=2)
|
|
65
|
+
outputs = brainstate.transform.for_loop(model,xs)
|
|
66
|
+
return u.math.mean(outputs[-5:],axis=0)
|
|
67
|
+
prediction = evaluate(held_inputs)
|
|
68
|
+
ablated = evaluate(u.math.zeros_like(held_inputs))
|
|
69
|
+
accuracy = u.math.mean((prediction[:,0]>0)==(held_targets[:,0]>0))
|
|
70
|
+
ablated_accuracy = u.math.mean((ablated[:,0]>0)==(held_targets[:,0]>0))
|
|
71
|
+
metrics = {"initial_loss":initial,"final_loss":final,"held_accuracy":float(accuracy),
|
|
72
|
+
"cue_ablated_accuracy":float(ablated_accuracy),"prediction":prediction[:,0].tolist()}
|
|
73
|
+
return model,metrics
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
if __name__ == "__main__":
|
|
77
|
+
_,metrics = train()
|
|
78
|
+
print(json.dumps(metrics))
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Run a single constant-current LIF neuron on the CPU."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def main():
|
|
7
|
+
os.environ["JAX_PLATFORMS"] = "cpu"
|
|
8
|
+
|
|
9
|
+
import brainspike
|
|
10
|
+
import brainstate
|
|
11
|
+
import brainunit as u
|
|
12
|
+
|
|
13
|
+
brainstate.environ.set(precision=64)
|
|
14
|
+
sim = brainspike.Simulator(dt=0.1 * u.ms)
|
|
15
|
+
neuron = sim.create(brainspike.iaf_psc_alpha, 1, I_e=500.0 * u.pA)
|
|
16
|
+
recorder = sim.create(brainspike.spike_recorder)
|
|
17
|
+
sim.connect(neuron, recorder)
|
|
18
|
+
|
|
19
|
+
spikes = sim.simulate(100.0 * u.ms).spikes(recorder)
|
|
20
|
+
count = int(spikes.sum())
|
|
21
|
+
devices = {device.platform for device in spikes.devices()}
|
|
22
|
+
if spikes.shape != (1000, 1) or count <= 0 or devices != {"cpu"}:
|
|
23
|
+
raise RuntimeError(
|
|
24
|
+
f"Expected shape (1000, 1) and positive firing on CPU; "
|
|
25
|
+
f"got shape={spikes.shape}, count={count}, devices={devices}"
|
|
26
|
+
)
|
|
27
|
+
print(f"PASS: shape={spikes.shape}, spikes={count}, device=cpu")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
if __name__ == "__main__":
|
|
31
|
+
main()
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Causal same-clock composition of point, cellular, and regional dynamics."""
|
|
2
|
+
import braincell
|
|
3
|
+
import brainmass
|
|
4
|
+
import brainstate
|
|
5
|
+
import brainunit as u
|
|
6
|
+
from native_workflows import LIF
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class HH(braincell.SingleCompartment):
|
|
10
|
+
def __init__(self):
|
|
11
|
+
super().__init__(1, V_th=20.0 * u.mV, solver="exp_euler")
|
|
12
|
+
self.na = braincell.ion.SodiumFixed(1, E=50.0 * u.mV)
|
|
13
|
+
self.na.add(INa=braincell.channel.Na_HH1952(1))
|
|
14
|
+
self.k = braincell.ion.PotassiumFixed(1, E=-77.0 * u.mV)
|
|
15
|
+
self.k.add(IK=braincell.channel.K_HH1952(1))
|
|
16
|
+
self.IL = braincell.channel.IL(1, E=-54.387 * u.mV, g_max=0.03 * u.mS / u.cm**2)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CoupledScales(brainstate.nn.Module):
|
|
20
|
+
"""Every target consumes source values from the previous completed step."""
|
|
21
|
+
def __init__(self, gain=1.0):
|
|
22
|
+
super().__init__()
|
|
23
|
+
self.point = LIF(1)
|
|
24
|
+
self.cell = HH()
|
|
25
|
+
self.mass = brainmass.HopfStep(in_size=1, a=-0.25, w=0.3)
|
|
26
|
+
self.gain = gain
|
|
27
|
+
|
|
28
|
+
def update(self):
|
|
29
|
+
previous_spikes = self.point.get_spike()
|
|
30
|
+
previous_mass = self.mass.x.value
|
|
31
|
+
previous_cell = (self.cell.V.value + 65.0 * u.mV) / (100.0 * u.mV)
|
|
32
|
+
rate = previous_spikes / brainstate.environ.get_dt()
|
|
33
|
+
self.point(0.5 * u.nA + self.gain * (previous_mass + previous_cell) * 0.05 * u.nA)
|
|
34
|
+
self.cell.update(self.gain * previous_spikes * 0.1 * u.uA / u.cm**2)
|
|
35
|
+
self.mass.update(x_inp=self.gain * rate / (1000.0 * u.Hz), y_inp=0.0)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Small native conductance E/I network; run from this file's directory or directly."""
|
|
2
|
+
import json
|
|
3
|
+
import brainevent
|
|
4
|
+
import brainstate
|
|
5
|
+
import brainunit as u
|
|
6
|
+
from native_workflows import LIF, ExponentialConductance
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class EINetwork(brainstate.nn.Module):
|
|
10
|
+
def __init__(self, n_exc=16, n_inh=4):
|
|
11
|
+
super().__init__()
|
|
12
|
+
self.n_exc, self.n_inh = n_exc, n_inh
|
|
13
|
+
self.exc, self.inh = LIF(n_exc), LIF(n_inh)
|
|
14
|
+
n = n_exc+n_inh
|
|
15
|
+
self.w_exc = brainstate.random.bernoulli(0.3, size=(n_exc,n))*0.3*u.nS
|
|
16
|
+
self.w_inh = brainstate.random.bernoulli(0.3, size=(n_inh,n))*0.8*u.nS
|
|
17
|
+
self.syn_exc = ExponentialConductance(n, tau=5*u.ms)
|
|
18
|
+
self.syn_inh = ExponentialConductance(n, tau=10*u.ms)
|
|
19
|
+
|
|
20
|
+
def update(self, drive):
|
|
21
|
+
# Snapshot previous events and voltage before advancing either population.
|
|
22
|
+
exc_spikes, inh_spikes = self.exc.get_spike(), self.inh.get_spike()
|
|
23
|
+
voltage = u.math.concatenate((self.exc.V.value, self.inh.V.value))
|
|
24
|
+
g_exc = self.syn_exc(brainevent.BinaryArray(exc_spikes != 0) @ self.w_exc)
|
|
25
|
+
g_inh = self.syn_inh(brainevent.BinaryArray(inh_spikes != 0) @ self.w_inh)
|
|
26
|
+
i_exc = g_exc*(0*u.mV-voltage)
|
|
27
|
+
i_inh = g_inh*(-80*u.mV-voltage)
|
|
28
|
+
current = drive+i_exc+i_inh
|
|
29
|
+
exc = self.exc(current[:self.n_exc])
|
|
30
|
+
inh = self.inh(current[self.n_exc:])
|
|
31
|
+
return {"spikes": u.math.concatenate((exc,inh)), "g_exc": g_exc,
|
|
32
|
+
"g_inh": g_inh, "i_exc": i_exc, "i_inh": i_inh,
|
|
33
|
+
"voltage": u.math.concatenate((self.exc.V.value,self.inh.V.value))}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def simulate(steps=300):
|
|
37
|
+
brainstate.environ.set(precision=64,dt=0.1*u.ms)
|
|
38
|
+
brainstate.random.seed(7)
|
|
39
|
+
net = EINetwork()
|
|
40
|
+
brainstate.nn.init_all_states(net)
|
|
41
|
+
outputs = brainstate.transform.for_loop(lambda _: net(0.2*u.nA), u.math.arange(steps))
|
|
42
|
+
return net, outputs
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
_, outputs = simulate()
|
|
47
|
+
print(json.dumps({"spikes":float(outputs["spikes"].sum()), "shape":outputs["spikes"].shape}))
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Public BrainSpike Neuron composition; independent of the NEST Simulator."""
|
|
2
|
+
import brainspike
|
|
3
|
+
import brainstate
|
|
4
|
+
import braintrace
|
|
5
|
+
import braintools
|
|
6
|
+
import brainunit as u
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LIF(brainspike.Neuron):
|
|
10
|
+
"""Euler LIF with a unit-aware drive and an explicit soft reset."""
|
|
11
|
+
def __init__(self, size):
|
|
12
|
+
super().__init__(size, spk_fun=braintools.surrogate.InvSquareGrad())
|
|
13
|
+
self.size = size
|
|
14
|
+
self.tau = 10.0 * u.ms
|
|
15
|
+
self.resistance = 100.0 * u.Mohm
|
|
16
|
+
self.rest = -65.0 * u.mV
|
|
17
|
+
self.threshold = -50.0 * u.mV
|
|
18
|
+
|
|
19
|
+
def init_state(self, batch_size=None, **kwargs):
|
|
20
|
+
shape = (self.size,) if batch_size is None else (batch_size, self.size)
|
|
21
|
+
self.V = brainstate.HiddenState(u.math.full(shape, self.rest))
|
|
22
|
+
self.spike = brainstate.HiddenState(u.math.zeros(shape))
|
|
23
|
+
|
|
24
|
+
def reset_state(self, batch_size=None, **kwargs):
|
|
25
|
+
shape = (self.size,) if batch_size is None else (batch_size, self.size)
|
|
26
|
+
self.V.value = u.math.full(shape, self.rest)
|
|
27
|
+
self.spike.value = u.math.zeros(shape)
|
|
28
|
+
|
|
29
|
+
def get_spike(self):
|
|
30
|
+
return self.spike.value
|
|
31
|
+
|
|
32
|
+
def update(self, current):
|
|
33
|
+
current = self.sum_current_inputs(current)
|
|
34
|
+
voltage = self.V.value + brainstate.environ.get_dt() / self.tau * (
|
|
35
|
+
self.rest - self.V.value + self.resistance * current
|
|
36
|
+
)
|
|
37
|
+
spike = self.spk_fun((voltage - self.threshold) / (10.0 * u.mV))
|
|
38
|
+
self.V.value = voltage - spike * (self.threshold - self.rest)
|
|
39
|
+
self.spike.value = spike
|
|
40
|
+
return spike
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RecurrentSNN(brainstate.nn.Module):
|
|
44
|
+
"""ETP-aware input/recurrent weights and a trainable spike readout."""
|
|
45
|
+
def __init__(self, size=3):
|
|
46
|
+
super().__init__()
|
|
47
|
+
self.drive = braintrace.nn.Linear(
|
|
48
|
+
1 + size, size,
|
|
49
|
+
w_init=braintools.init.Constant(0.4),
|
|
50
|
+
b_init=braintools.init.ZeroInit(),
|
|
51
|
+
)
|
|
52
|
+
self.neuron = LIF(size)
|
|
53
|
+
self.readout = braintrace.nn.Linear(size, 1)
|
|
54
|
+
|
|
55
|
+
def update(self, x):
|
|
56
|
+
features = u.math.concatenate((x, self.neuron.get_spike()), axis=-1)
|
|
57
|
+
spikes = self.neuron(self.drive(features) * u.nA)
|
|
58
|
+
return self.readout(spikes)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class ExponentialConductance(brainspike.Synapse):
|
|
62
|
+
"""Post-aligned linear filter: decay old conductance, then add new events."""
|
|
63
|
+
def __init__(self, size, tau=5.0 * u.ms):
|
|
64
|
+
super().__init__(size)
|
|
65
|
+
self.size, self.tau = size, tau
|
|
66
|
+
|
|
67
|
+
def init_state(self, batch_size=None, **kwargs):
|
|
68
|
+
shape = (self.size,) if batch_size is None else (batch_size, self.size)
|
|
69
|
+
self.g = brainstate.HiddenState(u.math.zeros(shape) * u.nS)
|
|
70
|
+
|
|
71
|
+
def reset_state(self, batch_size=None, **kwargs):
|
|
72
|
+
shape = (self.size,) if batch_size is None else (batch_size, self.size)
|
|
73
|
+
self.g.value = u.math.zeros(shape) * u.nS
|
|
74
|
+
|
|
75
|
+
def update(self, increment):
|
|
76
|
+
self.g.value = self.g.value * u.math.exp(-brainstate.environ.get_dt() / self.tau) + increment
|
|
77
|
+
return self.g.value
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Release-scoped NEST delay paths, custom scheduling, and hard-spike fitting."""
|
|
2
|
+
import brainspike
|
|
3
|
+
import brainstate
|
|
4
|
+
import braintools
|
|
5
|
+
import brainunit as u
|
|
6
|
+
import jax.numpy as jnp
|
|
7
|
+
import numpy as np
|
|
8
|
+
from native_workflows import LIF
|
|
9
|
+
from train_nest_simulator import rollout
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AutonomousLIF(LIF):
|
|
13
|
+
"""Minimal zero-argument Simulator update; no incoming synapse contract."""
|
|
14
|
+
def update(self):
|
|
15
|
+
return super().update(.5*u.nA)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def delay_arrivals(delay,via="direct",n_source=1):
|
|
19
|
+
sim=brainspike.Simulator(dt=.1*u.ms)
|
|
20
|
+
source=sim.create(brainspike.spike_generator,n_source,spike_times=jnp.asarray([1.])*u.ms)
|
|
21
|
+
target=sim.create(brainspike.iaf_psc_delta,2,E_L=0*u.mV,V_reset=0*u.mV,
|
|
22
|
+
V_th=20*u.mV,t_ref=0*u.ms,V_initializer=braintools.init.Constant(0*u.mV))
|
|
23
|
+
if via=="direct":
|
|
24
|
+
sim.connect(source,target,weight=30*u.mV,delay=delay)
|
|
25
|
+
elif via=="spec":
|
|
26
|
+
sim.connect(source,target,synapse=brainspike.static_synapse(weight=30*u.mV,delay=delay))
|
|
27
|
+
elif via=="continuous":
|
|
28
|
+
sim.connect(source,target,synapse=brainspike.cont_delay_synapse(weight=30*u.mV,delay=delay))
|
|
29
|
+
elif via=="set":
|
|
30
|
+
sim.connect(source,target,synapse=brainspike.static_synapse(weight=30*u.mV,delay=.2*u.ms))
|
|
31
|
+
sim.get_connections().set("delay",delay)
|
|
32
|
+
else:
|
|
33
|
+
raise ValueError("unknown delay path")
|
|
34
|
+
rec=sim.create(brainspike.spike_recorder)
|
|
35
|
+
sim.connect(target,rec)
|
|
36
|
+
spikes=np.asarray(sim.simulate(3*u.ms).spikes(rec))
|
|
37
|
+
return [np.flatnonzero(spikes[:,i]).tolist() for i in range(2)]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def neuron_delay_matrix(mode="grouped"):
|
|
41
|
+
sim=brainspike.Simulator(dt=.1*u.ms)
|
|
42
|
+
driver=sim.create(brainspike.spike_generator,spike_times=jnp.asarray([1.])*u.ms)
|
|
43
|
+
params=dict(E_L=0*u.mV,V_reset=0*u.mV,V_th=20*u.mV,t_ref=0*u.ms,
|
|
44
|
+
V_initializer=braintools.init.Constant(0*u.mV))
|
|
45
|
+
pre=sim.create(brainspike.iaf_psc_delta,2,params=params)
|
|
46
|
+
post=sim.create(brainspike.iaf_psc_delta,2,params=params)
|
|
47
|
+
sim.connect(driver,pre,weight=30*u.mV,delay=.1*u.ms)
|
|
48
|
+
delays=jnp.asarray([[.1,.2],[.3,.4]])*u.ms
|
|
49
|
+
if mode=="grouped":
|
|
50
|
+
for i in range(2):
|
|
51
|
+
for j in range(2):
|
|
52
|
+
sim.connect(pre[i:i+1],post[j:j+1],weight=30*u.mV,delay=delays[i,j])
|
|
53
|
+
else:
|
|
54
|
+
delay=delays if mode=="matrix" else .2*u.ms
|
|
55
|
+
sim.connect(pre,post,weight=30*u.mV,delay=delay)
|
|
56
|
+
recorder=sim.create(brainspike.spike_recorder);sim.connect(post,recorder)
|
|
57
|
+
spikes=np.asarray(sim.simulate(4*u.ms).spikes(recorder))
|
|
58
|
+
return [np.flatnonzero(spikes[:,i]).tolist() for i in range(2)]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def voltage_trace(delay_ms,path="direct"):
|
|
62
|
+
sim=brainspike.Simulator(dt=.1*u.ms)
|
|
63
|
+
source=sim.create(brainspike.spike_generator,spike_times=jnp.asarray([1.])*u.ms)
|
|
64
|
+
target=sim.create(brainspike.iaf_psc_exp,1,E_L=0*u.mV,V_reset=0*u.mV,
|
|
65
|
+
V_th=10000*u.mV,V_initializer=braintools.init.Constant(0*u.mV))
|
|
66
|
+
if path=="direct":
|
|
67
|
+
sim.connect(source,target,weight=250*u.pA,delay=delay_ms*u.ms)
|
|
68
|
+
else:
|
|
69
|
+
spec={"spec":brainspike.static_synapse,"continuous":brainspike.cont_delay_synapse}[path]
|
|
70
|
+
sim.connect(source,target,synapse=spec(weight=250*u.pA,delay=delay_ms*u.ms))
|
|
71
|
+
meter=sim.create(brainspike.multimeter,record_from=["V_m"])
|
|
72
|
+
sim.connect(meter,target)
|
|
73
|
+
return np.asarray(sim.simulate(5*u.ms).trace(meter,"V_m").to_decimal(u.mV))[:,0]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def window_voltage(weight,continued=False):
|
|
77
|
+
sim=brainspike.Simulator(dt=.1*u.ms)
|
|
78
|
+
source=sim.create(brainspike.spike_generator,spike_times=jnp.asarray([1.,2.,3.])*u.ms)
|
|
79
|
+
target=sim.create(brainspike.iaf_psc_alpha,1,
|
|
80
|
+
V_initializer=braintools.init.Constant(-65*u.mV))
|
|
81
|
+
sim.connect(source,target,weight=weight*100*u.pA,delay=.1*u.ms)
|
|
82
|
+
meter=sim.create(brainspike.multimeter,record_from=["V_m"]);sim.connect(meter,target)
|
|
83
|
+
if continued:
|
|
84
|
+
sim.cont(5*u.ms)
|
|
85
|
+
result=sim.cont(5*u.ms)
|
|
86
|
+
else:
|
|
87
|
+
result=sim.simulate(10*u.ms)
|
|
88
|
+
return result.trace(meter,"V_m").to_decimal(u.mV)[-1,0]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def fit_hard_count():
|
|
92
|
+
brainstate.environ.set(precision=64)
|
|
93
|
+
brainstate.random.seed(7)
|
|
94
|
+
def count(current):
|
|
95
|
+
return jnp.sum(rollout(jnp.asarray(.5),current=current,duration=20)[1])
|
|
96
|
+
optimizer=braintools.optim.ScipyOptimizer(
|
|
97
|
+
loss_fun=lambda current:(count(current)-5.)**2,
|
|
98
|
+
bounds=[(jnp.asarray(5.),jnp.asarray(20.))],method="Powell",
|
|
99
|
+
)
|
|
100
|
+
result=optimizer.minimize(n_iter=1)
|
|
101
|
+
current=float(np.asarray(result.x[0]))
|
|
102
|
+
return {"current_multiplier":current,"count":float(count(current)),"loss":float(result.fun)}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
if __name__=="__main__":
|
|
106
|
+
brainstate.environ.set(precision=64)
|
|
107
|
+
print("edge delays",delay_arrivals(jnp.asarray([.2,.5])*u.ms))
|
|
108
|
+
print("hard-count bounded fit",fit_hard_count())
|