brainx-skill 1.0.3 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +29 -64
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/{lib → installation/lib}/installer.js +8 -5
- package/manifest.json +7 -1
- package/package.json +25 -10
- package/skills/braincell/SKILL.md +182 -0
- package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
- package/skills/braincell/references/channel-library.md +170 -0
- package/skills/braincell/references/ion-library.md +154 -0
- package/skills/braincell/references/mixions-for-adaptation.md +81 -0
- package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
- package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
- package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
- package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
- package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
- package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
- package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
- package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
- package/skills/braincell/references/scripts/channel_ablation.py +61 -0
- package/skills/braincell/references/scripts/fi_curve.py +68 -0
- package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
- package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
- package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
- package/skills/braincell/references/solver-library-with-effects.md +188 -0
- package/skills/brainevent/SKILL.md +268 -0
- package/skills/brainevent/references/connectivity-variants.md +312 -0
- package/skills/brainevent/references/custom-operators-cpu.md +304 -0
- package/skills/brainevent/references/custom-operators-gpu.md +468 -0
- package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
- package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
- package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
- package/skills/brainevent/references/sparse-formats.md +182 -0
- package/skills/brainevent/references/synaptic-plasticity.md +285 -0
- package/skills/brainpy-state/SKILL.md +232 -0
- package/skills/brainpy-state/references/array-creation.md +158 -0
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
- package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
- package/skills/brainpy-state/references/braintools/metric.md +152 -0
- package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
- package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
- package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
- package/skills/brainpy-state/references/component-selection.md +273 -0
- package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
- package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
- package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
- package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
- package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
- package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
- package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
- package/skills/brainpy-state/references/projection-patterns.md +125 -0
- package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
- package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
- package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
- package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
- package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
- package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
- package/skills/brainstate/SKILL.md +399 -0
- package/skills/brainstate/agents/openai.yaml +4 -0
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +293 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
- package/skills/brainstate/references/model-interop-and-migration.md +305 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +279 -0
- package/skills/brainstate/references/state-graph-operations.md +216 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
- package/skills/brainstate/scripts/integrator_rnn.py +359 -0
- package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
- package/skills/brainstate/scripts/modern_cnn.py +73 -0
- package/skills/brainstate/scripts/resnet.py +130 -0
- package/skills/brainunit/SKILL.md +287 -0
- package/skills/brainunit/references/array-creation.md +158 -0
- package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
- package/skills/brainunit/references/array-mechanics.md +165 -0
- package/skills/brainunit/references/math-function-library.md +433 -0
- package/skills/brainunit/references/physical-constant-library.md +58 -0
- package/skills/brainunit/references/prefix-library.md +116 -0
- package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
- package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
- package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
- package/skills/brainx-general-guard/SKILL.md +153 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
- package/skills/brainx-install/SKILL.md +2 -2
- package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
- /package/{bin → installation/bin}/brainx.js +0 -0
- /package/{lib → installation/lib}/adapter-transaction.js +0 -0
- /package/{lib → installation/lib}/bundle.js +0 -0
- /package/{lib → installation/lib}/cli.js +0 -0
- /package/{lib → installation/lib}/constants.js +0 -0
- /package/{lib → installation/lib}/hash.js +0 -0
- /package/{lib → installation/lib}/paths.js +0 -0
- /package/{lib → installation/lib}/prompts.js +0 -0
- /package/{lib → installation/lib}/receipt.js +0 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# BrainState constrained and regularized parameters
|
|
2
|
+
|
|
3
|
+
Use this reference after `skills/brainstate/SKILL.md` has selected
|
|
4
|
+
`brainstate.nn.Param` for a value that needs a valid-domain transform, a
|
|
5
|
+
regularization penalty, a modeling prior, or fixed parameter-like storage. It
|
|
6
|
+
owns the operational workflow and common patterns. Open
|
|
7
|
+
`references/brainstate/parameter-transforms-regularizers-catalog.md` only when
|
|
8
|
+
selecting an exact built-in transform or regularizer beyond the common choices
|
|
9
|
+
shown here.
|
|
10
|
+
|
|
11
|
+
Keep `brainstate.nn` parameter transforms separate from execution transforms such as `brainstate.transform.jit`, `grad`, and `vmap`.
|
|
12
|
+
|
|
13
|
+
## Choose the parameter representation
|
|
14
|
+
|
|
15
|
+
| Need | Use | Key constraint |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| An unconstrained trainable value | `ParamState` | Read and write `.value`; no transform or regularizer contract is attached. |
|
|
18
|
+
| A constrained or regularized trainable value | `nn.Param` | Use `.value()` in model computation and update the underlying `.val` through the optimizer. |
|
|
19
|
+
| A fixed value that belongs in the Module graph | `nn.Const` | It is excluded from `ParamState` collection, gradients, and optimizer updates. |
|
|
20
|
+
|
|
21
|
+
## Parameter contract
|
|
22
|
+
|
|
23
|
+
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.
|
|
24
|
+
|
|
25
|
+
- `param.val` is the underlying `ParamState`; optimizers update its unconstrained array.
|
|
26
|
+
- `param.value()` applies the forward transform and returns the constrained model-space value. With the default `IdentityT`, constrained and unconstrained values coincide.
|
|
27
|
+
- `param.set_value(value)` applies the inverse transform when storing a constrained value back.
|
|
28
|
+
- `param.reg_loss()` evaluates the attached `reg=` object on the current constrained value. The loss function must explicitly add this penalty to its objective.
|
|
29
|
+
- `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.
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
33
|
+
Official sources:
|
|
34
|
+
|
|
35
|
+
- https://brainx.chaobrain.com/brainstate/concepts/the_parameter_model.html
|
|
36
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
37
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
38
|
+
|
|
39
|
+
## Canonical constrained training workflow
|
|
40
|
+
|
|
41
|
+
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:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import brainstate
|
|
45
|
+
from brainstate import nn
|
|
46
|
+
import brainunit as u
|
|
47
|
+
import jax.numpy as jnp
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ConstrainedLinear(nn.Module):
|
|
51
|
+
def __init__(self, din, dout):
|
|
52
|
+
super().__init__()
|
|
53
|
+
self.w = nn.Param(
|
|
54
|
+
brainstate.random.randn(din, dout) * 0.1,
|
|
55
|
+
reg=nn.L2Reg(1e-3),
|
|
56
|
+
)
|
|
57
|
+
self.gain = nn.Param(
|
|
58
|
+
jnp.array(1.0),
|
|
59
|
+
t=nn.SoftplusT(lower=0.0),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def __call__(self, x):
|
|
63
|
+
return (x @ self.w.value()) * self.gain.value()
|
|
64
|
+
|
|
65
|
+
def reg_penalty(self):
|
|
66
|
+
return sum(p.reg_loss() for p in self.nodes(nn.Param).values())
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
model = ConstrainedLinear(4, 2)
|
|
70
|
+
params = model.states(brainstate.ParamState)
|
|
71
|
+
x = brainstate.random.randn(16, 4)
|
|
72
|
+
y = brainstate.random.randn(16, 2)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def loss_fn():
|
|
76
|
+
mse = jnp.mean((model(x) - y) ** 2)
|
|
77
|
+
return mse + u.get_magnitude(model.reg_penalty())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@brainstate.transform.jit
|
|
81
|
+
def train_step():
|
|
82
|
+
grads, loss = brainstate.transform.grad(
|
|
83
|
+
loss_fn,
|
|
84
|
+
params,
|
|
85
|
+
return_value=True,
|
|
86
|
+
)()
|
|
87
|
+
for key in params:
|
|
88
|
+
params[key].value -= 0.1 * grads[key]
|
|
89
|
+
return loss
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`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()`.
|
|
93
|
+
|
|
94
|
+
Official sources:
|
|
95
|
+
|
|
96
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
97
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
98
|
+
|
|
99
|
+
## Common constraint patterns
|
|
100
|
+
|
|
101
|
+
Use `.value()` in model computation. Mutate `.val.value` only as optimizer-side, unconstrained storage.
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
rate = nn.Param(
|
|
105
|
+
jnp.array(0.5),
|
|
106
|
+
t=nn.SoftplusT(lower=0.0),
|
|
107
|
+
)
|
|
108
|
+
rate.val.value = jnp.array(-10.0)
|
|
109
|
+
assert float(u.get_magnitude(rate.value())) > 0.0
|
|
110
|
+
|
|
111
|
+
mix = nn.Param(
|
|
112
|
+
jnp.array(0.5),
|
|
113
|
+
t=nn.SigmoidT(lower=0.0, upper=1.0),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
probs = nn.Param(
|
|
117
|
+
jnp.zeros(3),
|
|
118
|
+
t=nn.SimplexT(),
|
|
119
|
+
)
|
|
120
|
+
p = u.get_magnitude(probs.value())
|
|
121
|
+
assert jnp.all(p >= 0.0)
|
|
122
|
+
assert jnp.isclose(p.sum(), 1.0)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
- `SoftplusT(lower)` smoothly maps the real line to `(lower, infinity)`.
|
|
126
|
+
- `SigmoidT(lower, upper)` smoothly maps to the open interval `(lower, upper)`.
|
|
127
|
+
- `SimplexT()` produces non-negative entries that sum to one. Its output has one more final-axis entry than its unconstrained input.
|
|
128
|
+
|
|
129
|
+
Open `parameter-transforms-regularizers-catalog.md` for negative, symmetric bounded, ordered, unit-vector, masked, composite, or projection-like transforms.
|
|
130
|
+
|
|
131
|
+
Official source: https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
132
|
+
|
|
133
|
+
## Regularization patterns
|
|
134
|
+
|
|
135
|
+
Call `reg.loss(value)` directly for a standalone penalty, or attach the regularizer with `reg=` and call `param.reg_loss()`:
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
weights = jnp.array([3.0, -4.0])
|
|
139
|
+
|
|
140
|
+
l1_penalty = nn.L1Reg(0.1).loss(weights)
|
|
141
|
+
l2_penalty = nn.L2Reg(0.1).loss(weights)
|
|
142
|
+
|
|
143
|
+
p = nn.Param(
|
|
144
|
+
weights,
|
|
145
|
+
reg=nn.ElasticNetReg(
|
|
146
|
+
l1_weight=1.0,
|
|
147
|
+
l2_weight=1.0,
|
|
148
|
+
alpha=0.5,
|
|
149
|
+
),
|
|
150
|
+
)
|
|
151
|
+
elastic_net_penalty = p.reg_loss()
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
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.
|
|
155
|
+
|
|
156
|
+
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()`.
|
|
157
|
+
|
|
158
|
+
Open `parameter-transforms-regularizers-catalog.md` to select classical, structural, or prior-distribution regularizers.
|
|
159
|
+
|
|
160
|
+
Official sources:
|
|
161
|
+
|
|
162
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
163
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
164
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
|
|
165
|
+
|
|
166
|
+
## Fixed values with `nn.Const`
|
|
167
|
+
|
|
168
|
+
Use `nn.Const` when a value belongs in the module graph and forward computation but must not be collected as trainable state:
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
class Scaler(nn.Module):
|
|
172
|
+
def __init__(self):
|
|
173
|
+
super().__init__()
|
|
174
|
+
self.weight = nn.Param(jnp.ones(3))
|
|
175
|
+
self.gain = nn.Const(jnp.array(2.0))
|
|
176
|
+
|
|
177
|
+
def __call__(self, x):
|
|
178
|
+
return x * self.weight.value() * self.gain.value()
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
model = Scaler()
|
|
182
|
+
trainable = model.states(brainstate.ParamState)
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`trainable` contains the underlying State for `weight`; `gain` is absent. `Const` means non-trainable, not immutable: explicit `set_value()` calls can still change it.
|
|
186
|
+
|
|
187
|
+
Official sources:
|
|
188
|
+
|
|
189
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
190
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Const.html
|
|
191
|
+
|
|
192
|
+
## Decision and failure rules
|
|
193
|
+
|
|
194
|
+
- Need only a valid domain: attach `t=` without inventing a regularizer.
|
|
195
|
+
- Need only a penalty or modeling prior: attach `reg=` without inventing a transform.
|
|
196
|
+
- Need both: attach `t=` and `reg=` to the same `nn.Param`, read `.value()` in the model, and add `.reg_loss()` to the objective.
|
|
197
|
+
- Need a fixed graph value: use `nn.Const`; do not expect it in a `ParamState` collection.
|
|
198
|
+
- Need an exact built-in transform or regularizer: open `parameter-transforms-regularizers-catalog.md`.
|
|
199
|
+
- Never read `param.val` as the constrained forward value or update `param.value()` as optimizer storage.
|
|
200
|
+
- Do not treat `SigmoidT` bounds as inclusive or `SoftplusT(lower)` as able to attain `lower`.
|
|
201
|
+
- Do not attach regularization and assume the training objective includes it automatically.
|
|
202
|
+
- Match a prior's support to the parameter domain; use `t=` when the domain must be guaranteed by construction.
|
|
203
|
+
- Do not assume every `nn.Transform` subclass is a smooth bijection; the catalog distinguishes projection-like transforms.
|
|
204
|
+
|
|
205
|
+
## Mirror source urls
|
|
206
|
+
|
|
207
|
+
- https://brainx.chaobrain.com/brainstate/concepts/the_parameter_model.html
|
|
208
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
209
|
+
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
210
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
211
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
|
|
212
|
+
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Param.html
|
|
213
|
+
- 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
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# Brainstate randomness and reproducibility
|
|
2
|
+
|
|
3
|
+
Use this reference after `skills/brainstate/SKILL.md` for advanced randomness. It covers independent streams, stochastic transforms, key control, parallel keys, replay, and checkpointing.
|
|
4
|
+
|
|
5
|
+
The root skill owns `brainstate.random.DEFAULT` and ordinary seeding. This reference owns advanced stream and key control.
|
|
6
|
+
|
|
7
|
+
## Independent streams
|
|
8
|
+
|
|
9
|
+
Use one `RandomState` per independent concern. Calls consume successive keys from that stream.
|
|
10
|
+
|
|
11
|
+
| API | Description |
|
|
12
|
+
|---|---|
|
|
13
|
+
| `RandomState(seed=...)` | Create an independent stateful random stream. |
|
|
14
|
+
| `rng.seed(seed)` | Restart a custom stream from a seed. |
|
|
15
|
+
| `rng.value` | Inspect the custom stream's current key. |
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
import brainstate
|
|
19
|
+
import jax.numpy as jnp
|
|
20
|
+
|
|
21
|
+
init_rng = brainstate.random.RandomState(seed=42)
|
|
22
|
+
augment_rng = brainstate.random.RandomState(seed=123)
|
|
23
|
+
|
|
24
|
+
initial_weights = init_rng.randn(5)
|
|
25
|
+
augmented_values = augment_rng.randn(5)
|
|
26
|
+
|
|
27
|
+
assert not jnp.allclose(initial_weights, augmented_values)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Do not pass a custom stream to the global `set_key(...)`. The sources document `rng.value` inspection and `rng.seed(...)` reseeding. They do not document restoring a saved custom-stream key.
|
|
31
|
+
|
|
32
|
+
## Stochastic calls under transforms
|
|
33
|
+
|
|
34
|
+
BrainState random calls advance state and work under JIT. Transform the complete stateful operation with `brainstate.transform`.
|
|
35
|
+
|
|
36
|
+
| API | Description |
|
|
37
|
+
|---|---|
|
|
38
|
+
| `brainstate.random.bernoulli(p, size)` | Draw binary events or masks with probability `p`. |
|
|
39
|
+
| `brainstate.random.normal(loc, scale, size)` | Draw Gaussian initialization or noise. |
|
|
40
|
+
| `brainstate.transform.jit(fn)` | Compile the complete stochastic operation while preserving State effects. |
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
import brainstate
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Dropout(brainstate.nn.Module):
|
|
47
|
+
def __init__(self, drop_rate=0.5):
|
|
48
|
+
super().__init__()
|
|
49
|
+
self.drop_rate = drop_rate
|
|
50
|
+
|
|
51
|
+
def __call__(self, x):
|
|
52
|
+
if not brainstate.environ.get("fit", False):
|
|
53
|
+
return x
|
|
54
|
+
|
|
55
|
+
keep_prob = 1.0 - self.drop_rate
|
|
56
|
+
mask = brainstate.random.bernoulli(keep_prob, x.shape)
|
|
57
|
+
return x * mask / keep_prob
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
With `fit=False`, dropout returns `x` without drawing. With `fit=True`, each call draws a new mask and applies inverse-keep scaling. Noise drawn inside a Module call behaves the same way.
|
|
61
|
+
|
|
62
|
+
Open `references/brainstate/transformation-vmap-expansion.md` for mapped State axes, per-example randomness, and concrete `vmap` workflows.
|
|
63
|
+
|
|
64
|
+
## Exact replay and checkpoints
|
|
65
|
+
|
|
66
|
+
Snapshot the global key immediately before the sequence to replay. Restoring that snapshot reproduces the next draw.
|
|
67
|
+
|
|
68
|
+
| API | Description |
|
|
69
|
+
|---|---|
|
|
70
|
+
| `get_key()` | Return the current global key. |
|
|
71
|
+
| `set_key(key)` | Set the global key to an explicit snapshot. |
|
|
72
|
+
| `restore_key()` | Restore the default key to its previous state; do not substitute it for `set_key(saved_key)`. |
|
|
73
|
+
| `get_key_data()` | Return the global key as raw `uint32[2]` data for interchange. |
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
import brainstate
|
|
77
|
+
import jax.numpy as jnp
|
|
78
|
+
|
|
79
|
+
saved_key = brainstate.random.get_key()
|
|
80
|
+
sample = brainstate.random.randn(3)
|
|
81
|
+
|
|
82
|
+
brainstate.random.set_key(saved_key)
|
|
83
|
+
replayed = brainstate.random.randn(3)
|
|
84
|
+
|
|
85
|
+
assert jnp.allclose(sample, replayed)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
For exact continuation, save the model and RNG key together:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
checkpoint = {
|
|
92
|
+
"model": model.state_dict(),
|
|
93
|
+
"rng_key": brainstate.random.get_key(),
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
# Restore model state first, then restore the RNG before the next random call.
|
|
97
|
+
brainstate.random.set_key(checkpoint["rng_key"])
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Capture the key after every random operation included in the completed run. An earlier key intentionally replays later draws.
|
|
101
|
+
|
|
102
|
+
## Parallel key preparation
|
|
103
|
+
|
|
104
|
+
Prepare independent keys before parallel work. Do not infer mapped key-consumption semantics from these utilities alone.
|
|
105
|
+
|
|
106
|
+
| API | Description |
|
|
107
|
+
|---|---|
|
|
108
|
+
| `split_key(n=...)` | Create new key or keys from the current seed; use `n` for parallel preparation. |
|
|
109
|
+
| `split_keys(...)` | Create multiple independent keys from the current seed. |
|
|
110
|
+
| `self_assign_multi_keys(...)` | Assign multiple keys to the global random state for parallel access. |
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
keys = brainstate.random.split_key(n=4)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Open `references/brainstate/transformation-vmap-expansion.md` for mapped axes, mapped State, and concrete `vmap` mechanics.
|
|
117
|
+
|
|
118
|
+
## Generator helpers
|
|
119
|
+
|
|
120
|
+
| API | Description |
|
|
121
|
+
|---|---|
|
|
122
|
+
| `default_rng(...)` | Get the default random state or create one from a seed. |
|
|
123
|
+
| `clone_rng(...)` | Clone a random state or create a new one. |
|
|
124
|
+
| `seed_context(...)` | Temporarily change the seed and restore it on exit. |
|
|
125
|
+
|
|
126
|
+
The API table names `seed_context`; its example uses `local_seed`. Check the installed BrainState version before calling either name.
|
|
127
|
+
|
|
128
|
+
## Official sources
|
|
129
|
+
|
|
130
|
+
- [Random number generation](https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html)
|
|
131
|
+
- [`brainstate.random` API](https://brainx.chaobrain.com/brainstate/apis/random.html)
|