brainx-skill 1.0.2 → 1.0.6
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/LICENSE +1 -1
- package/README.md +24 -56
- package/{lib → installation/lib}/installer.js +4 -4
- package/manifest.json +3 -1
- package/package.json +19 -9
- package/skills/brainstate/SKILL.md +399 -0
- package/skills/brainstate/agents/openai.yaml +4 -0
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +483 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +176 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +199 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +166 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +210 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +450 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +157 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +286 -0
- package/skills/brainstate/references/braintools-optimizer-reference.md +133 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +282 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +217 -0
- package/skills/brainstate/references/libraries/solver-library-with-effects.md +85 -0
- package/skills/brainstate/references/model-interop-and-migration.md +295 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +268 -0
- package/skills/brainstate/references/state-graph-operations.md +218 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +224 -0
- package/skills/brainstate/scripts/integrator_rnn.py +359 -0
- package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
- package/skills/brainstate/scripts/modern_cnn.py +73 -0
- package/skills/brainstate/scripts/resnet.py +130 -0
- package/skills/brainunit/SKILL.md +287 -0
- package/skills/brainunit/references/array-creation.md +158 -0
- package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
- package/skills/brainunit/references/array-mechanics.md +165 -0
- package/skills/brainunit/references/math-function-library.md +433 -0
- package/skills/brainunit/references/physical-constant-library.md +58 -0
- package/skills/brainunit/references/prefix-library.md +116 -0
- package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
- package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
- package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
- package/skills/brainx-install/SKILL.md +21 -13
- package/skills/brainx-install/references/compatibility-and-release-matching.md +12 -10
- package/skills/brainx-install/references/uninstall-and-cleanup.md +186 -0
- /package/{bin → installation/bin}/brainx.js +0 -0
- /package/{lib → installation/lib}/adapter-transaction.js +0 -0
- /package/{lib → installation/lib}/bundle.js +0 -0
- /package/{lib → installation/lib}/cli.js +0 -0
- /package/{lib → installation/lib}/constants.js +0 -0
- /package/{lib → installation/lib}/hash.js +0 -0
- /package/{lib → installation/lib}/paths.js +0 -0
- /package/{lib → installation/lib}/prompts.js +0 -0
- /package/{lib → installation/lib}/receipt.js +0 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# Braincell solver library with effects
|
|
2
|
+
|
|
3
|
+
## Purpose
|
|
4
|
+
|
|
5
|
+
Catalog BrainCell integration and solver choices with their expected modeling consequences.
|
|
6
|
+
|
|
7
|
+
## Source pages
|
|
8
|
+
|
|
9
|
+
* https://brainx.chaobrain.com/braincell/concepts/integration.html
|
|
10
|
+
* https://brainx.chaobrain.com/braincell/apis/integration.html
|
|
11
|
+
* https://brainx.chaobrain.com/braincell/examples/integration_methods.html
|
|
12
|
+
|
|
13
|
+
## Core model
|
|
14
|
+
|
|
15
|
+
* `DiffEqState` is a state variable that carries its derivative.
|
|
16
|
+
* `DiffEqModule` exposes a right-hand side over integrable states.
|
|
17
|
+
* Cells implement this protocol, so solvers can advance them without user code touching the protocol in ordinary modeling.
|
|
18
|
+
* `braincell.quad` holds a registry of solvers selectable by name.
|
|
19
|
+
* `get_integrator` resolves an integrator from a string or callable; `register_integrator` adds a function to the global registry; `all_integrators` exposes registered names.
|
|
20
|
+
|
|
21
|
+
## Solver families
|
|
22
|
+
|
|
23
|
+
| Family | Names / APIs | Use |
|
|
24
|
+
| --- | --- | --- |
|
|
25
|
+
| Exponential Euler | `exp_euler`, `ind_exp_euler`, `exp_exp_euler` | Good default family for HH-style gating; stable at practical point-neuron step sizes. |
|
|
26
|
+
| Explicit Runge-Kutta | `euler`, `midpoint`, `rk2`, `rk3`, `rk4`, `heun2`, `heun3`, `ssprk3`, `ralston2`, `ralston3`, `ralston4` | Useful for comparisons and non-stiff problems; may need tiny time steps for stiff HH dynamics. |
|
|
27
|
+
| Implicit | `backward_euler`, `implicit_euler`, `implicit_exp_euler`, `implicit_rk4` | Use when implicit stepping is required; inspect official API and examples first. |
|
|
28
|
+
| Composite / cable | `cn_exp_euler`, `cn_rk4`, `splitting`, `staggered`, `dhs_voltage` | Designed for multicompartment/cable coupling; delegate geometry tasks to `skills/braincell/SKILL.md`, which selects its multicompartment parent. |
|
|
29
|
+
|
|
30
|
+
List available names at runtime:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import braincell.quad as quad
|
|
34
|
+
|
|
35
|
+
sorted(quad.all_integrators)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Single-compartment defaults
|
|
39
|
+
|
|
40
|
+
* Use `exp_euler` for high-precision single-cell HH traces and electrophysiology-style examples.
|
|
41
|
+
* Use `ind_exp_euler` for large vectorized point-neuron or network simulations when speed matters.
|
|
42
|
+
* Use `rk4` when the user asks for classical Runge-Kutta comparison or explicitly requests it.
|
|
43
|
+
* Treat method-dependent waveform changes as numerical artifacts until proven otherwise.
|
|
44
|
+
|
|
45
|
+
## Solver effects from official hh comparison
|
|
46
|
+
|
|
47
|
+
The official integration-methods example compares `exp_euler` and `ind_exp_euler` on HH dynamics:
|
|
48
|
+
|
|
49
|
+
* `exp_euler` produces smoother curves and more accurately fits tightly coupled gating variables and membrane potential.
|
|
50
|
+
* `ind_exp_euler` updates state variables independently, can deviate slightly during rapid changes, and is faster for large-scale simulations.
|
|
51
|
+
* For high-precision single-cell simulations, prefer `exp_euler`.
|
|
52
|
+
* For large-scale network simulations with thousands of neurons, prefer `ind_exp_euler` when the approximation is acceptable.
|
|
53
|
+
|
|
54
|
+
## Usage pattern
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
class HH(braincell.SingleCompartment):
|
|
58
|
+
def __init__(self, size, solver="exp_euler"):
|
|
59
|
+
super().__init__(size, V_th=20. * u.mV, solver=solver)
|
|
60
|
+
self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)
|
|
61
|
+
self.na.add(INa=braincell.channel.Na_HH1952(size))
|
|
62
|
+
self.k = braincell.ion.PotassiumFixed(size, E=-77. * u.mV)
|
|
63
|
+
self.k.add(IK=braincell.channel.K_HH1952(size))
|
|
64
|
+
self.IL = braincell.channel.IL(size, E=-54.387 * u.mV, g_max=0.03 * (u.mS / u.cm ** 2))
|
|
65
|
+
|
|
66
|
+
hh_exp = HH(1, solver="exp_euler")
|
|
67
|
+
hh_ind = HH(1, solver="ind_exp_euler")
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Always keep `dt` explicit in a BrainState environment context:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
with brainstate.environ.context(dt=0.01 * u.ms):
|
|
74
|
+
times = u.math.arange(0. * u.ms, 100. * u.ms, brainstate.environ.get_dt())
|
|
75
|
+
vs, spikes = brainstate.transform.for_loop(step, times)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Common mistakes -> fix
|
|
79
|
+
|
|
80
|
+
* Choosing solver blindly -> name the solver and why it fits the task.
|
|
81
|
+
* Using too-large `dt` -> reduce `dt` before blaming model biology.
|
|
82
|
+
* Treating solver differences as biological findings -> compare methods and report as numerical effects.
|
|
83
|
+
* Using `rk4` as the default for stiff HH gating -> prefer exponential-Euler variants unless comparison requires RK.
|
|
84
|
+
* Using cable/composite solvers in a point-neuron task -> only use them when morphology/cable coupling exists.
|
|
85
|
+
* Forgetting units on `dt` -> use `0.01 * u.ms`, not `0.01`.
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
# Brainstate model interoperation and migration
|
|
2
|
+
|
|
3
|
+
Use this reference after the main BrainState skill when a task must move registered weighted layers between BrainState, Flax NNX, Flax Linen, or Equinox, or translate a PyTorch workflow into BrainState equivalents. It assumes the main skill's `State`, `Module`, parameter-collection, randomness, and state-aware transformation model; this file covers only interoperability and migration deltas.
|
|
4
|
+
|
|
5
|
+
## Interop contract and api surface
|
|
6
|
+
|
|
7
|
+
Source: https://brainx.chaobrain.com/brainstate/apis/interop.html
|
|
8
|
+
|
|
9
|
+
`brainstate.interop` converts standard-layer models between `brainstate.nn` and `flax.nnx`, `flax.linen`, or `equinox`. The public functions construct an architecturally equivalent target model and transfer weights. For supported single layers and `Sequential` stacks, conversion guarantees numerical output equivalence; unsupported layers or structures raise informative errors instead of producing a silently wrong model.
|
|
10
|
+
|
|
11
|
+
Direction is encoded in each function name:
|
|
12
|
+
|
|
13
|
+
| Function | Exact role |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `from_nnx(model, *, sample_input)` | Convert a `flax.nnx` model into an equivalent `brainstate.nn` model. |
|
|
16
|
+
| `to_nnx(model, *, rngs)` | Convert a `brainstate.nn` model into an equivalent `flax.nnx` model. |
|
|
17
|
+
| `from_linen(module, params, *, sample_input)` | Convert a `flax.linen` module and parameters into an equivalent `brainstate.nn` model. |
|
|
18
|
+
| `to_linen(model)` | Convert a `brainstate.nn` model into a Flax Linen `(module, params)` pair. |
|
|
19
|
+
| `from_equinox(model, *, sample_input)` | Convert an Equinox model into an equivalent `brainstate.nn` model. |
|
|
20
|
+
| `to_equinox(model, *, key)` | Convert a `brainstate.nn` model into an equivalent Equinox model. |
|
|
21
|
+
|
|
22
|
+
The layer-mapping registry drives conversion:
|
|
23
|
+
|
|
24
|
+
- `LayerMapping` describes a bidirectional conversion mapping for one layer type.
|
|
25
|
+
- `register_layer_mapping` registers or overrides a `LayerMapping` in both directions. Supply the to/from conversion functions to add a custom layer type; built-in mappings use the same mechanism.
|
|
26
|
+
- `supported_layers` lists the BrainState layer types with registered conversions.
|
|
27
|
+
|
|
28
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
|
|
29
|
+
|
|
30
|
+
Inspect support before selecting an interop path:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
layers = interop.supported_layers()
|
|
34
|
+
for framework, names in layers.items():
|
|
35
|
+
print(f'{framework:8} : {", ".join(names)}')
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The official example reports:
|
|
39
|
+
|
|
40
|
+
```text
|
|
41
|
+
nnx : BatchNorm1d, BatchNorm2d, BatchNorm3d, Conv1d, Conv2d, Conv3d, Dropout, Embedding, GroupNorm, LSTMCell, LayerNorm, Linear, RMSNorm
|
|
42
|
+
linen : BatchNorm1d, BatchNorm2d, BatchNorm3d, Conv1d, Conv2d, Conv3d, Dropout, Embedding, GroupNorm, LSTMCell, LayerNorm, Linear, RMSNorm
|
|
43
|
+
equinox : Conv1d, Conv2d, Conv3d, Dropout, Embedding, GroupNorm, LSTMCell, LayerNorm, Linear, RMSNorm
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
This support list is version-specific; call `supported_layers()` in the installed environment rather than assuming the rendered list is current.
|
|
47
|
+
|
|
48
|
+
### Convertible boundary
|
|
49
|
+
|
|
50
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
|
|
51
|
+
|
|
52
|
+
Conversion operates on registered, weight-bearing layers and `Sequential` stacks of them.
|
|
53
|
+
|
|
54
|
+
- Activation functions are not layers in this conversion model. A weightless nonlinearity such as ReLU stays in the caller's forward code; conversion rebuilds the weighted structure.
|
|
55
|
+
- Custom forward logic is not convertible. Branching, skip connections, or hand-written control flow cannot be mechanically rebuilt; only single registered layers and `Sequential` stacks round-trip.
|
|
56
|
+
|
|
57
|
+
Use this exact convertible shape for the examples below:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import jax
|
|
61
|
+
import jax.numpy as jnp
|
|
62
|
+
import flax.nnx as nnx
|
|
63
|
+
|
|
64
|
+
import brainstate
|
|
65
|
+
from brainstate import interop
|
|
66
|
+
|
|
67
|
+
brainstate.random.seed(0)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def make_model():
|
|
71
|
+
return brainstate.nn.Sequential(
|
|
72
|
+
brainstate.nn.Linear(4, 8),
|
|
73
|
+
brainstate.nn.LayerNorm(8),
|
|
74
|
+
brainstate.nn.Linear(8, 2),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
x = brainstate.random.randn(3, 4)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Conversion failures
|
|
82
|
+
|
|
83
|
+
Source: https://brainx.chaobrain.com/brainstate/apis/interop.html
|
|
84
|
+
|
|
85
|
+
Handle the documented error hierarchy rather than catching a generic failure without diagnosis:
|
|
86
|
+
|
|
87
|
+
| Error | Documented condition |
|
|
88
|
+
|---|---|
|
|
89
|
+
| `InteropError` | Base class for all `brainstate.interop` errors. |
|
|
90
|
+
| `MissingDependencyError` | The optional Flax or Equinox dependency is not installed. |
|
|
91
|
+
| `UnmappedLayerError` | No conversion mapping is registered for a leaf layer type. |
|
|
92
|
+
| `UnsupportedLayerError` | A known layer type is deliberately unsupported in this version. |
|
|
93
|
+
| `UnsupportedStructureError` | A container's forward logic cannot be reconstructed. |
|
|
94
|
+
| `MissingShapeError` | A spatial layer such as Conv or BatchNorm is imported without a sample input. |
|
|
95
|
+
| `ConversionError` | Weight transfer fails because of a shape, dtype, or unit mismatch. |
|
|
96
|
+
|
|
97
|
+
## Flax nnx round trip
|
|
98
|
+
|
|
99
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
|
|
100
|
+
|
|
101
|
+
`to_nnx` needs `nnx.Rngs` to construct foreign layers; their weights are then overwritten with converted values. `from_nnx` converts in the reverse direction. Bundle conversion with an output-equivalence check:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
model = make_model()
|
|
105
|
+
reference = model(x)
|
|
106
|
+
|
|
107
|
+
# BrainState -> NNX
|
|
108
|
+
nnx_model = interop.to_nnx(model, rngs=nnx.Rngs(0))
|
|
109
|
+
print('to_nnx output matches :', bool(jnp.allclose(reference, nnx_model(x), atol=1e-5)))
|
|
110
|
+
|
|
111
|
+
# NNX -> BrainState
|
|
112
|
+
back = interop.from_nnx(nnx_model)
|
|
113
|
+
print('from_nnx output matches:', bool(jnp.allclose(reference, back(x), atol=1e-5)))
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Expected result:
|
|
117
|
+
|
|
118
|
+
```text
|
|
119
|
+
to_nnx output matches : True
|
|
120
|
+
from_nnx output matches: True
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Flax linen round trip
|
|
124
|
+
|
|
125
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
|
|
126
|
+
|
|
127
|
+
Linen separates the module definition from parameters, so `to_linen` returns `(module, params)` and execution uses `module.apply(params, x)`. `from_linen` requires both objects:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
model = make_model()
|
|
131
|
+
reference = model(x)
|
|
132
|
+
|
|
133
|
+
# BrainState -> Linen
|
|
134
|
+
linen_module, params = interop.to_linen(model)
|
|
135
|
+
print('to_linen output matches :', bool(jnp.allclose(reference, linen_module.apply(params, x), atol=1e-5)))
|
|
136
|
+
|
|
137
|
+
# Linen -> BrainState
|
|
138
|
+
back = interop.from_linen(linen_module, params)
|
|
139
|
+
print('from_linen output matches:', bool(jnp.allclose(reference, back(x), atol=1e-5)))
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Expected result:
|
|
143
|
+
|
|
144
|
+
```text
|
|
145
|
+
to_linen output matches : True
|
|
146
|
+
from_linen output matches: True
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Equinox round trip
|
|
150
|
+
|
|
151
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
|
|
152
|
+
|
|
153
|
+
`to_equinox` accepts an optional PRNG `key` for constructing foreign layers. The exported Equinox module operates on one example, so batch its call with `jax.vmap`; `from_equinox` returns a batched BrainState model:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
model = make_model()
|
|
157
|
+
reference = model(x)
|
|
158
|
+
|
|
159
|
+
# BrainState -> Equinox (call per-example, so vmap over the batch)
|
|
160
|
+
eqx_model = interop.to_equinox(model, key=jax.random.PRNGKey(0))
|
|
161
|
+
eqx_out = jax.vmap(eqx_model)(x)
|
|
162
|
+
print('to_equinox output matches :', bool(jnp.allclose(reference, eqx_out, atol=1e-5)))
|
|
163
|
+
|
|
164
|
+
# Equinox -> BrainState
|
|
165
|
+
back = interop.from_equinox(eqx_model)
|
|
166
|
+
print('from_equinox output matches:', bool(jnp.allclose(reference, back(x), atol=1e-5)))
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Expected result:
|
|
170
|
+
|
|
171
|
+
```text
|
|
172
|
+
to_equinox output matches : True
|
|
173
|
+
from_equinox output matches: True
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## Import spatial layers with `sample_input`
|
|
177
|
+
|
|
178
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
|
|
179
|
+
|
|
180
|
+
Importing a convolution or spatial normalization requires its input shape because BrainState materializes the layer input size up front. Pass one unbatched example or its shape through `sample_input` to `from_nnx`, `from_linen`, or `from_equinox`:
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
conv = nnx.Conv(in_features=3, out_features=4, kernel_size=(3, 3), rngs=nnx.Rngs(0))
|
|
184
|
+
bst_conv = interop.from_nnx(conv, sample_input=(8, 8, 3)) # H, W, C (no batch dim)
|
|
185
|
+
image = brainstate.random.randn(2, 8, 8, 3)
|
|
186
|
+
print('converted conv output shape:', bst_conv(image).shape)
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Expected result:
|
|
190
|
+
|
|
191
|
+
```text
|
|
192
|
+
converted conv output shape: (2, 8, 8, 4)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Pytorch-to-brainstate migration deltas
|
|
196
|
+
|
|
197
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/migrate_from_pytorch.html
|
|
198
|
+
|
|
199
|
+
The official PyTorch route is a concept-by-concept, module-at-a-time port, not one of the `brainstate.interop` converters. Use the main BrainState skill for the underlying APIs and this mapping only to translate PyTorch responsibilities:
|
|
200
|
+
|
|
201
|
+
| PyTorch | BrainState migration target | Operational delta |
|
|
202
|
+
|---|---|---|
|
|
203
|
+
| `torch.Tensor` | `jax.Array` / `jnp.ndarray` | Use `jax.numpy` semantics. |
|
|
204
|
+
| `nn.Module` | `brainstate.nn.Module` | Replace the model container; define the relevant State attributes. |
|
|
205
|
+
| `nn.Parameter` | `brainstate.ParamState` | Retrieve trainable weights through `.states(brainstate.ParamState)`. |
|
|
206
|
+
| `autograd.grad` / `backward()` | `brainstate.transform.grad` | Explicitly select State or arguments that receive gradients. |
|
|
207
|
+
| `torch.optim` optimizers | `braintools.optim` (optional) | Register and update the selected State tree. |
|
|
208
|
+
| `torch.jit.script` / `torch.jit.trace` | `brainstate.transform.jit` | Use the BrainState transform for pure or stateful functions. |
|
|
209
|
+
| `state_dict()` / `load_state_dict()` | `brainstate.graph.treefy_states` / `brainstate.graph.update_states` | Serialize and restore State trees. |
|
|
210
|
+
| `torch.manual_seed` | `brainstate.random.seed` / `RandomState` | Use BrainState's JAX-key-backed random interface. |
|
|
211
|
+
|
|
212
|
+
### Port optimizer ownership
|
|
213
|
+
|
|
214
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/migrate_from_pytorch.html
|
|
215
|
+
|
|
216
|
+
PyTorch optimizers receive an implicit parameter list; `braintools.optim` operates on the explicitly selected State tree. The source's migration pattern is:
|
|
217
|
+
|
|
218
|
+
```python
|
|
219
|
+
import braintools.optim as optim
|
|
220
|
+
|
|
221
|
+
params = model.states(brainstate.ParamState)
|
|
222
|
+
optimizer = optim.SGD(lr=1e-1)
|
|
223
|
+
optimizer.register_trainable_weights(params)
|
|
224
|
+
|
|
225
|
+
# After brainstate.transform.grad returns grads for params:
|
|
226
|
+
optimizer.update(grads)
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
`params.to_flat()` mirrors the role of `state_dict()` when inspecting the parameter paths.
|
|
230
|
+
|
|
231
|
+
### Port `state_dict()` save and restore
|
|
232
|
+
|
|
233
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/migrate_from_pytorch.html
|
|
234
|
+
|
|
235
|
+
Bundle the `state_dict()` / `load_state_dict()` replacement as one round trip:
|
|
236
|
+
|
|
237
|
+
```python
|
|
238
|
+
state_tree = brainstate.graph.treefy_states(model)
|
|
239
|
+
print('stored keys:', list(state_tree.to_flat().keys()))
|
|
240
|
+
|
|
241
|
+
# Later (or in another process):
|
|
242
|
+
restored = LinearModel(1, 1)
|
|
243
|
+
brainstate.graph.update_states(restored, state_tree)
|
|
244
|
+
print('restored weight:', restored.weight.value)
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
For file-backed parameter persistence, the same source gives:
|
|
248
|
+
|
|
249
|
+
```python
|
|
250
|
+
import braintools.file
|
|
251
|
+
|
|
252
|
+
params = model.states(brainstate.ParamState)
|
|
253
|
+
braintools.file.msgpack_save('example.msgpack', params, verbose=False)
|
|
254
|
+
restored = braintools.file.msgpack_load('example.msgpack', target=params, verbose=False)
|
|
255
|
+
print('parameters saved and restored via msgpack')
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
The source assigns the return from `msgpack_load` to `restored`.
|
|
259
|
+
|
|
260
|
+
### Port gradients for model state plus an explicit argument
|
|
261
|
+
|
|
262
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/migrate_from_pytorch.html
|
|
263
|
+
|
|
264
|
+
PyTorch's manual `requires_grad` selection maps to explicit `grad_states` and `argnums`. This source example differentiates with respect to both the model parameter tree and `alpha`:
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
scale = jnp.array(0.1)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def scaled_loss(alpha, inputs, targets):
|
|
271
|
+
preds = model(inputs)
|
|
272
|
+
mse = jnp.mean((preds - targets) ** 2)
|
|
273
|
+
return mse + alpha * jnp.sum(model.weight.value ** 2)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
(grads_state, alpha_grad), loss_val = grad(
|
|
277
|
+
scaled_loss,
|
|
278
|
+
grad_states=params,
|
|
279
|
+
argnums=0,
|
|
280
|
+
return_value=True,
|
|
281
|
+
)(scale, x_train, y_train)
|
|
282
|
+
|
|
283
|
+
print('loss:', float(loss_val))
|
|
284
|
+
print('grad w.r.t alpha:', float(alpha_grad))
|
|
285
|
+
for path, g in grads_state.items():
|
|
286
|
+
print(path, g.shape)
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Here `argnums=0` selects the explicit `alpha` argument while `grad_states=params` selects the model State tree; do not replace one with the other during a port.
|
|
290
|
+
|
|
291
|
+
## Source pages
|
|
292
|
+
|
|
293
|
+
- `brainstate.interop` module: https://brainx.chaobrain.com/brainstate/apis/interop.html
|
|
294
|
+
- Interoperate with Flax and Equinox: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
|
|
295
|
+
- Migrating Concepts from PyTorch to BrainState: https://brainx.chaobrain.com/brainstate/how_to/migrate_from_pytorch.html
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# Simulation environment
|
|
2
|
+
|
|
3
|
+
Use this reference when a task needs more than the canonical `brainstate.environ.context(dt=..., fit=...)` rollout in `SKILL.md`: nested overrides, persistent defaults, isolated environments, precision or platform control, one-step exponential-Euler integration, or diagnosis of leaked and missing settings.
|
|
4
|
+
|
|
5
|
+
Sources:
|
|
6
|
+
|
|
7
|
+
- [Time and Environment](https://brainx.chaobrain.com/brainstate/concepts/time_and_environment.html)
|
|
8
|
+
- [`brainstate.environ` API](https://brainx.chaobrain.com/brainstate/apis/environ.html)
|
|
9
|
+
- [`brainstate.nn.exp_euler_step` API](https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.exp_euler_step.html)
|
|
10
|
+
|
|
11
|
+
## Treat the environment as run context
|
|
12
|
+
|
|
13
|
+
Put values that describe the run, rather than one Module, in `brainstate.environ`. The environment is a stack of settings:
|
|
14
|
+
|
|
15
|
+
- `set()` installs a persistent default that remains active until changed or reset.
|
|
16
|
+
- `context()` pushes temporary values and restores the previous values on exit, including exceptional exit.
|
|
17
|
+
- `get(key, default=...)` searches the active context before persistent settings; it returns the value or explicit default and otherwise raises `KeyError`.
|
|
18
|
+
- Typed accessors such as `get_dt()`, `get_precision()`, and `get_platform()` enforce the corresponding setting contract.
|
|
19
|
+
- A nested context inherits its outer context and overrides only the keys it supplies.
|
|
20
|
+
|
|
21
|
+
Do not treat `EnvironmentState` as model `State`. It stores thread-local environment configuration and does not belong in a Module graph or State collection.
|
|
22
|
+
|
|
23
|
+
Choose the narrowest lifetime:
|
|
24
|
+
|
|
25
|
+
| Need | Use |
|
|
26
|
+
|---|---|
|
|
27
|
+
| One simulation, training phase, evaluation phase, or step | `brainstate.environ.context(...)` |
|
|
28
|
+
| A persistent default in the selected environment | `brainstate.environ.set(...)` |
|
|
29
|
+
| The same context on every call to one Module | Use `brainstate.nn.EnvironContext(layer, **context)`; the wrapper executes the Module with the stored settings, merges optional call-specific settings, and returns the Module's result |
|
|
30
|
+
| Configuration isolated from the default environment | Create `brainstate.environ.EnvironmentState()` and pass it through every `env=` argument; operations then use its independent thread-local setting stack instead of the default environment |
|
|
31
|
+
|
|
32
|
+
Prefer `context()` for normal simulation and training. Use `set()` only when later code should intentionally inherit the setting.
|
|
33
|
+
|
|
34
|
+
## Advanced environment configuration
|
|
35
|
+
|
|
36
|
+
Construct a separate `EnvironmentState` only for an explicitly isolated configuration, and pass it consistently through the `env=` argument of `set()`, `context()`, and `get()` or `get_dt()`.
|
|
37
|
+
|
|
38
|
+
| Setting | Precise use |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `dt` | Numerical integration step; set before initialization or rollout and read with `brainstate.environ.get_dt()` |
|
|
41
|
+
| `t` | Current simulation time; set for each step and read with `brainstate.environ.get("t")` |
|
|
42
|
+
| `i` | Current integer step index; set for each step and read with `brainstate.environ.get("i")` |
|
|
43
|
+
| `fit` | Set `True` for training and `False` for evaluation; dropout and batch normalization observe it consistently |
|
|
44
|
+
| `precision` | Default numerical precision (`8`, `16`, `32`, `64`, or `"bf16"`); inspect with `brainstate.environ.get_precision()` |
|
|
45
|
+
| `platform` | Computing platform (`"cpu"`, `"gpu"`, or `"tpu"`); configure globally with `set()` or `set_platform()` |
|
|
46
|
+
| `host_device_count` | Number of host devices; configure globally before device-dependent work |
|
|
47
|
+
|
|
48
|
+
Keep `dt` unit-aware in physical simulations. A rate with units `[X] / [time]` multiplied by a unit-aware `dt` produces an increment with units `[X]`; a unit mismatch then fails instead of silently changing the model.
|
|
49
|
+
|
|
50
|
+
Do not set `platform` or `host_device_count` through `context()`. The API requires these process-level settings to be set globally.
|
|
51
|
+
|
|
52
|
+
## Nest training and evaluation scopes
|
|
53
|
+
|
|
54
|
+
Let an inner context override only the setting that changes:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
with brainstate.environ.context(dt=0.1 * u.ms, fit=True):
|
|
58
|
+
train_step()
|
|
59
|
+
|
|
60
|
+
with brainstate.environ.context(fit=False):
|
|
61
|
+
validation = evaluate()
|
|
62
|
+
|
|
63
|
+
train_step()
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The inner evaluation observes the outer `dt` and its own `fit=False`. On exit, `fit=True` is restored without mutating the persistent defaults.
|
|
67
|
+
|
|
68
|
+
An unset required key raises instead of supplying a guessed value. Set `dt` before calling code that uses `get_dt()`; use an explicit `default=` with `get()` only when that fallback is part of the intended behavior.
|
|
69
|
+
|
|
70
|
+
## Isolate a configuration
|
|
71
|
+
|
|
72
|
+
Use the isolated branch only when two configurations must not share defaults:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
isolated_env = brainstate.environ.EnvironmentState()
|
|
76
|
+
brainstate.environ.set(
|
|
77
|
+
dt=0.05 * u.ms,
|
|
78
|
+
precision=64,
|
|
79
|
+
env=isolated_env,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
with brainstate.environ.context(fit=False, env=isolated_env):
|
|
83
|
+
isolated_dt = brainstate.environ.get_dt(env=isolated_env)
|
|
84
|
+
isolated_fit = brainstate.environ.get("fit", env=isolated_env)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Omitting `env=isolated_env` from any operation silently switches that operation back to the default environment, so keep the argument consistent across the complete workflow.
|
|
88
|
+
|
|
89
|
+
## Advance one continuous-dynamics step
|
|
90
|
+
|
|
91
|
+
Use `brainstate.nn.exp_euler_step()` for one ODE or SDE step with the active environment `dt`; it returns the next state after integrating the diagonal linearized drift exponentially.
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
def decay(v, t, tau):
|
|
95
|
+
return -v / tau
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
v = jnp.ones(num_neurons) * u.mV
|
|
99
|
+
with brainstate.environ.context(dt=0.1 * u.ms):
|
|
100
|
+
v_next = brainstate.nn.exp_euler_step(
|
|
101
|
+
decay,
|
|
102
|
+
v,
|
|
103
|
+
0.0 * u.ms,
|
|
104
|
+
10.0 * u.ms,
|
|
105
|
+
)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Use a supported floating dtype. A state with units `[X]` requires drift units `[X] / [time]`; an SDE diffusion term requires `[X] / sqrt([time])`. Only the diagonal of the drift Jacobian is integrated exponentially, while off-diagonal coupling uses plain Euler, so do not use this step as an exact solver for strongly coupled systems.
|
|
109
|
+
|
|
110
|
+
## Common failures
|
|
111
|
+
|
|
112
|
+
- Use `context()` instead of `set()` when a setting must not leak beyond one run.
|
|
113
|
+
- Set `dt` before initialization when initialization depends on the integration step.
|
|
114
|
+
- Set `t` and `i` inside the per-step scope when model code reads current time or step index.
|
|
115
|
+
- Keep `fit` explicit around both training and evaluation.
|
|
116
|
+
- Do not mix reads from the default environment with writes to an isolated `EnvironmentState`.
|
|
117
|
+
- Do not assume `precision` changes every explicitly typed array; it governs BrainState's default dtype helpers.
|