brainx-skill 1.0.14 → 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 +143 -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
|
@@ -1,163 +0,0 @@
|
|
|
1
|
-
# More about legacy BrainPy simulation
|
|
2
|
-
|
|
3
|
-
Use this reference after a legacy `brainpy.DynamicalSystem` is constructed and
|
|
4
|
-
needs `DSRunner` monitor/input configuration, repeated rollouts, or parallel
|
|
5
|
-
parameter exploration. Keep model construction in the legacy workflow and use
|
|
6
|
-
the APIs here only to execute and observe it.
|
|
7
|
-
|
|
8
|
-
## Run a `DynamicalSystem`
|
|
9
|
-
|
|
10
|
-
`DSRunner` lowers repeated model updates through a structural loop while owning
|
|
11
|
-
time, input application, monitoring, optional JIT compilation, and result
|
|
12
|
-
conversion.
|
|
13
|
-
|
|
14
|
-
| API | Description |
|
|
15
|
-
|---|---|
|
|
16
|
-
| `bp.DSRunner(target, inputs=(), monitors=None, numpy_mon_after_run=True, jit=True, dyn_vars=None, memory_efficient=False, dt=None, t0=0.0, progress_bar=True, data_first_axis=None, fun_inputs=None, fun_monitors=None)` | Use to configure execution around one legacy `DynamicalSystem`; it records monitor histories in `runner.mon`. |
|
|
17
|
-
| `runner.run(duration, inputs=None, reset_state=False, shared_args=None, progress_bar=None, eval_time=False)` | Run for a physical duration and optionally override run inputs, reset State, provide shared arguments, or evaluate runtime. |
|
|
18
|
-
| `runner.predict(duration=None, inputs=None, reset_state=False, eval_time=False, shared_args=None, inputs_are_batching=None)` | Use the prediction interface when inputs may be unbatched `(time, ...)` or batched `(sample, time, ...)`. |
|
|
19
|
-
| `runner.reset_state()` | Reset the target through the runner before an independent rollout. |
|
|
20
|
-
|
|
21
|
-
```python
|
|
22
|
-
import brainpy as bp
|
|
23
|
-
|
|
24
|
-
neuron = bp.neurons.LIF(100)
|
|
25
|
-
runner = bp.DSRunner(
|
|
26
|
-
target=neuron,
|
|
27
|
-
monitors=['spike', 'V'],
|
|
28
|
-
inputs=[('input', 20.0)],
|
|
29
|
-
dt=0.1,
|
|
30
|
-
jit=True,
|
|
31
|
-
)
|
|
32
|
-
|
|
33
|
-
runner.run(100.0)
|
|
34
|
-
|
|
35
|
-
assert runner.mon.ts.shape[0] == runner.mon['V'].shape[0]
|
|
36
|
-
assert runner.mon['spike'].shape[1] == 100
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
The target must be a legacy `brainpy.DynamicalSystem`. Treat two calls as one
|
|
40
|
-
continuous rollout unless `reset_state=True` or `reset_state()` is used.
|
|
41
|
-
|
|
42
|
-
## Select monitor forms
|
|
43
|
-
|
|
44
|
-
Monitoring every value in a large network can dominate host memory. Record only
|
|
45
|
-
the paths, indices, or derived values needed for the scientific check.
|
|
46
|
-
|
|
47
|
-
| Monitor form | Use and result |
|
|
48
|
-
|---|---|
|
|
49
|
-
| `'E.spike'` | Resolve and record the named `bm.Variable`; retrieve it as `runner.mon['E.spike']`. |
|
|
50
|
-
| `('E.spike', [1, 2, 3])` | Record only the selected indices of a named variable. |
|
|
51
|
-
| `{'spike': net.E.spike}` | Record an explicitly supplied variable under a concise result key. |
|
|
52
|
-
| `{'spike': (net.E.spike, [1, 2, 3])}` | Record selected indices from an explicit target. |
|
|
53
|
-
| `{'E-I.spike': lambda: bm.concatenate((net.E.spike, net.I.spike))}` | Record a derived value returned by a callable. |
|
|
54
|
-
|
|
55
|
-
`runner.mon.ts` is the recorded time axis. With `numpy_mon_after_run=True`,
|
|
56
|
-
monitor arrays are converted after the run; keep them as device arrays when a
|
|
57
|
-
later compiled computation must consume them without a host transfer.
|
|
58
|
-
|
|
59
|
-
## Select input forms
|
|
60
|
-
|
|
61
|
-
An input specification identifies the target variable, value source, source
|
|
62
|
-
type, and update operation.
|
|
63
|
-
|
|
64
|
-
| Input form | Use and behavior |
|
|
65
|
-
|---|---|
|
|
66
|
-
| `('E.input', 20.0)` | Add one fixed scalar at every step; `'fix'` and `'+'` are the defaults. |
|
|
67
|
-
| `('E.input', current, 'iter')` | Consume axis 0 of `current` once per simulation step. |
|
|
68
|
-
| `('E.input', current, 'iter', '=')` | Assign rather than add each iterable sample. |
|
|
69
|
-
| `[spec1, spec2, ...]` | Apply several input operations to one or more target variables. |
|
|
70
|
-
| `inputs=input_function` | Execute a function that directly sets or updates target variables each step. |
|
|
71
|
-
|
|
72
|
-
```python
|
|
73
|
-
current, duration = bp.inputs.section_input(
|
|
74
|
-
values=[0.0, 20.0, 0.0],
|
|
75
|
-
durations=[100.0, 1000.0, 100.0],
|
|
76
|
-
dt=0.1,
|
|
77
|
-
return_length=True,
|
|
78
|
-
)
|
|
79
|
-
|
|
80
|
-
runner = bp.DSRunner(
|
|
81
|
-
target=network,
|
|
82
|
-
monitors=['E.spike'],
|
|
83
|
-
inputs=[
|
|
84
|
-
('E.input', current, 'iter'),
|
|
85
|
-
('I.input', current, 'iter'),
|
|
86
|
-
],
|
|
87
|
-
dt=0.1,
|
|
88
|
-
)
|
|
89
|
-
runner.run(duration)
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
For `predict(inputs_are_batching=False)`, each input leaf is time-major
|
|
93
|
-
`(num_time, ...)`. For `inputs_are_batching=True`, each leaf is
|
|
94
|
-
`(num_sample, num_time, ...)`. Do not infer batching from an ambiguous array;
|
|
95
|
-
set the flag when using the prediction interface.
|
|
96
|
-
|
|
97
|
-
## Choose a parameter-exploration executor
|
|
98
|
-
|
|
99
|
-
Each executor maps the same simulation function over parameter arrays, but its
|
|
100
|
-
parallelism and memory boundary differ.
|
|
101
|
-
|
|
102
|
-
| API | Use when | Key constraint |
|
|
103
|
-
|---|---|---|
|
|
104
|
-
| `bp.running.cpu_ordered_parallel(func, arguments, num_process=None, num_task=None, **tqdm_kwargs)` | Independent runs should use CPU worker processes and preserve input order. | Guard calls from Python files with `if __name__ == '__main__':`. |
|
|
105
|
-
| `bp.running.cpu_unordered_parallel(func, arguments, num_process=None, num_task=None, **tqdm_kwargs)` | Worker completion order is irrelevant and non-blocking collection is preferred. | Results do not preserve parameter order. |
|
|
106
|
-
| `bp.running.jax_vectorize_map(func, arguments, num_parallel, clear_buffer=False)` | Same-device vectorized execution is desired but the full parameter set is too large for one `jax.vmap`. | Tune `num_parallel` to device memory. |
|
|
107
|
-
| `bp.running.jax_parallelize_map(func, arguments, num_parallel, clear_buffer=False)` | Independent runs should be mapped over multiple JAX devices in bounded groups. | Device availability bounds meaningful parallelism. |
|
|
108
|
-
| `jax.vmap(func)(*arguments)` | The full parameter batch fits on one device and the function is vectorizable. | The whole mapped batch is compiled and resident together. |
|
|
109
|
-
| `jax.pmap(func)(*arguments)` | The leading mapped axis matches available devices. | Each mapped shard runs the same program on a separate device. |
|
|
110
|
-
|
|
111
|
-
```python
|
|
112
|
-
import brainpy as bp
|
|
113
|
-
import brainpy.math as bm
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
def spike_count(background_current):
|
|
117
|
-
neuron = bp.neurons.HH(1)
|
|
118
|
-
runner = bp.DSRunner(
|
|
119
|
-
neuron,
|
|
120
|
-
monitors=['spike'],
|
|
121
|
-
inputs=[('input', background_current)],
|
|
122
|
-
numpy_mon_after_run=False,
|
|
123
|
-
progress_bar=False,
|
|
124
|
-
)
|
|
125
|
-
runner.run(1000.0)
|
|
126
|
-
return runner.mon['spike'].sum()
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
currents = bm.linspace(1.0, 10.0, 20)
|
|
130
|
-
counts = bp.running.jax_vectorize_map(
|
|
131
|
-
spike_count,
|
|
132
|
-
[currents],
|
|
133
|
-
num_parallel=4,
|
|
134
|
-
clear_buffer=True,
|
|
135
|
-
)
|
|
136
|
-
|
|
137
|
-
assert counts.shape == currents.shape
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
Use `num_parallel` as the explicit memory-control knob. Start with a small value
|
|
141
|
-
and increase it only after measuring peak device memory and compilation cost.
|
|
142
|
-
|
|
143
|
-
## Manage process and device memory
|
|
144
|
-
|
|
145
|
-
- In a CPU worker function, call `bm.clear_buffer_memory()` only after converting
|
|
146
|
-
required results to NumPy. The operation clears JAX device buffers, so prefer
|
|
147
|
-
NumPy worker inputs and outputs when using it.
|
|
148
|
-
- Do not call `clear_buffer_memory()` inside a function mapped by
|
|
149
|
-
`jax_vectorize_map`; use that wrapper's `clear_buffer=` argument.
|
|
150
|
-
- Set virtual CPU device count before importing BrainPy or otherwise
|
|
151
|
-
initializing JAX. Changing it after backend initialization has no effect.
|
|
152
|
-
- Disable a runner progress bar inside `pmap`-style execution when its ordered
|
|
153
|
-
callback cannot be carried by the mapped computation.
|
|
154
|
-
- Use array sharding APIs for distributing one array or model computation. Open
|
|
155
|
-
`Multi-device array sharding.md` rather than treating an independent
|
|
156
|
-
parameter sweep as array partitioning.
|
|
157
|
-
|
|
158
|
-
## Official sources
|
|
159
|
-
|
|
160
|
-
- `https://brainpy.readthedocs.io/tutorial_simulation/simulation_dsrunner.html`
|
|
161
|
-
- `https://brainpy.readthedocs.io/tutorial_simulation/parallel_for_parameter_exploration.html`
|
|
162
|
-
- Generated `DSRunner` and `brainpy.running` pages linked by the official
|
|
163
|
-
documentation.
|
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
# Legacy BrainPy multi-device array sharding
|
|
2
|
-
|
|
3
|
-
Use this reference when a legacy `brainpy.math` array or PyTree must be placed
|
|
4
|
-
across a named JAX device mesh and the computation must preserve that placement.
|
|
5
|
-
This is array sharding, not independent parameter-sweep execution and not a
|
|
6
|
-
`brainpy.state` workflow.
|
|
7
|
-
|
|
8
|
-
## Build a named device mesh
|
|
9
|
-
|
|
10
|
-
`device_mesh` installs a scoped default `jax.sharding.Mesh`; array axis names
|
|
11
|
-
are resolved against that mesh to build a `NamedSharding` and `PartitionSpec`.
|
|
12
|
-
|
|
13
|
-
| API | Description |
|
|
14
|
-
|---|---|
|
|
15
|
-
| `bm.sharding.device_mesh(devices, axis_names)` | Use as a context manager to install a default mesh and restore the previous mesh on exit; the device-array rank must equal the number of mesh-axis names. |
|
|
16
|
-
| `bm.sharding.get_sharding(axis_names=None, mesh=None)` | Convert array axis names into `NamedSharding`; unresolved names become replicated `None` entries. |
|
|
17
|
-
| `bm.sharding.partition_by_axname(x, axis_names=None, mesh=None)` | Partition every supported array leaf by named array axes; the number of names must equal each leaf's rank. |
|
|
18
|
-
|
|
19
|
-
```python
|
|
20
|
-
import jax
|
|
21
|
-
import numpy as np
|
|
22
|
-
|
|
23
|
-
import brainpy.math as bm
|
|
24
|
-
from brainpy.math import sharding
|
|
25
|
-
|
|
26
|
-
devices = np.asarray(jax.devices())
|
|
27
|
-
|
|
28
|
-
with sharding.device_mesh(
|
|
29
|
-
devices,
|
|
30
|
-
axis_names=(sharding.BATCH_AXIS,),
|
|
31
|
-
) as mesh:
|
|
32
|
-
values = bm.arange(devices.size * 8).reshape((devices.size, 8))
|
|
33
|
-
values = sharding.partition_by_axname(
|
|
34
|
-
values,
|
|
35
|
-
axis_names=(sharding.BATCH_AXIS, None),
|
|
36
|
-
mesh=mesh,
|
|
37
|
-
)
|
|
38
|
-
|
|
39
|
-
assert values.shape == (devices.size, 8)
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
`None` leaves an array axis replicated. If no mesh is supplied and no default
|
|
43
|
-
mesh is active, `partition_by_axname()` returns the input unchanged. If every
|
|
44
|
-
requested string is absent from the mesh, `get_sharding()` warns and produces a
|
|
45
|
-
fully replicated specification; treat that warning as a misspelled sharding
|
|
46
|
-
plan, not as successful partitioning.
|
|
47
|
-
|
|
48
|
-
## Choose a placement interface
|
|
49
|
-
|
|
50
|
-
Use named axes for maintainable model code, an explicit `Sharding` when another
|
|
51
|
-
JAX component already owns the placement, and `partition()` only at generic
|
|
52
|
-
boundaries accepting several placement forms.
|
|
53
|
-
|
|
54
|
-
| API | Description |
|
|
55
|
-
|---|---|
|
|
56
|
-
| `bm.sharding.partition_by_axname(x, axis_names=None, mesh=None)` | Use for a BrainPy-defined named-axis plan and validate one axis name per array dimension. |
|
|
57
|
-
| `bm.sharding.partition_by_sharding(x, sharding=None)` | Use with an existing `jax.sharding.Sharding`; it raises `TypeError` for another strategy type. |
|
|
58
|
-
| `bm.sharding.partition(x, sharding=None)` | Use at a generic placement boundary; accept a JAX device, a `Sharding`, or a sequence containing named axes. |
|
|
59
|
-
| `bm.sharding.keep_constraint(x)` | Use inside computation to reapply each JAX array leaf's current sharding with `jax.lax.with_sharding_constraint`; it returns a matching PyTree. |
|
|
60
|
-
|
|
61
|
-
These placement functions traverse PyTrees. BrainPy arrays keep their wrapper
|
|
62
|
-
while their underlying value is device-placed; JAX or NumPy arrays are returned
|
|
63
|
-
through BrainPy's sharded-array wrapper.
|
|
64
|
-
|
|
65
|
-
## Use canonical axis names
|
|
66
|
-
|
|
67
|
-
The constants standardize intent across legacy BrainPy models; only names also
|
|
68
|
-
present in the active mesh cause partitioning.
|
|
69
|
-
|
|
70
|
-
| Constant | Value and use |
|
|
71
|
-
|---|---|
|
|
72
|
-
| `bm.sharding.NEU_AXIS` | `'neuron'`; shard a neuron axis. |
|
|
73
|
-
| `bm.sharding.PRE_AXIS` | `'pre'`; shard a presynaptic axis. |
|
|
74
|
-
| `bm.sharding.POST_AXIS` | `'post'`; shard a postsynaptic axis. |
|
|
75
|
-
| `bm.sharding.SYN_AXIS` | `'synapse'`; shard a synapse axis. |
|
|
76
|
-
| `bm.sharding.TIME_AXIS` | `'time'`; shard a time axis only when the algorithm supports distributed temporal data. |
|
|
77
|
-
| `bm.sharding.BATCH_AXIS` | `'batch'`; shard independent batch elements. |
|
|
78
|
-
|
|
79
|
-
The constant names do not create mesh axes. Include the selected value in
|
|
80
|
-
`device_mesh(..., axis_names=...)`, then use the same value in the array's axis
|
|
81
|
-
specification.
|
|
82
|
-
|
|
83
|
-
## Distinguish sharding from mapped simulations
|
|
84
|
-
|
|
85
|
-
| Need | Use |
|
|
86
|
-
|---|---|
|
|
87
|
-
| Partition one array or PyTree across a mesh | `bm.sharding.partition_by_axname()` or explicit `Sharding` placement. |
|
|
88
|
-
| Preserve placement through a compiled operation | `bm.sharding.keep_constraint()`. |
|
|
89
|
-
| Run one independent model per device | `jax.pmap()` or `bp.running.jax_parallelize_map()`. |
|
|
90
|
-
| Bound same-device vectorized sweep memory | `bp.running.jax_vectorize_map(..., num_parallel=...)`. |
|
|
91
|
-
|
|
92
|
-
Do not add a leading parameter axis and call it model sharding unless each
|
|
93
|
-
device is intentionally running an independent replica. Open `More about
|
|
94
|
-
simulation.md` for mapped parameter sweeps and their memory-management rules.
|
|
95
|
-
|
|
96
|
-
## Source-backed failures
|
|
97
|
-
|
|
98
|
-
- Make `np.asarray(devices).ndim == len(mesh_axis_names)` before entering
|
|
99
|
-
`device_mesh()`.
|
|
100
|
-
- Give `partition_by_axname()` one array-axis entry per leaf dimension; a
|
|
101
|
-
mismatch raises `ValueError`.
|
|
102
|
-
- Do not mix PyTree leaves of different ranks under one shared axis-name tuple;
|
|
103
|
-
partition those leaves with distinct specifications.
|
|
104
|
-
- Do not assume placement alone parallelizes an arbitrary legacy model. Verify
|
|
105
|
-
the compiled operation's input and output shardings on the actual hardware.
|
|
106
|
-
- Configure virtual CPU devices before BrainPy or JAX initializes its backend.
|
|
107
|
-
|
|
108
|
-
## Official sources
|
|
109
|
-
|
|
110
|
-
- `https://brainpy.readthedocs.io/apis/brainpy.math.sharding.html`
|
|
111
|
-
- `https://brainpy.readthedocs.io/tutorial_simulation/parallel_for_parameter_exploration.html`
|
|
112
|
-
- Generated sharding-function pages and the mirrored official module source
|
|
113
|
-
linked from the API index.
|
|
@@ -1,136 +0,0 @@
|
|
|
1
|
-
# Parallel experiment execution
|
|
2
|
-
|
|
3
|
-
Use this reference to map independent legacy BrainPy experiments across a device batch or CPU processes and to control monitor memory inside each long simulation. Keep model dynamics in ordinary `brainpy` objects; this reference owns experiment-level execution, not `brainpy.state` transformations.
|
|
4
|
-
|
|
5
|
-
## Selection map
|
|
6
|
-
|
|
7
|
-
| Need | Use | Key constraint |
|
|
8
|
-
|---|---|---|
|
|
9
|
-
| Vectorize independent array tasks on one CPU or GPU backend | `jax_vectorize_map(...)` | Every mapped argument leaf must have the same leading length. |
|
|
10
|
-
| Map independent tasks across multiple JAX devices | `jax_parallelize_map(...)` | The mapped batch must fit the available device count for each `pmap` call. |
|
|
11
|
-
| Run Python-level model tasks in separate native processes | `process_pool(...)` | Call it under an `if __name__ == '__main__':` guard. |
|
|
12
|
-
| Serialize a shared side effect across processes | `process_pool_lock(...)` | The worker must accept the supplied `lock` argument. |
|
|
13
|
-
| Run CPU tasks with a progress bar and preserve input order | `cpu_ordered_parallel(...)` | Ordered collection can wait for an earlier slow task. |
|
|
14
|
-
| Return CPU results as tasks finish | `cpu_unordered_parallel(...)` | Do not infer parameter order from the returned list. |
|
|
15
|
-
| Reduce monitor memory at a fixed sampling interval | Chunked `brainpy.math.for_loop(...)` | Reshape time and inputs so each outer item contains the steps between samples. |
|
|
16
|
-
| Monitor different variables at different intervals | A Python loop around `model.jit_step_run(...)` | Keep the compiled step but perform monitor selection explicitly. |
|
|
17
|
-
|
|
18
|
-
## Map experiments with JAX
|
|
19
|
-
|
|
20
|
-
Use the JAX mapping helpers when the experiment function is compatible with JAX array mapping and all tasks share one result structure.
|
|
21
|
-
|
|
22
|
-
| API | Description |
|
|
23
|
-
|---|---|
|
|
24
|
-
| `jax_vectorize_map(func, arguments, num_parallel, clear_buffer=False)` | Batch tasks through `jax.vmap`; use on CPU or GPU, especially for single-device GPU vectorization. It concatenates batch results and optionally clears cached buffer memory after each batch. |
|
|
25
|
-
| `jax_parallelize_map(func, arguments, num_parallel, clear_buffer=False)` | Batch tasks through `jax.pmap` across CPU or GPU devices. On a single CPU, configure the host device count with `brainpy.math.set_host_device_count(n)` before using this route. |
|
|
26
|
-
|
|
27
|
-
Pass `arguments` as a sequence of mapped positional-argument arrays or as a dictionary of mapped keyword-argument arrays. All leaves must have the same leading task count; otherwise the helpers raise an error rather than silently truncating the experiment set.
|
|
28
|
-
|
|
29
|
-
`num_parallel` is the batch size processed per map call. Set `clear_buffer=True` only when lower retained memory is worth recreating the mapped function and converting batch results between batches.
|
|
30
|
-
|
|
31
|
-
## Run experiments in CPU processes
|
|
32
|
-
|
|
33
|
-
Use process workers when each experiment constructs and runs a Python-level BrainPy model independently.
|
|
34
|
-
|
|
35
|
-
| API | Description |
|
|
36
|
-
|---|---|
|
|
37
|
-
| `process_pool(func, all_params, num_process)` | Run one task for each tuple/list of positional parameters or dictionary of keyword parameters and return a result list. |
|
|
38
|
-
| `process_pool_lock(func, all_params, num_process)` | Run the same task pattern while adding a shared process lock to each worker for synchronized file or resource access. |
|
|
39
|
-
| `cpu_ordered_parallel(func, arguments, num_process=None, num_task=None, **tqdm_kwargs)` | Apply `func` to iterable positional or keyword arguments with a progress bar and return results in input order. `num_process` may be a worker count or a fraction of available CPUs. |
|
|
40
|
-
| `cpu_unordered_parallel(func, arguments, num_process=None, num_task=None, **tqdm_kwargs)` | Apply the same CPU mapping interface but collect results in completion order. |
|
|
41
|
-
|
|
42
|
-
**Invariant:** place every multiprocessing call under the main-module guard. Without it, spawned workers can import the module and recursively launch more workers.
|
|
43
|
-
|
|
44
|
-
### Canonical CPU sweep
|
|
45
|
-
|
|
46
|
-
Construct the model inside the worker so each process owns independent model state:
|
|
47
|
-
|
|
48
|
-
```python
|
|
49
|
-
import brainpy as bp
|
|
50
|
-
import brainpy.math as bm
|
|
51
|
-
import numpy as np
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
def simulate(input_current):
|
|
55
|
-
current = bm.as_jax(input_current)
|
|
56
|
-
model = bp.dyn.HH(1)
|
|
57
|
-
runner = bp.DSRunner(
|
|
58
|
-
model,
|
|
59
|
-
monitors=["spike"],
|
|
60
|
-
progress_bar=False,
|
|
61
|
-
)
|
|
62
|
-
steps = int(100.0 / bm.get_dt())
|
|
63
|
-
inputs = bm.ones(steps) * current
|
|
64
|
-
runner.run(inputs=inputs)
|
|
65
|
-
spike_count = runner.mon.spike.sum()
|
|
66
|
-
bm.clear_buffer_memory()
|
|
67
|
-
return spike_count
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if __name__ == "__main__":
|
|
71
|
-
currents = np.linspace(1.0, 10.0, 8)
|
|
72
|
-
spike_counts = bp.running.cpu_ordered_parallel(
|
|
73
|
-
simulate,
|
|
74
|
-
[currents],
|
|
75
|
-
num_process=4,
|
|
76
|
-
)
|
|
77
|
-
assert len(spike_counts) == len(currents)
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
Use the unordered variant only when completion-order results are acceptable or when each worker returns its parameter identity with the result.
|
|
81
|
-
|
|
82
|
-
## Reduce monitor memory within an experiment
|
|
83
|
-
|
|
84
|
-
Long simulations can exhaust memory when every variable is recorded at every integration step. Sample only at the temporal precision required by the analysis.
|
|
85
|
-
|
|
86
|
-
### Use one interval for all monitored values
|
|
87
|
-
|
|
88
|
-
Reshape the step indices and inputs to `[n_samples, steps_per_sample]`. The function passed to `brainpy.math.for_loop(...)` runs the inner steps and returns only the final value to record for each outer sample.
|
|
89
|
-
|
|
90
|
-
```python
|
|
91
|
-
import brainpy as bp
|
|
92
|
-
import brainpy.math as bm
|
|
93
|
-
import numpy as np
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
class Accumulator(bp.DynamicalSystem):
|
|
97
|
-
def __init__(self):
|
|
98
|
-
super().__init__()
|
|
99
|
-
self.value = bm.Variable(bm.zeros(1))
|
|
100
|
-
|
|
101
|
-
def update(self, input_value):
|
|
102
|
-
self.value.value += input_value
|
|
103
|
-
|
|
104
|
-
def run(self, ids, values):
|
|
105
|
-
for step, input_value in zip(ids, values):
|
|
106
|
-
bp.share.save(i=step, t=bm.get_dt() * step)
|
|
107
|
-
self.update(input_value)
|
|
108
|
-
return self.value.value
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
steps_per_sample = 10
|
|
112
|
-
indices = np.arange(10_000).reshape(-1, steps_per_sample)
|
|
113
|
-
inputs = np.full(indices.shape, 20.0)
|
|
114
|
-
model = Accumulator()
|
|
115
|
-
|
|
116
|
-
sampled_values = bm.for_loop(
|
|
117
|
-
model.run,
|
|
118
|
-
(indices, inputs),
|
|
119
|
-
progress_bar=True,
|
|
120
|
-
)
|
|
121
|
-
|
|
122
|
-
assert sampled_values.shape == (indices.shape[0], 1)
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
The model's chunk method must still update shared time on every inner step, for example with `bp.share.save(i=step, t=bm.get_dt() * step)`, before calling its ordinary update method.
|
|
126
|
-
|
|
127
|
-
### Use different intervals for different values
|
|
128
|
-
|
|
129
|
-
Call `model.jit_step_run(step, input_value)` for each step, append fast monitors every step, and append slower monitors only when `step % interval == 0`. Convert the collected lists with `bm.as_numpy(...)` after the loop.
|
|
130
|
-
|
|
131
|
-
Choose this flexible Python monitor loop only when variables genuinely require different intervals. Use the chunked `for_loop` route when one interval is sufficient and whole-loop execution matters more than per-variable sampling flexibility.
|
|
132
|
-
|
|
133
|
-
## Sources
|
|
134
|
-
|
|
135
|
-
- https://brainpy.readthedocs.io/tutorial_simulation/monitor_per_multiple_steps.html
|
|
136
|
-
- https://brainpy.readthedocs.io/apis/running.html
|
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
# Legacy BrainPy array creation and mechanics
|
|
2
|
-
|
|
3
|
-
Use this reference for legacy `brainpy.math` array construction, mutable `Array` mechanics, NumPy-style transformations, backend conversion, random sampling, and named-axis operations. Use `../brainpy legacy workflow.md` for dynamical `Variable` lifecycle and model execution.
|
|
4
|
-
|
|
5
|
-
## Choose the array representation
|
|
6
|
-
|
|
7
|
-
Legacy `brainpy.math` follows NumPy syntax on a JAX backend while adding mutable wrappers needed by BrainPy's object-oriented transformations.
|
|
8
|
-
|
|
9
|
-
| API | Use when |
|
|
10
|
-
|---|---|
|
|
11
|
-
| `bm.Array(value, dtype=None)` | Wrap array-like data in BrainPy's mutable multidimensional array type. |
|
|
12
|
-
| `bm.array(a, dtype=None, copy=True, order='K', ndmin=0)` | Create a BrainPy `Array` from values, with copy and minimum-rank controls. |
|
|
13
|
-
| `bm.asarray(a, dtype=None, order=None)` | Convert input to a BrainPy `Array` without requesting an unnecessary copy. |
|
|
14
|
-
| `bm.Variable(value_or_size, ...)` | Mark model state that changes inside object-oriented transforms. A tuple or list can be interpreted as a shape, so wrap literal values with `bm.asarray(...)`. |
|
|
15
|
-
| `bm.TrainVar(value, ...)` | Mark a mutable value that optimizers should retrieve as trainable. |
|
|
16
|
-
| `bm.as_jax(tensor, dtype=None)` | Cross a library boundary with a JAX array. The returned value is not the mutable BrainPy wrapper. |
|
|
17
|
-
| `bm.as_numpy(tensor, dtype=None)` | Materialize a host NumPy array for plotting, serialization, or non-JAX code. |
|
|
18
|
-
| `bm.as_variable(tensor, dtype=None)` | Convert an existing array to `Variable`; pass a BrainPy or JAX array when the input is data rather than a shape. |
|
|
19
|
-
|
|
20
|
-
```python
|
|
21
|
-
import brainpy.math as bm
|
|
22
|
-
|
|
23
|
-
x = bm.array([[1.0, 2.0], [3.0, 4.0]])
|
|
24
|
-
x[0, 1] = 10.0
|
|
25
|
-
|
|
26
|
-
state = bm.as_variable(bm.asarray([1.0, 2.0]))
|
|
27
|
-
state.value = bm.asarray([3.0, 4.0])
|
|
28
|
-
|
|
29
|
-
assert x.shape == (2, 2)
|
|
30
|
-
assert state.shape == (2,)
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
**Invariant:** Use `Variable` for values mutated inside `bm.jit`, `bm.cls_jit`, `bm.grad`, or another BrainPy object transform. An ordinary array attribute is captured as static data and later Python-side replacement does not update already compiled code.
|
|
34
|
-
|
|
35
|
-
## Create arrays
|
|
36
|
-
|
|
37
|
-
Use the NumPy-equivalent constructor name unless BrainPy-specific mutability or conversion is the actual decision.
|
|
38
|
-
|
|
39
|
-
| API | Description |
|
|
40
|
-
|---|---|
|
|
41
|
-
| `bm.zeros(shape, dtype=None)` | Create an array filled with zero. |
|
|
42
|
-
| `bm.ones(shape, dtype=None)` | Create an array filled with one. |
|
|
43
|
-
| `bm.full(shape, fill_value, dtype=None)` | Create an array filled with one explicit value. |
|
|
44
|
-
| `bm.empty(shape, dtype=None)` | Allocate an array whose entries must be overwritten before use. |
|
|
45
|
-
| `bm.zeros_like(a, ...)` | Create zeros with an existing array's shape and default dtype. |
|
|
46
|
-
| `bm.ones_like(a, ...)` | Create ones with an existing array's shape and default dtype. |
|
|
47
|
-
| `bm.full_like(a, fill_value, ...)` | Fill an existing array's shape with one explicit value. |
|
|
48
|
-
| `bm.arange(start, stop=None, step=None, dtype=None)` | Create half-open regularly spaced values. |
|
|
49
|
-
| `bm.linspace(start, stop, num=50, endpoint=True, ...)` | Create a fixed number of evenly spaced values. |
|
|
50
|
-
| `bm.logspace(start, stop, num=50, endpoint=True, base=10.0, ...)` | Create values with evenly spaced exponents. |
|
|
51
|
-
| `bm.eye(N, M=None, k=0, dtype=None)` | Create a matrix with ones on diagonal `k`. |
|
|
52
|
-
| `bm.identity(n, dtype=None)` | Create a square identity matrix. |
|
|
53
|
-
| `bm.diag(v, k=0)` | Construct a diagonal matrix or extract a diagonal according to input rank. |
|
|
54
|
-
| `bm.meshgrid(*xi, copy=True, sparse=False, indexing='xy')` | Expand coordinate vectors into coordinate grids. |
|
|
55
|
-
|
|
56
|
-
```python
|
|
57
|
-
times = bm.arange(0.0, 100.0, bm.get_dt())
|
|
58
|
-
currents = bm.full(times.shape, 2.5)
|
|
59
|
-
grid_x, grid_y = bm.meshgrid(
|
|
60
|
-
bm.linspace(-1.0, 1.0, 5),
|
|
61
|
-
bm.linspace(0.0, 2.0, 3),
|
|
62
|
-
indexing='ij',
|
|
63
|
-
)
|
|
64
|
-
|
|
65
|
-
assert times.ndim == 1
|
|
66
|
-
assert currents.shape == times.shape
|
|
67
|
-
assert grid_x.shape == grid_y.shape == (5, 3)
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
Open `Input generation.md` when the values represent simulation stimuli with sections, ramps, oscillations, spike trains, or Poisson input rather than general-purpose arrays.
|
|
71
|
-
|
|
72
|
-
## Index, update, and inspect
|
|
73
|
-
|
|
74
|
-
`Array` permits NumPy-style in-place assignment even though its underlying JAX value is immutable; assignments update the wrapper's stored value.
|
|
75
|
-
|
|
76
|
-
| Operation | Result |
|
|
77
|
-
|---|---|
|
|
78
|
-
| `x[index]` | Select values with standard integer, slice, boolean, or advanced indexing. |
|
|
79
|
-
| `x[index] = value` | Replace selected values through the mutable BrainPy wrapper. |
|
|
80
|
-
| `x += value` and other augmented assignments | Update the wrapper in place. |
|
|
81
|
-
| `x.value` | Access the underlying JAX value of an `Array` or `Variable`. |
|
|
82
|
-
| `x.shape`, `x.ndim`, `x.size`, `x.dtype` | Inspect rank, extent, element count, and element type. |
|
|
83
|
-
| `bm.shape(x)`, `bm.ndim(x)`, `bm.size(x)` | Use functional metadata lookup in composed code. |
|
|
84
|
-
|
|
85
|
-
Assignment mutates aliases of the same wrapper:
|
|
86
|
-
|
|
87
|
-
```python
|
|
88
|
-
x = bm.arange(5)
|
|
89
|
-
alias = x
|
|
90
|
-
x[2] = 20
|
|
91
|
-
|
|
92
|
-
assert alias[2] == 20
|
|
93
|
-
```
|
|
94
|
-
|
|
95
|
-
Do not assume this behavior after `bm.as_jax(x)`; the returned JAX array uses functional `.at[...]` updates.
|
|
96
|
-
|
|
97
|
-
## Reshape and combine arrays
|
|
98
|
-
|
|
99
|
-
Use methods for local transformations and `bm` functions when composing several arrays.
|
|
100
|
-
|
|
101
|
-
| API | Description |
|
|
102
|
-
|---|---|
|
|
103
|
-
| `bm.reshape(a, shape, ...)` | Change shape without changing element order. |
|
|
104
|
-
| `bm.ravel(a, ...)` | Return a contiguous flattened view when possible. |
|
|
105
|
-
| `bm.flatten(a, start_dim=None, end_dim=None)` | Flatten all dimensions by default or only the selected dimension range. |
|
|
106
|
-
| `bm.squeeze(a, axis=None)` | Remove length-one axes. |
|
|
107
|
-
| `bm.expand_dims(a, axis)` | Insert a length-one axis. |
|
|
108
|
-
| `bm.transpose(a, axes=None)` | Permute axes. |
|
|
109
|
-
| `bm.swapaxes(a, axis1, axis2)` | Exchange two axes. |
|
|
110
|
-
| `bm.moveaxis(a, source, destination)` | Move selected axes while retaining the others' order. |
|
|
111
|
-
| `bm.concatenate(arrays, axis=0)` | Join arrays along an existing axis. |
|
|
112
|
-
| `bm.stack(arrays, axis=0)` | Join arrays along a new axis. |
|
|
113
|
-
| `bm.hstack(arrays)` | Stack according to NumPy's horizontal convention. |
|
|
114
|
-
| `bm.vstack(arrays)` | Stack according to NumPy's vertical convention. |
|
|
115
|
-
| `bm.dstack(arrays)` | Stack along a third axis. |
|
|
116
|
-
| `bm.column_stack(arrays)` | Stack one-dimensional arrays as columns. |
|
|
117
|
-
| `bm.block(arrays)` | Assemble an array from nested blocks. |
|
|
118
|
-
| `bm.split(a, indices_or_sections, axis=0)` | Split only when equal division or exact cut indices are known. |
|
|
119
|
-
| `bm.array_split(a, indices_or_sections, axis=0)` | Permit unequal sub-array lengths. |
|
|
120
|
-
| `bm.hsplit(a, indices_or_sections)` | Split using the horizontal convention. |
|
|
121
|
-
| `bm.vsplit(a, indices_or_sections)` | Split using the vertical convention. |
|
|
122
|
-
| `bm.dsplit(a, indices_or_sections)` | Split along the third axis. |
|
|
123
|
-
| `bm.broadcast_arrays(*args)` | Broadcast several arrays to one compatible shape. |
|
|
124
|
-
| `bm.broadcast_to(a, shape)` | Broadcast one array to an explicit shape. |
|
|
125
|
-
| `bm.repeat(a, repeats, axis=None)` | Repeat individual elements. |
|
|
126
|
-
| `bm.tile(a, reps)` | Repeat the whole array pattern. |
|
|
127
|
-
| `bm.take(a, indices, axis=None)` | Select values by integer indices. |
|
|
128
|
-
| `bm.choose(a, choices, ...)` | Select among arrays using an index array. |
|
|
129
|
-
| `bm.compress(condition, a, axis=None)` | Select entries along an axis using a boolean condition. |
|
|
130
|
-
| `bm.where(condition, x, y)` | Select elementwise between two values. |
|
|
131
|
-
| `bm.sort(a, axis=-1)` | Return values ordered along an axis. |
|
|
132
|
-
| `bm.argsort(a, axis=-1)` | Return indices that order values along an axis. |
|
|
133
|
-
| `bm.lexsort(keys, axis=-1)` | Return indices for an indirect stable sort over multiple keys. |
|
|
134
|
-
| `bm.flip(a, axis=None)` | Reverse element order along selected axes. |
|
|
135
|
-
| `bm.roll(a, shift, axis=None)` | Circularly shift elements. |
|
|
136
|
-
|
|
137
|
-
```python
|
|
138
|
-
a = bm.arange(6).reshape(2, 3)
|
|
139
|
-
b = bm.ones((2, 3))
|
|
140
|
-
|
|
141
|
-
rows = bm.concatenate([a, b], axis=0)
|
|
142
|
-
channels = bm.stack([a, b], axis=-1)
|
|
143
|
-
left, right = bm.split(a, [1], axis=1)
|
|
144
|
-
|
|
145
|
-
assert rows.shape == (4, 3)
|
|
146
|
-
assert channels.shape == (2, 3, 2)
|
|
147
|
-
assert left.shape == (2, 1) and right.shape == (2, 2)
|
|
148
|
-
```
|
|
149
|
-
|
|
150
|
-
## Reduce and contract arrays
|
|
151
|
-
|
|
152
|
-
Reduction axes determine which dimensions survive and must be chosen explicitly for batched or time-major model data.
|
|
153
|
-
|
|
154
|
-
| API | Description |
|
|
155
|
-
|---|---|
|
|
156
|
-
| `bm.sum(a, axis=None, ...)` | Sum values over selected axes. |
|
|
157
|
-
| `bm.mean(a, axis=None, ...)` | Compute the arithmetic mean over selected axes. |
|
|
158
|
-
| `bm.prod(a, axis=None, ...)` | Multiply values over selected axes. |
|
|
159
|
-
| `bm.min(a, axis=None, ...)` | Return minimum values. |
|
|
160
|
-
| `bm.max(a, axis=None, ...)` | Return maximum values. |
|
|
161
|
-
| `bm.std(a, axis=None, ...)` | Compute standard deviation. |
|
|
162
|
-
| `bm.var(a, axis=None, ...)` | Compute variance. |
|
|
163
|
-
| `bm.all(a, axis=None, ...)` | Require all boolean values along selected axes. |
|
|
164
|
-
| `bm.any(a, axis=None, ...)` | Require at least one true value along selected axes. |
|
|
165
|
-
| `bm.argmin(a, axis=None, ...)` | Return indices of minimum values. |
|
|
166
|
-
| `bm.argmax(a, axis=None, ...)` | Return indices of maximum values. |
|
|
167
|
-
| `bm.matmul(x1, x2, ...)` | Apply matrix multiplication with NumPy/JAX broadcasting rules. |
|
|
168
|
-
| `bm.dot(a, b, ...)` | Apply vector dot product or the documented higher-rank contraction. |
|
|
169
|
-
| `bm.tensordot(a, b, axes=2, ...)` | Contract explicitly selected axes. |
|
|
170
|
-
| `bm.einsum(subscripts, *operands, ...)` | Express a named index contraction. |
|
|
171
|
-
|
|
172
|
-
Use `axis=0` only after confirming that axis 0 is time or batch for the current workflow. Legacy trainers can accept different axis conventions through their own configuration.
|
|
173
|
-
|
|
174
|
-
## Use named-axis transformations
|
|
175
|
-
|
|
176
|
-
Use the `ein_*` functions when an axis pattern communicates the transformation more reliably than several positional reshape and transpose calls.
|
|
177
|
-
|
|
178
|
-
| API | Description |
|
|
179
|
-
|---|---|
|
|
180
|
-
| `bm.ein_rearrange(x, pattern, **axes_lengths)` | Reorder, compose, split, add, or remove axes without reduction. |
|
|
181
|
-
| `bm.ein_reduce(x, pattern, reduction, **axes_lengths)` | Rearrange and reduce with `sum`, `mean`, `max`, `min`, or another supported reduction. |
|
|
182
|
-
| `bm.ein_repeat(x, pattern, **axes_lengths)` | Rearrange while repeating or broadcasting elements. |
|
|
183
|
-
|
|
184
|
-
```python
|
|
185
|
-
x = bm.arange(2 * 3 * 4).astype(bm.float32).reshape(2, 3, 4)
|
|
186
|
-
|
|
187
|
-
flat = bm.ein_rearrange(x, 'b h w -> b (h w)')
|
|
188
|
-
pooled = bm.ein_reduce(x, 'b h w -> b', 'mean')
|
|
189
|
-
repeated = bm.ein_repeat(x, 'b h w -> b copies h w', copies=2)
|
|
190
|
-
|
|
191
|
-
assert flat.shape == (2, 12)
|
|
192
|
-
assert pooled.shape == (2,)
|
|
193
|
-
assert repeated.shape == (2, 2, 3, 4)
|
|
194
|
-
```
|
|
195
|
-
|
|
196
|
-
Axis order inside parentheses changes element order. A literal `1` or `()` represents a length-one axis and can be added or removed only where the pattern remains shape-compatible.
|
|
197
|
-
|
|
198
|
-
## Random-number behavior
|
|
199
|
-
|
|
200
|
-
`bm.random` manages a default `RandomState`, so ordinary calls do not require passing a JAX key. Seed the stream explicitly when results must be reproducible.
|
|
201
|
-
|
|
202
|
-
```python
|
|
203
|
-
bm.random.seed(123)
|
|
204
|
-
sample = bm.random.uniform(size=(2, 3))
|
|
205
|
-
normal = bm.random.normal(size=(2, 3))
|
|
206
|
-
```
|
|
207
|
-
|
|
208
|
-
Unlike direct `jax.random` calls, successive `bm.random` calls advance the stored key. Use an explicit `bm.random.RandomState(seed)` when independent reproducible streams are required.
|
|
209
|
-
|
|
210
|
-
## Common failures
|
|
211
|
-
|
|
212
|
-
- Do not pass a Python list of values directly to `bm.Variable` or `bm.as_variable` without checking whether it is interpreted as a shape; convert values with `bm.asarray` first.
|
|
213
|
-
- Do not mutate an ordinary JAX array with `x[index] = value`; retain the BrainPy `Array` wrapper or use JAX's functional update syntax.
|
|
214
|
-
- Do not convert to NumPy inside JIT-compiled model code.
|
|
215
|
-
- Do not use `bm.Array` where model state must be discovered and written back by an object-oriented transform; use `bm.Variable`.
|
|
216
|
-
- Do not reshape away the time or batch axis until the trainer or monitor convention has been verified.
|
|
217
|
-
|
|
218
|
-
## Sources mirrored
|
|
219
|
-
|
|
220
|
-
- https://brainpy.readthedocs.io/apis/brainpy.math.html
|
|
221
|
-
- https://brainpy.readthedocs.io/tutorial_math/Numpy_like_Operations.html
|
|
222
|
-
- https://brainpy.readthedocs.io/tutorial_math/einops_in_brainpy.html
|