brainx-skill 1.0.6 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +10 -8
  2. package/adapters/gemini.js +7 -0
  3. package/adapters/opencode.js +7 -0
  4. package/adapters/windsurf.js +7 -0
  5. package/installation/lib/installer.js +4 -1
  6. package/manifest.json +6 -1
  7. package/package.json +8 -2
  8. package/skills/braincell/SKILL.md +182 -0
  9. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  10. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +273 -0
  11. package/skills/braincell/references/channel-library.md +85 -0
  12. package/skills/braincell/references/ion-library.md +87 -0
  13. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  14. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  15. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  16. package/skills/braincell/references/multicompartment/filter-function-library.md +154 -0
  17. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  18. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  19. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  20. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +260 -0
  21. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  22. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  23. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  24. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  25. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  26. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  27. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  28. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  29. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  30. package/skills/brainevent/SKILL.md +268 -0
  31. package/skills/brainevent/references/connectivity-variants.md +312 -0
  32. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  33. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  34. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  35. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  36. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  37. package/skills/brainevent/references/sparse-formats.md +182 -0
  38. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  39. package/skills/brainmass/SKILL.md +290 -0
  40. package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
  41. package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
  42. package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  43. package/skills/brainmass/references/braintools/cogtask.md +190 -0
  44. package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
  45. package/skills/brainmass/references/braintools/metric.md +157 -0
  46. package/skills/brainmass/references/braintools/optimizer.md +187 -0
  47. package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
  48. package/skills/brainmass/references/braintools/surrogate.md +151 -0
  49. package/skills/brainmass/references/coupling-network-api.md +148 -0
  50. package/skills/brainmass/references/datasets-api.md +72 -0
  51. package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
  52. package/skills/brainmass/references/forward-observation-api.md +131 -0
  53. package/skills/brainmass/references/horn-task-training.md +199 -0
  54. package/skills/brainmass/references/modellibrary.md +104 -0
  55. package/skills/brainmass/references/noiseprocesses.md +121 -0
  56. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
  57. package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
  58. package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
  59. package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
  60. package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
  61. package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
  62. package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
  63. package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
  64. package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
  65. package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
  66. package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
  67. package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
  68. package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
  69. package/skills/brainmass/references/visualization-analysis-api.md +130 -0
  70. package/skills/brainpy-state/SKILL.md +232 -0
  71. package/skills/brainpy-state/references/array-creation.md +158 -0
  72. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  73. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  75. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  76. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  77. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  78. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  79. package/skills/brainpy-state/references/component-selection.md +273 -0
  80. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  81. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  82. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  83. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  84. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  85. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  86. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  87. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  88. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  89. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  90. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  91. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  92. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  93. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  94. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  95. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  96. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  97. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  98. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  99. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  100. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  101. package/skills/brainstate/SKILL.md +1 -1
  102. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
  103. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
  104. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
  105. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
  106. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
  107. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
  108. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
  109. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
  110. package/skills/brainstate/references/collective_model_operations.md +9 -9
  111. package/skills/brainstate/references/extension_mechanisms.md +12 -1
  112. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
  113. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
  114. package/skills/brainstate/references/model-interop-and-migration.md +11 -1
  115. package/skills/brainstate/references/size-inference-variations.md +11 -0
  116. package/skills/brainstate/references/state-graph-operations.md +13 -15
  117. package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
  118. package/skills/brainx-general-guard/SKILL.md +68 -0
  119. package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
  120. package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
@@ -1,6 +1,10 @@
1
- # Brainstate transformed diagnostics
1
+ # BrainState transformed diagnostics
2
2
 
3
- Open this first-layer reference after `skills/brainstate/SKILL.md` when runtime values, state updates, or failures must be inspected from transformed BrainState code. The skill owns the core transformation model; this reference only adds diagnostics that execute after tracing or turn value-dependent failures into data or runtime exceptions.
3
+ Use this reference after `skills/brainstate/SKILL.md` when runtime values, State
4
+ updates, or failures must be inspected from transformed BrainState code. The
5
+ skill owns the core transformation model; this reference only adds diagnostics
6
+ that execute after tracing or turn value-dependent failures into data or
7
+ runtime exceptions.
4
8
 
5
9
  ## Choose the diagnostic outcome
6
10
 
@@ -1,9 +1,23 @@
1
- # Brainstate constrained and regularized parameters
1
+ # BrainState constrained and regularized parameters
2
2
 
3
- Use this first-layer reference after `skills/brainstate/SKILL.md` has selected `brainstate.nn.Param` for a value that needs a valid-domain transform, a regularization penalty, a modeling prior, or fixed parameter-like storage. It owns the operational workflow and common patterns. Open `references/brainstate/parameter-transforms-regularizers-catalog.md` only when selecting an exact built-in transform or regularizer beyond the common choices shown here.
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.
4
10
 
5
11
  Keep `brainstate.nn` parameter transforms separate from execution transforms such as `brainstate.transform.jit`, `grad`, and `vmap`.
6
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
+
7
21
  ## Parameter contract
8
22
 
9
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.
@@ -1,6 +1,11 @@
1
- # Brainstate parameter transforms and regularizers catalog
2
-
3
- This is the exhaustive selection reference for `brainstate.nn` parameter transforms and regularizers. Open it only from `references/brainstate/parameter-constraints-regularization.md`, after that parent has established the operational `nn.Param` workflow. Return to the parent for `ParamState` versus `nn.Param`, `nn.Const`, forward computation, optimizer targeting, and loss integration.
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.
4
9
 
5
10
  These are parameter-value transforms, not execution transforms such as `brainstate.transform.jit`, `grad`, or `vmap`.
6
11
 
@@ -1,47 +1,55 @@
1
1
  # Brainstate randomness and reproducibility
2
2
 
3
- Open this reference after `skills/brainstate/SKILL.md` when a task needs independent streams, repeated stochastic trials, random calls inside a transformed operation, dropout or noise, direct key control, parallel key preparation, exact replay, or RNG state stored with a checkpoint.
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
4
 
5
- The skill owns the global `DEFAULT` generator and ordinary seeding path; do not repeat those basics here. The supplemental rule is that `brainstate.random` wraps JAX random generation in a stateful interface with automatic key splitting, while its random functions remain JIT-compatible.
5
+ The root skill owns `brainstate.random.DEFAULT` and ordinary seeding. This reference owns advanced stream and key control.
6
6
 
7
- Source: https://brainx.chaobrain.com/brainstate/apis/random.html
7
+ ## Independent streams
8
8
 
9
- ## Independent streams and repeated trials
9
+ Use one `RandomState` per independent concern. Calls consume successive keys from that stream.
10
10
 
11
- "For advanced use cases, you can create custom `RandomState` instances with independent random streams." Use one `RandomState` per concern whose sequence must advance independently, such as data augmentation and model initialization. Consecutive calls on one instance are successive stochastic trials from that stream.
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. |
12
16
 
13
17
  ```python
14
18
  import brainstate
15
19
  import jax.numpy as jnp
16
20
 
17
- rng1 = brainstate.random.RandomState(42)
18
- rng2 = brainstate.random.RandomState(123)
21
+ init_rng = brainstate.random.RandomState(seed=42)
22
+ augment_rng = brainstate.random.RandomState(seed=123)
19
23
 
20
- samples1 = rng1.randn(5)
21
- samples2 = rng2.randn(5)
24
+ initial_weights = init_rng.randn(5)
25
+ augmented_values = augment_rng.randn(5)
22
26
 
23
- assert not jnp.allclose(samples1, samples2)
27
+ assert not jnp.allclose(initial_weights, augmented_values)
24
28
  ```
25
29
 
26
- The API also supports the explicit keyword form `brainstate.random.RandomState(seed=123)` and instance methods such as `rng.normal(0, 1, size=(10, 10))`. Use the advanced section below when the task requires direct key manipulation.
27
-
28
- Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
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.
29
31
 
30
- ## Stochastic calls, transforms, dropout, and noise
32
+ ## Stochastic calls under transforms
31
33
 
32
- BrainState random functions are JIT-compatible. Apply the whole-operation `brainstate.transform` rule from `skills/brainstate/SKILL.md` to stochastic code just as you do to other stateful code. The advanced section below covers mapped randomness under `vmap`, parallel key assignment, and explicit key control.
34
+ BrainState random calls advance state and work under JIT. Transform the complete stateful operation with `brainstate.transform`.
33
35
 
34
- The tutorial's dropout pattern bundles fit-mode gating, mask generation, and inverse-keep scaling in the stochastic call:
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. |
35
41
 
36
42
  ```python
43
+ import brainstate
44
+
45
+
37
46
  class Dropout(brainstate.nn.Module):
38
47
  def __init__(self, drop_rate=0.5):
39
48
  super().__init__()
40
49
  self.drop_rate = drop_rate
41
50
 
42
51
  def __call__(self, x):
43
- fit = brainstate.environ.get('fit', False)
44
- if not fit:
52
+ if not brainstate.environ.get("fit", False):
45
53
  return x
46
54
 
47
55
  keep_prob = 1.0 - self.drop_rate
@@ -49,162 +57,75 @@ class Dropout(brainstate.nn.Module):
49
57
  return x * mask / keep_prob
50
58
  ```
51
59
 
52
- When `fit` is false, the module returns `x` unchanged. When fitting, `bernoulli` draws the mask with mean `keep_prob`, and division by `keep_prob` applies the tutorial's scaling.
53
-
54
- The tutorial's noisy-layer pattern keeps trainable values in `ParamState` and draws fresh Gaussian weight noise inside every call. Two consecutive calls are two stochastic trials because automatic key management advances the random state.
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.
55
61
 
56
- ```python
57
- class NoisyLayer(brainstate.nn.Module):
58
- def __init__(self, d_in, d_out, noise_std=0.1):
59
- super().__init__()
60
- self.noise_std = noise_std
61
- self.w = brainstate.ParamState(
62
- brainstate.random.randn(d_in, d_out) * 0.1
63
- )
64
- self.b = brainstate.ParamState(jnp.zeros(d_out))
62
+ Open `references/brainstate/transformation-vmap-expansion.md` for mapped State axes, per-example randomness, and concrete `vmap` workflows.
65
63
 
66
- def __call__(self, x):
67
- w_noisy = self.w.value + brainstate.random.normal(
68
- 0,
69
- self.noise_std,
70
- self.w.value.shape,
71
- )
72
- return x @ w_noisy + self.b.value
73
-
74
-
75
- layer = NoisyLayer(5, 3, noise_std=0.01)
76
- x = jnp.ones(5)
77
- y1 = layer(x)
78
- y2 = layer(x)
79
- ```
64
+ ## Exact replay and checkpoints
80
65
 
81
- Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
66
+ Snapshot the global key immediately before the sequence to replay. Restoring that snapshot reproduces the next draw.
82
67
 
83
- ## Checkpoint the rng with the model
84
-
85
- When exact stochastic continuation matters, the tutorial saves the model and current RNG key in the same checkpoint, then restores the key before continuing:
86
-
87
- ```python
88
- checkpoint = {
89
- 'model': model.state_dict(),
90
- 'rng_key': brainstate.random.get_key()
91
- }
92
-
93
- brainstate.random.set_key(checkpoint['rng_key'])
94
- ```
95
-
96
- Keep this compact checkpoint requirement here because it determines what must be saved. Read the advanced section below before adapting key restoration, restoring multiple streams, or defining more elaborate checkpoint behavior.
97
-
98
- Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
99
-
100
- ## Advanced brainstate randomness
101
-
102
- Use this section when a task needs direct key control, parallel key preparation, exact key replay, custom-generator state inspection, or checkpoint behavior beyond the ordinary stochastic path above.
103
-
104
- ### Snapshot a global key and replay from it
105
-
106
- The tutorial's advanced boundary is: "For advanced use cases, you can directly access and manipulate keys." Bundle inspection and restoration with the operation whose randomness must be replayed:
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. |
107
74
 
108
75
  ```python
109
76
  import brainstate
110
77
  import jax.numpy as jnp
111
78
 
112
79
  saved_key = brainstate.random.get_key()
113
- v1 = brainstate.random.randn(3)
114
- _ = brainstate.random.randn(3)
80
+ sample = brainstate.random.randn(3)
115
81
 
116
82
  brainstate.random.set_key(saved_key)
117
- v1_replayed = brainstate.random.randn(3)
83
+ replayed = brainstate.random.randn(3)
118
84
 
119
- assert jnp.allclose(v1, v1_replayed)
85
+ assert jnp.allclose(sample, replayed)
120
86
  ```
121
87
 
122
- The snapshot is the sequence position immediately before `v1`; restoring it makes the next draw reproduce `v1`. Use `get_key()` / `set_key(...)` for this explicit snapshot-and-replay contract. Keep `restore_key()` distinct: the API describes it only as restoring "the default random key to its previous state," so do not silently substitute it for a named checkpoint snapshot.
123
-
124
- Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
125
-
126
- API definitions: https://brainx.chaobrain.com/brainstate/apis/random.html
127
-
128
- ### Prepare keys for parallel or mapped work
129
-
130
- The API groups these as "Functions for creating independent random keys for parallel computation." The tutorial's documented parallel preparation is:
88
+ For exact continuation, save the model and RNG key together:
131
89
 
132
90
  ```python
133
- keys = brainstate.random.split_key(n=4)
91
+ checkpoint = {
92
+ "model": model.state_dict(),
93
+ "rng_key": brainstate.random.get_key(),
94
+ }
134
95
 
135
- for i, key in enumerate(keys):
136
- print(i, key)
96
+ # Restore model state first, then restore the RNG before the next random call.
97
+ brainstate.random.set_key(checkpoint["rng_key"])
137
98
  ```
138
99
 
139
- Select the narrowest documented operation:
140
-
141
- | API | Documented role |
142
- |---|---|
143
- | `split_key` | Create new random key(s) from the current seed. The tutorial uses `split_key(n=4)` for parallel operations. |
144
- | `split_keys` | Create multiple independent random keys from the current seed. |
145
- | `self_assign_multi_keys` | Assign multiple keys to the global random state for parallel access. |
146
-
147
- The routed pages do not provide a `vmap` call, mapped key-axis configuration, or per-example key-consumption rule. They only identify `vmap` as a next step and document the parallel key utilities above. Do not invent mapped semantics from these pages; combine these RNG operations with a separately documented BrainState mapping workflow when concrete `vmap` mechanics are required.
148
-
149
- Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
150
-
151
- API definitions: https://brainx.chaobrain.com/brainstate/apis/random.html
152
-
153
- ### Inspect custom-stream state and choose advanced generators
154
-
155
- After selecting a custom `RandomState`, the API documents its current key through `.value`:
156
-
157
- ```python
158
- rng = brainstate.random.RandomState(seed=123)
159
- _ = rng.normal(0, 1, size=(10, 10))
160
- current_stream_key = rng.value
161
- ```
100
+ Capture the key after every random operation included in the completed run. An earlier key intentionally replays later draws.
162
101
 
163
- This is the documented custom-stream state inspection surface. The routed pages demonstrate reseeding a custom generator with `rng.seed(999)`, but they do not demonstrate assigning a saved value back to a custom generator or restoring several custom streams. Do not apply the global `set_key(...)` API to `rng`: its documented target is the global random state.
102
+ ## Parallel key preparation
164
103
 
165
- For generator selection without restating the independent-stream example above:
104
+ Prepare independent keys before parallel work. Do not infer mapped key-consumption semantics from these utilities alone.
166
105
 
167
- | API | Documented role |
106
+ | API | Description |
168
107
  |---|---|
169
- | `default_rng` | Get the default random state or create a new one with a specified seed. |
170
- | `clone_rng` | Create a clone of the random state or a new random state. |
171
- | `seed_context` | Temporarily change the random seed with automatic restoration. |
172
-
173
- The same API page's example spells the temporary context as `local_seed(123)`, while its API table lists `seed_context`. Because the routed source is internally inconsistent, verify the installed BrainState version before choosing the callable name.
174
-
175
- Source: https://brainx.chaobrain.com/brainstate/apis/random.html
176
-
177
- Custom reseeding example: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
178
-
179
- ### Checkpoint at the intended sequence boundary
180
-
181
- The tutorial's checkpoint pattern stores the current global key beside the model and restores that exact key before stochastic work resumes:
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. |
182
111
 
183
112
  ```python
184
- checkpoint = {
185
- 'model': model.state_dict(),
186
- 'rng_key': brainstate.random.get_key(),
187
- }
188
-
189
- # Restore model state through the model's checkpoint path first.
190
- brainstate.random.set_key(checkpoint['rng_key'])
113
+ keys = brainstate.random.split_key(n=4)
191
114
  ```
192
115
 
193
- Capture `rng_key` after every random operation that belongs to the completed portion of the run. Restoring an earlier snapshot intentionally replays draws after that snapshot, as the replay script above demonstrates. A checkpoint with multiple custom streams additionally needs each stream's current key, but these routed pages document only reading a custom key through `rng.value`; they do not supply a multi-stream restoration script. Keep such restoration out of generated code until a source for that specific mechanism is selected.
194
-
195
- Source: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
116
+ Open `references/brainstate/transformation-vmap-expansion.md` for mapped axes, mapped State, and concrete `vmap` mechanics.
196
117
 
197
- ### Key api distinctions
118
+ ## Generator helpers
198
119
 
199
- - `get_key()` returns the current global random key.
200
- - `get_key_data()` returns the current global random key as raw `uint32[2]` data; use it only when raw key data is the required interchange form.
201
- - `set_key(...)` sets a new key on the global random state.
202
- - `restore_key()` restores the default key to its previous state.
203
- - `RandomState.value` is the API page's documented way to inspect the current key of a custom generator.
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. |
204
125
 
205
- Source: https://brainx.chaobrain.com/brainstate/apis/random.html
126
+ The API table names `seed_context`; its example uses `local_seed`. Check the installed BrainState version before calling either name.
206
127
 
207
128
  ## Official sources
208
129
 
209
- - https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
210
- - https://brainx.chaobrain.com/brainstate/apis/random.html
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)
@@ -1,4 +1,4 @@
1
- # Brainstate gradient and autodiff expansion
1
+ # BrainState gradient and autodiff expansion
2
2
 
3
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
4
 
@@ -10,6 +10,18 @@ Official sources:
10
10
  - https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html
11
11
  - https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
12
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
+
13
25
  ## Select the derivative target
14
26
 
15
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.
@@ -1,4 +1,4 @@
1
- # Brainstate jit expansion
1
+ # BrainState jit expansion
2
2
 
3
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
4
 
@@ -7,6 +7,16 @@ Official sources:
7
7
  - https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
8
8
  - https://brainx.chaobrain.com/brainstate/tutorials/core/06_transformations_essentials.html
9
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
+
10
20
  The examples share these imports:
11
21
 
12
22
  ```python
@@ -1,14 +1,32 @@
1
- # Brainstate vmap expansion
1
+ # BrainState vmap expansion
2
2
 
3
- ## Scope and source boundary
4
-
5
- Open this reference after the minimal `brainstate.transform.vmap` example in `skills/brainstate/SKILL.md`. The vectorization tutorial describes `brainstate.transform.vmap` as a state-aware wrapper around `jax.vmap`, but its detailed executable examples use `brainstate.transform.vmap2`. Preserve that distinction when adapting a script; do not silently substitute one API for the other.
3
+ Use this reference after the minimal `brainstate.transform.vmap` example in
4
+ `skills/brainstate/SKILL.md` when argument axes, State axes, random-key policy,
5
+ nested mappings, or unexpected State writes require explicit control.
6
6
 
7
7
  This reference covers only behavior demonstrated by these routed official tutorials:
8
8
 
9
9
  - Vectorization: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html
10
10
  - Random Number Generation: https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
11
11
 
12
+ The Vectorization tutorial describes `brainstate.transform.vmap` as a
13
+ state-aware wrapper around `jax.vmap`, but its detailed executable examples use
14
+ `brainstate.transform.vmap2`. Preserve that distinction; do not silently
15
+ substitute one API for the other.
16
+
17
+ ## Selection map
18
+
19
+ | Need | Control | Key constraint |
20
+ |---|---|---|
21
+ | Map or broadcast function arguments | `in_axes` | Use an integer axis to map and `None` to share. |
22
+ | Place the mapped output axis | `out_axes` | Match the downstream layout explicitly. |
23
+ | Map with no mapped input argument | `axis_size` | Supply the size because it cannot be inferred. |
24
+ | Use collectives over the mapped axis | `axis_name` | The collective must use the same name. |
25
+ | Map mutable State but share parameters | `vmap2(..., state_in_axes=..., state_out_axes=...)` with State filters | Define both input mapping and write-back for per-instance State. |
26
+ | Handle a written State omitted from `state_out_axes` | `vmap2(..., unexpected_out_state_mapping=...)` | The default `'auto'` infers and scatters the mapped axis; declare State axes when a coincidental leading-size match would be ambiguous. |
27
+ | Choose independent or shared random draws | BrainState automatic splitting or one broadcast JAX key | Shared keys intentionally correlate mapped results. |
28
+ | Build a custom mapping primitive | `StatefulMapping` | Use only when `vmap` or `vmap2` cannot express the required primitive. |
29
+
12
30
  The Vectorization tutorial imports the detailed mapping API and State filter as follows:
13
31
 
14
32
  ```python
@@ -128,10 +146,17 @@ Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vec
128
146
 
129
147
  ## Handle state writes outside `state_out_axes`
130
148
 
131
- `unexpected_out_state_mapping` controls behavior when a State is written but is not covered by `state_out_axes`. The tutorial demonstrates the default `'ignore'` policy with a written `LongTermState` that is not listed in State-axis filters.
149
+ `unexpected_out_state_mapping` controls behavior when a State is written but is
150
+ not covered by `state_out_axes`. The current generated `vmap2` API defaults to
151
+ `'auto'`, which infers the output axis and scatters the write. The `'raise'`
152
+ policy raises `BatchAxisError`; `'warn'` and `'ignore'` scatter with or without
153
+ a warning. The tutorial demonstrates an explicit `'ignore'` policy with a
154
+ written `LongTermState` that is not listed in State-axis filters.
132
155
 
133
156
  Source: https://brainx.chaobrain.com/brainstate/tutorials/transformations/03_vectorization.html#the-unexpected-out-state-mapping-parameter
134
157
 
158
+ Exact policy source: https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.transform.vmap2.html
159
+
135
160
  ```python
136
161
  temp_state = brainstate.ShortTermState(jnp.array(0.0))
137
162
  write_state = brainstate.LongTermState(jnp.asarray(0.0))
@@ -151,7 +176,10 @@ vmap_ignore = vmap2(
151
176
  result = vmap_ignore(jnp.array([1.0, 2.0, 3.0]))
152
177
  ```
153
178
 
154
- Treat an unexpected write as an explicit policy decision. Do not assume that mapping only the function arguments also specifies the output behavior of every State the function mutates.
179
+ Declare the State axes when an unexpected read-modify-write could be mistaken
180
+ for per-lane State because its leading size happens to match the mapped size.
181
+ Do not assume that mapping only the function arguments also specifies the
182
+ output behavior of every State the function mutates.
155
183
 
156
184
  ## Choose independent or shared randomness
157
185
 
@@ -281,6 +309,6 @@ Do not infer semantics for `vmap_new_states`, `vmap2_new_states`, `map`, `pmap2`
281
309
  - Match every non-`None` `in_axes` entry to an actual mapped dimension of the corresponding argument.
282
310
  - Decide whether mutable State is shared or mapped; use `state_in_axes` and `state_out_axes` together for per-instance State write-back.
283
311
  - Set `axis_size` when all inputs are static.
284
- - Set an explicit policy for State writes not covered by `state_out_axes`.
312
+ - Declare State axes or set an explicit policy when automatic output-axis inference would be ambiguous.
285
313
  - Expect automatic independent `RandomState` keys; use the documented broadcast-key pattern only when shared randomness is intentional.
286
314
  - Route direct key manipulation through the randomness reference rather than duplicating it here.
@@ -1,20 +1,20 @@
1
- # Brainstate collective operations
1
+ # BrainState collective operations
2
2
 
3
3
  Use this reference when one operation must initialise, reset, batch, invoke a common method on, or restore stateful objects throughout a model without manually traversing its module graph. It assumes familiarity with `brainstate.nn` modules and states and basic JAX `vmap` usage; BrainState requires `brainunit`.
4
4
 
5
- ## Overview of the api
5
+ ## Selection map
6
6
 
7
7
  Source: https://brainx.chaobrain.com/brainstate/how_to/collective_operations.html
8
8
 
9
9
  The official guide presents `brainstate.nn._collective_ops` through these public `brainstate.nn` utilities:
10
10
 
11
- | Operation | API |
12
- |---|---|
13
- | Fix the execution order of methods | `brainstate.nn.call_order` |
14
- | Call the same method on each model node | `brainstate.nn.call_all_fns`, `brainstate.nn.vmap_call_all_fns` |
15
- | Initialise state variables everywhere | `brainstate.nn.init_all_states`, `brainstate.nn.vmap_init_all_states` |
16
- | Reset existing states everywhere | `brainstate.nn.reset_all_states`, `brainstate.nn.vmap_reset_all_states` |
17
- | Restore values keyed by absolute state paths | `brainstate.nn.assign_state_values` |
11
+ | Need | API | Key constraint |
12
+ |---|---|---|
13
+ | Fix the execution order of methods | `brainstate.nn.call_order` | Lower order values run first. |
14
+ | Call the same method on each model node | `brainstate.nn.call_all_fns`, `brainstate.nn.vmap_call_all_fns` | Filter nodes deliberately and verify the installed call signature. |
15
+ | Initialise state variables everywhere | `brainstate.nn.init_all_states`, `brainstate.nn.vmap_init_all_states` | Run after construction and before the first rollout. |
16
+ | Reset existing states everywhere | `brainstate.nn.reset_all_states`, `brainstate.nn.vmap_reset_all_states` | Reset at the intended sequence boundary, not every time step. |
17
+ | Restore values keyed by absolute state paths | `brainstate.nn.assign_state_values` | Inspect both returned mismatch collections. |
18
18
 
19
19
  ## Ordering calls with `call_order`
20
20
 
@@ -1,7 +1,18 @@
1
- # Brainstate extension mechanisms
1
+ # BrainState extension mechanisms
2
2
 
3
3
  Use this reference when a BrainState task needs reusable class behavior, reusable constructor presets, runtime-mode objects, or callbacks around State operations. It deliberately does not restate ordinary State or Module construction and update patterns.
4
4
 
5
+ ## Selection map
6
+
7
+ | Need | Use | Key constraint |
8
+ |---|---|---|
9
+ | Add reusable behavior without owning construction | `mixin.Mixin` | Do not define a competing `__init__` in the mixin. |
10
+ | Capture a reusable constructor preset | `ParamDesc` or `ParamDescriber` | Call the descriptor to create a fresh concrete object. |
11
+ | Require all or any runtime types | `JointTypes` or `OneOfTypes` | These express intersection versus union checks. |
12
+ | Centralize runtime execution semantics | `Mode` and its concrete mode types | Keep mode in runtime configuration rather than trainable State. |
13
+ | Observe State reads or completed writes | `read` or `write_after` hooks | These hooks inspect only; they cannot transform or cancel the operation. |
14
+ | Transform or reject a pending State write | `write_before` hook | Set `ctx.transformed_value` to replace the value or `ctx.cancel` to preserve the previous value and raise `HookCancellationError`. |
15
+
5
16
  ## Mixin system
6
17
 
7
18
  Source: https://brainx.chaobrain.com/brainstate/how_to/custom_states_and_mixins.html