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.
Files changed (117) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -64
  3. package/adapters/gemini.js +7 -0
  4. package/adapters/opencode.js +7 -0
  5. package/adapters/windsurf.js +7 -0
  6. package/{lib → installation/lib}/installer.js +8 -5
  7. package/manifest.json +7 -1
  8. package/package.json +25 -10
  9. package/skills/braincell/SKILL.md +182 -0
  10. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  11. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
  12. package/skills/braincell/references/channel-library.md +170 -0
  13. package/skills/braincell/references/ion-library.md +154 -0
  14. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  15. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  16. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  17. package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
  18. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  19. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  20. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  21. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
  22. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  23. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  24. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  25. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  26. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  27. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  28. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  29. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  30. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  31. package/skills/brainevent/SKILL.md +268 -0
  32. package/skills/brainevent/references/connectivity-variants.md +312 -0
  33. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  34. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  35. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  36. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  37. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  38. package/skills/brainevent/references/sparse-formats.md +182 -0
  39. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  40. package/skills/brainpy-state/SKILL.md +232 -0
  41. package/skills/brainpy-state/references/array-creation.md +158 -0
  42. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  43. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  44. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  45. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  46. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  47. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  48. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  49. package/skills/brainpy-state/references/component-selection.md +273 -0
  50. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  51. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  52. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  53. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  54. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  55. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  56. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  57. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  58. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  59. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  60. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  61. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  62. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  63. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  64. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  65. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  66. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  67. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  68. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  69. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  70. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  71. package/skills/brainstate/SKILL.md +399 -0
  72. package/skills/brainstate/agents/openai.yaml +4 -0
  73. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
  75. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
  76. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  77. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
  78. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
  79. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
  80. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
  81. package/skills/brainstate/references/collective_model_operations.md +195 -0
  82. package/skills/brainstate/references/extension_mechanisms.md +293 -0
  83. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
  84. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
  85. package/skills/brainstate/references/model-interop-and-migration.md +305 -0
  86. package/skills/brainstate/references/simulation-environment.md +117 -0
  87. package/skills/brainstate/references/size-inference-variations.md +279 -0
  88. package/skills/brainstate/references/state-graph-operations.md +216 -0
  89. package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
  90. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  91. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  92. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  93. package/skills/brainstate/scripts/resnet.py +130 -0
  94. package/skills/brainunit/SKILL.md +287 -0
  95. package/skills/brainunit/references/array-creation.md +158 -0
  96. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  97. package/skills/brainunit/references/array-mechanics.md +165 -0
  98. package/skills/brainunit/references/math-function-library.md +433 -0
  99. package/skills/brainunit/references/physical-constant-library.md +58 -0
  100. package/skills/brainunit/references/prefix-library.md +116 -0
  101. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  102. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  103. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  104. package/skills/brainx-general-guard/SKILL.md +153 -0
  105. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
  106. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
  107. package/skills/brainx-install/SKILL.md +2 -2
  108. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  109. /package/{bin → installation/bin}/brainx.js +0 -0
  110. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  111. /package/{lib → installation/lib}/bundle.js +0 -0
  112. /package/{lib → installation/lib}/cli.js +0 -0
  113. /package/{lib → installation/lib}/constants.js +0 -0
  114. /package/{lib → installation/lib}/hash.js +0 -0
  115. /package/{lib → installation/lib}/paths.js +0 -0
  116. /package/{lib → installation/lib}/prompts.js +0 -0
  117. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,462 @@
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
+ ## Selection map
14
+
15
+ | Need | Use | Key constraint |
16
+ |---|---|---|
17
+ | Differentiate explicit function inputs | `argnums` | Select positional arguments; the return structure follows scalar versus multiple selection. |
18
+ | Differentiate registered values | `grad_states` | Pass a `State`, State mapping, or discovered State collection. |
19
+ | Differentiate inputs and State together | `argnums` plus `grad_states` | Destructure the result as separate argument and State gradient groups. |
20
+ | Return loss or auxiliary metrics from the same pass | `return_value=True` and/or `has_aux=True` | With `has_aux=True`, the function returns `(scalar_loss, aux)`. |
21
+ | Sum sensitivities of a vector output | `vector_grad` | It is not a full Jacobian. |
22
+ | Return full first- or second-order structure | `jacrev`, `jacfwd`, `jacobian`, or `hessian` | Choose reverse versus forward mode from input/output dimensions. |
23
+ | Discover State touched by an arbitrary function | `StateFinder` | Filter read and write State into a collection that can be passed to `grad_states`. |
24
+
25
+ ## Select the derivative target
26
+
27
+ 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.
28
+
29
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
30
+
31
+ ### Function arguments with `argnums`
32
+
33
+ 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.
34
+
35
+ ```python
36
+ import jax.numpy as jnp
37
+
38
+ from brainstate.transform import grad
39
+
40
+
41
+ def loss_fn(x, y, scale):
42
+ """Simple loss function with multiple arguments."""
43
+ return scale * jnp.sum((x - y) ** 2)
44
+
45
+
46
+ x = jnp.array([1.0, 2.0, 3.0])
47
+ y = jnp.array([0.5, 1.5, 2.5])
48
+ scale = 2.0
49
+
50
+ grad_fn_x = grad(loss_fn, argnums=0)
51
+ grad_x = grad_fn_x(x, y, scale)
52
+
53
+ grad_fn_xy = grad(loss_fn, argnums=[0, 1])
54
+ grad_x, grad_y = grad_fn_xy(x, y, scale)
55
+ ```
56
+
57
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
58
+
59
+ ### Arguments and state in one pass
60
+
61
+ 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)`.
62
+
63
+ ```python
64
+ import jax
65
+ import brainstate
66
+
67
+
68
+ class LinearRegressor(brainstate.nn.Module):
69
+ """Simple linear regression model."""
70
+
71
+ def __init__(self, in_features: int, out_features: int = 1):
72
+ super().__init__()
73
+ self.weight = brainstate.ParamState(
74
+ jnp.zeros((in_features, out_features))
75
+ )
76
+ self.bias = brainstate.ParamState(jnp.zeros((out_features,)))
77
+
78
+ def __call__(self, x: jax.Array) -> jax.Array:
79
+ return x @ self.weight.value + self.bias.value
80
+
81
+
82
+ reg_model = LinearRegressor(1)
83
+ xs = jnp.linspace(-1.0, 1.0, 5).reshape(-1, 1)
84
+ y_true = 3.0 * xs + 1.0
85
+
86
+
87
+ def penalized_loss(
88
+ l2_coeff: float,
89
+ inputs: jax.Array,
90
+ target: jax.Array,
91
+ ) -> jax.Array:
92
+ """Loss with L2 regularization."""
93
+ pred = reg_model(inputs)
94
+ mse = jnp.mean((pred - target) ** 2)
95
+ l2 = (
96
+ jnp.sum(reg_model.weight.value ** 2)
97
+ + jnp.sum(reg_model.bias.value ** 2)
98
+ )
99
+ return mse + l2_coeff * l2
100
+
101
+
102
+ grad_penalized = grad(
103
+ penalized_loss,
104
+ grad_states=reg_model.states(brainstate.ParamState),
105
+ argnums=0,
106
+ return_value=True,
107
+ )
108
+
109
+ (state_grads, coeff_grad), loss_val = grad_penalized(
110
+ 0.5,
111
+ xs,
112
+ y_true,
113
+ )
114
+ ```
115
+
116
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
117
+
118
+ ### Any `State` may be a gradient target
119
+
120
+ Gradient computation is not limited to `ParamState`. The official example targets an ordinary `State` directly:
121
+
122
+ ```python
123
+ regular_state = brainstate.State(
124
+ jnp.array(2.0),
125
+ name="regular_state",
126
+ )
127
+
128
+
129
+ def compute_with_state(x):
130
+ return jnp.sum((x * regular_state.value) ** 2)
131
+
132
+
133
+ grad_fn = grad(
134
+ compute_with_state,
135
+ grad_states=[regular_state],
136
+ )
137
+ gradient = grad_fn(jnp.array([1.0, 2.0, 3.0]))
138
+ ```
139
+
140
+ 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.
141
+
142
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
143
+
144
+ ## Discover state in an arbitrary function
145
+
146
+ 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`.
147
+
148
+ ```python
149
+ from brainstate.transform import StateFinder
150
+
151
+
152
+ scale = brainstate.ParamState(jnp.array(1.5), name="scale")
153
+ offset = brainstate.ParamState(jnp.array(-0.2), name="offset")
154
+ cache = brainstate.State(jnp.array(0.0), name="cache")
155
+
156
+
157
+ def energy(x: jax.Array) -> jax.Array:
158
+ """Energy function using external states."""
159
+ shifted = x * scale.value + offset.value
160
+ scale.value = scale.value + 0.0
161
+ cache.value = jnp.sum(shifted)
162
+ return jnp.sum(jnp.square(shifted))
163
+
164
+
165
+ finder = StateFinder(
166
+ energy,
167
+ filter=brainstate.ParamState,
168
+ usage="all",
169
+ return_type="dict",
170
+ )
171
+ all_param_states = finder(jnp.ones((2,)))
172
+
173
+ energy_grad = grad(
174
+ energy,
175
+ grad_states=all_param_states,
176
+ return_value=True,
177
+ )
178
+ state_grads, energy_value = energy_grad(
179
+ jnp.array([1.0, 3.0])
180
+ )
181
+ ```
182
+
183
+ The finder excludes `cache` because the filter selects only `ParamState`, even though `energy` writes that State.
184
+
185
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
186
+
187
+ ## Destructure gradient returns exactly
188
+
189
+ 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.
190
+
191
+ | `grad_states` | `argnums` | `has_aux` | `return_value` | Result |
192
+ |---|---|---:|---:|---|
193
+ | `None` | selected | `False` | `False` | `arg_grads` |
194
+ | `None` | selected | `True` | `False` | `(arg_grads, aux)` |
195
+ | `None` | selected | `False` | `True` | `(arg_grads, loss)` |
196
+ | `None` | selected | `True` | `True` | `(arg_grads, loss, aux)` |
197
+ | selected | `None` | `False` | `False` | `state_grads` |
198
+ | selected | `None` | `True` | `False` | `(state_grads, aux)` |
199
+ | selected | `None` | `False` | `True` | `(state_grads, loss)` |
200
+ | selected | `None` | `True` | `True` | `(state_grads, loss, aux)` |
201
+ | selected | selected | `False` | `False` | `(state_grads, arg_grads)` |
202
+ | selected | selected | `True` | `False` | `((state_grads, arg_grads), aux)` |
203
+ | selected | selected | `False` | `True` | `((state_grads, arg_grads), loss)` |
204
+ | selected | selected | `True` | `True` | `((state_grads, arg_grads), loss, aux)` |
205
+
206
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
207
+
208
+ Bundle the most information-rich case as one loss and one destructuring pattern:
209
+
210
+ ```python
211
+ example_model = LinearRegressor(1)
212
+
213
+
214
+ def loss_with_metrics(
215
+ l2_coeff: float,
216
+ x: jax.Array,
217
+ target: jax.Array,
218
+ ):
219
+ """Loss function that returns auxiliary metrics."""
220
+ pred = example_model(x)
221
+ mse = jnp.mean((pred - target) ** 2)
222
+ l2 = jnp.sum(example_model.weight.value ** 2)
223
+ loss = mse + l2_coeff * l2
224
+ metrics = {
225
+ "mae": jnp.mean(jnp.abs(pred - target)),
226
+ "mse": mse,
227
+ "l2": l2,
228
+ }
229
+ return loss, metrics
230
+
231
+
232
+ grad_complete = grad(
233
+ loss_with_metrics,
234
+ grad_states=example_model.states(brainstate.ParamState),
235
+ argnums=0,
236
+ has_aux=True,
237
+ return_value=True,
238
+ )
239
+
240
+ (
241
+ (state_grads, coeff_grad),
242
+ loss_val,
243
+ aux_metrics,
244
+ ) = grad_complete(0.3, xs, y_true)
245
+ ```
246
+
247
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
248
+
249
+ ## Select vector, jacobian, or second-order derivatives
250
+
251
+ BrainState provides `vector_grad`, `jacrev`, `jacfwd`, `jacobian`, and `hessian` with the same State-aware signature pattern as `grad`.
252
+
253
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
254
+
255
+ ### Sum gradients of vector outputs with `vector_grad`
256
+
257
+ `vector_grad` is for a vector-valued function and computes the sum of gradients across all output dimensions. It is not the full Jacobian.
258
+
259
+ ```python
260
+ from brainstate.transform import vector_grad
261
+
262
+
263
+ def vector_fun(x):
264
+ """Vector-valued function."""
265
+ return jnp.array(
266
+ [
267
+ x[0] * x[1],
268
+ jnp.sin(x[0]),
269
+ x[0] ** 2 + x[1] ** 2,
270
+ ]
271
+ )
272
+
273
+
274
+ x0 = jnp.array([1.0, 2.0])
275
+ vgrad = vector_grad(vector_fun)
276
+ result = vgrad(x0)
277
+ ```
278
+
279
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
280
+
281
+ ### Compute full jacobians
282
+
283
+ 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`.
284
+
285
+ ```python
286
+ from brainstate.transform import jacrev, jacfwd, jacobian
287
+
288
+
289
+ def multi_output(x):
290
+ """Function with multiple outputs."""
291
+ return jnp.array(
292
+ [
293
+ x[0] * x[1],
294
+ jnp.sin(x[0]),
295
+ jnp.exp(x[1]),
296
+ ]
297
+ )
298
+
299
+
300
+ x0 = jnp.array([1.0, 2.0])
301
+ result_rev = jacrev(multi_output)(x0)
302
+ result_fwd = jacfwd(multi_output)(x0)
303
+ result_alias = jacobian(multi_output)(x0)
304
+
305
+ assert jnp.allclose(result_rev, result_fwd)
306
+ assert jnp.allclose(result_rev, result_alias)
307
+ ```
308
+
309
+ The same transform can target State. In the official model example, the output-to-parameter Jacobian preserves State paths:
310
+
311
+ ```python
312
+ jac_model = LinearRegressor(2)
313
+
314
+
315
+ def model_output(x):
316
+ """Multiple outputs from a model."""
317
+ return jac_model(x)
318
+
319
+
320
+ jac_states = jacrev(
321
+ model_output,
322
+ grad_states=jac_model.states(brainstate.ParamState),
323
+ )
324
+
325
+ x_input = jnp.array([1.0, 2.0])
326
+ param_jacobian = jac_states(x_input)
327
+ ```
328
+
329
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
330
+
331
+ ### Compute second derivatives with `hessian`
332
+
333
+ `hessian` computes second-order derivatives.
334
+
335
+ ```python
336
+ from brainstate.transform import hessian
337
+
338
+
339
+ def quadratic(x):
340
+ """Quadratic function."""
341
+ return jnp.dot(x, x)
342
+
343
+
344
+ x0 = jnp.array([1.0, 2.0])
345
+ hess_fn = hessian(quadratic)
346
+ result = hess_fn(x0)
347
+
348
+ expected = 2 * jnp.eye(2)
349
+ assert jnp.allclose(result, expected)
350
+ ```
351
+
352
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
353
+
354
+ ## Bundle fitting loss, auxiliary metrics, and differentiation
355
+
356
+ 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`.
357
+
358
+ ```python
359
+ training_model = LinearRegressor(1)
360
+
361
+ true_weight = 3.0
362
+ true_bias = 1.0
363
+ x_train = jnp.linspace(-1.0, 1.0, 20).reshape(-1, 1)
364
+ y_train = (
365
+ true_weight * x_train
366
+ + true_bias
367
+ + 0.1 * brainstate.random.normal(size=x_train.shape)
368
+ )
369
+
370
+
371
+ @brainstate.transform.jit
372
+ def training_loss(x, y):
373
+ """MSE loss with L2 regularization."""
374
+ pred = training_model(x)
375
+ mse = jnp.mean((pred - y) ** 2)
376
+ l2 = 0.01 * (
377
+ jnp.sum(training_model.weight.value ** 2)
378
+ + jnp.sum(training_model.bias.value ** 2)
379
+ )
380
+ return mse + l2, {"mse": mse, "l2": l2}
381
+
382
+
383
+ loss_grad_fn = grad(
384
+ training_loss,
385
+ grad_states=training_model.states(brainstate.ParamState),
386
+ has_aux=True,
387
+ return_value=True,
388
+ )
389
+
390
+ grads, loss_val, aux = loss_grad_fn(x_train, y_train)
391
+ ```
392
+
393
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
394
+
395
+ 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:
396
+
397
+ ```python
398
+ def loss_fn():
399
+ data_loss = jnp.mean((model(x) - y) ** 2)
400
+ return data_loss + model.reg_penalty()
401
+ ```
402
+
403
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
404
+
405
+ ## Integrate with the compiled training step
406
+
407
+ 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.
408
+
409
+ ```python
410
+ import braintools
411
+ from brainstate.nn import clip_grad_norm
412
+ from braintools.metric import (
413
+ softmax_cross_entropy_with_integer_labels,
414
+ )
415
+
416
+
417
+ optimizer = braintools.optim.Adam(lr=1e-2)
418
+ optimizer.register_trainable_weights(
419
+ model.states(brainstate.ParamState)
420
+ )
421
+ params = model.states(brainstate.ParamState)
422
+
423
+
424
+ @brainstate.transform.jit
425
+ def train_step(x, y):
426
+ def loss_fn():
427
+ logits = model(x)
428
+ return softmax_cross_entropy_with_integer_labels(
429
+ logits,
430
+ y,
431
+ ).mean()
432
+
433
+ grads, loss = brainstate.transform.grad(
434
+ loss_fn,
435
+ params,
436
+ return_value=True,
437
+ )()
438
+ grads = clip_grad_norm(grads, max_norm=1.0)
439
+ optimizer.update(grads)
440
+ return loss
441
+ ```
442
+
443
+ Return to `skills/brainstate/SKILL.md` for the general training structure. Open `references/braintools-optimizer-reference.md` only for optimizer or scheduler selection.
444
+
445
+ Official source: https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html
446
+
447
+ ## Failure rules
448
+
449
+ - Match destructuring to all four controls: `grad_states`, `argnums`, `has_aux`, and `return_value`.
450
+ - When both `grad_states` and `argnums` are selected, do not flatten their gradients together; the result groups them as `(state_grads, arg_grads)`.
451
+ - With `has_aux=True`, return `(scalar_loss, aux)` from the differentiated function; do not make auxiliary metrics the differentiated result.
452
+ - Do not use `vector_grad` when the full output-by-input Jacobian is required; it sums gradients across output dimensions.
453
+ - Choose `jacrev` versus `jacfwd` from the documented input/output-size tradeoff, and remember that `jacobian` aliases `jacrev`.
454
+ - Do not assume only `ParamState` can receive gradients; any explicit `State` can be a sensitivity target.
455
+ - Do not assume an attached regularizer changes fitting unless its penalty is added to the scalar loss.
456
+ - Do not infer BrainCell integration, reset, unit, or solver semantics from these sources; route specialized dynamics to the matching BrainCell or BrainPy-State skill.
457
+
458
+ ## Mirror source urls
459
+
460
+ - https://brainx.chaobrain.com/brainstate/tutorials/transformations/02_autodiff.html
461
+ - https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html
462
+ - https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
@@ -0,0 +1,167 @@
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
+ ## Selection map
11
+
12
+ | Need | Use | Key constraint |
13
+ |---|---|---|
14
+ | Compile a complete State-reading or State-writing operation | `brainstate.transform.jit` | Keep the boundary around a stable whole step so every State effect is tracked. |
15
+ | Compile before the first normal invocation | `JittedFunction.compile(...)` | Supply representative argument shapes, dtypes, and static values. |
16
+ | Drop cached traces | `JittedFunction.clear_cache()` | The next compatible call retraces and recompiles. |
17
+ | Specialize Python control flow | `static_argnums` or `static_argnames` | Every distinct static value can create another compiled variant. |
18
+ | Use raw `jax.jit` | Expose a pure array/PyTree boundary | Do not close over mutable BrainState State. |
19
+
20
+ The examples share these imports:
21
+
22
+ ```python
23
+ import jax
24
+ import jax.numpy as jnp
25
+
26
+ import brainstate
27
+ ```
28
+
29
+ ## Verify write-back across multiple states
30
+
31
+ 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.
32
+
33
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
34
+
35
+ ```python
36
+ class RunningMean(brainstate.nn.Module):
37
+ def __init__(self):
38
+ super().__init__()
39
+ self.sum = brainstate.HiddenState(jnp.array(0.0))
40
+ self.count = brainstate.HiddenState(jnp.array(0))
41
+
42
+ def __call__(self, batch: jax.Array) -> jax.Array:
43
+ self.sum.value += jnp.sum(batch)
44
+ self.count.value += batch.size
45
+ return self.sum.value / self.count.value
46
+
47
+
48
+ tracker = RunningMean()
49
+
50
+
51
+ @brainstate.transform.jit
52
+ def update_running_mean(batch: jax.Array) -> jax.Array:
53
+ return tracker(batch)
54
+
55
+
56
+ for step in range(3):
57
+ data = jnp.arange(4.0) + step
58
+ print(f"step {step}: mean={float(update_running_mean(data)):.2f}")
59
+
60
+ assert float(tracker.sum.value) == 30.0
61
+ assert int(tracker.count.value) == 12
62
+ ```
63
+
64
+ 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.
65
+
66
+ ## Precompile or clear cached traces
67
+
68
+ `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.
69
+
70
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
71
+
72
+ ```python
73
+ @brainstate.transform.jit
74
+ def softplus(x: jax.Array) -> jax.Array:
75
+ return jnp.log1p(jnp.exp(-jnp.abs(x))) + jnp.maximum(x, 0)
76
+
77
+
78
+ example = jnp.ones((4,))
79
+ softplus.compile(example)
80
+ result = softplus(example)
81
+
82
+ softplus.clear_cache()
83
+ result_after_clear = softplus(jnp.linspace(-1.0, 1.0, 5))
84
+ ```
85
+
86
+ The routed tutorial identifies `origin_fun` but does not demonstrate how to call it. Do not infer a usage contract from its name alone.
87
+
88
+ When JIT is disabled globally, BrainState falls back to the original Python implementation automatically:
89
+
90
+ ```python
91
+ with jax.disable_jit():
92
+ result_without_jit = softplus(example * 2.0)
93
+ ```
94
+
95
+ ## Specialize python control with static arguments
96
+
97
+ 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`.
98
+
99
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
100
+
101
+ ```python
102
+ @brainstate.transform.jit(static_argnums=1)
103
+ def polynomial_series(x: jax.Array, degree: int) -> jax.Array:
104
+ powers = [x ** (i + 1) for i in range(degree)]
105
+ coeffs = jnp.arange(1, degree + 1, dtype=x.dtype)
106
+ return jnp.tensordot(
107
+ coeffs,
108
+ jnp.stack(powers, axis=0),
109
+ axes=1,
110
+ )
111
+
112
+
113
+ x = jnp.array([1.0, 2.0])
114
+ p1 = polynomial_series(x, 3)
115
+ p2 = polynomial_series(x, 3)
116
+ p3 = polynomial_series(x, 4)
117
+
118
+ assert jnp.allclose(p1, jnp.array([6.0, 34.0]))
119
+ assert jnp.allclose(p2, p1)
120
+ assert jnp.allclose(p3, jnp.array([10.0, 98.0]))
121
+ ```
122
+
123
+ 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.
124
+
125
+ ## Keep the compilation boundary at a whole step
126
+
127
+ `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.
128
+
129
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/06_transformations_essentials.html
130
+
131
+ 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.
132
+
133
+ ## Cross into raw `jax.jit` only with a pure interface
134
+
135
+ 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.
136
+
137
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
138
+
139
+ ```python
140
+ def running_mean_pure(carry, batch):
141
+ total, count = carry
142
+ total = total + jnp.sum(batch)
143
+ count = count + batch.size
144
+ return (total, count), total / count
145
+
146
+
147
+ jax_jitted = jax.jit(running_mean_pure)
148
+ carry = (jnp.array(0.0), jnp.array(0))
149
+
150
+ for step in range(3):
151
+ batch = jnp.arange(4.0) + step
152
+ carry, mean = jax_jitted(carry, batch)
153
+
154
+ total, count = carry
155
+ assert float(total) == 30.0
156
+ assert int(count) == 12
157
+ ```
158
+
159
+ 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.
160
+
161
+ ## Selection checklist
162
+
163
+ - Use the main skill for the canonical state-aware JIT rule and minimal forward script.
164
+ - Use this reference for multi-State write-back, `compile()`, `clear_cache()`, static specialization, whole-step boundaries, or a pure-JAX boundary.
165
+ - Use `brainstate.transform.jit` for module-centric stateful code.
166
+ - Use raw `jax.jit` only when the computation is pure or all mutable values are threaded explicitly.
167
+ - Do not claim lowering, benchmark methodology, or undocumented recompilation triggers from these two sources.