brainx-skill 1.0.3 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -64
  3. package/adapters/gemini.js +7 -0
  4. package/adapters/opencode.js +7 -0
  5. package/adapters/windsurf.js +7 -0
  6. package/{lib → installation/lib}/installer.js +8 -5
  7. package/manifest.json +7 -1
  8. package/package.json +25 -10
  9. package/skills/braincell/SKILL.md +182 -0
  10. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  11. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
  12. package/skills/braincell/references/channel-library.md +170 -0
  13. package/skills/braincell/references/ion-library.md +154 -0
  14. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  15. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  16. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  17. package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
  18. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  19. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  20. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  21. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
  22. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  23. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  24. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  25. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  26. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  27. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  28. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  29. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  30. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  31. package/skills/brainevent/SKILL.md +268 -0
  32. package/skills/brainevent/references/connectivity-variants.md +312 -0
  33. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  34. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  35. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  36. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  37. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  38. package/skills/brainevent/references/sparse-formats.md +182 -0
  39. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  40. package/skills/brainpy-state/SKILL.md +232 -0
  41. package/skills/brainpy-state/references/array-creation.md +158 -0
  42. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  43. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  44. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  45. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  46. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  47. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  48. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  49. package/skills/brainpy-state/references/component-selection.md +273 -0
  50. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  51. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  52. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  53. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  54. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  55. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  56. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  57. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  58. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  59. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  60. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  61. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  62. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  63. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  64. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  65. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  66. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  67. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  68. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  69. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  70. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  71. package/skills/brainstate/SKILL.md +399 -0
  72. package/skills/brainstate/agents/openai.yaml +4 -0
  73. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
  75. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
  76. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  77. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
  78. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
  79. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
  80. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
  81. package/skills/brainstate/references/collective_model_operations.md +195 -0
  82. package/skills/brainstate/references/extension_mechanisms.md +293 -0
  83. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
  84. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
  85. package/skills/brainstate/references/model-interop-and-migration.md +305 -0
  86. package/skills/brainstate/references/simulation-environment.md +117 -0
  87. package/skills/brainstate/references/size-inference-variations.md +279 -0
  88. package/skills/brainstate/references/state-graph-operations.md +216 -0
  89. package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
  90. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  91. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  92. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  93. package/skills/brainstate/scripts/resnet.py +130 -0
  94. package/skills/brainunit/SKILL.md +287 -0
  95. package/skills/brainunit/references/array-creation.md +158 -0
  96. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  97. package/skills/brainunit/references/array-mechanics.md +165 -0
  98. package/skills/brainunit/references/math-function-library.md +433 -0
  99. package/skills/brainunit/references/physical-constant-library.md +58 -0
  100. package/skills/brainunit/references/prefix-library.md +116 -0
  101. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  102. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  103. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  104. package/skills/brainx-general-guard/SKILL.md +153 -0
  105. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
  106. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
  107. package/skills/brainx-install/SKILL.md +2 -2
  108. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  109. /package/{bin → installation/bin}/brainx.js +0 -0
  110. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  111. /package/{lib → installation/lib}/bundle.js +0 -0
  112. /package/{lib → installation/lib}/cli.js +0 -0
  113. /package/{lib → installation/lib}/constants.js +0 -0
  114. /package/{lib → installation/lib}/hash.js +0 -0
  115. /package/{lib → installation/lib}/paths.js +0 -0
  116. /package/{lib → installation/lib}/prompts.js +0 -0
  117. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,305 @@
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
+ ## Selection map
6
+
7
+ | Need | Use | Key constraint |
8
+ |---|---|---|
9
+ | Convert one supported layer or `Sequential` stack | `brainstate.interop.from_*` or `to_*` | Check `supported_layers()` in the installed version and verify numerical output equivalence. |
10
+ | Convert a spatial layer into BrainState | `from_nnx`, `from_linen`, or `from_equinox` with `sample_input` | The sample fixes shape and layout information needed for construction. |
11
+ | Add a conversion for a custom layer | `LayerMapping` and `register_layer_mapping` | Implement and test both conversion directions. |
12
+ | Port a PyTorch workflow | Translate parameters, gradient selection, optimizer ownership, and checkpoint paths separately | This is a semantic migration, not an automatic whole-model conversion. |
13
+ | Convert branching, skip connections, or arbitrary custom forward code | Rebuild and validate manually | The automatic boundary is registered layers and supported `Sequential` structure. |
14
+
15
+ ## Interop contract and api surface
16
+
17
+ Source: https://brainx.chaobrain.com/brainstate/apis/interop.html
18
+
19
+ `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.
20
+
21
+ Direction is encoded in each function name:
22
+
23
+ | Function | Exact role |
24
+ |---|---|
25
+ | `from_nnx(model, *, sample_input)` | Convert a `flax.nnx` model into an equivalent `brainstate.nn` model. |
26
+ | `to_nnx(model, *, rngs)` | Convert a `brainstate.nn` model into an equivalent `flax.nnx` model. |
27
+ | `from_linen(module, params, *, sample_input)` | Convert a `flax.linen` module and parameters into an equivalent `brainstate.nn` model. |
28
+ | `to_linen(model)` | Convert a `brainstate.nn` model into a Flax Linen `(module, params)` pair. |
29
+ | `from_equinox(model, *, sample_input)` | Convert an Equinox model into an equivalent `brainstate.nn` model. |
30
+ | `to_equinox(model, *, key)` | Convert a `brainstate.nn` model into an equivalent Equinox model. |
31
+
32
+ The layer-mapping registry drives conversion:
33
+
34
+ - `LayerMapping` describes a bidirectional conversion mapping for one layer type.
35
+ - `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.
36
+ - `supported_layers` lists the BrainState layer types with registered conversions.
37
+
38
+ Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
39
+
40
+ Inspect support before selecting an interop path:
41
+
42
+ ```python
43
+ layers = interop.supported_layers()
44
+ for framework, names in layers.items():
45
+ print(f'{framework:8} : {", ".join(names)}')
46
+ ```
47
+
48
+ The official example reports:
49
+
50
+ ```text
51
+ nnx : BatchNorm1d, BatchNorm2d, BatchNorm3d, Conv1d, Conv2d, Conv3d, Dropout, Embedding, GroupNorm, LSTMCell, LayerNorm, Linear, RMSNorm
52
+ linen : BatchNorm1d, BatchNorm2d, BatchNorm3d, Conv1d, Conv2d, Conv3d, Dropout, Embedding, GroupNorm, LSTMCell, LayerNorm, Linear, RMSNorm
53
+ equinox : Conv1d, Conv2d, Conv3d, Dropout, Embedding, GroupNorm, LSTMCell, LayerNorm, Linear, RMSNorm
54
+ ```
55
+
56
+ This support list is version-specific; call `supported_layers()` in the installed environment rather than assuming the rendered list is current.
57
+
58
+ ### Convertible boundary
59
+
60
+ Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
61
+
62
+ Conversion operates on registered, weight-bearing layers and `Sequential` stacks of them.
63
+
64
+ - 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.
65
+ - 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.
66
+
67
+ Use this exact convertible shape for the examples below:
68
+
69
+ ```python
70
+ import jax
71
+ import jax.numpy as jnp
72
+ import flax.nnx as nnx
73
+
74
+ import brainstate
75
+ from brainstate import interop
76
+
77
+ brainstate.random.seed(0)
78
+
79
+
80
+ def make_model():
81
+ return brainstate.nn.Sequential(
82
+ brainstate.nn.Linear(4, 8),
83
+ brainstate.nn.LayerNorm(8),
84
+ brainstate.nn.Linear(8, 2),
85
+ )
86
+
87
+
88
+ x = brainstate.random.randn(3, 4)
89
+ ```
90
+
91
+ ### Conversion failures
92
+
93
+ Source: https://brainx.chaobrain.com/brainstate/apis/interop.html
94
+
95
+ Handle the documented error hierarchy rather than catching a generic failure without diagnosis:
96
+
97
+ | Error | Documented condition |
98
+ |---|---|
99
+ | `InteropError` | Base class for all `brainstate.interop` errors. |
100
+ | `MissingDependencyError` | The optional Flax or Equinox dependency is not installed. |
101
+ | `UnmappedLayerError` | No conversion mapping is registered for a leaf layer type. |
102
+ | `UnsupportedLayerError` | A known layer type is deliberately unsupported in this version. |
103
+ | `UnsupportedStructureError` | A container's forward logic cannot be reconstructed. |
104
+ | `MissingShapeError` | A spatial layer such as Conv or BatchNorm is imported without a sample input. |
105
+ | `ConversionError` | Weight transfer fails because of a shape, dtype, or unit mismatch. |
106
+
107
+ ## Flax nnx round trip
108
+
109
+ Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
110
+
111
+ `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:
112
+
113
+ ```python
114
+ model = make_model()
115
+ reference = model(x)
116
+
117
+ # BrainState -> NNX
118
+ nnx_model = interop.to_nnx(model, rngs=nnx.Rngs(0))
119
+ print('to_nnx output matches :', bool(jnp.allclose(reference, nnx_model(x), atol=1e-5)))
120
+
121
+ # NNX -> BrainState
122
+ back = interop.from_nnx(nnx_model)
123
+ print('from_nnx output matches:', bool(jnp.allclose(reference, back(x), atol=1e-5)))
124
+ ```
125
+
126
+ Expected result:
127
+
128
+ ```text
129
+ to_nnx output matches : True
130
+ from_nnx output matches: True
131
+ ```
132
+
133
+ ## Flax linen round trip
134
+
135
+ Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
136
+
137
+ 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:
138
+
139
+ ```python
140
+ model = make_model()
141
+ reference = model(x)
142
+
143
+ # BrainState -> Linen
144
+ linen_module, params = interop.to_linen(model)
145
+ print('to_linen output matches :', bool(jnp.allclose(reference, linen_module.apply(params, x), atol=1e-5)))
146
+
147
+ # Linen -> BrainState
148
+ back = interop.from_linen(linen_module, params)
149
+ print('from_linen output matches:', bool(jnp.allclose(reference, back(x), atol=1e-5)))
150
+ ```
151
+
152
+ Expected result:
153
+
154
+ ```text
155
+ to_linen output matches : True
156
+ from_linen output matches: True
157
+ ```
158
+
159
+ ## Equinox round trip
160
+
161
+ Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
162
+
163
+ `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:
164
+
165
+ ```python
166
+ model = make_model()
167
+ reference = model(x)
168
+
169
+ # BrainState -> Equinox (call per-example, so vmap over the batch)
170
+ eqx_model = interop.to_equinox(model, key=jax.random.PRNGKey(0))
171
+ eqx_out = jax.vmap(eqx_model)(x)
172
+ print('to_equinox output matches :', bool(jnp.allclose(reference, eqx_out, atol=1e-5)))
173
+
174
+ # Equinox -> BrainState
175
+ back = interop.from_equinox(eqx_model)
176
+ print('from_equinox output matches:', bool(jnp.allclose(reference, back(x), atol=1e-5)))
177
+ ```
178
+
179
+ Expected result:
180
+
181
+ ```text
182
+ to_equinox output matches : True
183
+ from_equinox output matches: True
184
+ ```
185
+
186
+ ## Import spatial layers with `sample_input`
187
+
188
+ Source: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
189
+
190
+ 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`:
191
+
192
+ ```python
193
+ conv = nnx.Conv(in_features=3, out_features=4, kernel_size=(3, 3), rngs=nnx.Rngs(0))
194
+ bst_conv = interop.from_nnx(conv, sample_input=(8, 8, 3)) # H, W, C (no batch dim)
195
+ image = brainstate.random.randn(2, 8, 8, 3)
196
+ print('converted conv output shape:', bst_conv(image).shape)
197
+ ```
198
+
199
+ Expected result:
200
+
201
+ ```text
202
+ converted conv output shape: (2, 8, 8, 4)
203
+ ```
204
+
205
+ ## Pytorch-to-brainstate migration deltas
206
+
207
+ Source: https://brainx.chaobrain.com/brainstate/how_to/migrate_from_pytorch.html
208
+
209
+ 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:
210
+
211
+ | PyTorch | BrainState migration target | Operational delta |
212
+ |---|---|---|
213
+ | `torch.Tensor` | `jax.Array` / `jnp.ndarray` | Use `jax.numpy` semantics. |
214
+ | `nn.Module` | `brainstate.nn.Module` | Replace the model container; define the relevant State attributes. |
215
+ | `nn.Parameter` | `brainstate.ParamState` | Retrieve trainable weights through `.states(brainstate.ParamState)`. |
216
+ | `autograd.grad` / `backward()` | `brainstate.transform.grad` | Explicitly select State or arguments that receive gradients. |
217
+ | `torch.optim` optimizers | `braintools.optim` (optional) | Register and update the selected State tree. |
218
+ | `torch.jit.script` / `torch.jit.trace` | `brainstate.transform.jit` | Use the BrainState transform for pure or stateful functions. |
219
+ | `state_dict()` / `load_state_dict()` | `brainstate.graph.treefy_states` / `brainstate.graph.update_states` | Serialize and restore State trees. |
220
+ | `torch.manual_seed` | `brainstate.random.seed` / `RandomState` | Use BrainState's JAX-key-backed random interface. |
221
+
222
+ ### Port optimizer ownership
223
+
224
+ Source: https://brainx.chaobrain.com/brainstate/how_to/migrate_from_pytorch.html
225
+
226
+ PyTorch optimizers receive an implicit parameter list; `braintools.optim` operates on the explicitly selected State tree. The source's migration pattern is:
227
+
228
+ ```python
229
+ import braintools.optim as optim
230
+
231
+ params = model.states(brainstate.ParamState)
232
+ optimizer = optim.SGD(lr=1e-1)
233
+ optimizer.register_trainable_weights(params)
234
+
235
+ # After brainstate.transform.grad returns grads for params:
236
+ optimizer.update(grads)
237
+ ```
238
+
239
+ `params.to_flat()` mirrors the role of `state_dict()` when inspecting the parameter paths.
240
+
241
+ ### Port `state_dict()` save and restore
242
+
243
+ Source: https://brainx.chaobrain.com/brainstate/how_to/migrate_from_pytorch.html
244
+
245
+ Bundle the `state_dict()` / `load_state_dict()` replacement as one round trip:
246
+
247
+ ```python
248
+ state_tree = brainstate.graph.treefy_states(model)
249
+ print('stored keys:', list(state_tree.to_flat().keys()))
250
+
251
+ # Later (or in another process):
252
+ restored = LinearModel(1, 1)
253
+ brainstate.graph.update_states(restored, state_tree)
254
+ print('restored weight:', restored.weight.value)
255
+ ```
256
+
257
+ For file-backed parameter persistence, the same source gives:
258
+
259
+ ```python
260
+ import braintools.file
261
+
262
+ params = model.states(brainstate.ParamState)
263
+ braintools.file.msgpack_save('example.msgpack', params, verbose=False)
264
+ restored = braintools.file.msgpack_load('example.msgpack', target=params, verbose=False)
265
+ print('parameters saved and restored via msgpack')
266
+ ```
267
+
268
+ The source assigns the return from `msgpack_load` to `restored`.
269
+
270
+ ### Port gradients for model state plus an explicit argument
271
+
272
+ Source: https://brainx.chaobrain.com/brainstate/how_to/migrate_from_pytorch.html
273
+
274
+ 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`:
275
+
276
+ ```python
277
+ scale = jnp.array(0.1)
278
+
279
+
280
+ def scaled_loss(alpha, inputs, targets):
281
+ preds = model(inputs)
282
+ mse = jnp.mean((preds - targets) ** 2)
283
+ return mse + alpha * jnp.sum(model.weight.value ** 2)
284
+
285
+
286
+ (grads_state, alpha_grad), loss_val = grad(
287
+ scaled_loss,
288
+ grad_states=params,
289
+ argnums=0,
290
+ return_value=True,
291
+ )(scale, x_train, y_train)
292
+
293
+ print('loss:', float(loss_val))
294
+ print('grad w.r.t alpha:', float(alpha_grad))
295
+ for path, g in grads_state.items():
296
+ print(path, g.shape)
297
+ ```
298
+
299
+ 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.
300
+
301
+ ## Source pages
302
+
303
+ - `brainstate.interop` module: https://brainx.chaobrain.com/brainstate/apis/interop.html
304
+ - Interoperate with Flax and Equinox: https://brainx.chaobrain.com/brainstate/how_to/interoperate_with_flax_equinox.html
305
+ - 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.