brainx-skill 1.0.8 → 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 +1 -6
- package/manifest.json +3 -2
- package/package.json +2 -1
- package/skills/braincell/SKILL.md +1 -1
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +107 -44
- package/skills/braincell/references/channel-library.md +0 -85
- package/skills/braincell/references/ion-library.md +0 -67
- package/skills/braincell/references/multicompartment/filter-function-library.md +0 -8
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +204 -65
- 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 +1 -1
- package/skills/brainx-general-guard/SKILL.md +43 -128
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +0 -303
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +0 -62
|
@@ -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
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# BrainState parameter transforms and regularizers catalog
|
|
2
|
+
|
|
3
|
+
Use this reference only from
|
|
4
|
+
`references/brainstate/parameter-constraints-regularization.md`, after that
|
|
5
|
+
parent has established the operational `nn.Param` workflow. It is the exhaustive
|
|
6
|
+
selection catalog for `brainstate.nn` parameter transforms and regularizers.
|
|
7
|
+
Return to the parent for `ParamState` versus `nn.Param`, `nn.Const`, forward
|
|
8
|
+
computation, optimizer targeting, and loss integration.
|
|
9
|
+
|
|
10
|
+
These are parameter-value transforms, not execution transforms such as `brainstate.transform.jit`, `grad`, or `vmap`.
|
|
11
|
+
|
|
12
|
+
## Transform contract
|
|
13
|
+
|
|
14
|
+
`nn.Transform` defines `forward()`, `inverse()`, and optional `log_abs_det_jacobian()` operations between stored and model-space values. `nn.Param` initializes its storage with `t.inverse(value)`, returns `t.forward(param.val)` from `param.value()`, and applies `t.inverse(value)` in `param.set_value()`.
|
|
15
|
+
|
|
16
|
+
The official API describes the family as bijective parameter transformations. The implementation also includes projection-like transforms such as `ClipT`, `ReluT`, and `UnitVectorT` whose forward operations are not one-to-one. Prefer a smooth bijection when unconstrained optimization and reversible change-of-variables semantics matter.
|
|
17
|
+
|
|
18
|
+
Official sources:
|
|
19
|
+
|
|
20
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
21
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Transform.html
|
|
22
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_transform.py
|
|
23
|
+
|
|
24
|
+
## Transform selection by target domain
|
|
25
|
+
|
|
26
|
+
The call forms below come from the current official `_transform.py` constructors. Check the installed-version generated class page before depending on a signature across BrainState releases.
|
|
27
|
+
|
|
28
|
+
### Identity, rescaling, and reparameterization
|
|
29
|
+
|
|
30
|
+
| Need | Class and current call form | Selection distinction |
|
|
31
|
+
|---|---|---|
|
|
32
|
+
| No constraint | `IdentityT()` | Default transform; stored and model values coincide. |
|
|
33
|
+
| Linear scale and shift | `AffineT(scale, shift)` | Applies a reversible affine reparameterization. |
|
|
34
|
+
| Box-Cox-style power map | `PowerT(lmbda=0.5)` | Select for the documented power transformation rather than a domain guarantee. |
|
|
35
|
+
|
|
36
|
+
### Positive, negative, and half-line values
|
|
37
|
+
|
|
38
|
+
| Need | Class and current call form | Selection distinction |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| Smooth value above a lower bound | `SoftplusT(lower)` | Maps the real line to `(lower, infinity)` with a softplus forward map. |
|
|
41
|
+
| Smooth value below an upper bound | `NegSoftplusT(upper)` | Maps the real line to `(-infinity, upper)` with a negative-softplus forward map. |
|
|
42
|
+
| Exponential value above a lower bound | `ExpT(lower)` | Maps the real line to `(lower, infinity)` with an exponential forward map. |
|
|
43
|
+
| Logarithmic forward reparameterization | `LogT(lower)` | `forward(x)` maps `(lower, infinity)` to the real line; its direction differs from `ExpT`. |
|
|
44
|
+
| ReLU lower bound | `ReluT(lower_bound=0.0)` | Projection-like lower bound; negative inputs collapse and the map is not one-to-one. |
|
|
45
|
+
| Strictly positive value | `PositiveT()` | Maps model values to `(0, infinity)`. |
|
|
46
|
+
| Strictly negative value | `NegativeT()` | Maps model values to `(-infinity, 0)`. |
|
|
47
|
+
|
|
48
|
+
`SoftplusT(lower)` is the canonical smooth positive-domain choice. Do not replace it with `ReluT` or clipping when the workflow needs gradients through a reversible unconstrained parameterization.
|
|
49
|
+
|
|
50
|
+
### Bounded values
|
|
51
|
+
|
|
52
|
+
| Need | Class and current call form | Selection distinction |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| Smooth open interval | `SigmoidT(lower, upper)` | Maps the real line to `(lower, upper)` and approaches, but does not cross, either bound. |
|
|
55
|
+
| Tanh-based open interval | `TanhT(lower, upper)` | Uses tanh for a bounded range. |
|
|
56
|
+
| Softsign-based open interval | `SoftsignT(lower, upper)` | Uses softsign for a bounded range. |
|
|
57
|
+
| Adjustable sigmoid sharpness | `ScaledSigmoidT(lower, upper, beta=1.0)` | Adds a `beta` sharpness/temperature control to the bounded sigmoid map. |
|
|
58
|
+
| Hard bounded projection | `ClipT(lower, upper)` | Clips in both `forward()` and `inverse()`; it is not a smooth bijection at or beyond the bounds. |
|
|
59
|
+
|
|
60
|
+
### Structured and composite values
|
|
61
|
+
|
|
62
|
+
| Need | Class and current call form | Selection distinction |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| Monotonically increasing entries | `OrderedT()` | Produces ordered output values. |
|
|
65
|
+
| Probability simplex | `SimplexT()` | Stick-breaking map to non-negative entries summing to one. An unconstrained final axis of length `n` produces a simplex axis of length `n + 1`. |
|
|
66
|
+
| Unit L2 norm | `UnitVectorT()` | Normalizes the input vector; the forward map is projection-like and its inverse returns the supplied value. |
|
|
67
|
+
| Sequential composition | `ChainT(*transforms)` | Applies transforms left to right in the supplied order and inverses in reverse order. |
|
|
68
|
+
| Selective transformation | `MaskedT(mask, transform, safe_value=1.0)` | Applies one transform only at Boolean-mask positions. |
|
|
69
|
+
|
|
70
|
+
Use the documented composition order:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
chained = nn.ChainT(
|
|
74
|
+
nn.AffineT(scale=2.0, shift=1.0),
|
|
75
|
+
nn.SoftplusT(lower=0.0),
|
|
76
|
+
)
|
|
77
|
+
value = chained.forward(jnp.array(0.0))
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`AffineT` runs first and `SoftplusT` runs second.
|
|
81
|
+
|
|
82
|
+
Official sources:
|
|
83
|
+
|
|
84
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
85
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
86
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
87
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_transform.py
|
|
88
|
+
|
|
89
|
+
## Regularization contract
|
|
90
|
+
|
|
91
|
+
`nn.Regularization` defines three operations:
|
|
92
|
+
|
|
93
|
+
- `loss(value)` returns the scalar penalty added to an objective.
|
|
94
|
+
- `sample_init(shape)` samples an initial value from the implied prior.
|
|
95
|
+
- `reset_value()` returns the value used by `nn.Param.reset_to_prior()`.
|
|
96
|
+
|
|
97
|
+
`nn.Param.reg_loss()` returns zero for a fixed parameter or a parameter without `reg=`; otherwise it evaluates `reg.loss(param.value())`. Attaching `reg=` never adds the result to the training objective automatically.
|
|
98
|
+
|
|
99
|
+
`nn.ChainedReg(*regularizations, weight=1.0, fit_hyper=False)` sums its component losses and multiplies the result by the overall weight. Its `sample_init()` and `reset_value()` use the first component.
|
|
100
|
+
|
|
101
|
+
Official sources:
|
|
102
|
+
|
|
103
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
104
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Regularization.html
|
|
105
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
|
|
106
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_regularization.py
|
|
107
|
+
|
|
108
|
+
## Classical and structural regularizer selection
|
|
109
|
+
|
|
110
|
+
| Modeling intent | Official API |
|
|
111
|
+
|---|---|
|
|
112
|
+
| Abstract regularization contract | `Regularization` |
|
|
113
|
+
| L1/Lasso sparsity | `L1Reg` |
|
|
114
|
+
| L2/Ridge shrinkage | `L2Reg` |
|
|
115
|
+
| Combined L1 and L2 | `ElasticNetReg` |
|
|
116
|
+
| Robust penalty | `HuberReg` |
|
|
117
|
+
| Group sparsity | `GroupLassoReg` |
|
|
118
|
+
| Total variation or local smoothness | `TotalVariationReg` |
|
|
119
|
+
| Soft maximum-norm pressure | `MaxNormReg` |
|
|
120
|
+
| Entropy pressure | `EntropyReg` |
|
|
121
|
+
| Orthogonal structure | `OrthogonalReg` |
|
|
122
|
+
| Spectral-norm structure | `SpectralNormReg` |
|
|
123
|
+
| Several penalties on one value | `ChainedReg` |
|
|
124
|
+
|
|
125
|
+
Use the generated class page for exact axes, reduction behavior, weights, and initialization arguments; these differ by regularizer and should not be inferred from neighboring classes.
|
|
126
|
+
|
|
127
|
+
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
128
|
+
|
|
129
|
+
## Prior-distribution regularizer selection
|
|
130
|
+
|
|
131
|
+
Prior regularizers encode distributional assumptions for Bayesian-inspired parameter estimation. Match both the scientific assumption and the prior's support. A regularizer contributes a preference through the loss; attach a transform separately when the parameter must remain in that support by construction.
|
|
132
|
+
|
|
133
|
+
| Parameter assumption | Official API |
|
|
134
|
+
|---|---|
|
|
135
|
+
| Gaussian prior | `GaussianReg` |
|
|
136
|
+
| Student's t prior | `StudentTReg` |
|
|
137
|
+
| Cauchy prior | `CauchyReg` |
|
|
138
|
+
| Bounded uniform prior | `UniformReg` |
|
|
139
|
+
| Value in `[0, 1]` under a Beta prior | `BetaReg` |
|
|
140
|
+
| Positive value under a log-normal prior | `LogNormalReg` |
|
|
141
|
+
| Positive value under an exponential prior | `ExponentialReg` |
|
|
142
|
+
| Positive value under a Gamma prior | `GammaReg` |
|
|
143
|
+
| Variance under an inverse-Gamma prior | `InverseGammaReg` |
|
|
144
|
+
| Scale-invariant log-uniform/Jeffreys prior | `LogUniformReg` |
|
|
145
|
+
| Strong sparsity with heavy tails | `HorseshoeReg` |
|
|
146
|
+
| Variable selection | `SpikeAndSlabReg` |
|
|
147
|
+
| Probability simplex | `DirichletReg` |
|
|
148
|
+
|
|
149
|
+
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
150
|
+
|
|
151
|
+
## Interaction safeguards
|
|
152
|
+
|
|
153
|
+
- Keep transform direction explicit: `nn.Param.value()` calls `forward()`, while initialization and `set_value()` call `inverse()`.
|
|
154
|
+
- Do not treat `LogT` and `ExpT` as interchangeable; their documented forward directions are opposite.
|
|
155
|
+
- Do not treat a projection-like transform as a smooth bijective change of variables.
|
|
156
|
+
- Do not assume `SimplexT` preserves the final-axis length.
|
|
157
|
+
- Apply `ChainT` in listed order and invert it in reverse order.
|
|
158
|
+
- Use `MaskedT` for Boolean-mask selection instead of hand-rolling selective transformation.
|
|
159
|
+
- Current source makes transformed-value caching explicit: `param.cache()` populates it, writes invalidate it, and `param.value()` otherwise recomputes without populating it.
|
|
160
|
+
- `reset_to_prior()` uses `reg.reset_value()`; use `reg.sample_init(shape)` separately when a random prior draw is required.
|
|
161
|
+
- Return to `parameter-constraints-regularization.md` for objective integration and complete workflow code.
|
|
162
|
+
|
|
163
|
+
## Mirror source urls
|
|
164
|
+
|
|
165
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
166
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
167
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
168
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
169
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_param.py
|
|
170
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_transform.py
|
|
171
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_regularization.py
|