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,235 @@
1
+ # BrainState state collections and utility toolkit
2
+
3
+ Use this reference for the collection-focused parts of BrainState's Utility Toolkit: managing mappings, nested configuration, dictionary conversion, immutable structured PyTrees, declarative filters, and readable PyTree containers. These utilities organize data; the core `State` and `Module` programming model remains in the parent `SKILL.md`.
4
+
5
+ Official page: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
6
+
7
+ ## Selection map
8
+
9
+ | Need | Use | Key constraint |
10
+ |---|---|---|
11
+ | Filter, split, or transform a mapping | `DictManager` | Operates on collection values; it does not preserve Module graph identity. |
12
+ | Access nested configuration by attribute | `DotDict` | Convert back with `to_dict()` at plain-dictionary boundaries. |
13
+ | Merge or convert dotted-key dictionaries | `merge_dicts`, `flatten_dict`, `unflatten_dict` | Dotted-string keys differ from tuple graph paths. |
14
+ | Keep an immutable structured mapping | `FrozenDict` and related PyTree utilities | Replace values functionally rather than mutating in place. |
15
+ | Build a reusable path/value predicate | `to_predicate`, `OfType`, `WithTag`, `Any`, or `All` | Filters receive both path and value. |
16
+ | Preserve readable nested or flat PyTree containers | `NestedDict`, `FlattedDict`, `PrettyList`, `flat_mapping`, `nest_mapping` | `flat_mapping` uses tuple paths, not dotted strings. |
17
+
18
+ ## Managing collections with `DictManager`
19
+
20
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
21
+
22
+ `DictManager` extends the standard mapping interface with filters, splits, combination operators, and JAX PyTree support. The page demonstrates `subset(...)` for one matching collection, `split(...)` for matching and remaining collections, and `map_values(...)` for transforming the retained values.
23
+
24
+ ```python
25
+ from brainstate.util import DictManager
26
+
27
+ modules = DictManager({
28
+ 'encoder': {'params': 32},
29
+ 'decoder': {'params': 45},
30
+ 'dropout': 0.1,
31
+ })
32
+
33
+ submods = modules.subset(dict)
34
+ dicts, remainder = modules.split(dict)
35
+ param_counts = submods.map_values(lambda layer: layer['params'])
36
+
37
+ print(submods)
38
+ print(dicts)
39
+ print(remainder)
40
+ print(param_counts)
41
+ ```
42
+
43
+ The demonstrated results retain `encoder` and `decoder` in `submods` and `dicts`, put only `dropout` in `remainder`, and produce `DictManager({'encoder': 32, 'decoder': 45})` for `param_counts`.
44
+
45
+ ## Configuration access with `DotDict`
46
+
47
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
48
+
49
+ `DotDict` lets nested dictionaries act like lightweight objects while preserving conversion back to standard dictionaries when needed.
50
+
51
+ ```python
52
+ from brainstate.util import DotDict
53
+
54
+ config = DotDict({
55
+ 'model': {
56
+ 'layers': 4,
57
+ 'hidden': 256,
58
+ },
59
+ 'training': {
60
+ 'lr': 3e-4,
61
+ 'scheduler': {'warmup_steps': 500},
62
+ },
63
+ })
64
+
65
+ print(config.model.hidden)
66
+ config.training.dropout = 0.2
67
+ round_trip = config.to_dict()
68
+ ```
69
+
70
+ The example reads `config.model.hidden` as `256`, adds `config.training.dropout`, and converts the complete nested configuration back with `to_dict()`.
71
+
72
+ ## Merge, flatten, and unflatten dictionaries
73
+
74
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
75
+
76
+ `merge_dicts` performs optional recursive merges. `flatten_dict` and `unflatten_dict` convert between nested and dotted-key representations, which the page uses for logging or CLI overrides.
77
+
78
+ ```python
79
+ from brainstate.util import flatten_dict, merge_dicts, unflatten_dict
80
+
81
+ base = {'optimizer': {'lr': 1e-3, 'beta1': 0.9}}
82
+ override = {'optimizer': {'lr': 5e-4}, 'seed': 1234}
83
+
84
+ merged = merge_dicts(base, override)
85
+ flat = flatten_dict(merged)
86
+ restored = unflatten_dict(flat)
87
+
88
+ print(merged)
89
+ print(flat)
90
+ print(restored)
91
+ ```
92
+
93
+ The recursive merge preserves `optimizer.beta1`, overrides `optimizer.lr`, and adds `seed`. The demonstrated flattened form is:
94
+
95
+ ```python
96
+ {
97
+ 'optimizer.lr': 0.0005,
98
+ 'optimizer.beta1': 0.9,
99
+ 'seed': 1234,
100
+ }
101
+ ```
102
+
103
+ `unflatten_dict(flat)` restores the nested representation.
104
+
105
+ ## Structured pytrees and frozen mappings
106
+
107
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
108
+
109
+ The `struct` submodule mirrors Flax-friendly data structures. Its `dataclass` decorator registers classes as PyTrees, while `FrozenDict` provides immutable mappings compatible with JAX transformations.
110
+
111
+ ```python
112
+ import jax
113
+ import jax.numpy as jnp
114
+ from brainstate.util import struct
115
+
116
+
117
+ @struct.dataclass
118
+ class LayerConfig:
119
+ weight: jax.Array
120
+ bias: jax.Array
121
+ name: str = struct.field(pytree_node=False, default='layer')
122
+
123
+
124
+ cfg = LayerConfig(
125
+ weight=jnp.ones((2, 2)),
126
+ bias=jnp.zeros(2),
127
+ )
128
+ cfg2 = cfg.replace(weight=jnp.full((2, 2), 3.0))
129
+ flat_leaves, _ = jax.tree_util.tree_flatten(cfg)
130
+
131
+ frozen = struct.freeze({'encoder': jnp.arange(3)})
132
+ unfrozen = struct.unfreeze(frozen)
133
+ ```
134
+
135
+ In the page's result, `cfg.replace(...)` returns a configuration whose weight is filled with `3.0`; flattening `cfg` yields array leaves with shapes `(2, 2)` and `(2,)`, so the `name` field marked `pytree_node=False` is not a dynamic leaf. `struct.freeze(...)` returns a `FrozenDict`, and `struct.unfreeze(...)` returns the ordinary dictionary again.
136
+
137
+ ## Filtering nested objects
138
+
139
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
140
+
141
+ `brainstate.util.filter` turns declarative filters into callables. The page combines tag, type, and path checks when traversing a nested object tree; each predicate is called with `(path, value)`.
142
+
143
+ ```python
144
+ from typing import Any
145
+
146
+ import jax.numpy as jnp
147
+ from brainstate.util import filter as util_filter
148
+
149
+
150
+ class Module:
151
+ def __init__(self, tag: str | None, kind: str):
152
+ self.tag = tag
153
+ self.kind = kind
154
+ self.params = jnp.arange(2)
155
+
156
+
157
+ model_tree = {
158
+ 'encoder': Module(tag='trainable', kind='linear'),
159
+ 'decoder': Module(tag='frozen', kind='linear'),
160
+ 'head': Module(tag='trainable', kind='mlp'),
161
+ }
162
+
163
+ tag_filter = util_filter.to_predicate('trainable')
164
+ type_filter = util_filter.OfType(Module)
165
+ combined = util_filter.All(
166
+ type_filter,
167
+ util_filter.WithTag('trainable'),
168
+ )
169
+
170
+
171
+ def collect(
172
+ tree: dict[str, Any],
173
+ predicate,
174
+ ) -> dict[str, Any]:
175
+ out = {}
176
+ for key, value in tree.items():
177
+ if predicate((key,), value):
178
+ out[key] = value
179
+ return out
180
+
181
+
182
+ trainable_modules = collect(model_tree, tag_filter)
183
+ both = collect(model_tree, combined)
184
+
185
+ print(tuple(trainable_modules.keys()))
186
+ print(tuple(both.keys()))
187
+ ```
188
+
189
+ Both predicates select `('encoder', 'head')` in the demonstrated tree. Use `to_predicate(...)` to normalize the tag filter, `OfType(...)` for the type check, `WithTag(...)` for tag matching, and `All(...)` to require both conditions.
190
+
191
+ ## Pretty pytree containers and tuple-path flattening
192
+
193
+ Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
194
+
195
+ `NestedDict`, `FlattedDict`, and `PrettyList` provide readable representations plus PyTree semantics. The page uses them to explore checkpoints or log structured configurations.
196
+
197
+ ```python
198
+ import jax.numpy as jnp
199
+ from brainstate.util import NestedDict, PrettyList, flat_mapping, nest_mapping
200
+
201
+ state = NestedDict({
202
+ 'encoder': {
203
+ 'weight': jnp.ones((2, 2)),
204
+ 'bias': jnp.zeros(2),
205
+ },
206
+ 'decoder': {
207
+ 'weight': jnp.eye(2),
208
+ },
209
+ })
210
+ print(state)
211
+
212
+ flat_state = flat_mapping(state)
213
+ print(list(flat_state.keys()))
214
+
215
+ round_trip = nest_mapping(flat_state)
216
+ print(round_trip == state)
217
+
218
+ history = PrettyList([
219
+ {'loss': 0.8},
220
+ {'loss': 0.42},
221
+ ])
222
+ print(history)
223
+ ```
224
+
225
+ The displayed flat keys are tuple paths:
226
+
227
+ ```python
228
+ [
229
+ ('encoder', 'weight'),
230
+ ('encoder', 'bias'),
231
+ ('decoder', 'weight'),
232
+ ]
233
+ ```
234
+
235
+ `nest_mapping(flat_state)` round-trips to the nested mapping (`True` in the page), while `NestedDict` and `PrettyList` print their nested contents in an indented, readable form. This tuple-path representation is the one demonstrated by `flat_mapping`; the dictionary utilities section above separately demonstrates dotted-string keys from `flatten_dict`.
@@ -0,0 +1,359 @@
1
+ """
2
+ Reference script mirrored from:
3
+ https://brainx.chaobrain.com/brainstate/examples/deep_learning/integrator_rnn.html
4
+
5
+ Purpose:
6
+ Nested full stateful sequence-training reference for synthetic temporal data, a custom
7
+ RNNCell, trainable initial state, ParamState collection, Adam optimization,
8
+ JIT prediction/training steps, gradient update, L2 regularization, epoch loop,
9
+ and evaluation visualization.
10
+ """
11
+
12
+ from typing import Callable
13
+
14
+ import jax
15
+ import jax.numpy as jnp
16
+ import matplotlib.pyplot as plt
17
+ import numpy as np
18
+
19
+ import brainstate
20
+ import braintools
21
+
22
+ # Set random seeds
23
+ np.random.seed(42)
24
+ brainstate.random.seed(42)
25
+
26
+ # Task parameters
27
+ dt = 0.04 # Time step
28
+ num_step = int(1.0 / dt) # Steps per trial (25 steps for 1.0 time unit)
29
+ num_batch = 512 # Batch size
30
+
31
+ # Network parameters
32
+ num_hidden = 100 # Hidden units in RNN
33
+
34
+ # Training parameters
35
+ learning_rate = 0.025
36
+ lr_decay_rate = 0.99975
37
+ l2_reg = 2e-4
38
+ num_epochs = 5
39
+ batches_per_epoch = 500
40
+
41
+ print(f"Configuration:")
42
+ print(f" Sequence length: {num_step} steps")
43
+ print(f" Batch size: {num_batch}")
44
+ print(f" Hidden units: {num_hidden}")
45
+ print(f" Training batches: {num_epochs * batches_per_epoch}")
46
+
47
+
48
+ @brainstate.transform.jit(static_argnums=2)
49
+ def build_inputs_and_targets(mean=0.025, scale=0.01, batch_size=10):
50
+ """Generate integration task data.
51
+
52
+ Args:
53
+ mean: Mean of the random walk bias
54
+ scale: Standard deviation of noise
55
+ batch_size: Number of sequences
56
+
57
+ Returns:
58
+ inputs: [num_step, batch_size, 1] - Input sequences
59
+ targets: [num_step, batch_size, 1] - Target cumulative sums
60
+ """
61
+ # Create initial bias
62
+ sample = brainstate.random.normal(size=(1, batch_size, 1))
63
+ bias = mean * 2.0 * (sample - 0.5)
64
+
65
+ # Generate white noise
66
+ samples = brainstate.random.normal(size=(num_step, batch_size, 1))
67
+ noise_t = scale / dt ** 0.5 * samples
68
+
69
+ # Inputs = bias + noise
70
+ inputs = bias + noise_t
71
+
72
+ # Targets = cumulative sum of inputs
73
+ targets = jnp.cumsum(inputs, axis=0)
74
+
75
+ return inputs, targets
76
+
77
+
78
+ def train_data():
79
+ """Generator for training data."""
80
+ for _ in range(batches_per_epoch * num_epochs):
81
+ yield build_inputs_and_targets(0.025, 0.01, num_batch)
82
+
83
+
84
+ # Generate one batch for visualization
85
+ sample_inputs, sample_targets = build_inputs_and_targets(0.025, 0.01, 3)
86
+
87
+ fig, axes = plt.subplots(1, 2, figsize=(14, 4))
88
+
89
+ # Plot inputs
90
+ for i in range(3):
91
+ axes[0].plot(sample_inputs[:, i, 0], alpha=0.7, label=f'Sample {i+1}')
92
+ axes[0].set_xlabel('Time Step')
93
+ axes[0].set_ylabel('Input Value')
94
+ axes[0].set_title('Input Sequences (Random Walks)', fontweight='bold')
95
+ axes[0].legend()
96
+ axes[0].grid(True, alpha=0.3)
97
+
98
+ # Plot targets
99
+ for i in range(3):
100
+ axes[1].plot(sample_targets[:, i, 0], alpha=0.7, label=f'Sample {i+1}')
101
+ axes[1].set_xlabel('Time Step')
102
+ axes[1].set_ylabel('Cumulative Sum')
103
+ axes[1].set_title('Target Sequences (Integrals)', fontweight='bold')
104
+ axes[1].legend()
105
+ axes[1].grid(True, alpha=0.3)
106
+
107
+ plt.tight_layout()
108
+ plt.show()
109
+
110
+
111
+ class RNNCell(brainstate.nn.Module):
112
+ """Vanilla RNN cell with trainable weights.
113
+
114
+ h_t = activation(W_combined @ [x_t; h_{t-1}] + b)
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ num_in: int,
120
+ num_out: int,
121
+ state_initializer: Callable = braintools.init.ZeroInit(),
122
+ w_initializer: Callable = braintools.init.XavierNormal(),
123
+ b_initializer: Callable = braintools.init.ZeroInit(),
124
+ activation: Callable = brainstate.nn.relu,
125
+ train_state: bool = False, # Whether to train initial state
126
+ ):
127
+ super().__init__()
128
+
129
+ self.num_out = num_out
130
+ self.train_state = train_state
131
+
132
+ # Activation function
133
+ self.activation = activation
134
+
135
+ # Combined weight matrix [input; hidden] -> hidden
136
+ W = braintools.init.param(
137
+ w_initializer,
138
+ (num_in + num_out, num_out)
139
+ )
140
+ b = braintools.init.param(b_initializer, (num_out,))
141
+
142
+ self.W = brainstate.ParamState(W)
143
+ self.b = brainstate.ParamState(b) if b is not None else None
144
+
145
+ # Trainable initial state (optional)
146
+ if train_state:
147
+ self.state2train = brainstate.ParamState(
148
+ braintools.init.ZeroInit()(num_out)
149
+ )
150
+
151
+ self._state_initializer = state_initializer
152
+
153
+ def init_state(self, batch_size=None, **kwargs):
154
+ """Initialize hidden state."""
155
+ self.state = brainstate.HiddenState(
156
+ braintools.init.param(
157
+ self._state_initializer,
158
+ (self.num_out,),
159
+ batch_size
160
+ )
161
+ )
162
+
163
+ # Use trainable initial state if specified
164
+ if self.train_state:
165
+ self.state.value = jnp.repeat(
166
+ jnp.expand_dims(self.state2train.value, axis=0),
167
+ batch_size,
168
+ axis=0
169
+ )
170
+
171
+ def update(self, x):
172
+ """Update RNN cell for one time step.
173
+
174
+ Args:
175
+ x: Input [batch, input_dim]
176
+
177
+ Returns:
178
+ h: New hidden state [batch, hidden_dim]
179
+ """
180
+ # Concatenate input and previous hidden state
181
+ x_combined = jnp.concatenate([x, self.state.value], axis=-1)
182
+
183
+ # Linear transformation
184
+ h = x_combined @ self.W.value
185
+ if self.b is not None:
186
+ h += self.b.value
187
+
188
+ # Apply activation
189
+ h = self.activation(h)
190
+
191
+ # Update state
192
+ self.state.value = h
193
+
194
+ return h
195
+
196
+
197
+ class RNN(brainstate.nn.Module):
198
+ """RNN with recurrent layer and linear output."""
199
+
200
+ def __init__(self, num_in, num_hidden):
201
+ super().__init__()
202
+
203
+ # RNN layer with trainable initial state
204
+ self.rnn = RNNCell(num_in, num_hidden, train_state=True)
205
+
206
+ # Output projection
207
+ self.out = brainstate.nn.Linear(num_hidden, 1)
208
+
209
+ def update(self, x):
210
+ """Process one time step.
211
+
212
+ Args:
213
+ x: Input at current time step
214
+
215
+ Returns:
216
+ output: Prediction at current time step
217
+ """
218
+ # RNN forward pass using >> operator (pipe)
219
+ return x >> self.rnn >> self.out
220
+
221
+
222
+ # Create RNN model
223
+ model = RNN(num_in=1, num_hidden=num_hidden)
224
+
225
+ # Get trainable parameters
226
+ weights = model.states(brainstate.ParamState)
227
+
228
+ # Create optimizer with learning rate decay
229
+ lr_schedule = braintools.optim.ExponentialDecayLR(
230
+ learning_rate,
231
+ decay_steps=1,
232
+ decay_rate=lr_decay_rate
233
+ )
234
+ optimizer = braintools.optim.Adam(lr=lr_schedule, eps=1e-1)
235
+ optimizer.register_trainable_weights(weights)
236
+
237
+ brainstate.nn.count_parameters(model)
238
+
239
+
240
+ @brainstate.transform.jit
241
+ def f_predict(inputs):
242
+ """Make predictions for a sequence.
243
+
244
+ Args:
245
+ inputs: [num_steps, batch_size, 1]
246
+
247
+ Returns:
248
+ predictions: [num_steps, batch_size, 1]
249
+ """
250
+ # Initialize RNN state
251
+ brainstate.nn.init_all_states(model, batch_size=inputs.shape[1])
252
+
253
+ # Process sequence
254
+ return brainstate.transform.for_loop(model.update, inputs)
255
+
256
+
257
+ def f_loss(inputs, targets, l2_reg=2e-4):
258
+ """Compute loss with L2 regularization.
259
+
260
+ Args:
261
+ inputs: Input sequences
262
+ targets: Target sequences
263
+ l2_reg: L2 regularization coefficient
264
+
265
+ Returns:
266
+ loss: Total loss value
267
+ """
268
+ # Get predictions
269
+ predictions = f_predict(inputs)
270
+
271
+ # Mean squared error
272
+ mse = braintools.metric.squared_error(predictions, targets).mean()
273
+
274
+ # L2 regularization on weights
275
+ l2 = 0.0
276
+ for weight in weights.values():
277
+ for leaf in jax.tree.leaves(weight.value):
278
+ l2 += jnp.sum(leaf ** 2)
279
+
280
+ return mse + l2_reg * l2
281
+
282
+
283
+ @brainstate.transform.jit
284
+ def f_train(inputs, targets):
285
+ """Perform one training step.
286
+
287
+ Args:
288
+ inputs: Input sequences
289
+ targets: Target sequences
290
+
291
+ Returns:
292
+ loss: Loss value
293
+ """
294
+ # Compute gradients
295
+ grads, loss = brainstate.transform.grad(
296
+ f_loss,
297
+ weights,
298
+ return_value=True
299
+ )(inputs, targets)
300
+
301
+ # Update parameters
302
+ optimizer.update(grads)
303
+
304
+ return loss
305
+
306
+
307
+ print("Starting training...\n")
308
+
309
+ for i_epoch in range(num_epochs):
310
+ epoch_losses = []
311
+
312
+ for i_batch, (inputs, targets) in enumerate(train_data()):
313
+ if i_batch >= batches_per_epoch:
314
+ break
315
+
316
+ loss = f_train(inputs, targets)
317
+ epoch_losses.append(float(loss))
318
+
319
+ if (i_batch + 1) % 100 == 0:
320
+ avg_loss = np.mean(epoch_losses[-100:])
321
+ print(f'Epoch {i_epoch}, Batch {i_batch + 1:3d}, Loss {avg_loss:.5f}')
322
+
323
+ avg_epoch_loss = np.mean(epoch_losses)
324
+ print(f'\nEpoch {i_epoch} completed: Avg Loss = {avg_epoch_loss:.5f}\n')
325
+
326
+ print("Training complete!")
327
+
328
+ # Generate test data
329
+ brainstate.nn.init_all_states(model, 1)
330
+ x_test, y_test = build_inputs_and_targets(0.025, 0.01, 1)
331
+ predictions = f_predict(x_test)
332
+
333
+ print(f"Test data generated:")
334
+ print(f" Input shape: {x_test.shape}")
335
+ print(f" Target shape: {y_test.shape}")
336
+ print(f" Prediction shape: {predictions.shape}")
337
+
338
+ plt.figure(figsize=(12, 5))
339
+
340
+ # Convert to numpy for plotting
341
+ y_true = np.asarray(y_test[:, 0]).flatten()
342
+ y_pred = np.asarray(predictions[:, 0]).flatten()
343
+ time_steps = np.arange(len(y_true))
344
+
345
+ # Plot ground truth and predictions
346
+ plt.plot(time_steps, y_true, 'b-', linewidth=2, label='Ground Truth', alpha=0.7)
347
+ plt.plot(time_steps, y_pred, 'r--', linewidth=2, label='RNN Prediction', alpha=0.7)
348
+
349
+ plt.xlabel('Time Step', fontsize=12)
350
+ plt.ylabel('Cumulative Value', fontsize=12)
351
+ plt.title('RNN Integration Task Performance', fontsize=14, fontweight='bold')
352
+ plt.legend(fontsize=11)
353
+ plt.grid(True, alpha=0.3)
354
+ plt.tight_layout()
355
+ plt.show()
356
+
357
+ # Compute final error
358
+ mse = np.mean((y_true - y_pred) ** 2)
359
+ print(f"\nTest MSE: {mse:.6f}")
@@ -0,0 +1,52 @@
1
+ """LIFNeuron state-management reference.
2
+
3
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/core/01_state_and_pytrees.html
4
+ """
5
+
6
+ import jax.numpy as jnp
7
+ import brainstate
8
+
9
+
10
+ class LIFNeuron(brainstate.nn.Module):
11
+ """Leaky Integrate-and-Fire neuron model."""
12
+
13
+ def __init__(self, n_neurons, tau=10.0, V_th=1.0, V_reset=0.0):
14
+ super().__init__()
15
+ self.tau = tau
16
+ self.V_th = V_th
17
+ self.V_reset = V_reset
18
+
19
+ # Hidden state: membrane potential (evolves continuously)
20
+ self.V = brainstate.HiddenState(jnp.full(n_neurons, V_reset))
21
+
22
+ # Short-term state: refractory period counter
23
+ self.t_last_spike = brainstate.ShortTermState(jnp.full(n_neurons, -1e7))
24
+
25
+ # Parameters: input weights
26
+ self.w_in = brainstate.ParamState(brainstate.random.randn(n_neurons, n_neurons) * 0.1)
27
+
28
+ def __call__(self, I_ext, t):
29
+ # Membrane potential dynamics
30
+ dV = (-self.V.value + I_ext) / self.tau
31
+ self.V.value = self.V.value + dV
32
+
33
+ # Spike generation
34
+ spike = self.V.value >= self.V_th
35
+
36
+ # Reset
37
+ self.V.value = jnp.where(spike, self.V_reset, self.V.value)
38
+ self.t_last_spike.value = jnp.where(spike, t, self.t_last_spike.value)
39
+
40
+ return spike
41
+
42
+ # Create and test the neuron
43
+ neuron = LIFNeuron(n_neurons=5)
44
+ print("Initial state:")
45
+ print(f"V: {neuron.V.value}")
46
+
47
+ # Simulate
48
+ for t in range(20):
49
+ I_ext = jnp.ones(5) * 0.2 # External current
50
+ spikes = neuron(I_ext, t)
51
+ if jnp.any(spikes):
52
+ print(f"t={t}: Spikes at neurons {jnp.where(spikes)[0]}")