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.
Files changed (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +24 -56
  3. package/{lib → installation/lib}/installer.js +4 -4
  4. package/manifest.json +3 -1
  5. package/package.json +19 -9
  6. package/skills/brainstate/SKILL.md +399 -0
  7. package/skills/brainstate/agents/openai.yaml +4 -0
  8. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +483 -0
  9. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +176 -0
  10. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +199 -0
  11. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +166 -0
  12. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +210 -0
  13. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +450 -0
  14. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +157 -0
  15. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +286 -0
  16. package/skills/brainstate/references/braintools-optimizer-reference.md +133 -0
  17. package/skills/brainstate/references/collective_model_operations.md +195 -0
  18. package/skills/brainstate/references/extension_mechanisms.md +282 -0
  19. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -0
  20. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +217 -0
  21. package/skills/brainstate/references/libraries/solver-library-with-effects.md +85 -0
  22. package/skills/brainstate/references/model-interop-and-migration.md +295 -0
  23. package/skills/brainstate/references/simulation-environment.md +117 -0
  24. package/skills/brainstate/references/size-inference-variations.md +268 -0
  25. package/skills/brainstate/references/state-graph-operations.md +218 -0
  26. package/skills/brainstate/references/state_collections_and_utilities.md +224 -0
  27. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  28. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  29. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  30. package/skills/brainstate/scripts/resnet.py +130 -0
  31. package/skills/brainunit/SKILL.md +287 -0
  32. package/skills/brainunit/references/array-creation.md +158 -0
  33. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  34. package/skills/brainunit/references/array-mechanics.md +165 -0
  35. package/skills/brainunit/references/math-function-library.md +433 -0
  36. package/skills/brainunit/references/physical-constant-library.md +58 -0
  37. package/skills/brainunit/references/prefix-library.md +116 -0
  38. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  39. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  40. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  41. package/skills/brainx-install/SKILL.md +21 -13
  42. package/skills/brainx-install/references/compatibility-and-release-matching.md +12 -10
  43. package/skills/brainx-install/references/uninstall-and-cleanup.md +186 -0
  44. /package/{bin → installation/bin}/brainx.js +0 -0
  45. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  46. /package/{lib → installation/lib}/bundle.js +0 -0
  47. /package/{lib → installation/lib}/cli.js +0 -0
  48. /package/{lib → installation/lib}/constants.js +0 -0
  49. /package/{lib → installation/lib}/hash.js +0 -0
  50. /package/{lib → installation/lib}/paths.js +0 -0
  51. /package/{lib → installation/lib}/prompts.js +0 -0
  52. /package/{lib → installation/lib}/receipt.js +0 -0
package/LICENSE CHANGED
@@ -186,7 +186,7 @@
186
186
  same "printed page" as the copyright notice for easier
187
187
  identification within third-party archives.
188
188
 
189
- Copyright [yyyy] [name of copyright owner]
189
+ Copyright 2026 BrainX Team
190
190
 
191
191
  Licensed under the Apache License, Version 2.0 (the "License");
192
192
  you may not use this file except in compliance with the License.
package/README.md CHANGED
@@ -1,29 +1,39 @@
1
- # BrainX Agent Skills
1
+ # BrainX Skill
2
2
 
3
- ## What BrainX installs
3
+ [![Supported BrainX release](https://img.shields.io/badge/BrainX-v2026.7.9-007EC6?style=flat)](skills/brainx-install/references/compatibility-and-release-matching.md#version-compatibility-matrix)
4
+ [![License](https://img.shields.io/badge/License-Apache%202.0-4C1?style=flat)](LICENSE)
5
+ [![npm downloads](https://img.shields.io/npm/dm/brainx-skill?label=npm&color=007EC6&style=flat)](https://www.npmjs.com/package/brainx-skill)
6
+ [![Skills](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fchaobrain%2FBrainX-skill%2Fmain%2Fmanifest.json&query=%24.skills.length&label=Skills&color=007EC6&style=flat)](manifest.json)
7
+ [![Agent Skills validation](https://img.shields.io/github/actions/workflow/status/chaobrain/BrainX-skill/agent-skills-validation.yml?branch=main&label=Agent%20Skills&style=flat)](https://github.com/chaobrain/BrainX-skill/actions/workflows/agent-skills-validation.yml)
8
+ [![OpenSSF Scorecard](https://img.shields.io/ossf-scorecard/github.com/chaobrain/BrainX-skill?label=OpenSSF&style=flat)](https://scorecard.dev/viewer/?uri=github.com/chaobrain/BrainX-skill)
4
9
 
5
- `brainx-skill` distributes one canonical BrainX Agent Skill bundle for Claude Code, Codex, and Cursor. The current bundle contains only `brainx-install`. The npm package version is the release version for the CLI and the complete published bundle.
10
+ [![Works with Claude Code, Codex, and Cursor](https://img.shields.io/badge/Works%20with-Claude%20Code%20%7C%20Codex%20%7C%20Cursor-007EC6?style=flat)](#installation-locations)
11
+
12
+ make your coding agent understand the power of BrainX
6
13
 
7
14
  ## Requirements
8
15
 
9
16
  - Node.js 18 or newer
10
17
  - macOS, Linux, or Windows
11
- - Write access to your user-level skill directories
12
-
13
- The installer does not require harness executables to be on `PATH`.
14
-
15
18
  ## Install
16
19
 
17
20
  ```bash
18
21
  npx brainx-skill install
19
22
  ```
20
23
 
21
- The installer detects existing harness directories, lets you keep the detected set or customize it, then installs globally or in the current project. Global installation is the default.
24
+ ```bash
25
+ # Claude Code, current project
26
+ npx skills add chaobrain/BrainX-skill --agent claude-code
22
27
 
23
- If npm resolves a stale cached package, request the latest release explicitly:
28
+ # Codex, current project
29
+ npx skills add chaobrain/BrainX-skill --agent codex
24
30
 
25
- ```bash
26
- npx brainx-skill@latest install
31
+ # Claude Code, globally
32
+ npx skills add chaobrain/BrainX-skill --agent claude-code --global
33
+
34
+ # Specific project
35
+ cd /actual/path/to/project
36
+ npx skills add chaobrain/BrainX-skill --agent codex
27
37
  ```
28
38
 
29
39
  ## Update
@@ -32,14 +42,13 @@ npx brainx-skill@latest install
32
42
  npx brainx-skill update
33
43
  ```
34
44
 
35
- To force npm to resolve the latest published release:
45
+
46
+ ## Install when the internet connection is low
36
47
 
37
48
  ```bash
38
- npx brainx-skill@latest update
49
+ npx --registry=https://registry.npmmirror.com brainx-skill install
39
50
  ```
40
51
 
41
- Update uses the harness destinations recorded by the previous installation and does not prompt again. It replaces only skill directories proven to be owned by `brainx-skill`. If no managed installation exists, it leaves all destinations unchanged.
42
-
43
52
  ## Installation locations
44
53
 
45
54
  Depending on the selected scope, the canonical `brainx-install` skill is installed into:
@@ -51,44 +60,3 @@ Cursor: ~/.cursor/skills/<skill-name> or <cwd>/.cursor/skills/<skill-name>
51
60
  ```
52
61
 
53
62
  Installation ownership is recorded in `~/.brainx/receipt.json`.
54
-
55
- ## Managed-files warning
56
-
57
- Installed BrainX skill directories are package-managed and may be replaced during install or update. Do not edit installed copies. Edit the canonical skill in the source repository and publish a new package release instead.
58
-
59
- Directories that are not proven to be BrainX-managed are never overwritten or deleted.
60
-
61
- ## Troubleshooting
62
-
63
- - Conflict errors identify an existing unowned directory. Move or remove that directory, then retry.
64
- - Permission errors identify the affected agent and path. Restore write access to that user-level directory, then retry.
65
- - An invalid receipt blocks destructive changes. Inspect `~/.brainx/receipt.json` and restore a valid receipt before retrying.
66
- - A partial failure can leave one agent updated and the other unchanged. Resolve the reported destination and run the same command again.
67
-
68
- ## Development and publishing notes
69
-
70
- Run the tests and inspect the package contents without publishing:
71
-
72
- ```bash
73
- npm test
74
- npm pack --dry-run
75
- npm pack
76
- test_home="$(mktemp -d '/tmp/brainx skills.XXXXXX')"
77
- HOME="$test_home" npx --yes --package ./brainx-skill-1.0.2.tgz brainx install
78
- HOME="$test_home" npx --yes --package ./brainx-skill-1.0.2.tgz brainx update
79
- ```
80
-
81
- To preview the interaction directly from this checkout:
82
-
83
- ```bash
84
- npx --yes --package . brainx install
85
- ```
86
-
87
- Recheck that the npm name is available, authenticate, and publish with:
88
-
89
- ```bash
90
- npm view brainx-skill
91
- npm publish --access public
92
- ```
93
-
94
- Do not run the publication command until the package contents and release version have been reviewed.
@@ -3,9 +3,9 @@
3
3
  const os = require('node:os');
4
4
  const fs = require('node:fs/promises');
5
5
  const path = require('node:path');
6
- const codex = require('../adapters/codex');
7
- const claude = require('../adapters/claude');
8
- const cursor = require('../adapters/cursor');
6
+ const codex = require('../../adapters/codex');
7
+ const claude = require('../../adapters/claude');
8
+ const cursor = require('../../adapters/cursor');
9
9
  const { prepareAdapter, AdapterOperationError } = require('./adapter-transaction');
10
10
  const { validateBundle } = require('./bundle');
11
11
  const { PACKAGE_NAME, RECEIPT_SCHEMA_VERSION } = require('./constants');
@@ -51,7 +51,7 @@ async function runInstaller(command, options = {}) {
51
51
  const availableAdapters = options.adapters || DEFAULT_ADAPTERS;
52
52
  const stdout = options.stdout || process.stdout;
53
53
  const stderr = options.stderr || process.stderr;
54
- const packageRoot = options.packageRoot || path.resolve(__dirname, '..');
54
+ const packageRoot = options.packageRoot || path.resolve(__dirname, '../..');
55
55
  const homeDir = options.homeDir || os.homedir();
56
56
  const cwd = options.cwd || process.cwd();
57
57
  const now = options.now || (() => new Date().toISOString());
package/manifest.json CHANGED
@@ -1,6 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "skills": [
4
- "brainx-install"
4
+ "brainx-install",
5
+ "brainunit",
6
+ "brainstate"
5
7
  ]
6
8
  }
package/package.json CHANGED
@@ -1,17 +1,22 @@
1
1
  {
2
2
  "name": "brainx-skill",
3
- "version": "1.0.2",
3
+ "version": "1.0.6",
4
4
  "description": "Portable BrainX Agent Skills for Claude Code, Codex, and Cursor",
5
5
  "license": "Apache-2.0",
6
6
  "type": "commonjs",
7
+ "scripts": {
8
+ "test": "node --test .github/scripts/*.test.mjs",
9
+ "prepublishOnly": "npm test"
10
+ },
7
11
  "bin": {
8
- "brainx": "bin/brainx.js"
12
+ "brainx": "installation/bin/brainx.js"
9
13
  },
10
14
  "files": [
11
15
  "adapters/",
12
- "bin/",
13
- "lib/",
16
+ "installation/",
14
17
  "skills/brainx-install/",
18
+ "skills/brainunit/",
19
+ "skills/brainstate/",
15
20
  "manifest.json",
16
21
  "README.md",
17
22
  "LICENSE"
@@ -22,17 +27,22 @@
22
27
  "dependencies": {
23
28
  "enquirer": "^2.4.1"
24
29
  },
25
- "scripts": {
26
- "test": "node --test test/bundle.test.js test/cli.test.js test/installer.test.js test/paths.test.js test/prompts.test.js",
27
- "prepublishOnly": "npm test"
28
- },
29
30
  "repository": {
30
31
  "type": "git",
31
- "url": "git+https://github.com/Wilsonnijc-bot/BrainX-skill.git"
32
+ "url": "git+https://github.com/chaobrain/BrainX-skill.git"
33
+ },
34
+ "homepage": "https://github.com/chaobrain/BrainX-skill#readme",
35
+ "bugs": {
36
+ "url": "https://github.com/chaobrain/BrainX-skill/issues"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public",
40
+ "provenance": true
32
41
  },
33
42
  "keywords": [
34
43
  "agent-skills",
35
44
  "brainx",
45
+ "brainunit",
36
46
  "claude-code",
37
47
  "codex",
38
48
  "cursor"
@@ -0,0 +1,399 @@
1
+ ---
2
+ name: brainstate
3
+ description: BrainState is the central stateful execution infrastructure for BrainX modeling and simulation. Use this skill for mutable State and `.value`, ParamState and other State roles, Module graphs, environment-scoped simulations, state initialization, operational randomness, size-aware neural-network composition, state-aware jit/grad/vmap, or a BrainState training step.
4
+ ---
5
+
6
+ # Brainstate
7
+
8
+ ## Purpose and boundary
9
+
10
+ Use this skill for BrainState's general stateful workflow: mutable `State`, registered `brainstate.nn.Module` graphs, environment-scoped simulation, state initialization and collection, randomness, state-aware transforms, and simulation or training.
11
+
12
+ Canonical path:
13
+
14
+ `classify State roles -> construct Modules -> register State and children -> initialize -> set the run environment -> transform the whole operation -> validate State and outputs`
15
+
16
+ Open the routed reference for specialized variants; route specialized neuronal or network dynamics to the matching BrainCell or BrainPy-State skill.
17
+
18
+ ## Underlying principle of BrainState
19
+
20
+ BrainState reconciles mutable models with JAX by making mutation explicit: store every value that changes during transformed execution in `State`. Its State roles match distinct model lifecycles; for example, `HiddenState` holds voltages, firing rates, and other dynamics updated each simulation step.
21
+
22
+ Wrap the complete stateful operation in `brainstate.transform`. Unlike raw JAX transforms, its JAX-like `jit`, `grad`, and `vmap` discover State reads and writes, differentiate selected State collections, and map or share State during vectorization.
23
+
24
+ ### API structure
25
+
26
+ Choose the namespace that owns the operation:
27
+
28
+ | API | Use |
29
+ |---|---|
30
+ | `brainstate` | Store values that mutate during transformed execution in `State`, and mark their lifecycle with semantic State subclasses. |
31
+ | `brainstate.graph` | Inspect, split, merge, or reconstruct Module and State graphs while preserving shared references and cycles. |
32
+ | `brainstate.nn` | Build registered `Module` graphs from parameters, layers, dynamics, delays, and metrics. |
33
+ | `brainstate.transform` | Apply State-aware JIT, differentiation, vectorization, parallelization, or control flow to a complete stateful operation. |
34
+ | `brainstate.interop` | Convert supported standard-layer models between `brainstate.nn`, Flax NNX, Flax Linen, and Equinox. |
35
+ | `brainstate.random` | Seed and sample reproducibly through stateful JAX keys with automatic splitting. |
36
+ | `brainstate.util` | Organize supporting mappings, filters, representations, dataclasses, and caches that do not require model-graph identity; use `graph` for Module or State structure. |
37
+ | `brainstate.typing` | Annotate arrays, shapes, dtypes, keys, filters, and PyTrees with JAX-, NumPy-, and BrainUnit-compatible types. |
38
+ | `brainstate.mixin` | Add reusable behavioral contracts, computation modes, or deferred `.desc()` construction to components. |
39
+ | `brainstate.environ` | Share run settings such as time, fitting mode, precision, and platform without storing them in model State or threading them through Module signatures. |
40
+
41
+ ### 1. State is the mutation boundary
42
+
43
+ `State` is a typed, mutable container for an array or stable PyTree; read and replace it through `.value`, including inside BrainState transformations. Treat it as a fixed-structure slot: keep static configuration in ordinary attributes and preserve value type, shape, dtype, and PyTree structure across writes.
44
+
45
+ #### Create scalar, array, and pytree state
46
+
47
+ ```python
48
+ import brainstate
49
+ import brainstate.nn as nn
50
+ import brainunit as u
51
+ import jax.numpy as jnp
52
+
53
+ counter = brainstate.State(jnp.array(0))
54
+ vector = brainstate.State(jnp.zeros(10))
55
+ neuron = brainstate.State({
56
+ "V": jnp.zeros(5),
57
+ "u": jnp.ones(5),
58
+ })
59
+
60
+ value = neuron.value
61
+ neuron.value = {
62
+ "V": value["V"] + 0.1,
63
+ "u": value["u"],
64
+ }
65
+
66
+ with brainstate.check_state_value_tree():
67
+ neuron.value = {
68
+ "V": jnp.zeros(5),
69
+ "u": jnp.ones(5),
70
+ }
71
+ ```
72
+
73
+
74
+ #### Substate
75
+
76
+ State subclasses remain State containers but act as semantic markers for filtering and model organization. Use these non-parameter roles for hidden or runtime values:
77
+
78
+ | Role | Use |
79
+ |---|---|
80
+ | `HiddenState` | Internal activations or dynamical state retained between updates |
81
+ | `ShortTermState` | Transient runtime values such as current input or last spike time |
82
+ | `LongTermState` | Persistent non-parameter values such as running statistics |
83
+
84
+ ```python
85
+ h = brainstate.HiddenState(jnp.zeros(5))
86
+ last_spike = brainstate.ShortTermState(jnp.full(5, -1e7))
87
+ running_mean = brainstate.LongTermState(jnp.zeros(5))
88
+ ```
89
+
90
+ ### 2. Modules form registered state graphs
91
+
92
+ Subclass `brainstate.nn.Module`, assign each `State` and child `Module` to an attribute, and implement computation in `update()`; assignment registers a traversable graph whose State leaves can be filtered by role:
93
+
94
+ ```python
95
+ params = model.states(brainstate.ParamState)
96
+ ```
97
+
98
+ #### Add state to a module
99
+
100
+ ```python
101
+ class Counter(brainstate.nn.Module):
102
+ def __init__(self):
103
+ super().__init__()
104
+ self.count = brainstate.ShortTermState(jnp.array(0))
105
+
106
+ def update(self, x):
107
+ self.count.value = self.count.value + 1
108
+ return x * self.count.value
109
+
110
+
111
+ counter_module = Counter()
112
+ for _ in range(5):
113
+ print(counter_module(jnp.array(10.0)), counter_module.count.value)
114
+ ```
115
+
116
+ The output advances through `(10, 1)`, `(20, 2)`, ..., `(50, 5)` because the registered State is updated explicitly.
117
+
118
+ #### Use basic prebuilt layers
119
+
120
+ ```python
121
+ brainstate.random.seed(42)
122
+
123
+ linear = nn.Linear(in_size=(10,), out_size=(5,))
124
+ relu = nn.ReLU()
125
+ conv = nn.Conv2d(
126
+ in_size=(28, 28, 3),
127
+ out_channels=32,
128
+ kernel_size=3,
129
+ padding="SAME",
130
+ )
131
+
132
+ x = brainstate.random.randn(8, 10)
133
+ y = relu(linear(x))
134
+ assert y.shape == (8, 5)
135
+ ```
136
+
137
+ Open the layer and activation catalogs instead of guessing an uncommon class name or signature.
138
+
139
+ #### Parameter
140
+
141
+ `nn.Param` wraps an underlying `ParamState` with an optional constraint transform and regularizer; model code reads `.value()`, while optimizers update `.val`.
142
+
143
+ | Role | Use |
144
+ |---|---|
145
+ | `ParamState` | Trainable weights, biases, or other unconstrained values that need no parameter transform or regularizer |
146
+ | `nn.Param` | A trainable parameter that needs the richer transform or regularization contract |
147
+ | `nn.Const` | A fixed forward value kept in the Module graph but excluded from `ParamState` collection, gradients, and optimizer updates |
148
+
149
+ Use `nn.SoftplusT(lower=L)` for a value constrained to `(L, infinity)`; `.value()` stays in range while `.val` remains unconstrained. Do not confuse parameter transforms with execution transforms such as `brainstate.transform.jit`.
150
+
151
+ ```python
152
+ w = brainstate.ParamState(brainstate.random.randn(10, 5) * 0.1)
153
+ b = brainstate.ParamState(jnp.zeros(5))
154
+
155
+ gain = nn.Param(jnp.array(1.0))
156
+ positive_tau = nn.Param(jnp.array(2.0), t=nn.SoftplusT(lower=0.1))
157
+ fixed_scale = nn.Const(jnp.array(10.0))
158
+
159
+ print(gain.value()) # IdentityT by default; usable and stored values coincide
160
+ print(positive_tau.value()) # constrained model value, always greater than 0.1
161
+ print(positive_tau.val) # underlying unconstrained ParamState
162
+ print(fixed_scale.value()) # fixed value, excluded from ParamState collection
163
+ ```
164
+
165
+ ### 3. Size inference drives composition
166
+
167
+ Size-aware Modules carry feature-shape metadata without the batch dimension, so composition code can construct and validate each next layer before execution.
168
+
169
+ | API | Description |
170
+ |---|---|
171
+ | `Module.in_size` | Set the expected per-sample feature shape on the first or a standalone layer when it is known; the layer uses it to initialize shape-dependent values, validate inputs, and infer `out_size`, returning a size tuple or `None`. |
172
+ | `Module.out_size` | Read the inferred per-sample output shape after construction when wiring the next layer; it returns a size tuple or `None` and avoids duplicating shape calculations. |
173
+ | `nn.Sequential(first, *layers)` | Use for an ordered input-output pipeline; it feeds each runtime output to the next layer, propagates size metadata through the chain, and exposes the first `in_size` and final `out_size`. |
174
+ | `Layer.desc(**kwargs)` | Use after the first layer when the next layer's `in_size` should come from the preceding `out_size`; it stores the other constructor arguments, and `Sequential` replaces the descriptor with a concrete layer initialized with that inferred size. |
175
+
176
+ ```python
177
+ model = nn.Sequential(
178
+ nn.Linear(in_size=(10,), out_size=(8,)),
179
+ nn.ReLU(),
180
+ nn.Linear.desc(out_size=(2,)),
181
+ )
182
+
183
+ x = brainstate.random.randn(4, 10)
184
+ y = model(x)
185
+
186
+ assert model.layers[2].in_size == (8,)
187
+ assert model.out_size == (2,)
188
+ assert y.shape == (4, 2)
189
+ ```
190
+
191
+ Open `references/size-inference-variations.md` to compose `ComplexNet` with `Sequential` and `.desc()`, or when convolution, pooling, and flattening make size propagation non-obvious.
192
+
193
+ ### 4. Environment context drives simulations
194
+
195
+ Use `brainstate.environ` to share run settings across a computation, where scoped contexts override persistent defaults and model code reads the active value.
196
+
197
+ | API | Description |
198
+ |---|---|
199
+ | `brainstate.environ.context(**settings)` | Use for one simulation, training phase, evaluation phase, or step; it pushes temporary settings, inherits unspecified outer values, and restores the previous values on exit, including exceptional exit. |
200
+ | `brainstate.environ.get_dt()` | Use inside numerical dynamics that require the active integration step; it returns `dt` from the selected environment and raises `KeyError` when `dt` is unset. |
201
+ | `brainstate.nn.init_all_states(target, **kwargs)` | Use after constructing a stateful Module and before its first rollout; it calls `init_state()` across the graph in `@call_order` order and returns the initialized target. |
202
+ | `brainstate.transform.for_loop(step, *xs)` | Use for a State-aware time loop; it slices each input along its leading axis and returns the stacked per-step outputs. |
203
+
204
+ ```python
205
+ with brainstate.environ.context(dt=0.1 * u.ms, fit=False):
206
+ brainstate.nn.init_all_states(net)
207
+ times = u.math.arange(
208
+ 0.0 * u.ms,
209
+ 100.0 * u.ms,
210
+ brainstate.environ.get_dt(),
211
+ )
212
+ step_indices = jnp.arange(times.shape[0])
213
+
214
+ def step(t, i):
215
+ with brainstate.environ.context(t=t, i=i):
216
+ return net.update(input_current)
217
+
218
+ outputs = brainstate.transform.for_loop(
219
+ step,
220
+ times,
221
+ step_indices,
222
+ )
223
+ ```
224
+
225
+ Open `references/simulation-environment.md` for persistent defaults, generic setting access, nested or isolated environments, precision and platform controls, `exp_euler_step()`, and environment-specific failures.
226
+
227
+ ### 5. State-aware transforms
228
+
229
+ Wrap the complete forward, simulation, or training step in `brainstate.transform`; its JAX-like `jit`, `grad`, and `vmap` track State reads and writes, while raw JAX transforms can lose State mutations.
230
+
231
+ #### Canonical transformation setup
232
+
233
+ ```python
234
+ brainstate.random.seed(0)
235
+ model = nn.Linear(in_size=(3,), out_size=(1,))
236
+ x_train = brainstate.random.randn(64, 3)
237
+ y_train = brainstate.random.randn(64, 1)
238
+ params = model.states(brainstate.ParamState)
239
+ ```
240
+
241
+ #### State-aware jit example
242
+
243
+ ```python
244
+ forward = brainstate.transform.jit(model)
245
+ prediction = forward(x_train)
246
+ assert prediction.shape == (64, 1)
247
+ ```
248
+
249
+ The first compatible call traces and compiles the complete forward pass; later compatible calls reuse it while BrainState handles State effects.
250
+
251
+ #### Gradient and parameter update example
252
+
253
+ `grad` differentiates with respect to a State collection and returns gradients keyed by the same State paths. `return_value=True` returns the loss from the same pass.
254
+
255
+ ```python
256
+ def loss_fn():
257
+ return jnp.mean((model(x_train) - y_train) ** 2)
258
+
259
+
260
+ grads, loss = brainstate.transform.grad(
261
+ loss_fn,
262
+ params,
263
+ return_value=True,
264
+ )()
265
+
266
+ for key in params:
267
+ params[key].value -= 0.1 * grads[key]
268
+ ```
269
+
270
+ #### Composed training-step transform
271
+
272
+ ```python
273
+ @brainstate.transform.jit
274
+ def train_step():
275
+ grads, loss = brainstate.transform.grad(
276
+ loss_fn,
277
+ params,
278
+ return_value=True,
279
+ )()
280
+ for key in params:
281
+ params[key].value -= 0.1 * grads[key]
282
+ return loss
283
+
284
+
285
+ loss = train_step()
286
+ ```
287
+
288
+ Use `jit(grad(...))` as the default compiled training-step backbone. Open the optimizer reference when manual updates should become optimizer-managed updates.
289
+
290
+ #### State-aware `vmap`
291
+
292
+ ```python
293
+ def predict_one(x_row):
294
+ return model(x_row[None, :])[0]
295
+
296
+
297
+ predict_batch = brainstate.transform.vmap(predict_one)
298
+ batched_prediction = predict_batch(x_train)
299
+ assert batched_prediction.shape == (64, 1)
300
+ ```
301
+
302
+ This maps a function written for one example over a batch. Open the `vmap` expansion for mapped State axes, ensembles, parameter sweeps, or the documented `state_in_axes` / `state_out_axes` controls. The routed tutorial does not define the rough draft's `in_states` / `out_states` names.
303
+
304
+ ### 6. Randomness
305
+
306
+ In BrainX modeling, seed BrainState's stateful generator before model construction or simulation so initialization, stochastic inputs, noise, dropout, and data order follow the same automatically split key sequence.
307
+
308
+ | API | Description |
309
+ |---|---|
310
+ | `brainstate.random.DEFAULT` | Global `RandomState` used by module-level random functions; it manages and splits JAX keys automatically. |
311
+ | `brainstate.random.seed(seed)` | Set the global seed for JAX and NumPy; call it before random work that must be reproducible. |
312
+ | `brainstate.random.rand(*shape)` / `random(size)` | Draw uniform samples in `[0, 1)` for stochastic thresholds such as spike or dropout probabilities. |
313
+ | `brainstate.random.randn(*shape)` / `normal(loc, scale, size)` | Draw standard or parameterized Gaussian samples for parameter initialization and model noise. |
314
+ | `brainstate.random.bernoulli(p, size)` | Draw Bernoulli samples for binary events and masks. |
315
+ | `brainstate.random.shuffle(x, axis=0)` / `permutation(x)` | Randomly reorder data, trials, or indices; `shuffle()` returns a shuffled copy along the selected axis. |
316
+
317
+ #### Generate reproducible stochastic input
318
+
319
+ ```python
320
+ brainstate.random.seed(42)
321
+
322
+ num_steps, batch_size, num_inputs = 100, 128, 100
323
+ firing_rate = 5.0 * u.Hz
324
+
325
+ with brainstate.environ.context(dt=1.0 * u.ms):
326
+ spike_probability = firing_rate * brainstate.environ.get_dt()
327
+ input_spikes = (
328
+ brainstate.random.rand(num_steps, batch_size, num_inputs)
329
+ < spike_probability
330
+ )
331
+
332
+ assert input_spikes.shape == (num_steps, batch_size, num_inputs)
333
+ ```
334
+
335
+ Open `references/brainstate/randomness-and-reproducibility.md` for independent `RandomState` streams, direct key control, stochastic mapping, exact replay, or checkpointed RNG State.
336
+
337
+ ## Script references
338
+
339
+ - `scripts/integrator_rnn.py`: full stateful sequence-training workflow with a custom RNN cell, trainable initial state, optimization, compiled steps, and evaluation.
340
+ - `scripts/lif_neuron_model.py`: extended combination of `HiddenState`, `ShortTermState`, and `ParamState` with explicit `.value` updates.
341
+ - `scripts/modern_cnn.py`: full convolution, normalization, activation, pooling, dropout, and dense Module composition. Select it through the layer or activation branch.
342
+ - `scripts/resnet.py`: residual Modules and dynamically registered child blocks.
343
+
344
+ ## Reference routing
345
+
346
+ Route by the outcome the task needs, then open only the smallest reference that owns that variant.
347
+
348
+ ### State graphs, collections, and lifecycle
349
+
350
+ | Reference | Open when |
351
+ |---|---|
352
+ | `references/state-graph-operations.md` | Splitting, transforming, checkpointing, or reconstructing Module graphs while preserving sharing and cycles |
353
+ | `references/state_collections_and_utilities.md` | Filtering, freezing, flattening, configuring, or inspecting supporting mappings without graph identity |
354
+ | `references/collective_model_operations.md` | Initializing, resetting, restoring, or invoking methods across a Module graph, including vmapped lifecycle operations |
355
+
356
+ ### Simulation environment
357
+
358
+ | Reference | Open when |
359
+ |---|---|
360
+ | `references/simulation-environment.md` | Managing persistent, scoped, nested, Module-bound, or isolated environments, including precision, platform, and `exp_euler_step()` |
361
+
362
+ ### Model composition, extension, and interoperation
363
+
364
+ | Reference | Open when |
365
+ |---|---|
366
+ | `references/size-inference-variations.md` | Resolving convolution, padding, pooling, or `Flatten` size propagation in `Sequential` / `.desc()` pipelines |
367
+ | `references/extension_mechanisms.md` | Adding reusable `Mixin` behavior, deferred `ParamDesc` construction, runtime `Mode` semantics, or State hooks |
368
+ | `references/model-interop-and-migration.md` | Converting models or weights among BrainState, Flax NNX/Linen, Equinox, and PyTorch |
369
+
370
+ ### Parameters, optimization, and randomness
371
+
372
+ | Reference | Open when |
373
+ |---|---|
374
+ | `references/brainstate/parameter-constraints-regularization.md` | Using `nn.Param` transforms, regularizers, priors, penalties, or `nn.Const` |
375
+ | `references/braintools-optimizer-reference.md` | Selecting a `braintools.optim`, Optax, SciPy, or Nevergrad optimizer or scheduler |
376
+ | `references/brainstate/randomness-and-reproducibility.md` | Creating independent random streams or exact stochastic replay across transforms and checkpoints |
377
+
378
+ The remaining nested reference has one inbound route:
379
+
380
+ - Only `parameter-constraints-regularization.md` may open `parameter-transforms-regularizers-catalog.md`.
381
+
382
+ ### Layer libraries
383
+
384
+ | Reference | Open when |
385
+ |---|---|
386
+ | `references/libraries/prebuilt-layer-library.md` | Selecting a BrainState linear, convolutional, normalization, pooling, padding, or dropout layer |
387
+ | `references/libraries/prebuilt-activation-library.md` | Selecting a Module activation or pure lowercase activation function |
388
+
389
+ ### Stateful transformations
390
+
391
+ | Reference | Open when |
392
+ |---|---|
393
+ | `references/brainstate/transformation-jit-expansion.md` | Controlling State write-back, raw `jax.jit` boundaries, caching, or static specialization |
394
+ | `references/brainstate/transformation-grad-expansion.md` | Controlling `argnums`, `grad_states`, gradient returns, higher-order transforms, or fitting overlays |
395
+ | `references/brainstate/transformation-vmap-expansion.md` | Mapping or sharing State across batches, ensembles, or sweeps, including State axes and randomness |
396
+ | `references/brainstate/brainstate-control-flow-patterns.md` | Choosing transform-safe loops, scans, branches, or checkpointed control flow |
397
+ | `references/brainstate/brainstate-transformed-diagnostics.md` | Debugging runtime values or enforcing invariants inside transformed stateful code |
398
+
399
+ Do not route to dynamics or solver references from this skill; they are outside the architecture supplied for this BrainState skill.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "BrainState"
3
+ short_description: "Build stateful BrainState modules and transforms"
4
+ default_prompt: "Use $brainstate to build or debug a stateful BrainState model."