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.
- package/LICENSE +1 -1
- package/README.md +29 -64
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/{lib → installation/lib}/installer.js +8 -5
- package/manifest.json +7 -1
- package/package.json +25 -10
- package/skills/braincell/SKILL.md +182 -0
- package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
- package/skills/braincell/references/channel-library.md +170 -0
- package/skills/braincell/references/ion-library.md +154 -0
- package/skills/braincell/references/mixions-for-adaptation.md +81 -0
- package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
- package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
- package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
- package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
- package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
- package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
- package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
- package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
- package/skills/braincell/references/scripts/channel_ablation.py +61 -0
- package/skills/braincell/references/scripts/fi_curve.py +68 -0
- package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
- package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
- package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
- package/skills/braincell/references/solver-library-with-effects.md +188 -0
- package/skills/brainevent/SKILL.md +268 -0
- package/skills/brainevent/references/connectivity-variants.md +312 -0
- package/skills/brainevent/references/custom-operators-cpu.md +304 -0
- package/skills/brainevent/references/custom-operators-gpu.md +468 -0
- package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
- package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
- package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
- package/skills/brainevent/references/sparse-formats.md +182 -0
- package/skills/brainevent/references/synaptic-plasticity.md +285 -0
- package/skills/brainpy-state/SKILL.md +232 -0
- package/skills/brainpy-state/references/array-creation.md +158 -0
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
- package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
- package/skills/brainpy-state/references/braintools/metric.md +152 -0
- package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
- package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
- package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
- package/skills/brainpy-state/references/component-selection.md +273 -0
- package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
- package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
- package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
- package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
- package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
- package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
- package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
- package/skills/brainpy-state/references/projection-patterns.md +125 -0
- package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
- package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
- package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
- package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
- package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
- package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
- 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 +334 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +293 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
- package/skills/brainstate/references/model-interop-and-migration.md +305 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +279 -0
- package/skills/brainstate/references/state-graph-operations.md +216 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +235 -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-general-guard/SKILL.md +153 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
- package/skills/brainx-install/SKILL.md +2 -2
- package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
- /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,399 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: brainstate
|
|
3
|
+
description: BrainState is the central stateful execution infrastructure for BrainX modeling and simulation. Use this skill for mutable State and `.value`, ParamState and other State roles, Module graphs, environment-scoped simulations, state initialization, operational randomness, size-aware neural-network composition, state-aware jit/grad/vmap, or a BrainState training step.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Brainstate
|
|
7
|
+
|
|
8
|
+
## Purpose and boundary
|
|
9
|
+
|
|
10
|
+
Use this skill for BrainState's general stateful workflow: mutable `State`, registered `brainstate.nn.Module` graphs, environment-scoped simulation, state initialization and collection, randomness, state-aware transforms, and simulation or training.
|
|
11
|
+
|
|
12
|
+
Canonical path:
|
|
13
|
+
|
|
14
|
+
`classify State roles -> construct Modules -> register State and children -> initialize -> set the run environment -> transform the whole operation -> validate State and outputs`
|
|
15
|
+
|
|
16
|
+
Open the routed reference for specialized variants; route specialized neuronal or network dynamics to the matching BrainCell or BrainPy-State skill.
|
|
17
|
+
|
|
18
|
+
## Underlying principle of BrainState
|
|
19
|
+
|
|
20
|
+
BrainState reconciles mutable models with JAX by making mutation explicit: store every value that changes during transformed execution in `State`. Its State roles match distinct model lifecycles; for example, `HiddenState` holds voltages, firing rates, and other dynamics updated each simulation step.
|
|
21
|
+
|
|
22
|
+
Wrap the complete stateful operation in `brainstate.transform`. Unlike raw JAX transforms, its JAX-like `jit`, `grad`, and `vmap` discover State reads and writes, differentiate selected State collections, and map or share State during vectorization.
|
|
23
|
+
|
|
24
|
+
### API structure
|
|
25
|
+
|
|
26
|
+
Choose the namespace that owns the operation:
|
|
27
|
+
|
|
28
|
+
| API | Use |
|
|
29
|
+
|---|---|
|
|
30
|
+
| `brainstate` | Store values that mutate during transformed execution in `State`, and mark their lifecycle with semantic State subclasses. |
|
|
31
|
+
| `brainstate.graph` | Inspect, split, merge, or reconstruct Module and State graphs while preserving shared references and cycles. |
|
|
32
|
+
| `brainstate.nn` | Build registered `Module` graphs from parameters, layers, dynamics, delays, and metrics. |
|
|
33
|
+
| `brainstate.transform` | Apply State-aware JIT, differentiation, vectorization, parallelization, or control flow to a complete stateful operation. |
|
|
34
|
+
| `brainstate.interop` | Convert supported standard-layer models between `brainstate.nn`, Flax NNX, Flax Linen, and Equinox. |
|
|
35
|
+
| `brainstate.random` | Seed and sample reproducibly through stateful JAX keys with automatic splitting. |
|
|
36
|
+
| `brainstate.util` | Organize supporting mappings, filters, representations, dataclasses, and caches that do not require model-graph identity; use `graph` for Module or State structure. |
|
|
37
|
+
| `brainstate.typing` | Annotate arrays, shapes, dtypes, keys, filters, and PyTrees with JAX-, NumPy-, and BrainUnit-compatible types. |
|
|
38
|
+
| `brainstate.mixin` | Add reusable behavioral contracts, computation modes, or deferred `.desc()` construction to components. |
|
|
39
|
+
| `brainstate.environ` | Share run settings such as time, fitting mode, precision, and platform without storing them in model State or threading them through Module signatures. |
|
|
40
|
+
|
|
41
|
+
### 1. State is the mutation boundary
|
|
42
|
+
|
|
43
|
+
`State` is a typed, mutable container for an array or stable PyTree; read and replace it through `.value`, including inside BrainState transformations. Treat it as a fixed-structure slot: keep static configuration in ordinary attributes and preserve value type, shape, dtype, and PyTree structure across writes.
|
|
44
|
+
|
|
45
|
+
#### Create scalar, array, and pytree state
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import brainstate
|
|
49
|
+
import brainstate.nn as nn
|
|
50
|
+
import brainunit as u
|
|
51
|
+
import jax.numpy as jnp
|
|
52
|
+
|
|
53
|
+
counter = brainstate.State(jnp.array(0))
|
|
54
|
+
vector = brainstate.State(jnp.zeros(10))
|
|
55
|
+
neuron = brainstate.State({
|
|
56
|
+
"V": jnp.zeros(5),
|
|
57
|
+
"u": jnp.ones(5),
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
value = neuron.value
|
|
61
|
+
neuron.value = {
|
|
62
|
+
"V": value["V"] + 0.1,
|
|
63
|
+
"u": value["u"],
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
with brainstate.check_state_value_tree():
|
|
67
|
+
neuron.value = {
|
|
68
|
+
"V": jnp.zeros(5),
|
|
69
|
+
"u": jnp.ones(5),
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
#### Substate
|
|
75
|
+
|
|
76
|
+
State subclasses remain State containers but act as semantic markers for filtering and model organization. Use these non-parameter roles for hidden or runtime values:
|
|
77
|
+
|
|
78
|
+
| Role | Use |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `HiddenState` | Internal activations or dynamical state retained between updates |
|
|
81
|
+
| `ShortTermState` | Transient runtime values such as current input or last spike time |
|
|
82
|
+
| `LongTermState` | Persistent non-parameter values such as running statistics |
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
h = brainstate.HiddenState(jnp.zeros(5))
|
|
86
|
+
last_spike = brainstate.ShortTermState(jnp.full(5, -1e7))
|
|
87
|
+
running_mean = brainstate.LongTermState(jnp.zeros(5))
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 2. Modules form registered state graphs
|
|
91
|
+
|
|
92
|
+
Subclass `brainstate.nn.Module`, assign each `State` and child `Module` to an attribute, and implement computation in `update()`; assignment registers a traversable graph whose State leaves can be filtered by role:
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
params = model.states(brainstate.ParamState)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
#### Add state to a module
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
class Counter(brainstate.nn.Module):
|
|
102
|
+
def __init__(self):
|
|
103
|
+
super().__init__()
|
|
104
|
+
self.count = brainstate.ShortTermState(jnp.array(0))
|
|
105
|
+
|
|
106
|
+
def update(self, x):
|
|
107
|
+
self.count.value = self.count.value + 1
|
|
108
|
+
return x * self.count.value
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
counter_module = Counter()
|
|
112
|
+
for _ in range(5):
|
|
113
|
+
print(counter_module(jnp.array(10.0)), counter_module.count.value)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
The output advances through `(10, 1)`, `(20, 2)`, ..., `(50, 5)` because the registered State is updated explicitly.
|
|
117
|
+
|
|
118
|
+
#### Use basic prebuilt layers
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
brainstate.random.seed(42)
|
|
122
|
+
|
|
123
|
+
linear = nn.Linear(in_size=(10,), out_size=(5,))
|
|
124
|
+
relu = nn.ReLU()
|
|
125
|
+
conv = nn.Conv2d(
|
|
126
|
+
in_size=(28, 28, 3),
|
|
127
|
+
out_channels=32,
|
|
128
|
+
kernel_size=3,
|
|
129
|
+
padding="SAME",
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
x = brainstate.random.randn(8, 10)
|
|
133
|
+
y = relu(linear(x))
|
|
134
|
+
assert y.shape == (8, 5)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Open the layer and activation catalogs instead of guessing an uncommon class name or signature.
|
|
138
|
+
|
|
139
|
+
#### Parameter
|
|
140
|
+
|
|
141
|
+
`nn.Param` wraps an underlying `ParamState` with an optional constraint transform and regularizer; model code reads `.value()`, while optimizers update `.val`.
|
|
142
|
+
|
|
143
|
+
| Role | Use |
|
|
144
|
+
|---|---|
|
|
145
|
+
| `ParamState` | Trainable weights, biases, or other unconstrained values that need no parameter transform or regularizer |
|
|
146
|
+
| `nn.Param` | A trainable parameter that needs the richer transform or regularization contract |
|
|
147
|
+
| `nn.Const` | A fixed forward value kept in the Module graph but excluded from `ParamState` collection, gradients, and optimizer updates |
|
|
148
|
+
|
|
149
|
+
Use `nn.SoftplusT(lower=L)` for a value constrained to `(L, infinity)`; `.value()` stays in range while `.val` remains unconstrained. Do not confuse parameter transforms with execution transforms such as `brainstate.transform.jit`.
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
w = brainstate.ParamState(brainstate.random.randn(10, 5) * 0.1)
|
|
153
|
+
b = brainstate.ParamState(jnp.zeros(5))
|
|
154
|
+
|
|
155
|
+
gain = nn.Param(jnp.array(1.0))
|
|
156
|
+
positive_tau = nn.Param(jnp.array(2.0), t=nn.SoftplusT(lower=0.1))
|
|
157
|
+
fixed_scale = nn.Const(jnp.array(10.0))
|
|
158
|
+
|
|
159
|
+
print(gain.value()) # IdentityT by default; usable and stored values coincide
|
|
160
|
+
print(positive_tau.value()) # constrained model value, always greater than 0.1
|
|
161
|
+
print(positive_tau.val) # underlying unconstrained ParamState
|
|
162
|
+
print(fixed_scale.value()) # fixed value, excluded from ParamState collection
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### 3. Size inference drives composition
|
|
166
|
+
|
|
167
|
+
Size-aware Modules carry feature-shape metadata without the batch dimension, so composition code can construct and validate each next layer before execution.
|
|
168
|
+
|
|
169
|
+
| API | Description |
|
|
170
|
+
|---|---|
|
|
171
|
+
| `Module.in_size` | Set the expected per-sample feature shape on the first or a standalone layer when it is known; the layer uses it to initialize shape-dependent values, validate inputs, and infer `out_size`, returning a size tuple or `None`. |
|
|
172
|
+
| `Module.out_size` | Read the inferred per-sample output shape after construction when wiring the next layer; it returns a size tuple or `None` and avoids duplicating shape calculations. |
|
|
173
|
+
| `nn.Sequential(first, *layers)` | Use for an ordered input-output pipeline; it feeds each runtime output to the next layer, propagates size metadata through the chain, and exposes the first `in_size` and final `out_size`. |
|
|
174
|
+
| `Layer.desc(**kwargs)` | Use after the first layer when the next layer's `in_size` should come from the preceding `out_size`; it stores the other constructor arguments, and `Sequential` replaces the descriptor with a concrete layer initialized with that inferred size. |
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
model = nn.Sequential(
|
|
178
|
+
nn.Linear(in_size=(10,), out_size=(8,)),
|
|
179
|
+
nn.ReLU(),
|
|
180
|
+
nn.Linear.desc(out_size=(2,)),
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
x = brainstate.random.randn(4, 10)
|
|
184
|
+
y = model(x)
|
|
185
|
+
|
|
186
|
+
assert model.layers[2].in_size == (8,)
|
|
187
|
+
assert model.out_size == (2,)
|
|
188
|
+
assert y.shape == (4, 2)
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Open `references/size-inference-variations.md` to compose `ComplexNet` with `Sequential` and `.desc()`, or when convolution, pooling, and flattening make size propagation non-obvious.
|
|
192
|
+
|
|
193
|
+
### 4. Environment context drives simulations
|
|
194
|
+
|
|
195
|
+
Use `brainstate.environ` to share run settings across a computation, where scoped contexts override persistent defaults and model code reads the active value.
|
|
196
|
+
|
|
197
|
+
| API | Description |
|
|
198
|
+
|---|---|
|
|
199
|
+
| `brainstate.environ.context(**settings)` | Use for one simulation, training phase, evaluation phase, or step; it pushes temporary settings, inherits unspecified outer values, and restores the previous values on exit, including exceptional exit. |
|
|
200
|
+
| `brainstate.environ.get_dt()` | Use inside numerical dynamics that require the active integration step; it returns `dt` from the selected environment and raises `KeyError` when `dt` is unset. |
|
|
201
|
+
| `brainstate.nn.init_all_states(target, **kwargs)` | Use after constructing a stateful Module and before its first rollout; it calls `init_state()` across the graph in `@call_order` order and returns the initialized target. |
|
|
202
|
+
| `brainstate.transform.for_loop(step, *xs)` | Use for a State-aware time loop; it slices each input along its leading axis and returns the stacked per-step outputs. |
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
with brainstate.environ.context(dt=0.1 * u.ms, fit=False):
|
|
206
|
+
brainstate.nn.init_all_states(net)
|
|
207
|
+
times = u.math.arange(
|
|
208
|
+
0.0 * u.ms,
|
|
209
|
+
100.0 * u.ms,
|
|
210
|
+
brainstate.environ.get_dt(),
|
|
211
|
+
)
|
|
212
|
+
step_indices = jnp.arange(times.shape[0])
|
|
213
|
+
|
|
214
|
+
def step(t, i):
|
|
215
|
+
with brainstate.environ.context(t=t, i=i):
|
|
216
|
+
return net.update(input_current)
|
|
217
|
+
|
|
218
|
+
outputs = brainstate.transform.for_loop(
|
|
219
|
+
step,
|
|
220
|
+
times,
|
|
221
|
+
step_indices,
|
|
222
|
+
)
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Open `references/simulation-environment.md` for persistent defaults, generic setting access, nested or isolated environments, precision and platform controls, `exp_euler_step()`, and environment-specific failures.
|
|
226
|
+
|
|
227
|
+
### 5. State-aware transforms
|
|
228
|
+
|
|
229
|
+
Wrap the complete forward, simulation, or training step in `brainstate.transform`; its JAX-like `jit`, `grad`, and `vmap` track State reads and writes, while raw JAX transforms can lose State mutations.
|
|
230
|
+
|
|
231
|
+
#### Canonical transformation setup
|
|
232
|
+
|
|
233
|
+
```python
|
|
234
|
+
brainstate.random.seed(0)
|
|
235
|
+
model = nn.Linear(in_size=(3,), out_size=(1,))
|
|
236
|
+
x_train = brainstate.random.randn(64, 3)
|
|
237
|
+
y_train = brainstate.random.randn(64, 1)
|
|
238
|
+
params = model.states(brainstate.ParamState)
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
#### State-aware jit example
|
|
242
|
+
|
|
243
|
+
```python
|
|
244
|
+
forward = brainstate.transform.jit(model)
|
|
245
|
+
prediction = forward(x_train)
|
|
246
|
+
assert prediction.shape == (64, 1)
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
The first compatible call traces and compiles the complete forward pass; later compatible calls reuse it while BrainState handles State effects.
|
|
250
|
+
|
|
251
|
+
#### Gradient and parameter update example
|
|
252
|
+
|
|
253
|
+
`grad` differentiates with respect to a State collection and returns gradients keyed by the same State paths. `return_value=True` returns the loss from the same pass.
|
|
254
|
+
|
|
255
|
+
```python
|
|
256
|
+
def loss_fn():
|
|
257
|
+
return jnp.mean((model(x_train) - y_train) ** 2)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
grads, loss = brainstate.transform.grad(
|
|
261
|
+
loss_fn,
|
|
262
|
+
params,
|
|
263
|
+
return_value=True,
|
|
264
|
+
)()
|
|
265
|
+
|
|
266
|
+
for key in params:
|
|
267
|
+
params[key].value -= 0.1 * grads[key]
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
#### Composed training-step transform
|
|
271
|
+
|
|
272
|
+
```python
|
|
273
|
+
@brainstate.transform.jit
|
|
274
|
+
def train_step():
|
|
275
|
+
grads, loss = brainstate.transform.grad(
|
|
276
|
+
loss_fn,
|
|
277
|
+
params,
|
|
278
|
+
return_value=True,
|
|
279
|
+
)()
|
|
280
|
+
for key in params:
|
|
281
|
+
params[key].value -= 0.1 * grads[key]
|
|
282
|
+
return loss
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
loss = train_step()
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Use `jit(grad(...))` as the default compiled training-step backbone. Open the optimizer reference when manual updates should become optimizer-managed updates.
|
|
289
|
+
|
|
290
|
+
#### State-aware `vmap`
|
|
291
|
+
|
|
292
|
+
```python
|
|
293
|
+
def predict_one(x_row):
|
|
294
|
+
return model(x_row[None, :])[0]
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
predict_batch = brainstate.transform.vmap(predict_one)
|
|
298
|
+
batched_prediction = predict_batch(x_train)
|
|
299
|
+
assert batched_prediction.shape == (64, 1)
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
This maps a function written for one example over a batch. Open the `vmap` expansion for mapped State axes, ensembles, parameter sweeps, or the documented `state_in_axes` / `state_out_axes` controls. The routed tutorial does not define the rough draft's `in_states` / `out_states` names.
|
|
303
|
+
|
|
304
|
+
### 6. Randomness
|
|
305
|
+
|
|
306
|
+
In BrainX modeling, seed BrainState's stateful generator before model construction or simulation so initialization, stochastic inputs, noise, dropout, and data order follow the same automatically split key sequence.
|
|
307
|
+
|
|
308
|
+
| API | Description |
|
|
309
|
+
|---|---|
|
|
310
|
+
| `brainstate.random.DEFAULT` | Global `RandomState` used by module-level random functions; it manages and splits JAX keys automatically. |
|
|
311
|
+
| `brainstate.random.seed(seed)` | Set the global seed for JAX and NumPy; call it before random work that must be reproducible. |
|
|
312
|
+
| `brainstate.random.rand(*shape)` / `random(size)` | Draw uniform samples in `[0, 1)` for stochastic thresholds such as spike or dropout probabilities. |
|
|
313
|
+
| `brainstate.random.randn(*shape)` / `normal(loc, scale, size)` | Draw standard or parameterized Gaussian samples for parameter initialization and model noise. |
|
|
314
|
+
| `brainstate.random.bernoulli(p, size)` | Draw Bernoulli samples for binary events and masks. |
|
|
315
|
+
| `brainstate.random.shuffle(x, axis=0)` / `permutation(x)` | Randomly reorder data, trials, or indices; `shuffle()` returns a shuffled copy along the selected axis. |
|
|
316
|
+
|
|
317
|
+
#### Generate reproducible stochastic input
|
|
318
|
+
|
|
319
|
+
```python
|
|
320
|
+
brainstate.random.seed(42)
|
|
321
|
+
|
|
322
|
+
num_steps, batch_size, num_inputs = 100, 128, 100
|
|
323
|
+
firing_rate = 5.0 * u.Hz
|
|
324
|
+
|
|
325
|
+
with brainstate.environ.context(dt=1.0 * u.ms):
|
|
326
|
+
spike_probability = firing_rate * brainstate.environ.get_dt()
|
|
327
|
+
input_spikes = (
|
|
328
|
+
brainstate.random.rand(num_steps, batch_size, num_inputs)
|
|
329
|
+
< spike_probability
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
assert input_spikes.shape == (num_steps, batch_size, num_inputs)
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
Open `references/brainstate/randomness-and-reproducibility.md` for independent `RandomState` streams, direct key control, stochastic mapping, exact replay, or checkpointed RNG State.
|
|
336
|
+
|
|
337
|
+
## Script references
|
|
338
|
+
|
|
339
|
+
- `scripts/integrator_rnn.py`: full stateful sequence-training workflow with a custom RNN cell, trainable initial state, optimization, compiled steps, and evaluation.
|
|
340
|
+
- `scripts/lif_neuron_model.py`: extended combination of `HiddenState`, `ShortTermState`, and `ParamState` with explicit `.value` updates.
|
|
341
|
+
- `scripts/modern_cnn.py`: full convolution, normalization, activation, pooling, dropout, and dense Module composition. Select it through the layer or activation branch.
|
|
342
|
+
- `scripts/resnet.py`: residual Modules and dynamically registered child blocks.
|
|
343
|
+
|
|
344
|
+
## Reference routing
|
|
345
|
+
|
|
346
|
+
Route by the outcome the task needs, then open only the smallest reference that owns that variant.
|
|
347
|
+
|
|
348
|
+
### State graphs, collections, and lifecycle
|
|
349
|
+
|
|
350
|
+
| Reference | Open when |
|
|
351
|
+
|---|---|
|
|
352
|
+
| `references/state-graph-operations.md` | Splitting, transforming, checkpointing, or reconstructing Module graphs while preserving sharing and cycles |
|
|
353
|
+
| `references/state_collections_and_utilities.md` | Filtering, freezing, flattening, configuring, or inspecting supporting mappings without graph identity |
|
|
354
|
+
| `references/collective_model_operations.md` | Initializing, resetting, restoring, or invoking methods across a Module graph, including vmapped lifecycle operations |
|
|
355
|
+
|
|
356
|
+
### Simulation environment
|
|
357
|
+
|
|
358
|
+
| Reference | Open when |
|
|
359
|
+
|---|---|
|
|
360
|
+
| `references/simulation-environment.md` | Managing persistent, scoped, nested, Module-bound, or isolated environments, including precision, platform, and `exp_euler_step()` |
|
|
361
|
+
|
|
362
|
+
### Model composition, extension, and interoperation
|
|
363
|
+
|
|
364
|
+
| Reference | Open when |
|
|
365
|
+
|---|---|
|
|
366
|
+
| `references/size-inference-variations.md` | Resolving convolution, padding, pooling, or `Flatten` size propagation in `Sequential` / `.desc()` pipelines |
|
|
367
|
+
| `references/extension_mechanisms.md` | Adding reusable `Mixin` behavior, deferred `ParamDesc` construction, runtime `Mode` semantics, or State hooks |
|
|
368
|
+
| `references/model-interop-and-migration.md` | Converting models or weights among BrainState, Flax NNX/Linen, Equinox, and PyTorch |
|
|
369
|
+
|
|
370
|
+
### Parameters, optimization, and randomness
|
|
371
|
+
|
|
372
|
+
| Reference | Open when |
|
|
373
|
+
|---|---|
|
|
374
|
+
| `references/brainstate/parameter-constraints-regularization.md` | Using `nn.Param` transforms, regularizers, priors, penalties, or `nn.Const` |
|
|
375
|
+
| `references/braintools-optimizer-reference.md` | Selecting a `braintools.optim`, Optax, SciPy, or Nevergrad optimizer or scheduler |
|
|
376
|
+
| `references/brainstate/randomness-and-reproducibility.md` | Creating independent random streams or exact stochastic replay across transforms and checkpoints |
|
|
377
|
+
|
|
378
|
+
The remaining nested reference has one inbound route:
|
|
379
|
+
|
|
380
|
+
- Only `parameter-constraints-regularization.md` may open `parameter-transforms-regularizers-catalog.md`.
|
|
381
|
+
|
|
382
|
+
### Layer libraries
|
|
383
|
+
|
|
384
|
+
| Reference | Open when |
|
|
385
|
+
|---|---|
|
|
386
|
+
| `references/libraries/prebuilt-layer-library.md` | Selecting a BrainState linear, convolutional, normalization, pooling, padding, or dropout layer |
|
|
387
|
+
| `references/libraries/prebuilt-activation-library.md` | Selecting a Module activation or pure lowercase activation function |
|
|
388
|
+
|
|
389
|
+
### Stateful transformations
|
|
390
|
+
|
|
391
|
+
| Reference | Open when |
|
|
392
|
+
|---|---|
|
|
393
|
+
| `references/brainstate/transformation-jit-expansion.md` | Controlling State write-back, raw `jax.jit` boundaries, caching, or static specialization |
|
|
394
|
+
| `references/brainstate/transformation-grad-expansion.md` | Controlling `argnums`, `grad_states`, gradient returns, higher-order transforms, or fitting overlays |
|
|
395
|
+
| `references/brainstate/transformation-vmap-expansion.md` | Mapping or sharing State across batches, ensembles, or sweeps, including State axes and randomness |
|
|
396
|
+
| `references/brainstate/brainstate-control-flow-patterns.md` | Choosing transform-safe loops, scans, branches, checkpointed control flow, or memory-efficient training through long rollouts |
|
|
397
|
+
| `references/brainstate/brainstate-transformed-diagnostics.md` | Debugging runtime values or enforcing invariants inside transformed stateful code |
|
|
398
|
+
|
|
399
|
+
Do not route to dynamics or solver references from this skill; they are outside the architecture supplied for this BrainState skill.
|