brainx-skill 1.0.2 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +24 -56
- package/{lib → installation/lib}/installer.js +4 -4
- package/manifest.json +3 -1
- package/package.json +19 -9
- package/skills/brainstate/SKILL.md +399 -0
- package/skills/brainstate/agents/openai.yaml +4 -0
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +483 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +176 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +199 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +166 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +210 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +450 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +157 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +286 -0
- package/skills/brainstate/references/braintools-optimizer-reference.md +133 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +282 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +217 -0
- package/skills/brainstate/references/libraries/solver-library-with-effects.md +85 -0
- package/skills/brainstate/references/model-interop-and-migration.md +295 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +268 -0
- package/skills/brainstate/references/state-graph-operations.md +218 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +224 -0
- package/skills/brainstate/scripts/integrator_rnn.py +359 -0
- package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
- package/skills/brainstate/scripts/modern_cnn.py +73 -0
- package/skills/brainstate/scripts/resnet.py +130 -0
- package/skills/brainunit/SKILL.md +287 -0
- package/skills/brainunit/references/array-creation.md +158 -0
- package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
- package/skills/brainunit/references/array-mechanics.md +165 -0
- package/skills/brainunit/references/math-function-library.md +433 -0
- package/skills/brainunit/references/physical-constant-library.md +58 -0
- package/skills/brainunit/references/prefix-library.md +116 -0
- package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
- package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
- package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
- package/skills/brainx-install/SKILL.md +21 -13
- package/skills/brainx-install/references/compatibility-and-release-matching.md +12 -10
- package/skills/brainx-install/references/uninstall-and-cleanup.md +186 -0
- /package/{bin → installation/bin}/brainx.js +0 -0
- /package/{lib → installation/lib}/adapter-transaction.js +0 -0
- /package/{lib → installation/lib}/bundle.js +0 -0
- /package/{lib → installation/lib}/cli.js +0 -0
- /package/{lib → installation/lib}/constants.js +0 -0
- /package/{lib → installation/lib}/hash.js +0 -0
- /package/{lib → installation/lib}/paths.js +0 -0
- /package/{lib → installation/lib}/prompts.js +0 -0
- /package/{lib → installation/lib}/receipt.js +0 -0
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
# Brainstate constrained and regularized parameters
|
|
2
|
+
|
|
3
|
+
Use this first-layer reference after `skills/brainstate/SKILL.md` has selected `brainstate.nn.Param` for a value that needs a valid-domain transform, a regularization penalty, a modeling prior, or fixed parameter-like storage. It owns the operational workflow and common patterns. Open `references/brainstate/parameter-transforms-regularizers-catalog.md` only when selecting an exact built-in transform or regularizer beyond the common choices shown here.
|
|
4
|
+
|
|
5
|
+
Keep `brainstate.nn` parameter transforms separate from execution transforms such as `brainstate.transform.jit`, `grad`, and `vmap`.
|
|
6
|
+
|
|
7
|
+
## Parameter contract
|
|
8
|
+
|
|
9
|
+
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.
|
|
10
|
+
|
|
11
|
+
- `param.val` is the underlying `ParamState`; optimizers update its unconstrained array.
|
|
12
|
+
- `param.value()` applies the forward transform and returns the constrained model-space value. With the default `IdentityT`, constrained and unconstrained values coincide.
|
|
13
|
+
- `param.set_value(value)` applies the inverse transform when storing a constrained value back.
|
|
14
|
+
- `param.reg_loss()` evaluates the attached `reg=` object on the current constrained value. The loss function must explicitly add this penalty to its objective.
|
|
15
|
+
- `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.
|
|
16
|
+
|
|
17
|
+
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.
|
|
18
|
+
|
|
19
|
+
Official sources:
|
|
20
|
+
|
|
21
|
+
- https://brainx.chaobrain.com/brainstate/concepts/the_parameter_model.html
|
|
22
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
23
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
24
|
+
|
|
25
|
+
## Canonical constrained training workflow
|
|
26
|
+
|
|
27
|
+
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:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import brainstate
|
|
31
|
+
from brainstate import nn
|
|
32
|
+
import brainunit as u
|
|
33
|
+
import jax.numpy as jnp
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ConstrainedLinear(nn.Module):
|
|
37
|
+
def __init__(self, din, dout):
|
|
38
|
+
super().__init__()
|
|
39
|
+
self.w = nn.Param(
|
|
40
|
+
brainstate.random.randn(din, dout) * 0.1,
|
|
41
|
+
reg=nn.L2Reg(1e-3),
|
|
42
|
+
)
|
|
43
|
+
self.gain = nn.Param(
|
|
44
|
+
jnp.array(1.0),
|
|
45
|
+
t=nn.SoftplusT(lower=0.0),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def __call__(self, x):
|
|
49
|
+
return (x @ self.w.value()) * self.gain.value()
|
|
50
|
+
|
|
51
|
+
def reg_penalty(self):
|
|
52
|
+
return sum(p.reg_loss() for p in self.nodes(nn.Param).values())
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
model = ConstrainedLinear(4, 2)
|
|
56
|
+
params = model.states(brainstate.ParamState)
|
|
57
|
+
x = brainstate.random.randn(16, 4)
|
|
58
|
+
y = brainstate.random.randn(16, 2)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def loss_fn():
|
|
62
|
+
mse = jnp.mean((model(x) - y) ** 2)
|
|
63
|
+
return mse + u.get_magnitude(model.reg_penalty())
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@brainstate.transform.jit
|
|
67
|
+
def train_step():
|
|
68
|
+
grads, loss = brainstate.transform.grad(
|
|
69
|
+
loss_fn,
|
|
70
|
+
params,
|
|
71
|
+
return_value=True,
|
|
72
|
+
)()
|
|
73
|
+
for key in params:
|
|
74
|
+
params[key].value -= 0.1 * grads[key]
|
|
75
|
+
return loss
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`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()`.
|
|
79
|
+
|
|
80
|
+
Official sources:
|
|
81
|
+
|
|
82
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
83
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
84
|
+
|
|
85
|
+
## Common constraint patterns
|
|
86
|
+
|
|
87
|
+
Use `.value()` in model computation. Mutate `.val.value` only as optimizer-side, unconstrained storage.
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
rate = nn.Param(
|
|
91
|
+
jnp.array(0.5),
|
|
92
|
+
t=nn.SoftplusT(lower=0.0),
|
|
93
|
+
)
|
|
94
|
+
rate.val.value = jnp.array(-10.0)
|
|
95
|
+
assert float(u.get_magnitude(rate.value())) > 0.0
|
|
96
|
+
|
|
97
|
+
mix = nn.Param(
|
|
98
|
+
jnp.array(0.5),
|
|
99
|
+
t=nn.SigmoidT(lower=0.0, upper=1.0),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
probs = nn.Param(
|
|
103
|
+
jnp.zeros(3),
|
|
104
|
+
t=nn.SimplexT(),
|
|
105
|
+
)
|
|
106
|
+
p = u.get_magnitude(probs.value())
|
|
107
|
+
assert jnp.all(p >= 0.0)
|
|
108
|
+
assert jnp.isclose(p.sum(), 1.0)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
- `SoftplusT(lower)` smoothly maps the real line to `(lower, infinity)`.
|
|
112
|
+
- `SigmoidT(lower, upper)` smoothly maps to the open interval `(lower, upper)`.
|
|
113
|
+
- `SimplexT()` produces non-negative entries that sum to one. Its output has one more final-axis entry than its unconstrained input.
|
|
114
|
+
|
|
115
|
+
Open `parameter-transforms-regularizers-catalog.md` for negative, symmetric bounded, ordered, unit-vector, masked, composite, or projection-like transforms.
|
|
116
|
+
|
|
117
|
+
Official source: https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
118
|
+
|
|
119
|
+
## Regularization patterns
|
|
120
|
+
|
|
121
|
+
Call `reg.loss(value)` directly for a standalone penalty, or attach the regularizer with `reg=` and call `param.reg_loss()`:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
weights = jnp.array([3.0, -4.0])
|
|
125
|
+
|
|
126
|
+
l1_penalty = nn.L1Reg(0.1).loss(weights)
|
|
127
|
+
l2_penalty = nn.L2Reg(0.1).loss(weights)
|
|
128
|
+
|
|
129
|
+
p = nn.Param(
|
|
130
|
+
weights,
|
|
131
|
+
reg=nn.ElasticNetReg(
|
|
132
|
+
l1_weight=1.0,
|
|
133
|
+
l2_weight=1.0,
|
|
134
|
+
alpha=0.5,
|
|
135
|
+
),
|
|
136
|
+
)
|
|
137
|
+
elastic_net_penalty = p.reg_loss()
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
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.
|
|
141
|
+
|
|
142
|
+
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()`.
|
|
143
|
+
|
|
144
|
+
Open `parameter-transforms-regularizers-catalog.md` to select classical, structural, or prior-distribution regularizers.
|
|
145
|
+
|
|
146
|
+
Official sources:
|
|
147
|
+
|
|
148
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
149
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
150
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
|
|
151
|
+
|
|
152
|
+
## Fixed values with `nn.Const`
|
|
153
|
+
|
|
154
|
+
Use `nn.Const` when a value belongs in the module graph and forward computation but must not be collected as trainable state:
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
class Scaler(nn.Module):
|
|
158
|
+
def __init__(self):
|
|
159
|
+
super().__init__()
|
|
160
|
+
self.weight = nn.Param(jnp.ones(3))
|
|
161
|
+
self.gain = nn.Const(jnp.array(2.0))
|
|
162
|
+
|
|
163
|
+
def __call__(self, x):
|
|
164
|
+
return x * self.weight.value() * self.gain.value()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
model = Scaler()
|
|
168
|
+
trainable = model.states(brainstate.ParamState)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
`trainable` contains the underlying State for `weight`; `gain` is absent. `Const` means non-trainable, not immutable: explicit `set_value()` calls can still change it.
|
|
172
|
+
|
|
173
|
+
Official sources:
|
|
174
|
+
|
|
175
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
176
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Const.html
|
|
177
|
+
|
|
178
|
+
## Decision and failure rules
|
|
179
|
+
|
|
180
|
+
- Need only a valid domain: attach `t=` without inventing a regularizer.
|
|
181
|
+
- Need only a penalty or modeling prior: attach `reg=` without inventing a transform.
|
|
182
|
+
- Need both: attach `t=` and `reg=` to the same `nn.Param`, read `.value()` in the model, and add `.reg_loss()` to the objective.
|
|
183
|
+
- Need a fixed graph value: use `nn.Const`; do not expect it in a `ParamState` collection.
|
|
184
|
+
- Need an exact built-in transform or regularizer: open `parameter-transforms-regularizers-catalog.md`.
|
|
185
|
+
- Never read `param.val` as the constrained forward value or update `param.value()` as optimizer storage.
|
|
186
|
+
- Do not treat `SigmoidT` bounds as inclusive or `SoftplusT(lower)` as able to attain `lower`.
|
|
187
|
+
- Do not attach regularization and assume the training objective includes it automatically.
|
|
188
|
+
- Match a prior's support to the parameter domain; use `t=` when the domain must be guaranteed by construction.
|
|
189
|
+
- Do not assume every `nn.Transform` subclass is a smooth bijection; the catalog distinguishes projection-like transforms.
|
|
190
|
+
|
|
191
|
+
## Mirror source urls
|
|
192
|
+
|
|
193
|
+
- https://brainx.chaobrain.com/brainstate/concepts/the_parameter_model.html
|
|
194
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
195
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
196
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
197
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
198
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Param.html
|
|
199
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Const.html
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# Brainstate parameter transforms and regularizers catalog
|
|
2
|
+
|
|
3
|
+
This is the exhaustive selection reference for `brainstate.nn` parameter transforms and regularizers. Open it only from `references/brainstate/parameter-constraints-regularization.md`, after that parent has established the operational `nn.Param` workflow. Return to the parent for `ParamState` versus `nn.Param`, `nn.Const`, forward computation, optimizer targeting, and loss integration.
|
|
4
|
+
|
|
5
|
+
These are parameter-value transforms, not execution transforms such as `brainstate.transform.jit`, `grad`, or `vmap`.
|
|
6
|
+
|
|
7
|
+
## Transform contract
|
|
8
|
+
|
|
9
|
+
`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()`.
|
|
10
|
+
|
|
11
|
+
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.
|
|
12
|
+
|
|
13
|
+
Official sources:
|
|
14
|
+
|
|
15
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
16
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Transform.html
|
|
17
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_transform.py
|
|
18
|
+
|
|
19
|
+
## Transform selection by target domain
|
|
20
|
+
|
|
21
|
+
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.
|
|
22
|
+
|
|
23
|
+
### Identity, rescaling, and reparameterization
|
|
24
|
+
|
|
25
|
+
| Need | Class and current call form | Selection distinction |
|
|
26
|
+
|---|---|---|
|
|
27
|
+
| No constraint | `IdentityT()` | Default transform; stored and model values coincide. |
|
|
28
|
+
| Linear scale and shift | `AffineT(scale, shift)` | Applies a reversible affine reparameterization. |
|
|
29
|
+
| Box-Cox-style power map | `PowerT(lmbda=0.5)` | Select for the documented power transformation rather than a domain guarantee. |
|
|
30
|
+
|
|
31
|
+
### Positive, negative, and half-line values
|
|
32
|
+
|
|
33
|
+
| Need | Class and current call form | Selection distinction |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| Smooth value above a lower bound | `SoftplusT(lower)` | Maps the real line to `(lower, infinity)` with a softplus forward map. |
|
|
36
|
+
| Smooth value below an upper bound | `NegSoftplusT(upper)` | Maps the real line to `(-infinity, upper)` with a negative-softplus forward map. |
|
|
37
|
+
| Exponential value above a lower bound | `ExpT(lower)` | Maps the real line to `(lower, infinity)` with an exponential forward map. |
|
|
38
|
+
| Logarithmic forward reparameterization | `LogT(lower)` | `forward(x)` maps `(lower, infinity)` to the real line; its direction differs from `ExpT`. |
|
|
39
|
+
| ReLU lower bound | `ReluT(lower_bound=0.0)` | Projection-like lower bound; negative inputs collapse and the map is not one-to-one. |
|
|
40
|
+
| Strictly positive value | `PositiveT()` | Maps model values to `(0, infinity)`. |
|
|
41
|
+
| Strictly negative value | `NegativeT()` | Maps model values to `(-infinity, 0)`. |
|
|
42
|
+
|
|
43
|
+
`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.
|
|
44
|
+
|
|
45
|
+
### Bounded values
|
|
46
|
+
|
|
47
|
+
| Need | Class and current call form | Selection distinction |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| Smooth open interval | `SigmoidT(lower, upper)` | Maps the real line to `(lower, upper)` and approaches, but does not cross, either bound. |
|
|
50
|
+
| Tanh-based open interval | `TanhT(lower, upper)` | Uses tanh for a bounded range. |
|
|
51
|
+
| Softsign-based open interval | `SoftsignT(lower, upper)` | Uses softsign for a bounded range. |
|
|
52
|
+
| Adjustable sigmoid sharpness | `ScaledSigmoidT(lower, upper, beta=1.0)` | Adds a `beta` sharpness/temperature control to the bounded sigmoid map. |
|
|
53
|
+
| Hard bounded projection | `ClipT(lower, upper)` | Clips in both `forward()` and `inverse()`; it is not a smooth bijection at or beyond the bounds. |
|
|
54
|
+
|
|
55
|
+
### Structured and composite values
|
|
56
|
+
|
|
57
|
+
| Need | Class and current call form | Selection distinction |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| Monotonically increasing entries | `OrderedT()` | Produces ordered output values. |
|
|
60
|
+
| 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`. |
|
|
61
|
+
| Unit L2 norm | `UnitVectorT()` | Normalizes the input vector; the forward map is projection-like and its inverse returns the supplied value. |
|
|
62
|
+
| Sequential composition | `ChainT(*transforms)` | Applies transforms left to right in the supplied order and inverses in reverse order. |
|
|
63
|
+
| Selective transformation | `MaskedT(mask, transform, safe_value=1.0)` | Applies one transform only at Boolean-mask positions. |
|
|
64
|
+
|
|
65
|
+
Use the documented composition order:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
chained = nn.ChainT(
|
|
69
|
+
nn.AffineT(scale=2.0, shift=1.0),
|
|
70
|
+
nn.SoftplusT(lower=0.0),
|
|
71
|
+
)
|
|
72
|
+
value = chained.forward(jnp.array(0.0))
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`AffineT` runs first and `SoftplusT` runs second.
|
|
76
|
+
|
|
77
|
+
Official sources:
|
|
78
|
+
|
|
79
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
80
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
81
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
82
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_transform.py
|
|
83
|
+
|
|
84
|
+
## Regularization contract
|
|
85
|
+
|
|
86
|
+
`nn.Regularization` defines three operations:
|
|
87
|
+
|
|
88
|
+
- `loss(value)` returns the scalar penalty added to an objective.
|
|
89
|
+
- `sample_init(shape)` samples an initial value from the implied prior.
|
|
90
|
+
- `reset_value()` returns the value used by `nn.Param.reset_to_prior()`.
|
|
91
|
+
|
|
92
|
+
`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.
|
|
93
|
+
|
|
94
|
+
`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.
|
|
95
|
+
|
|
96
|
+
Official sources:
|
|
97
|
+
|
|
98
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
99
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Regularization.html
|
|
100
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
|
|
101
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_regularization.py
|
|
102
|
+
|
|
103
|
+
## Classical and structural regularizer selection
|
|
104
|
+
|
|
105
|
+
| Modeling intent | Official API |
|
|
106
|
+
|---|---|
|
|
107
|
+
| Abstract regularization contract | `Regularization` |
|
|
108
|
+
| L1/Lasso sparsity | `L1Reg` |
|
|
109
|
+
| L2/Ridge shrinkage | `L2Reg` |
|
|
110
|
+
| Combined L1 and L2 | `ElasticNetReg` |
|
|
111
|
+
| Robust penalty | `HuberReg` |
|
|
112
|
+
| Group sparsity | `GroupLassoReg` |
|
|
113
|
+
| Total variation or local smoothness | `TotalVariationReg` |
|
|
114
|
+
| Soft maximum-norm pressure | `MaxNormReg` |
|
|
115
|
+
| Entropy pressure | `EntropyReg` |
|
|
116
|
+
| Orthogonal structure | `OrthogonalReg` |
|
|
117
|
+
| Spectral-norm structure | `SpectralNormReg` |
|
|
118
|
+
| Several penalties on one value | `ChainedReg` |
|
|
119
|
+
|
|
120
|
+
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.
|
|
121
|
+
|
|
122
|
+
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
123
|
+
|
|
124
|
+
## Prior-distribution regularizer selection
|
|
125
|
+
|
|
126
|
+
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.
|
|
127
|
+
|
|
128
|
+
| Parameter assumption | Official API |
|
|
129
|
+
|---|---|
|
|
130
|
+
| Gaussian prior | `GaussianReg` |
|
|
131
|
+
| Student's t prior | `StudentTReg` |
|
|
132
|
+
| Cauchy prior | `CauchyReg` |
|
|
133
|
+
| Bounded uniform prior | `UniformReg` |
|
|
134
|
+
| Value in `[0, 1]` under a Beta prior | `BetaReg` |
|
|
135
|
+
| Positive value under a log-normal prior | `LogNormalReg` |
|
|
136
|
+
| Positive value under an exponential prior | `ExponentialReg` |
|
|
137
|
+
| Positive value under a Gamma prior | `GammaReg` |
|
|
138
|
+
| Variance under an inverse-Gamma prior | `InverseGammaReg` |
|
|
139
|
+
| Scale-invariant log-uniform/Jeffreys prior | `LogUniformReg` |
|
|
140
|
+
| Strong sparsity with heavy tails | `HorseshoeReg` |
|
|
141
|
+
| Variable selection | `SpikeAndSlabReg` |
|
|
142
|
+
| Probability simplex | `DirichletReg` |
|
|
143
|
+
|
|
144
|
+
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
145
|
+
|
|
146
|
+
## Interaction safeguards
|
|
147
|
+
|
|
148
|
+
- Keep transform direction explicit: `nn.Param.value()` calls `forward()`, while initialization and `set_value()` call `inverse()`.
|
|
149
|
+
- Do not treat `LogT` and `ExpT` as interchangeable; their documented forward directions are opposite.
|
|
150
|
+
- Do not treat a projection-like transform as a smooth bijective change of variables.
|
|
151
|
+
- Do not assume `SimplexT` preserves the final-axis length.
|
|
152
|
+
- Apply `ChainT` in listed order and invert it in reverse order.
|
|
153
|
+
- Use `MaskedT` for Boolean-mask selection instead of hand-rolling selective transformation.
|
|
154
|
+
- Current source makes transformed-value caching explicit: `param.cache()` populates it, writes invalidate it, and `param.value()` otherwise recomputes without populating it.
|
|
155
|
+
- `reset_to_prior()` uses `reg.reset_value()`; use `reg.sample_init(shape)` separately when a random prior draw is required.
|
|
156
|
+
- Return to `parameter-constraints-regularization.md` for objective integration and complete workflow code.
|
|
157
|
+
|
|
158
|
+
## Mirror source urls
|
|
159
|
+
|
|
160
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
161
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
162
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
163
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
164
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_param.py
|
|
165
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_transform.py
|
|
166
|
+
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_regularization.py
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
# Brainstate randomness and reproducibility
|
|
2
|
+
|
|
3
|
+
Open this reference after `skills/brainstate/SKILL.md` when a task needs independent streams, repeated stochastic trials, random calls inside a transformed operation, dropout or noise, direct key control, parallel key preparation, exact replay, or RNG state stored with a checkpoint.
|
|
4
|
+
|
|
5
|
+
The skill owns the global `DEFAULT` generator and ordinary seeding path; do not repeat those basics here. The supplemental rule is that `brainstate.random` wraps JAX random generation in a stateful interface with automatic key splitting, while its random functions remain JIT-compatible.
|
|
6
|
+
|
|
7
|
+
Source: https://brainx.chaobrain.com/brainstate/apis/random.html
|
|
8
|
+
|
|
9
|
+
## Independent streams and repeated trials
|
|
10
|
+
|
|
11
|
+
"For advanced use cases, you can create custom `RandomState` instances with independent random streams." Use one `RandomState` per concern whose sequence must advance independently, such as data augmentation and model initialization. Consecutive calls on one instance are successive stochastic trials from that stream.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import brainstate
|
|
15
|
+
import jax.numpy as jnp
|
|
16
|
+
|
|
17
|
+
rng1 = brainstate.random.RandomState(42)
|
|
18
|
+
rng2 = brainstate.random.RandomState(123)
|
|
19
|
+
|
|
20
|
+
samples1 = rng1.randn(5)
|
|
21
|
+
samples2 = rng2.randn(5)
|
|
22
|
+
|
|
23
|
+
assert not jnp.allclose(samples1, samples2)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The API also supports the explicit keyword form `brainstate.random.RandomState(seed=123)` and instance methods such as `rng.normal(0, 1, size=(10, 10))`. Use the advanced section below when the task requires direct key manipulation.
|
|
27
|
+
|
|
28
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
|
|
29
|
+
|
|
30
|
+
## Stochastic calls, transforms, dropout, and noise
|
|
31
|
+
|
|
32
|
+
BrainState random functions are JIT-compatible. Apply the whole-operation `brainstate.transform` rule from `skills/brainstate/SKILL.md` to stochastic code just as you do to other stateful code. The advanced section below covers mapped randomness under `vmap`, parallel key assignment, and explicit key control.
|
|
33
|
+
|
|
34
|
+
The tutorial's dropout pattern bundles fit-mode gating, mask generation, and inverse-keep scaling in the stochastic call:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
class Dropout(brainstate.nn.Module):
|
|
38
|
+
def __init__(self, drop_rate=0.5):
|
|
39
|
+
super().__init__()
|
|
40
|
+
self.drop_rate = drop_rate
|
|
41
|
+
|
|
42
|
+
def __call__(self, x):
|
|
43
|
+
fit = brainstate.environ.get('fit', False)
|
|
44
|
+
if not fit:
|
|
45
|
+
return x
|
|
46
|
+
|
|
47
|
+
keep_prob = 1.0 - self.drop_rate
|
|
48
|
+
mask = brainstate.random.bernoulli(keep_prob, x.shape)
|
|
49
|
+
return x * mask / keep_prob
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
When `fit` is false, the module returns `x` unchanged. When fitting, `bernoulli` draws the mask with mean `keep_prob`, and division by `keep_prob` applies the tutorial's scaling.
|
|
53
|
+
|
|
54
|
+
The tutorial's noisy-layer pattern keeps trainable values in `ParamState` and draws fresh Gaussian weight noise inside every call. Two consecutive calls are two stochastic trials because automatic key management advances the random state.
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
class NoisyLayer(brainstate.nn.Module):
|
|
58
|
+
def __init__(self, d_in, d_out, noise_std=0.1):
|
|
59
|
+
super().__init__()
|
|
60
|
+
self.noise_std = noise_std
|
|
61
|
+
self.w = brainstate.ParamState(
|
|
62
|
+
brainstate.random.randn(d_in, d_out) * 0.1
|
|
63
|
+
)
|
|
64
|
+
self.b = brainstate.ParamState(jnp.zeros(d_out))
|
|
65
|
+
|
|
66
|
+
def __call__(self, x):
|
|
67
|
+
w_noisy = self.w.value + brainstate.random.normal(
|
|
68
|
+
0,
|
|
69
|
+
self.noise_std,
|
|
70
|
+
self.w.value.shape,
|
|
71
|
+
)
|
|
72
|
+
return x @ w_noisy + self.b.value
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
layer = NoisyLayer(5, 3, noise_std=0.01)
|
|
76
|
+
x = jnp.ones(5)
|
|
77
|
+
y1 = layer(x)
|
|
78
|
+
y2 = layer(x)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
|
|
82
|
+
|
|
83
|
+
## Checkpoint the rng with the model
|
|
84
|
+
|
|
85
|
+
When exact stochastic continuation matters, the tutorial saves the model and current RNG key in the same checkpoint, then restores the key before continuing:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
checkpoint = {
|
|
89
|
+
'model': model.state_dict(),
|
|
90
|
+
'rng_key': brainstate.random.get_key()
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
brainstate.random.set_key(checkpoint['rng_key'])
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Keep this compact checkpoint requirement here because it determines what must be saved. Read the advanced section below before adapting key restoration, restoring multiple streams, or defining more elaborate checkpoint behavior.
|
|
97
|
+
|
|
98
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
|
|
99
|
+
|
|
100
|
+
## Advanced brainstate randomness
|
|
101
|
+
|
|
102
|
+
Use this section when a task needs direct key control, parallel key preparation, exact key replay, custom-generator state inspection, or checkpoint behavior beyond the ordinary stochastic path above.
|
|
103
|
+
|
|
104
|
+
### Snapshot a global key and replay from it
|
|
105
|
+
|
|
106
|
+
The tutorial's advanced boundary is: "For advanced use cases, you can directly access and manipulate keys." Bundle inspection and restoration with the operation whose randomness must be replayed:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
import brainstate
|
|
110
|
+
import jax.numpy as jnp
|
|
111
|
+
|
|
112
|
+
saved_key = brainstate.random.get_key()
|
|
113
|
+
v1 = brainstate.random.randn(3)
|
|
114
|
+
_ = brainstate.random.randn(3)
|
|
115
|
+
|
|
116
|
+
brainstate.random.set_key(saved_key)
|
|
117
|
+
v1_replayed = brainstate.random.randn(3)
|
|
118
|
+
|
|
119
|
+
assert jnp.allclose(v1, v1_replayed)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The snapshot is the sequence position immediately before `v1`; restoring it makes the next draw reproduce `v1`. Use `get_key()` / `set_key(...)` for this explicit snapshot-and-replay contract. Keep `restore_key()` distinct: the API describes it only as restoring "the default random key to its previous state," so do not silently substitute it for a named checkpoint snapshot.
|
|
123
|
+
|
|
124
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
|
|
125
|
+
|
|
126
|
+
API definitions: https://brainx.chaobrain.com/brainstate/apis/random.html
|
|
127
|
+
|
|
128
|
+
### Prepare keys for parallel or mapped work
|
|
129
|
+
|
|
130
|
+
The API groups these as "Functions for creating independent random keys for parallel computation." The tutorial's documented parallel preparation is:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
keys = brainstate.random.split_key(n=4)
|
|
134
|
+
|
|
135
|
+
for i, key in enumerate(keys):
|
|
136
|
+
print(i, key)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Select the narrowest documented operation:
|
|
140
|
+
|
|
141
|
+
| API | Documented role |
|
|
142
|
+
|---|---|
|
|
143
|
+
| `split_key` | Create new random key(s) from the current seed. The tutorial uses `split_key(n=4)` for parallel operations. |
|
|
144
|
+
| `split_keys` | Create multiple independent random keys from the current seed. |
|
|
145
|
+
| `self_assign_multi_keys` | Assign multiple keys to the global random state for parallel access. |
|
|
146
|
+
|
|
147
|
+
The routed pages do not provide a `vmap` call, mapped key-axis configuration, or per-example key-consumption rule. They only identify `vmap` as a next step and document the parallel key utilities above. Do not invent mapped semantics from these pages; combine these RNG operations with a separately documented BrainState mapping workflow when concrete `vmap` mechanics are required.
|
|
148
|
+
|
|
149
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
|
|
150
|
+
|
|
151
|
+
API definitions: https://brainx.chaobrain.com/brainstate/apis/random.html
|
|
152
|
+
|
|
153
|
+
### Inspect custom-stream state and choose advanced generators
|
|
154
|
+
|
|
155
|
+
After selecting a custom `RandomState`, the API documents its current key through `.value`:
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
rng = brainstate.random.RandomState(seed=123)
|
|
159
|
+
_ = rng.normal(0, 1, size=(10, 10))
|
|
160
|
+
current_stream_key = rng.value
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
This is the documented custom-stream state inspection surface. The routed pages demonstrate reseeding a custom generator with `rng.seed(999)`, but they do not demonstrate assigning a saved value back to a custom generator or restoring several custom streams. Do not apply the global `set_key(...)` API to `rng`: its documented target is the global random state.
|
|
164
|
+
|
|
165
|
+
For generator selection without restating the independent-stream example above:
|
|
166
|
+
|
|
167
|
+
| API | Documented role |
|
|
168
|
+
|---|---|
|
|
169
|
+
| `default_rng` | Get the default random state or create a new one with a specified seed. |
|
|
170
|
+
| `clone_rng` | Create a clone of the random state or a new random state. |
|
|
171
|
+
| `seed_context` | Temporarily change the random seed with automatic restoration. |
|
|
172
|
+
|
|
173
|
+
The same API page's example spells the temporary context as `local_seed(123)`, while its API table lists `seed_context`. Because the routed source is internally inconsistent, verify the installed BrainState version before choosing the callable name.
|
|
174
|
+
|
|
175
|
+
Source: https://brainx.chaobrain.com/brainstate/apis/random.html
|
|
176
|
+
|
|
177
|
+
Custom reseeding example: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
|
|
178
|
+
|
|
179
|
+
### Checkpoint at the intended sequence boundary
|
|
180
|
+
|
|
181
|
+
The tutorial's checkpoint pattern stores the current global key beside the model and restores that exact key before stochastic work resumes:
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
checkpoint = {
|
|
185
|
+
'model': model.state_dict(),
|
|
186
|
+
'rng_key': brainstate.random.get_key(),
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
# Restore model state through the model's checkpoint path first.
|
|
190
|
+
brainstate.random.set_key(checkpoint['rng_key'])
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Capture `rng_key` after every random operation that belongs to the completed portion of the run. Restoring an earlier snapshot intentionally replays draws after that snapshot, as the replay script above demonstrates. A checkpoint with multiple custom streams additionally needs each stream's current key, but these routed pages document only reading a custom key through `rng.value`; they do not supply a multi-stream restoration script. Keep such restoration out of generated code until a source for that specific mechanism is selected.
|
|
194
|
+
|
|
195
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
|
|
196
|
+
|
|
197
|
+
### Key api distinctions
|
|
198
|
+
|
|
199
|
+
- `get_key()` returns the current global random key.
|
|
200
|
+
- `get_key_data()` returns the current global random key as raw `uint32[2]` data; use it only when raw key data is the required interchange form.
|
|
201
|
+
- `set_key(...)` sets a new key on the global random state.
|
|
202
|
+
- `restore_key()` restores the default key to its previous state.
|
|
203
|
+
- `RandomState.value` is the API page's documented way to inspect the current key of a custom generator.
|
|
204
|
+
|
|
205
|
+
Source: https://brainx.chaobrain.com/brainstate/apis/random.html
|
|
206
|
+
|
|
207
|
+
## Official sources
|
|
208
|
+
|
|
209
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
|
|
210
|
+
- https://brainx.chaobrain.com/brainstate/apis/random.html
|