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,450 @@
|
|
|
1
|
+
# Brainstate gradient and autodiff expansion
|
|
2
|
+
|
|
3
|
+
Use this reference after `skills/brainstate/SKILL.md` when a task needs gradient targets beyond the main skill's minimal parameter update, exact `return_value`/`has_aux` destructuring, state discovery in an arbitrary function, vector- or matrix-valued sensitivities, second derivatives, or an optimizer-integrated fitting step. The main skill owns the canonical `ParamState` collection and manual update; the parameter reference owns the choice between `ParamState` and `nn.Param`.
|
|
4
|
+
|
|
5
|
+
These three sources do not establish BrainCell solver, reset, or conductance-fitting semantics. Specialized dynamics belongs to the matching BrainCell or BrainPy-State skill; use this reference only for the source-supported autodiff contract around that computation.
|
|
6
|
+
|
|
7
|
+
Official sources:
|
|
8
|
+
|
|
9
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
10
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html
|
|
11
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
12
|
+
|
|
13
|
+
## Select the derivative target
|
|
14
|
+
|
|
15
|
+
BrainState's gradient system has two independent selectors: `argnums` selects positional function arguments, as in JAX, and `grad_states` selects `State` objects. Both selectors can be active in one transform.
|
|
16
|
+
|
|
17
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
18
|
+
|
|
19
|
+
### Function arguments with `argnums`
|
|
20
|
+
|
|
21
|
+
Use this path for sensitivities of explicit inputs or scalar hyperparameters. A scalar `argnums` returns one argument gradient; a list returns gradients in the selected argument order.
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import jax.numpy as jnp
|
|
25
|
+
|
|
26
|
+
from brainstate.transform import grad
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def loss_fn(x, y, scale):
|
|
30
|
+
"""Simple loss function with multiple arguments."""
|
|
31
|
+
return scale * jnp.sum((x - y) ** 2)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
x = jnp.array([1.0, 2.0, 3.0])
|
|
35
|
+
y = jnp.array([0.5, 1.5, 2.5])
|
|
36
|
+
scale = 2.0
|
|
37
|
+
|
|
38
|
+
grad_fn_x = grad(loss_fn, argnums=0)
|
|
39
|
+
grad_x = grad_fn_x(x, y, scale)
|
|
40
|
+
|
|
41
|
+
grad_fn_xy = grad(loss_fn, argnums=[0, 1])
|
|
42
|
+
grad_x, grad_y = grad_fn_xy(x, y, scale)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
46
|
+
|
|
47
|
+
### Arguments and state in one pass
|
|
48
|
+
|
|
49
|
+
Use both selectors when one loss depends on explicit differentiable arguments and mutable model State. In the official example, `grad_states` targets the model collection while `argnums=0` also differentiates the regularization coefficient; therefore the gradient result is grouped as `(state_grads, coeff_grad)`.
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import jax
|
|
53
|
+
import brainstate
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class LinearRegressor(brainstate.nn.Module):
|
|
57
|
+
"""Simple linear regression model."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, in_features: int, out_features: int = 1):
|
|
60
|
+
super().__init__()
|
|
61
|
+
self.weight = brainstate.ParamState(
|
|
62
|
+
jnp.zeros((in_features, out_features))
|
|
63
|
+
)
|
|
64
|
+
self.bias = brainstate.ParamState(jnp.zeros((out_features,)))
|
|
65
|
+
|
|
66
|
+
def __call__(self, x: jax.Array) -> jax.Array:
|
|
67
|
+
return x @ self.weight.value + self.bias.value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
reg_model = LinearRegressor(1)
|
|
71
|
+
xs = jnp.linspace(-1.0, 1.0, 5).reshape(-1, 1)
|
|
72
|
+
y_true = 3.0 * xs + 1.0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def penalized_loss(
|
|
76
|
+
l2_coeff: float,
|
|
77
|
+
inputs: jax.Array,
|
|
78
|
+
target: jax.Array,
|
|
79
|
+
) -> jax.Array:
|
|
80
|
+
"""Loss with L2 regularization."""
|
|
81
|
+
pred = reg_model(inputs)
|
|
82
|
+
mse = jnp.mean((pred - target) ** 2)
|
|
83
|
+
l2 = (
|
|
84
|
+
jnp.sum(reg_model.weight.value ** 2)
|
|
85
|
+
+ jnp.sum(reg_model.bias.value ** 2)
|
|
86
|
+
)
|
|
87
|
+
return mse + l2_coeff * l2
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
grad_penalized = grad(
|
|
91
|
+
penalized_loss,
|
|
92
|
+
grad_states=reg_model.states(brainstate.ParamState),
|
|
93
|
+
argnums=0,
|
|
94
|
+
return_value=True,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
(state_grads, coeff_grad), loss_val = grad_penalized(
|
|
98
|
+
0.5,
|
|
99
|
+
xs,
|
|
100
|
+
y_true,
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
105
|
+
|
|
106
|
+
### Any `State` may be a gradient target
|
|
107
|
+
|
|
108
|
+
Gradient computation is not limited to `ParamState`. The official example targets an ordinary `State` directly:
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
regular_state = brainstate.State(
|
|
112
|
+
jnp.array(2.0),
|
|
113
|
+
name="regular_state",
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def compute_with_state(x):
|
|
118
|
+
return jnp.sum((x * regular_state.value) ** 2)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
grad_fn = grad(
|
|
122
|
+
compute_with_state,
|
|
123
|
+
grad_states=[regular_state],
|
|
124
|
+
)
|
|
125
|
+
gradient = grad_fn(jnp.array([1.0, 2.0, 3.0]))
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Here `gradient[0]` corresponds to the first State in the supplied list. This capability does not redefine which States should be trained; it only widens the set of valid sensitivity targets.
|
|
129
|
+
|
|
130
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
131
|
+
|
|
132
|
+
## Discover state in an arbitrary function
|
|
133
|
+
|
|
134
|
+
Use `StateFinder` when the differentiable computation is not an `nn.Module` and its State dependencies must be discovered. `filter` selects State types, `usage='all'` finds read and write State, and `return_type='dict'` returns a dictionary that can be passed as `grad_states`.
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from brainstate.transform import StateFinder
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
scale = brainstate.ParamState(jnp.array(1.5), name="scale")
|
|
141
|
+
offset = brainstate.ParamState(jnp.array(-0.2), name="offset")
|
|
142
|
+
cache = brainstate.State(jnp.array(0.0), name="cache")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def energy(x: jax.Array) -> jax.Array:
|
|
146
|
+
"""Energy function using external states."""
|
|
147
|
+
shifted = x * scale.value + offset.value
|
|
148
|
+
scale.value = scale.value + 0.0
|
|
149
|
+
cache.value = jnp.sum(shifted)
|
|
150
|
+
return jnp.sum(jnp.square(shifted))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
finder = StateFinder(
|
|
154
|
+
energy,
|
|
155
|
+
filter=brainstate.ParamState,
|
|
156
|
+
usage="all",
|
|
157
|
+
return_type="dict",
|
|
158
|
+
)
|
|
159
|
+
all_param_states = finder(jnp.ones((2,)))
|
|
160
|
+
|
|
161
|
+
energy_grad = grad(
|
|
162
|
+
energy,
|
|
163
|
+
grad_states=all_param_states,
|
|
164
|
+
return_value=True,
|
|
165
|
+
)
|
|
166
|
+
state_grads, energy_value = energy_grad(
|
|
167
|
+
jnp.array([1.0, 3.0])
|
|
168
|
+
)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
The finder excludes `cache` because the filter selects only `ParamState`, even though `energy` writes that State.
|
|
172
|
+
|
|
173
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
174
|
+
|
|
175
|
+
## Destructure gradient returns exactly
|
|
176
|
+
|
|
177
|
+
All BrainState gradient transformations share a return structure controlled by `grad_states`, `argnums`, `has_aux`, and `return_value`. `has_aux=True` means the differentiated function returns `(loss, aux)`; `return_value=True` additionally returns the differentiated loss value from the same pass.
|
|
178
|
+
|
|
179
|
+
| `grad_states` | `argnums` | `has_aux` | `return_value` | Result |
|
|
180
|
+
|---|---|---:|---:|---|
|
|
181
|
+
| `None` | selected | `False` | `False` | `arg_grads` |
|
|
182
|
+
| `None` | selected | `True` | `False` | `(arg_grads, aux)` |
|
|
183
|
+
| `None` | selected | `False` | `True` | `(arg_grads, loss)` |
|
|
184
|
+
| `None` | selected | `True` | `True` | `(arg_grads, loss, aux)` |
|
|
185
|
+
| selected | `None` | `False` | `False` | `state_grads` |
|
|
186
|
+
| selected | `None` | `True` | `False` | `(state_grads, aux)` |
|
|
187
|
+
| selected | `None` | `False` | `True` | `(state_grads, loss)` |
|
|
188
|
+
| selected | `None` | `True` | `True` | `(state_grads, loss, aux)` |
|
|
189
|
+
| selected | selected | `False` | `False` | `(state_grads, arg_grads)` |
|
|
190
|
+
| selected | selected | `True` | `False` | `((state_grads, arg_grads), aux)` |
|
|
191
|
+
| selected | selected | `False` | `True` | `((state_grads, arg_grads), loss)` |
|
|
192
|
+
| selected | selected | `True` | `True` | `((state_grads, arg_grads), loss, aux)` |
|
|
193
|
+
|
|
194
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
195
|
+
|
|
196
|
+
Bundle the most information-rich case as one loss and one destructuring pattern:
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
example_model = LinearRegressor(1)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def loss_with_metrics(
|
|
203
|
+
l2_coeff: float,
|
|
204
|
+
x: jax.Array,
|
|
205
|
+
target: jax.Array,
|
|
206
|
+
):
|
|
207
|
+
"""Loss function that returns auxiliary metrics."""
|
|
208
|
+
pred = example_model(x)
|
|
209
|
+
mse = jnp.mean((pred - target) ** 2)
|
|
210
|
+
l2 = jnp.sum(example_model.weight.value ** 2)
|
|
211
|
+
loss = mse + l2_coeff * l2
|
|
212
|
+
metrics = {
|
|
213
|
+
"mae": jnp.mean(jnp.abs(pred - target)),
|
|
214
|
+
"mse": mse,
|
|
215
|
+
"l2": l2,
|
|
216
|
+
}
|
|
217
|
+
return loss, metrics
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
grad_complete = grad(
|
|
221
|
+
loss_with_metrics,
|
|
222
|
+
grad_states=example_model.states(brainstate.ParamState),
|
|
223
|
+
argnums=0,
|
|
224
|
+
has_aux=True,
|
|
225
|
+
return_value=True,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
(
|
|
229
|
+
(state_grads, coeff_grad),
|
|
230
|
+
loss_val,
|
|
231
|
+
aux_metrics,
|
|
232
|
+
) = grad_complete(0.3, xs, y_true)
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
236
|
+
|
|
237
|
+
## Select vector, jacobian, or second-order derivatives
|
|
238
|
+
|
|
239
|
+
BrainState provides `vector_grad`, `jacrev`, `jacfwd`, `jacobian`, and `hessian` with the same State-aware signature pattern as `grad`.
|
|
240
|
+
|
|
241
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
242
|
+
|
|
243
|
+
### Sum gradients of vector outputs with `vector_grad`
|
|
244
|
+
|
|
245
|
+
`vector_grad` is for a vector-valued function and computes the sum of gradients across all output dimensions. It is not the full Jacobian.
|
|
246
|
+
|
|
247
|
+
```python
|
|
248
|
+
from brainstate.transform import vector_grad
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def vector_fun(x):
|
|
252
|
+
"""Vector-valued function."""
|
|
253
|
+
return jnp.array(
|
|
254
|
+
[
|
|
255
|
+
x[0] * x[1],
|
|
256
|
+
jnp.sin(x[0]),
|
|
257
|
+
x[0] ** 2 + x[1] ** 2,
|
|
258
|
+
]
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
x0 = jnp.array([1.0, 2.0])
|
|
263
|
+
vgrad = vector_grad(vector_fun)
|
|
264
|
+
result = vgrad(x0)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
268
|
+
|
|
269
|
+
### Compute full jacobians
|
|
270
|
+
|
|
271
|
+
The tutorial defines `jacrev` as reverse-mode Jacobian, efficient for many inputs and few outputs; `jacfwd` is forward-mode, efficient for few inputs and many outputs; `jacobian` is an alias for `jacrev`.
|
|
272
|
+
|
|
273
|
+
```python
|
|
274
|
+
from brainstate.transform import jacrev, jacfwd, jacobian
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def multi_output(x):
|
|
278
|
+
"""Function with multiple outputs."""
|
|
279
|
+
return jnp.array(
|
|
280
|
+
[
|
|
281
|
+
x[0] * x[1],
|
|
282
|
+
jnp.sin(x[0]),
|
|
283
|
+
jnp.exp(x[1]),
|
|
284
|
+
]
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
x0 = jnp.array([1.0, 2.0])
|
|
289
|
+
result_rev = jacrev(multi_output)(x0)
|
|
290
|
+
result_fwd = jacfwd(multi_output)(x0)
|
|
291
|
+
result_alias = jacobian(multi_output)(x0)
|
|
292
|
+
|
|
293
|
+
assert jnp.allclose(result_rev, result_fwd)
|
|
294
|
+
assert jnp.allclose(result_rev, result_alias)
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
The same transform can target State. In the official model example, the output-to-parameter Jacobian preserves State paths:
|
|
298
|
+
|
|
299
|
+
```python
|
|
300
|
+
jac_model = LinearRegressor(2)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def model_output(x):
|
|
304
|
+
"""Multiple outputs from a model."""
|
|
305
|
+
return jac_model(x)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
jac_states = jacrev(
|
|
309
|
+
model_output,
|
|
310
|
+
grad_states=jac_model.states(brainstate.ParamState),
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
x_input = jnp.array([1.0, 2.0])
|
|
314
|
+
param_jacobian = jac_states(x_input)
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
318
|
+
|
|
319
|
+
### Compute second derivatives with `hessian`
|
|
320
|
+
|
|
321
|
+
`hessian` computes second-order derivatives.
|
|
322
|
+
|
|
323
|
+
```python
|
|
324
|
+
from brainstate.transform import hessian
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def quadratic(x):
|
|
328
|
+
"""Quadratic function."""
|
|
329
|
+
return jnp.dot(x, x)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
x0 = jnp.array([1.0, 2.0])
|
|
333
|
+
hess_fn = hessian(quadratic)
|
|
334
|
+
result = hess_fn(x0)
|
|
335
|
+
|
|
336
|
+
expected = 2 * jnp.eye(2)
|
|
337
|
+
assert jnp.allclose(result, expected)
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
341
|
+
|
|
342
|
+
## Bundle fitting loss, auxiliary metrics, and differentiation
|
|
343
|
+
|
|
344
|
+
The autodiff tutorial's fitting example compiles an MSE-plus-L2 objective, returns the MSE and L2 terms as auxiliary data, and builds one State-targeted gradient callable. Keep the loss scalar first and auxiliary diagnostics second when `has_aux=True`.
|
|
345
|
+
|
|
346
|
+
```python
|
|
347
|
+
training_model = LinearRegressor(1)
|
|
348
|
+
|
|
349
|
+
true_weight = 3.0
|
|
350
|
+
true_bias = 1.0
|
|
351
|
+
x_train = jnp.linspace(-1.0, 1.0, 20).reshape(-1, 1)
|
|
352
|
+
y_train = (
|
|
353
|
+
true_weight * x_train
|
|
354
|
+
+ true_bias
|
|
355
|
+
+ 0.1 * brainstate.random.normal(size=x_train.shape)
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
@brainstate.transform.jit
|
|
360
|
+
def training_loss(x, y):
|
|
361
|
+
"""MSE loss with L2 regularization."""
|
|
362
|
+
pred = training_model(x)
|
|
363
|
+
mse = jnp.mean((pred - y) ** 2)
|
|
364
|
+
l2 = 0.01 * (
|
|
365
|
+
jnp.sum(training_model.weight.value ** 2)
|
|
366
|
+
+ jnp.sum(training_model.bias.value ** 2)
|
|
367
|
+
)
|
|
368
|
+
return mse + l2, {"mse": mse, "l2": l2}
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
loss_grad_fn = grad(
|
|
372
|
+
training_loss,
|
|
373
|
+
grad_states=training_model.states(brainstate.ParamState),
|
|
374
|
+
has_aux=True,
|
|
375
|
+
return_value=True,
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
grads, loss_val, aux = loss_grad_fn(x_train, y_train)
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
382
|
+
|
|
383
|
+
For `nn.Param` regularization, the parameters tutorial places the penalty inside the differentiated scalar objective. Attaching a regularizer without adding its result to the loss does not reproduce this training path:
|
|
384
|
+
|
|
385
|
+
```python
|
|
386
|
+
def loss_fn():
|
|
387
|
+
data_loss = jnp.mean((model(x) - y) ** 2)
|
|
388
|
+
return data_loss + model.reg_penalty()
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
392
|
+
|
|
393
|
+
## Integrate with the compiled training step
|
|
394
|
+
|
|
395
|
+
The training tutorial's advanced step differentiates once, receives the loss with `return_value=True`, clips the gradient PyTree, and passes the clipped gradients to a registered optimizer. The whole step is wrapped in `brainstate.transform.jit`, so State reads and writes are tracked across the transform boundary.
|
|
396
|
+
|
|
397
|
+
```python
|
|
398
|
+
import braintools
|
|
399
|
+
from brainstate.nn import clip_grad_norm
|
|
400
|
+
from braintools.metric import (
|
|
401
|
+
softmax_cross_entropy_with_integer_labels,
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
optimizer = braintools.optim.Adam(lr=1e-2)
|
|
406
|
+
optimizer.register_trainable_weights(
|
|
407
|
+
model.states(brainstate.ParamState)
|
|
408
|
+
)
|
|
409
|
+
params = model.states(brainstate.ParamState)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
@brainstate.transform.jit
|
|
413
|
+
def train_step(x, y):
|
|
414
|
+
def loss_fn():
|
|
415
|
+
logits = model(x)
|
|
416
|
+
return softmax_cross_entropy_with_integer_labels(
|
|
417
|
+
logits,
|
|
418
|
+
y,
|
|
419
|
+
).mean()
|
|
420
|
+
|
|
421
|
+
grads, loss = brainstate.transform.grad(
|
|
422
|
+
loss_fn,
|
|
423
|
+
params,
|
|
424
|
+
return_value=True,
|
|
425
|
+
)()
|
|
426
|
+
grads = clip_grad_norm(grads, max_norm=1.0)
|
|
427
|
+
optimizer.update(grads)
|
|
428
|
+
return loss
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
Return to `skills/brainstate/SKILL.md` for the general training structure. Open `references/braintools-optimizer-reference.md` only for optimizer or scheduler selection.
|
|
432
|
+
|
|
433
|
+
Official source: https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html
|
|
434
|
+
|
|
435
|
+
## Failure rules
|
|
436
|
+
|
|
437
|
+
- Match destructuring to all four controls: `grad_states`, `argnums`, `has_aux`, and `return_value`.
|
|
438
|
+
- When both `grad_states` and `argnums` are selected, do not flatten their gradients together; the result groups them as `(state_grads, arg_grads)`.
|
|
439
|
+
- With `has_aux=True`, return `(scalar_loss, aux)` from the differentiated function; do not make auxiliary metrics the differentiated result.
|
|
440
|
+
- Do not use `vector_grad` when the full output-by-input Jacobian is required; it sums gradients across output dimensions.
|
|
441
|
+
- Choose `jacrev` versus `jacfwd` from the documented input/output-size tradeoff, and remember that `jacobian` aliases `jacrev`.
|
|
442
|
+
- Do not assume only `ParamState` can receive gradients; any explicit `State` can be a sensitivity target.
|
|
443
|
+
- Do not assume an attached regularizer changes fitting unless its penalty is added to the scalar loss.
|
|
444
|
+
- Do not infer BrainCell integration, reset, unit, or solver semantics from these sources; route specialized dynamics to the matching BrainCell or BrainPy-State skill.
|
|
445
|
+
|
|
446
|
+
## Mirror source urls
|
|
447
|
+
|
|
448
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
|
|
449
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html
|
|
450
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# Brainstate jit expansion
|
|
2
|
+
|
|
3
|
+
Use this reference after the main BrainState skill's minimal state-aware JIT workflow. It covers supplemental write-back behavior, `JittedFunction` cache controls, static specialization, compilation boundaries, and the boundary where raw `jax.jit` remains appropriate. It does not repeat the basic forward-pass example.
|
|
4
|
+
|
|
5
|
+
Official sources:
|
|
6
|
+
|
|
7
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
|
|
8
|
+
- https://brainx.chaobrain.com/brainstate/tutorials/core/06_transformations_essentials.html
|
|
9
|
+
|
|
10
|
+
The examples share these imports:
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
import jax
|
|
14
|
+
import jax.numpy as jnp
|
|
15
|
+
|
|
16
|
+
import brainstate
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Verify write-back across multiple states
|
|
20
|
+
|
|
21
|
+
Use this pattern when a compiled call updates more than one piece of hidden state and the caller must observe every update after each invocation. BrainState records and replays the state updates around the compiled executable, so the hidden states remain in sync.
|
|
22
|
+
|
|
23
|
+
Source URL: https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
class RunningMean(brainstate.nn.Module):
|
|
27
|
+
def __init__(self):
|
|
28
|
+
super().__init__()
|
|
29
|
+
self.sum = brainstate.HiddenState(jnp.array(0.0))
|
|
30
|
+
self.count = brainstate.HiddenState(jnp.array(0))
|
|
31
|
+
|
|
32
|
+
def __call__(self, batch: jax.Array) -> jax.Array:
|
|
33
|
+
self.sum.value += jnp.sum(batch)
|
|
34
|
+
self.count.value += batch.size
|
|
35
|
+
return self.sum.value / self.count.value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
tracker = RunningMean()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@brainstate.transform.jit
|
|
42
|
+
def update_running_mean(batch: jax.Array) -> jax.Array:
|
|
43
|
+
return tracker(batch)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
for step in range(3):
|
|
47
|
+
data = jnp.arange(4.0) + step
|
|
48
|
+
print(f"step {step}: mean={float(update_running_mean(data)):.2f}")
|
|
49
|
+
|
|
50
|
+
assert float(tracker.sum.value) == 30.0
|
|
51
|
+
assert int(tracker.count.value) == 12
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The three calls print means `1.50`, `2.00`, and `2.50`. Validate both the returned value and the final `State` values when write-back is part of the function's contract.
|
|
55
|
+
|
|
56
|
+
## Precompile or clear cached traces
|
|
57
|
+
|
|
58
|
+
`brainstate.transform.jit` returns a `JittedFunction`. The tutorial names `compile`, `clear_cache`, and `origin_fun` as helper surfaces and demonstrates the first two: `compile()` precompiles an executable for example inputs, while `clear_cache()` explicitly drops cached traces. Subsequent compatible calls otherwise reuse the compiled executable.
|
|
59
|
+
|
|
60
|
+
Source URL: https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
@brainstate.transform.jit
|
|
64
|
+
def softplus(x: jax.Array) -> jax.Array:
|
|
65
|
+
return jnp.log1p(jnp.exp(-jnp.abs(x))) + jnp.maximum(x, 0)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
example = jnp.ones((4,))
|
|
69
|
+
softplus.compile(example)
|
|
70
|
+
result = softplus(example)
|
|
71
|
+
|
|
72
|
+
softplus.clear_cache()
|
|
73
|
+
result_after_clear = softplus(jnp.linspace(-1.0, 1.0, 5))
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The routed tutorial identifies `origin_fun` but does not demonstrate how to call it. Do not infer a usage contract from its name alone.
|
|
77
|
+
|
|
78
|
+
When JIT is disabled globally, BrainState falls back to the original Python implementation automatically:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
with jax.disable_jit():
|
|
82
|
+
result_without_jit = softplus(example * 2.0)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Specialize python control with static arguments
|
|
86
|
+
|
|
87
|
+
Static-argument handling mirrors `jax.jit`. Use `static_argnums` when a positional value controls Python structure; the tutorial specializes the compiled polynomial program by `degree`.
|
|
88
|
+
|
|
89
|
+
Source URL: https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
@brainstate.transform.jit(static_argnums=1)
|
|
93
|
+
def polynomial_series(x: jax.Array, degree: int) -> jax.Array:
|
|
94
|
+
powers = [x ** (i + 1) for i in range(degree)]
|
|
95
|
+
coeffs = jnp.arange(1, degree + 1, dtype=x.dtype)
|
|
96
|
+
return jnp.tensordot(
|
|
97
|
+
coeffs,
|
|
98
|
+
jnp.stack(powers, axis=0),
|
|
99
|
+
axes=1,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
x = jnp.array([1.0, 2.0])
|
|
104
|
+
p1 = polynomial_series(x, 3)
|
|
105
|
+
p2 = polynomial_series(x, 3)
|
|
106
|
+
p3 = polynomial_series(x, 4)
|
|
107
|
+
|
|
108
|
+
assert jnp.allclose(p1, jnp.array([6.0, 34.0]))
|
|
109
|
+
assert jnp.allclose(p2, p1)
|
|
110
|
+
assert jnp.allclose(p3, jnp.array([10.0, 98.0]))
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Here `degree=3` and `degree=4` select different static specializations. The sources do not enumerate other cache-key or recompilation triggers, so do not add shape-, dtype-, or Python-object rules without a separate official source.
|
|
114
|
+
|
|
115
|
+
## Keep the compilation boundary at a whole step
|
|
116
|
+
|
|
117
|
+
`jit` traces a function on its first call, compiles it with XLA, and reuses the compiled version afterwards. Apply it to a whole forward pass or training step, not to tiny operations. For training, preserve the main skill's `jit(grad(...))` composition as one compiled step instead of wrapping its internal arithmetic separately.
|
|
118
|
+
|
|
119
|
+
Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/06_transformations_essentials.html
|
|
120
|
+
|
|
121
|
+
The two routed tutorials demonstrate first-call compilation, later executable reuse, explicit precompilation, and cache clearing. They do not demonstrate a lowering API, a synchronized timing protocol, or a benchmark. Do not invent `lower()` or benchmarking instructions in this reference; route performance measurement to a source that documents it.
|
|
122
|
+
|
|
123
|
+
## Cross into raw `jax.jit` only with a pure interface
|
|
124
|
+
|
|
125
|
+
Use raw `jax.jit` for a pure stateless function when it is the leanest choice. If the computation owns mutable values, pull each value out, pass it through the call signature, and return the updated value for the next call.
|
|
126
|
+
|
|
127
|
+
Source URL: https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
def running_mean_pure(carry, batch):
|
|
131
|
+
total, count = carry
|
|
132
|
+
total = total + jnp.sum(batch)
|
|
133
|
+
count = count + batch.size
|
|
134
|
+
return (total, count), total / count
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
jax_jitted = jax.jit(running_mean_pure)
|
|
138
|
+
carry = (jnp.array(0.0), jnp.array(0))
|
|
139
|
+
|
|
140
|
+
for step in range(3):
|
|
141
|
+
batch = jnp.arange(4.0) + step
|
|
142
|
+
carry, mean = jax_jitted(carry, batch)
|
|
143
|
+
|
|
144
|
+
total, count = carry
|
|
145
|
+
assert float(total) == 30.0
|
|
146
|
+
assert int(count) == 12
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
This boundary is explicit: the raw JAX function receives and returns `carry`; no BrainState mutation is hidden inside it. When a `GraphDef` or explicit module reconstruction is required, route to `../state-graph-operations.md` rather than expanding graph splitting here.
|
|
150
|
+
|
|
151
|
+
## Selection checklist
|
|
152
|
+
|
|
153
|
+
- Use the main skill for the canonical state-aware JIT rule and minimal forward script.
|
|
154
|
+
- Use this reference for multi-State write-back, `compile()`, `clear_cache()`, static specialization, whole-step boundaries, or a pure-JAX boundary.
|
|
155
|
+
- Use `brainstate.transform.jit` for module-centric stateful code.
|
|
156
|
+
- Use raw `jax.jit` only when the computation is pure or all mutable values are threaded explicitly.
|
|
157
|
+
- Do not claim lowering, benchmark methodology, or undocumented recompilation triggers from these two sources.
|