brainx-skill 1.0.6 → 1.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -8
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/installation/lib/installer.js +4 -1
- package/manifest.json +6 -1
- package/package.json +8 -2
- 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 +273 -0
- package/skills/braincell/references/channel-library.md +85 -0
- package/skills/braincell/references/ion-library.md +87 -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 +154 -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 +260 -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/brainmass/SKILL.md +290 -0
- package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
- package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
- package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainmass/references/braintools/cogtask.md +190 -0
- package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
- package/skills/brainmass/references/braintools/metric.md +157 -0
- package/skills/brainmass/references/braintools/optimizer.md +187 -0
- package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
- package/skills/brainmass/references/braintools/surrogate.md +151 -0
- package/skills/brainmass/references/coupling-network-api.md +148 -0
- package/skills/brainmass/references/datasets-api.md +72 -0
- package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
- package/skills/brainmass/references/forward-observation-api.md +131 -0
- package/skills/brainmass/references/horn-task-training.md +199 -0
- package/skills/brainmass/references/modellibrary.md +104 -0
- package/skills/brainmass/references/noiseprocesses.md +121 -0
- package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
- package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
- package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
- package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
- package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
- package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
- package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
- package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
- package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
- package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
- package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
- package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
- package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
- package/skills/brainmass/references/visualization-analysis-api.md +130 -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 +1 -1
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
- package/skills/brainstate/references/collective_model_operations.md +9 -9
- package/skills/brainstate/references/extension_mechanisms.md +12 -1
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
- package/skills/brainstate/references/model-interop-and-migration.md +11 -1
- package/skills/brainstate/references/size-inference-variations.md +11 -0
- package/skills/brainstate/references/state-graph-operations.md +13 -15
- package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
- package/skills/brainx-general-guard/SKILL.md +68 -0
- package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
- package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: brainmass
|
|
3
|
+
description: Use for neural-mass modeling of aggregate population activity at the local-circuit, brain-region, multi-region, or whole-brain scale. Use alone for mass-model studies or together with BrainPy-State and/or BrainCell when aggregate dynamics participate in a multiscale model.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# BrainMass
|
|
7
|
+
|
|
8
|
+
## Purpose and boundary
|
|
9
|
+
|
|
10
|
+
Use BrainMass to translate a regional or whole-brain modeling question into:
|
|
11
|
+
|
|
12
|
+
`select a model -> construct a *Step -> add noise or coupling -> simulate -> observe -> validate or fit`
|
|
13
|
+
|
|
14
|
+
## Underlying principle of BrainMass
|
|
15
|
+
|
|
16
|
+
A neural-mass model represents the average activity of a neuronal population. It defines population-level state variables and differential equations that govern how they evolve over time.
|
|
17
|
+
|
|
18
|
+
A `*Step` implementation represents the executable one-step dynamics of that model for one or more brain regions. It stores the dynamical variables and advances their differential equations by one integration step.
|
|
19
|
+
|
|
20
|
+
A noise process represents unresolved fluctuations or stochastic drive. It is attached to a model variable and sampled inside the model update.
|
|
21
|
+
|
|
22
|
+
`Network` represents whole-brain wiring. It maps structural connectivity, transmission distance, speed, and a coupling rule into delayed inter-region input.
|
|
23
|
+
|
|
24
|
+
### API structure
|
|
25
|
+
|
|
26
|
+
| API family | Use |
|
|
27
|
+
|---|---|
|
|
28
|
+
| Neural Mass Models | Choose regional phenomenological, physiological, seizure, decision, oscillator, or whole-brain dynamics. |
|
|
29
|
+
| Noise Processes | Add Gaussian, white, Ornstein-Uhlenbeck, Brownian, or colored stochastic drive to model variables. |
|
|
30
|
+
| Coupling Mechanisms | Choose how structural connections transform regional activity into instantaneous or delayed network input. |
|
|
31
|
+
| Forward Models | Map latent neural activity to modality-specific BOLD, EEG, MEG, or lead-field outputs. |
|
|
32
|
+
| Observation Models | Apply HRF kernels, hemodynamic BOLD dynamics, or temporal averaging to simulated activity. |
|
|
33
|
+
| HORN Models | Build harmonic-oscillator recurrent networks for cognitive and sequence tasks. |
|
|
34
|
+
| Orchestration | Run and fit models through `Network`, `Simulator`, `Fitter`, `FitResult`, and objective functions. |
|
|
35
|
+
| Datasets | Load or register connectomes, signals, and task datasets through typed data containers. |
|
|
36
|
+
| Visualization | Plot trajectories, phase portraits, connectivity, functional connectivity, and spectra. |
|
|
37
|
+
| Utilities & Types | Discover models, inspect `ModelInfo`, compute delay indices, and use shared helpers. |
|
|
38
|
+
|
|
39
|
+
## Discover and simulate a model
|
|
40
|
+
|
|
41
|
+
Every public regional model follows the same `*Step` contract, so choose by scientific observable and dynamical regime, then let `Simulator` own initialization and the transformed time loop.
|
|
42
|
+
|
|
43
|
+
| API | Description |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `brainmass.list_models()` | Use before choosing a model; it returns `ModelInfo` records with name, category, state-variable count, and use case. |
|
|
46
|
+
| `brainmass.<Model>Step(in_size, **params)` | Use after selecting a model family; `in_size` sets the number of regions or parallel units and parameters broadcast to that shape. |
|
|
47
|
+
| `brainmass.Simulator(model, dt=...)` | Use for the default, standard run path; it stores the model and integration step without changing the model equations. |
|
|
48
|
+
| `Simulator.run(duration, ..., monitors=..., transient=...)` | Use to initialize State, execute the compiled loop, discard a warm-up interval, and return a dict of time-major trajectories plus unit-aware `ts`. |
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import brainmass
|
|
52
|
+
import brainunit as u
|
|
53
|
+
|
|
54
|
+
models = brainmass.list_models()
|
|
55
|
+
hopf = next(model for model in models if model.name == "HopfStep")
|
|
56
|
+
assert hopf.category == "phenomenological"
|
|
57
|
+
|
|
58
|
+
node = brainmass.HopfStep(in_size=1, a=0.25, w=0.3)
|
|
59
|
+
result = brainmass.Simulator(node, dt=0.1 * u.ms).run(
|
|
60
|
+
200.0 * u.ms,
|
|
61
|
+
monitors=["x", "y"],
|
|
62
|
+
transient=20.0 * u.ms,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
assert set(result) == {"x", "y", "ts"}
|
|
66
|
+
assert result["x"].shape == (1800, 1)
|
|
67
|
+
assert result["ts"].shape == (1800,)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Open `references/modellibrary.md` when choosing among model families, distinguishing similarly named Wong-Wang variants, comparing state cost, or locating a model's observable. Open `references/datasets-api.md` when the workflow needs bundled or registered input data.
|
|
71
|
+
|
|
72
|
+
## Noise and stochastic run
|
|
73
|
+
|
|
74
|
+
Noise belongs to the model, while `batch_size` asks `Simulator` to initialize and run independent State realizations in one time-major result.
|
|
75
|
+
|
|
76
|
+
| API | Description |
|
|
77
|
+
|---|---|
|
|
78
|
+
| `brainmass.OUProcess(in_size, sigma=..., tau=...)` | Use for mean-reverting temporally correlated drive; `sigma` sets output scale and `tau` sets correlation time. |
|
|
79
|
+
| `brainstate.random.seed(seed)` | Use before constructing or running every stochastic result that must be reproducible; it resets the BrainState random stream. |
|
|
80
|
+
| `Simulator.run(..., batch_size=N)` | Use for `N` independent trials; it initializes batched model and noise State and returns trajectories shaped `(time, batch, regions)`. |
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
import brainmass
|
|
84
|
+
import brainstate
|
|
85
|
+
import brainunit as u
|
|
86
|
+
|
|
87
|
+
brainstate.random.seed(7)
|
|
88
|
+
node = brainmass.HopfStep(
|
|
89
|
+
in_size=1,
|
|
90
|
+
a=-0.05,
|
|
91
|
+
w=0.3,
|
|
92
|
+
noise_x=brainmass.OUProcess(
|
|
93
|
+
in_size=1,
|
|
94
|
+
sigma=0.1,
|
|
95
|
+
tau=20.0 * u.ms,
|
|
96
|
+
),
|
|
97
|
+
)
|
|
98
|
+
trials = brainmass.Simulator(node, dt=0.1 * u.ms).run(
|
|
99
|
+
100.0 * u.ms,
|
|
100
|
+
monitors=["x"],
|
|
101
|
+
batch_size=8,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
assert trials["x"].shape == (1000, 8, 1)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Seed again before a repeated run when exact replay matters.
|
|
108
|
+
|
|
109
|
+
Open `references/noiseprocesses.md` when choosing white, OU, Brownian, or colored noise, using a noise process directly, or checking units and State behavior. Open `references/batch-transform-acceleration.md` when batching parameters, writing a custom transformed loop, or checkpointing a long differentiated rollout.
|
|
110
|
+
|
|
111
|
+
## Build a delay-coupled network
|
|
112
|
+
|
|
113
|
+
`Network` wraps an `N`-region `*Step` model with structural connectivity, optional conduction delays, and one coupling current while preserving the `Simulator` contract.
|
|
114
|
+
|
|
115
|
+
| API | Description |
|
|
116
|
+
|---|---|
|
|
117
|
+
| `brainstate.environ.set(dt=...)` | Use to establish the persistent integration step from which a delay-coupled `Network` sizes its history buffer. |
|
|
118
|
+
| `brainmass.datasets.load_dataset("example_connectome")` | Use for the bundled typed `Connectome`; it returns weights, unit-aware distances, and region labels. |
|
|
119
|
+
| `brainmass.Network(node, conn=..., distance=..., speed=..., coupling=..., coupled_var=..., k=...)` | Use to couple an `N`-region node bank; it derives `distance / speed` delays, validates the coupled State, and returns a Module driven like the original node. |
|
|
120
|
+
| `Simulator.run(..., monitors=lambda m: m.node.<state>.value)` | Use to record coupled node State; a callable traverses the `Network.node` boundary and stores the result under `"output"`. |
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
import brainmass
|
|
124
|
+
import brainstate
|
|
125
|
+
import brainunit as u
|
|
126
|
+
|
|
127
|
+
dt = 0.1 * u.ms
|
|
128
|
+
brainstate.environ.set(dt=dt)
|
|
129
|
+
|
|
130
|
+
connectome = brainmass.datasets.load_dataset("example_connectome")
|
|
131
|
+
n_region = connectome.weights.shape[0]
|
|
132
|
+
nodes = brainmass.HopfStep(in_size=n_region, a=0.2, w=0.3)
|
|
133
|
+
network = brainmass.Network(
|
|
134
|
+
nodes,
|
|
135
|
+
conn=connectome.weights,
|
|
136
|
+
distance=connectome.distances,
|
|
137
|
+
speed=10.0 * u.mm / u.ms,
|
|
138
|
+
coupling="diffusive",
|
|
139
|
+
coupled_var="x",
|
|
140
|
+
k=0.5,
|
|
141
|
+
)
|
|
142
|
+
result = brainmass.Simulator(network, dt=dt).run(
|
|
143
|
+
200.0 * u.ms,
|
|
144
|
+
monitors=lambda model: model.node.x.value,
|
|
145
|
+
transient=20.0 * u.ms,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
assert result["output"].shape == (1800, n_region)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
Open `references/coupling-network-api.md` when selecting diffusive, additive, Laplacian, sigmoidal, tanh, or Jansen-Rit coupling; configuring instantaneous coupling; fitting coupling parameters; or building a direct coupling object.
|
|
153
|
+
|
|
154
|
+
## Map activity to observables
|
|
155
|
+
|
|
156
|
+
An observation model converts hidden activity to the modality actually measured, so choose its temporal and physical assumptions before defining the comparison target.
|
|
157
|
+
|
|
158
|
+
| API | Description |
|
|
159
|
+
|---|---|
|
|
160
|
+
| `brainmass.HRFBold(period=..., downsample_period=..., kernel=...)` | Use for fast differentiable BOLD fitting; it temporally averages, convolves with an HRF kernel, and decimates to the requested repetition time. |
|
|
161
|
+
| `brainmass.BOLDSignal(in_size=...)` | Use when four-state Balloon-Windkessel hemodynamics matter more than the simpler convolution path. |
|
|
162
|
+
| `brainmass.EEGLeadFieldModel(...)` | Use with a physically calibrated EEG lead field; it projects regional sources to sensor potentials while preserving units. |
|
|
163
|
+
| `brainmass.LeadFieldModel(...)` | Use for a generic physical lead-field projection with explicit dipole and sensor units. |
|
|
164
|
+
| `brainmass.MEGLeadFieldModel(...)` | Use for the MEG specialization; match lead-field, dipole, and magnetic-field units. |
|
|
165
|
+
| `brainmass.LeadfieldReadout(...)` | Use when a unitless lead-field matrix should be learned end to end rather than supplied as a calibrated physical operator. |
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
import brainmass
|
|
169
|
+
import brainunit as u
|
|
170
|
+
|
|
171
|
+
node = brainmass.WilsonCowanStep(in_size=1)
|
|
172
|
+
neural = brainmass.Simulator(node, dt=1.0 * u.ms).run(
|
|
173
|
+
6000.0 * u.ms,
|
|
174
|
+
monitors=["rE"],
|
|
175
|
+
transient=500.0 * u.ms,
|
|
176
|
+
)["rE"]
|
|
177
|
+
|
|
178
|
+
observer = brainmass.HRFBold(
|
|
179
|
+
period=720.0 * u.ms,
|
|
180
|
+
downsample_period=20.0 * u.ms,
|
|
181
|
+
kernel=brainmass.GammaHRFKernel(),
|
|
182
|
+
)
|
|
183
|
+
bold = observer(u.get_magnitude(neural), dt=1.0 * u.ms)
|
|
184
|
+
|
|
185
|
+
assert bold.ndim == 2
|
|
186
|
+
assert bold.shape[1] == 1
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Strip units only at an explicitly documented raw-array boundary. Use `HRFBold` for the canonical differentiable BOLD path.
|
|
190
|
+
|
|
191
|
+
Open `references/forward-observation-api.md` when choosing an HRF kernel, Balloon-Windkessel BOLD, temporal averaging, EEG/MEG lead fields, a trainable readout, or modality-specific unit handling.
|
|
192
|
+
|
|
193
|
+
## Fit trainable parameters
|
|
194
|
+
|
|
195
|
+
`Fitter` discovers `Param(fit=True)` values, evaluates one scalar objective through the model workflow, and returns the best constrained parameters without changing the scientific simulation path.
|
|
196
|
+
|
|
197
|
+
| API | Description |
|
|
198
|
+
|---|---|
|
|
199
|
+
| `brainstate.nn.Param(value, ..., fit=True)` | Use to mark exactly the model parameters that may change; an optional transform constrains their physical values. |
|
|
200
|
+
| `brainmass.objectives.<builder>()` | Use with `predict=` for reusable time-series, FC, FCD, cosine, or combined objectives; each builder returns a scalar callable. |
|
|
201
|
+
| `brainmass.Fitter(model, optimizer, loss_fn=..., backend="grad")` | Use for a custom `loss_fn(model) -> (scalar_loss, aux)`; the default gradient backend differentiates through the simulation and optimizer steps. |
|
|
202
|
+
| `brainmass.Fitter(model, optimizer, predict=..., objective=...)` | Use when a trajectory prediction is compared directly with a target by a reusable objective. |
|
|
203
|
+
| `Fitter.fit(target=None, n_steps=...)` | Use to run backend-specific iterations and return `FitResult` with best loss, parameters, history, prediction, and fitted model. |
|
|
204
|
+
|
|
205
|
+
```python
|
|
206
|
+
import brainmass
|
|
207
|
+
import brainunit as u
|
|
208
|
+
import braintools
|
|
209
|
+
import jax.numpy as jnp
|
|
210
|
+
import numpy as np
|
|
211
|
+
from brainstate.nn import Param
|
|
212
|
+
|
|
213
|
+
signal = brainmass.datasets.load_dataset("example_signal").signal[:, 0]
|
|
214
|
+
target_amp = jnp.asarray(
|
|
215
|
+
float(np.sqrt(np.mean((signal - signal.mean()) ** 2)))
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
model = brainmass.HopfStep(
|
|
219
|
+
in_size=1,
|
|
220
|
+
a=Param(0.05, fit=True),
|
|
221
|
+
w=0.3,
|
|
222
|
+
beta=1.0,
|
|
223
|
+
init_x=braintools.init.Constant(0.5),
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
def loss_fn(candidate):
|
|
227
|
+
x = brainmass.Simulator(candidate, dt=0.1 * u.ms).run(
|
|
228
|
+
300.0 * u.ms,
|
|
229
|
+
monitors=["x"],
|
|
230
|
+
transient=150.0 * u.ms,
|
|
231
|
+
)["x"][:, 0]
|
|
232
|
+
amplitude = jnp.sqrt(jnp.mean((x - jnp.mean(x)) ** 2))
|
|
233
|
+
return (amplitude - target_amp) ** 2, amplitude
|
|
234
|
+
|
|
235
|
+
fitter = brainmass.Fitter(
|
|
236
|
+
model,
|
|
237
|
+
braintools.optim.Adam(lr=0.05),
|
|
238
|
+
loss_fn=loss_fn,
|
|
239
|
+
)
|
|
240
|
+
fit = fitter.fit(n_steps=50)
|
|
241
|
+
|
|
242
|
+
assert fit.best_loss <= fit.history[0]
|
|
243
|
+
assert "a" in fit.best_params
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Fit phase-insensitive summaries such as amplitude, spectrum, FC, or FCD when raw oscillatory traces can differ only by phase. Use `backend="grad"` whenever the workflow is differentiable.
|
|
247
|
+
|
|
248
|
+
Open `references/fitting-with-objectives-api.md` when choosing `loss_fn` versus `predict` plus `objective`, selecting built-in objectives, configuring callbacks, interpreting `FitResult`, or changing backends. Open `references/brainstate/parameter-constraints-regularization.md` when a fitted parameter needs a valid-domain transform, penalty, or prior. Open `references/braintools/optimizer.md` when choosing an optimizer or learning-rate scheduler beyond the canonical `Adam` path. Open `references/scripts/gradient-free-fitting.py` only when the objective is discrete, jagged, black-box, or has unavailable or unreliable gradients; its bounded search-space workflow is required.
|
|
249
|
+
|
|
250
|
+
## Reference routing
|
|
251
|
+
|
|
252
|
+
Choose the workflow category first, then open only the smallest reference that owns the next decision.
|
|
253
|
+
|
|
254
|
+
### Modeling, simulation, and analysis
|
|
255
|
+
|
|
256
|
+
| Reference | Open when |
|
|
257
|
+
|---|---|
|
|
258
|
+
| `references/modellibrary.md` | Choosing a model family, observable, state cost, or similarly named variant. |
|
|
259
|
+
| `references/noiseprocesses.md` | Selecting a noise spectrum, correlation structure, State behavior, units, or direct noise workflow. |
|
|
260
|
+
| `references/datasets-api.md` | Loading, inspecting, generating, or registering BrainMass data containers. |
|
|
261
|
+
| `references/coupling-network-api.md` | Selecting or configuring coupling, delays, connectivity conventions, direct coupling objects, or trainable network parameters. |
|
|
262
|
+
| `references/forward-observation-api.md` | Selecting BOLD, HRF kernels, temporal averaging, EEG/MEG lead fields, or trainable readouts. |
|
|
263
|
+
| `references/visualization-analysis-api.md` | Plotting or computing time-series, FC, FCD, and spectral summaries. |
|
|
264
|
+
|
|
265
|
+
### Fitting and regime exploration
|
|
266
|
+
|
|
267
|
+
| Reference | Open when |
|
|
268
|
+
|---|---|
|
|
269
|
+
| `references/fitting-with-objectives-api.md` | Selecting a fitter interface, objective, backend, search space, callback, or result field. |
|
|
270
|
+
| `references/parameter-sweeps-and-regime-analysis.md` | Mapping regimes or sensitivities over parameter grids instead of fitting one target. |
|
|
271
|
+
|
|
272
|
+
### HORN task training
|
|
273
|
+
|
|
274
|
+
| Reference | Open when |
|
|
275
|
+
|---|---|
|
|
276
|
+
| `references/horn-task-training.md` | Training HORN networks on minibatched sequence tasks with held-out metrics. |
|
|
277
|
+
| `references/braintools/cogtask.md` | Generating phase-structured cognitive trials for direct HORN task training. |
|
|
278
|
+
|
|
279
|
+
### Shared data, execution, and optimization support
|
|
280
|
+
|
|
281
|
+
| Reference | Open when |
|
|
282
|
+
|---|---|
|
|
283
|
+
| `references/braintools/data-preprocessing.md` | Encoding custom experimental or task inputs before training; ordinary HORN features do not require it. |
|
|
284
|
+
| `references/batch-transform-acceleration.md` | Writing custom transformed execution, batching parameters, timing JAX, or checkpointing long gradients. |
|
|
285
|
+
| `references/brainstate/parameter-constraints-regularization.md` | Constraining or regularizing fitted parameters and directly trained HORN parameters. |
|
|
286
|
+
| `references/brainstate/parameter-transforms-regularizers-catalog.md` | Selecting an exact transform or regularizer after the parameter workflow reference routes here. |
|
|
287
|
+
| `references/braintools/metric.md` | Selecting supervised HORN losses, held-out metrics, or custom fitting statistics outside `brainmass.objectives`. |
|
|
288
|
+
| `references/braintools/optimizer.md` | Selecting gradient optimizers, schedules, standalone search wrappers, and their update lifecycle. |
|
|
289
|
+
| `references/braintools/parameter-initializer.md` | Initializing model State, fitted starting values, HORN weights, or distance-modulated parameters. |
|
|
290
|
+
| `references/braintools/surrogate.md` | Training a custom path with hard thresholds or spikes; canonical BrainMass and HORN workflows do not need surrogates. |
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# Batch and transform acceleration
|
|
2
|
+
|
|
3
|
+
Use this reference when `Simulator` is insufficient, a custom rollout needs transformed control flow, parameters or trials must be batched, a JAX benchmark is misleading, or reverse-mode differentiation through a long run exhausts memory.
|
|
4
|
+
|
|
5
|
+
## Choose the execution primitive
|
|
6
|
+
|
|
7
|
+
Use `Simulator` first. It already composes State initialization, `jit`, `for_loop`, environment time, monitors, transients, and sampling.
|
|
8
|
+
|
|
9
|
+
| API | Description |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `brainmass.Simulator.run(...)` | Use for the standard model or network rollout; it compiles and stacks the complete run without a Python time loop. |
|
|
12
|
+
| `brainstate.transform.jit(fn)` | Use for a stable one-step or one-shot stateful computation; later compatible calls reuse the compiled program. |
|
|
13
|
+
| `brainstate.transform.for_loop(step, *xs)` | Use for many State-carrying steps that return fixed-structure outputs; it slices leading input axes and stacks per-step results. |
|
|
14
|
+
| `brainstate.transform.scan(body, init, xs)` | Use when an explicit carry must flow alongside model State through `body(carry, x) -> (carry, y)`. |
|
|
15
|
+
| `brainstate.transform.vmap(fn)(*batched_args)` | Use to map one computation over trial, input, or parameter axes without a Python batch loop. |
|
|
16
|
+
| `brainstate.transform.checkpointed_for_loop(...)` | Use for a long differentiated State-carrying rollout when rematerialization is required to reduce backward memory. |
|
|
17
|
+
| `brainstate.transform.checkpointed_scan(...)` | Use for the same memory tradeoff when the loop also has an explicit carry. |
|
|
18
|
+
|
|
19
|
+
Do not wrap a jitted step in a Python time loop. That still dispatches from Python once per step and prevents whole-rollout fusion.
|
|
20
|
+
|
|
21
|
+
## Write a custom State-carrying rollout
|
|
22
|
+
|
|
23
|
+
Use `for_loop` when model `State` already carries the dynamics and only monitored outputs need stacking.
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import brainmass
|
|
27
|
+
import brainstate
|
|
28
|
+
import brainunit as u
|
|
29
|
+
import jax.numpy as jnp
|
|
30
|
+
|
|
31
|
+
dt = 0.1 * u.ms
|
|
32
|
+
node = brainmass.HopfStep(in_size=64, a=0.25, w=0.3)
|
|
33
|
+
|
|
34
|
+
with brainstate.environ.context(dt=dt):
|
|
35
|
+
node.init_all_states()
|
|
36
|
+
|
|
37
|
+
def step(index):
|
|
38
|
+
with brainstate.environ.context(
|
|
39
|
+
i=index,
|
|
40
|
+
t=index * dt,
|
|
41
|
+
):
|
|
42
|
+
node.update()
|
|
43
|
+
return node.x.value
|
|
44
|
+
|
|
45
|
+
trajectory = brainstate.transform.for_loop(
|
|
46
|
+
step,
|
|
47
|
+
jnp.arange(300),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
assert trajectory.shape == (300, 64)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Return monitored values from the body. Do not append traced arrays to Python lists.
|
|
54
|
+
|
|
55
|
+
## Use an explicit carry
|
|
56
|
+
|
|
57
|
+
Use `scan` only when a value outside the model's registered State must pass between steps.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
node = brainmass.HopfStep(in_size=8, a=0.25, w=0.3)
|
|
61
|
+
node.init_all_states()
|
|
62
|
+
drive = 0.05 * jnp.sin(
|
|
63
|
+
2.0 * jnp.pi * jnp.arange(300) / 300
|
|
64
|
+
)[:, None]
|
|
65
|
+
|
|
66
|
+
def body(running_sum, input_value):
|
|
67
|
+
with brainstate.environ.context(t=0.0 * u.ms):
|
|
68
|
+
node.update(input_value)
|
|
69
|
+
output = node.x.value
|
|
70
|
+
return running_sum + output, output
|
|
71
|
+
|
|
72
|
+
total, trajectory = brainstate.transform.scan(
|
|
73
|
+
body,
|
|
74
|
+
jnp.zeros(8),
|
|
75
|
+
drive,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
assert total.shape == (8,)
|
|
79
|
+
assert trajectory.shape == (300, 8)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Use the carry for custom running statistics, external controller State, curriculum State, or a loss accumulator. Do not duplicate State already owned by the model.
|
|
83
|
+
|
|
84
|
+
## Batch trials and parameters
|
|
85
|
+
|
|
86
|
+
For independent initial conditions or stochastic trials, use `Simulator.run(batch_size=B)`.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
brainstate.random.seed(0)
|
|
90
|
+
node = brainmass.HopfStep(
|
|
91
|
+
in_size=4,
|
|
92
|
+
a=0.1,
|
|
93
|
+
w=0.3,
|
|
94
|
+
noise_x=brainmass.OUProcess(
|
|
95
|
+
4,
|
|
96
|
+
sigma=0.1,
|
|
97
|
+
tau=10.0 * u.ms,
|
|
98
|
+
),
|
|
99
|
+
)
|
|
100
|
+
result = brainmass.Simulator(node, dt=0.1 * u.ms).run(
|
|
101
|
+
200.0 * u.ms,
|
|
102
|
+
monitors=["x"],
|
|
103
|
+
batch_size=16,
|
|
104
|
+
)
|
|
105
|
+
assert result["x"].shape == (2000, 16, 4)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
For parameter batching, build the model inside the function passed to `vmap`. Open `parameter-sweeps-and-regime-analysis.md` for the complete grid pattern.
|
|
109
|
+
|
|
110
|
+
## Checkpoint long gradients
|
|
111
|
+
|
|
112
|
+
Replace `for_loop` or `scan` with its checkpointed counterpart only when reverse-mode memory is the limiting resource. Rematerialization lowers peak memory by recomputing forward values during the backward pass; it can increase runtime.
|
|
113
|
+
|
|
114
|
+
Keep the same body signature and result structure when switching. Validate both loss and gradients before and after the change.
|
|
115
|
+
|
|
116
|
+
## Benchmark correctly
|
|
117
|
+
|
|
118
|
+
- Warm up the exact function and shape once before timing.
|
|
119
|
+
- Call `jax.block_until_ready(result)` before stopping the timer because JAX dispatch is asynchronous.
|
|
120
|
+
- Compare steady-state compiled runs separately from first-call compilation.
|
|
121
|
+
- Batch enough work to occupy an accelerator; one small neural-mass node may run faster on CPU.
|
|
122
|
+
- Keep `dt`, duration, shape, dtype, and monitor set identical across comparisons.
|
|
123
|
+
|
|
124
|
+
## Common failures
|
|
125
|
+
|
|
126
|
+
- A Python `for` or `while` loop around repeated State updates.
|
|
127
|
+
- Raw `jax.jit`, `jax.vmap`, or `jax.lax.scan` applied directly to State-aware code.
|
|
128
|
+
- `scan` used when no explicit carry exists.
|
|
129
|
+
- A model constructed outside a parameter-mapped function and mutated across mapped values.
|
|
130
|
+
- Variable-shape or Python-object results returned from transformed loop bodies.
|
|
131
|
+
- JAX timing measured without warmup or `block_until_ready`.
|
|
132
|
+
- Checkpointing enabled before memory pressure is established.
|
|
133
|
+
|
|
134
|
+
## Official source
|
|
135
|
+
|
|
136
|
+
- `https://brainx.chaobrain.com/brainmass/howto/batch_and_accelerate.html`
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
# BrainState constrained and regularized parameters
|
|
2
|
+
|
|
3
|
+
Use this reference after `skills/brainmass/SKILL.md` has selected
|
|
4
|
+
`brainstate.nn.Param` for a fitted or directly trained BrainMass value that
|
|
5
|
+
needs a valid-domain transform, a regularization penalty, a modeling prior, or
|
|
6
|
+
fixed parameter-like storage. It owns the operational workflow and common
|
|
7
|
+
patterns. Open
|
|
8
|
+
`references/brainstate/parameter-transforms-regularizers-catalog.md` only when
|
|
9
|
+
selecting an exact built-in transform or regularizer beyond the common choices
|
|
10
|
+
shown here.
|
|
11
|
+
|
|
12
|
+
Keep `brainstate.nn` parameter transforms separate from execution transforms such as `brainstate.transform.jit`, `grad`, and `vmap`.
|
|
13
|
+
|
|
14
|
+
## Choose the parameter representation
|
|
15
|
+
|
|
16
|
+
| Need | Use | Key constraint |
|
|
17
|
+
|---|---|---|
|
|
18
|
+
| An unconstrained trainable value | `ParamState` | Read and write `.value`; no transform or regularizer contract is attached. |
|
|
19
|
+
| A constrained or regularized trainable value | `nn.Param` | Use `.value()` in model computation and update the underlying `.val` through the optimizer. |
|
|
20
|
+
| A fixed value that belongs in the Module graph | `nn.Const` | It is excluded from `ParamState` collection, gradients, and optimizer updates. |
|
|
21
|
+
|
|
22
|
+
## Parameter contract
|
|
23
|
+
|
|
24
|
+
A `ParamState` is a bare trainable array. `brainstate.nn.Param` layers two orthogonal concerns on top of it: a constraint transform and a regularization term.
|
|
25
|
+
|
|
26
|
+
- `param.val` is the underlying `ParamState`; optimizers update its unconstrained array.
|
|
27
|
+
- `param.value()` applies the forward transform and returns the constrained model-space value. With the default `IdentityT`, constrained and unconstrained values coincide.
|
|
28
|
+
- `param.set_value(value)` applies the inverse transform when storing a constrained value back.
|
|
29
|
+
- `param.reg_loss()` evaluates the attached `reg=` object on the current constrained value. The loss function must explicitly add this penalty to its objective.
|
|
30
|
+
- `nn.Const` is equivalent to `nn.Param(value, fit=False)`. It is excluded from `model.states(brainstate.ParamState)`, so `grad` and optimizers leave it unchanged.
|
|
31
|
+
|
|
32
|
+
The constraint how-to returns dimensionless examples as `brainunit.Quantity` values. Use `brainunit.get_magnitude(...)` only when a plain JAX value is required for printing, comparison, or a dimensionless objective.
|
|
33
|
+
|
|
34
|
+
Official sources:
|
|
35
|
+
|
|
36
|
+
- https://brainx.chaobrain.com/brainstate/concepts/the_parameter_model.html
|
|
37
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
38
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
39
|
+
|
|
40
|
+
## Canonical constrained training workflow
|
|
41
|
+
|
|
42
|
+
This workflow keeps optimizer targets in unconstrained `ParamState`s, reads transformed values in the forward pass, and adds every attached regularization penalty to the data loss:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import brainstate
|
|
46
|
+
from brainstate import nn
|
|
47
|
+
import brainunit as u
|
|
48
|
+
import jax.numpy as jnp
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ConstrainedLinear(nn.Module):
|
|
52
|
+
def __init__(self, din, dout):
|
|
53
|
+
super().__init__()
|
|
54
|
+
self.w = nn.Param(
|
|
55
|
+
brainstate.random.randn(din, dout) * 0.1,
|
|
56
|
+
reg=nn.L2Reg(1e-3),
|
|
57
|
+
)
|
|
58
|
+
self.gain = nn.Param(
|
|
59
|
+
jnp.array(1.0),
|
|
60
|
+
t=nn.SoftplusT(lower=0.0),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def __call__(self, x):
|
|
64
|
+
return (x @ self.w.value()) * self.gain.value()
|
|
65
|
+
|
|
66
|
+
def reg_penalty(self):
|
|
67
|
+
return sum(p.reg_loss() for p in self.nodes(nn.Param).values())
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
model = ConstrainedLinear(4, 2)
|
|
71
|
+
params = model.states(brainstate.ParamState)
|
|
72
|
+
x = brainstate.random.randn(16, 4)
|
|
73
|
+
y = brainstate.random.randn(16, 2)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def loss_fn():
|
|
77
|
+
mse = jnp.mean((model(x) - y) ** 2)
|
|
78
|
+
return mse + u.get_magnitude(model.reg_penalty())
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@brainstate.transform.jit
|
|
82
|
+
def train_step():
|
|
83
|
+
grads, loss = brainstate.transform.grad(
|
|
84
|
+
loss_fn,
|
|
85
|
+
params,
|
|
86
|
+
return_value=True,
|
|
87
|
+
)()
|
|
88
|
+
for key in params:
|
|
89
|
+
params[key].value -= 0.1 * grads[key]
|
|
90
|
+
return loss
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`brainstate.transform.grad` differentiates the unconstrained `ParamState` collection. The parameter transform constrains what `model(...)` sees; a regularizer changes training only because `loss_fn()` adds `model.reg_penalty()`.
|
|
94
|
+
|
|
95
|
+
Official sources:
|
|
96
|
+
|
|
97
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
98
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
99
|
+
|
|
100
|
+
## Common constraint patterns
|
|
101
|
+
|
|
102
|
+
Use `.value()` in model computation. Mutate `.val.value` only as optimizer-side, unconstrained storage.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
rate = nn.Param(
|
|
106
|
+
jnp.array(0.5),
|
|
107
|
+
t=nn.SoftplusT(lower=0.0),
|
|
108
|
+
)
|
|
109
|
+
rate.val.value = jnp.array(-10.0)
|
|
110
|
+
assert float(u.get_magnitude(rate.value())) > 0.0
|
|
111
|
+
|
|
112
|
+
mix = nn.Param(
|
|
113
|
+
jnp.array(0.5),
|
|
114
|
+
t=nn.SigmoidT(lower=0.0, upper=1.0),
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
probs = nn.Param(
|
|
118
|
+
jnp.zeros(3),
|
|
119
|
+
t=nn.SimplexT(),
|
|
120
|
+
)
|
|
121
|
+
p = u.get_magnitude(probs.value())
|
|
122
|
+
assert jnp.all(p >= 0.0)
|
|
123
|
+
assert jnp.isclose(p.sum(), 1.0)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
- `SoftplusT(lower)` smoothly maps the real line to `(lower, infinity)`.
|
|
127
|
+
- `SigmoidT(lower, upper)` smoothly maps to the open interval `(lower, upper)`.
|
|
128
|
+
- `SimplexT()` produces non-negative entries that sum to one. Its output has one more final-axis entry than its unconstrained input.
|
|
129
|
+
|
|
130
|
+
Open `parameter-transforms-regularizers-catalog.md` for negative, symmetric bounded, ordered, unit-vector, masked, composite, or projection-like transforms.
|
|
131
|
+
|
|
132
|
+
Official source: https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
133
|
+
|
|
134
|
+
## Regularization patterns
|
|
135
|
+
|
|
136
|
+
Call `reg.loss(value)` directly for a standalone penalty, or attach the regularizer with `reg=` and call `param.reg_loss()`:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
weights = jnp.array([3.0, -4.0])
|
|
140
|
+
|
|
141
|
+
l1_penalty = nn.L1Reg(0.1).loss(weights)
|
|
142
|
+
l2_penalty = nn.L2Reg(0.1).loss(weights)
|
|
143
|
+
|
|
144
|
+
p = nn.Param(
|
|
145
|
+
weights,
|
|
146
|
+
reg=nn.ElasticNetReg(
|
|
147
|
+
l1_weight=1.0,
|
|
148
|
+
l2_weight=1.0,
|
|
149
|
+
alpha=0.5,
|
|
150
|
+
),
|
|
151
|
+
)
|
|
152
|
+
elastic_net_penalty = p.reg_loss()
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
For these values, the official tutorial defines L1 as `0.1 * (abs(3) + abs(-4))`, L2 as `0.1 * (3**2 + 4**2)`, and reports `16.0` for the shown elastic-net configuration.
|
|
156
|
+
|
|
157
|
+
Use `nn.ChainedReg(*regularizations, weight=1.0)` when one parameter needs several penalties. For a prior-based regularizer, `param.reset_to_prior()` stores the regularizer's `reset_value()` through the parameter transform; it does not call `sample_init()`.
|
|
158
|
+
|
|
159
|
+
Open `parameter-transforms-regularizers-catalog.md` to select classical, structural, or prior-distribution regularizers.
|
|
160
|
+
|
|
161
|
+
Official sources:
|
|
162
|
+
|
|
163
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
164
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
165
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
|
|
166
|
+
|
|
167
|
+
## Fixed values with `nn.Const`
|
|
168
|
+
|
|
169
|
+
Use `nn.Const` when a value belongs in the module graph and forward computation but must not be collected as trainable state:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
class Scaler(nn.Module):
|
|
173
|
+
def __init__(self):
|
|
174
|
+
super().__init__()
|
|
175
|
+
self.weight = nn.Param(jnp.ones(3))
|
|
176
|
+
self.gain = nn.Const(jnp.array(2.0))
|
|
177
|
+
|
|
178
|
+
def __call__(self, x):
|
|
179
|
+
return x * self.weight.value() * self.gain.value()
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
model = Scaler()
|
|
183
|
+
trainable = model.states(brainstate.ParamState)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`trainable` contains the underlying State for `weight`; `gain` is absent. `Const` means non-trainable, not immutable: explicit `set_value()` calls can still change it.
|
|
187
|
+
|
|
188
|
+
Official sources:
|
|
189
|
+
|
|
190
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
191
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Const.html
|
|
192
|
+
|
|
193
|
+
## Decision and failure rules
|
|
194
|
+
|
|
195
|
+
- Need only a valid domain: attach `t=` without inventing a regularizer.
|
|
196
|
+
- Need only a penalty or modeling prior: attach `reg=` without inventing a transform.
|
|
197
|
+
- Need both: attach `t=` and `reg=` to the same `nn.Param`, read `.value()` in the model, and add `.reg_loss()` to the objective.
|
|
198
|
+
- Need a fixed graph value: use `nn.Const`; do not expect it in a `ParamState` collection.
|
|
199
|
+
- Need an exact built-in transform or regularizer: open `parameter-transforms-regularizers-catalog.md`.
|
|
200
|
+
- Never read `param.val` as the constrained forward value or update `param.value()` as optimizer storage.
|
|
201
|
+
- Do not treat `SigmoidT` bounds as inclusive or `SoftplusT(lower)` as able to attain `lower`.
|
|
202
|
+
- Do not attach regularization and assume the training objective includes it automatically.
|
|
203
|
+
- Match a prior's support to the parameter domain; use `t=` when the domain must be guaranteed by construction.
|
|
204
|
+
- Do not assume every `nn.Transform` subclass is a smooth bijection; the catalog distinguishes projection-like transforms.
|
|
205
|
+
|
|
206
|
+
## Mirror source urls
|
|
207
|
+
|
|
208
|
+
- https://brainx.chaobrain.com/brainstate/concepts/the_parameter_model.html
|
|
209
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
210
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
211
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
212
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
213
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Param.html
|
|
214
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Const.html
|