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,293 @@
1
+ # BrainState extension mechanisms
2
+
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
+
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
+
16
+ ## Mixin system
17
+
18
+ Source: https://brainx.chaobrain.com/brainstate/how_to/custom_states_and_mixins.html
19
+
20
+ ### Reuse focused behavior with `Mixin`
21
+
22
+ A mixin is a lightweight class that contributes methods or attributes without forcing a rigid inheritance hierarchy. In BrainState, every mixin inherits from `brainstate.mixin.Mixin`: it provides optional behavior, should not define its own `__init__`, and is usually paired with a core component such as `brainstate.nn.Module`.
23
+
24
+ ```python
25
+ import datetime
26
+
27
+ import brainstate
28
+ from brainstate import mixin
29
+
30
+
31
+ class LoggingMixin(mixin.Mixin):
32
+ """Attach timestamped logging without touching the host constructor."""
33
+
34
+ def log(self, message: str) -> None:
35
+ stamp = datetime.datetime.now().strftime('%H:%M:%S')
36
+ print(f'[LOG {stamp}] {self.__class__.__name__}: {message}')
37
+
38
+
39
+ class Accumulator(brainstate.nn.Module, LoggingMixin):
40
+ def __init__(self):
41
+ super().__init__()
42
+ self.total = 0.0
43
+
44
+ def add(self, value):
45
+ self.total += float(value)
46
+ self.log(f'updated running total to {self.total:.2f}')
47
+ return self.total
48
+ ```
49
+
50
+ Keep mixins focused, avoid new required constructor arguments, and document any host attributes that a mixin reads or writes. Several small mixins compose better than one opinionated base class.
51
+
52
+ ### Capture constructor presets with `ParamDesc`
53
+
54
+ `ParamDesc.desc(...)` stores constructor arguments in a `ParamDescriber`. Calling the descriptor creates a new object, and call-time arguments may override stored arguments. The descriptor is hashable; `descriptor.identifier` is safe to use as a dictionary key.
55
+
56
+ ```python
57
+ from brainstate import mixin
58
+
59
+
60
+ class DenseBlock(mixin.ParamDesc):
61
+ def __init__(self, in_features, out_features, *, activation='relu'):
62
+ self.in_features = in_features
63
+ self.out_features = out_features
64
+ self.activation = activation
65
+
66
+
67
+ encoder_block = DenseBlock.desc(256, 128, activation='gelu')
68
+
69
+ gelu_block = encoder_block()
70
+ relu_block = encoder_block(activation='relu') # override at call time
71
+ cache_key = encoder_block.identifier
72
+ ```
73
+
74
+ For a class that does not inherit from `ParamDesc`, construct `ParamDescriber` directly:
75
+
76
+ ```python
77
+ from dataclasses import dataclass
78
+
79
+ from brainstate import mixin
80
+
81
+
82
+ @dataclass
83
+ class OptimConfig:
84
+ lr: float
85
+ beta1: float = 0.9
86
+ beta2: float = 0.999
87
+
88
+
89
+ adam_template = mixin.ParamDescriber(
90
+ OptimConfig,
91
+ lr=1e-3,
92
+ beta1=0.95,
93
+ )
94
+ opt_a = adam_template()
95
+ opt_b = adam_template(lr=5e-4)
96
+ ```
97
+
98
+ ### Express runtime type expectations
99
+
100
+ `JointTypes[A, B, ...]` behaves like an intersection: an instance must satisfy all listed types. `OneOfTypes[A, B, ...]` behaves like a union: an instance may satisfy any listed type.
101
+
102
+ ```python
103
+ from brainstate import mixin
104
+
105
+
106
+ class Persistable:
107
+ pass
108
+
109
+
110
+ class Visualisable:
111
+ pass
112
+
113
+
114
+ class Report(Persistable, Visualisable):
115
+ pass
116
+
117
+
118
+ FullFeatureType = mixin.JointTypes[Persistable, Visualisable]
119
+ OptionalNumber = mixin.OneOfTypes[int, float, type(None)]
120
+
121
+ assert isinstance(Report(), FullFeatureType)
122
+ assert isinstance(3.14, OptionalNumber)
123
+ assert isinstance(None, OptionalNumber)
124
+ ```
125
+
126
+ These helpers make interface expectations explicit; they are used with `isinstance` in the official example.
127
+
128
+ ### Centralize runtime behavior with modes
129
+
130
+ Mode objects capture the context in which computation happens. The lightweight `Mode` base class and the built-ins `Training`, `Batching`, and `JointMode` cover common runtime switches. `mode.has(SomeModeType)` tests membership. A `JointMode` exposes member attributes, so `mode.batch_size` works when one member is `Batching(batch_size=...)`.
131
+
132
+ ```python
133
+ import jax.numpy as jnp
134
+ from brainstate import mixin
135
+
136
+
137
+ class ToyPipeline:
138
+ def __init__(self):
139
+ self.mode: mixin.Mode = mixin.Mode()
140
+
141
+ def set_mode(self, *modes: mixin.Mode):
142
+ if not modes:
143
+ self.mode = mixin.Mode()
144
+ elif len(modes) == 1:
145
+ self.mode = modes[0]
146
+ else:
147
+ self.mode = mixin.JointMode(*modes)
148
+
149
+ def forward(self, values):
150
+ x = jnp.asarray(values, dtype=jnp.float32)
151
+ if self.mode.has(mixin.Training):
152
+ x = x + 0.1
153
+ if self.mode.has(mixin.Batching):
154
+ x = x.reshape((self.mode.batch_size, -1)).mean(axis=1)
155
+ return x
156
+
157
+
158
+ pipeline = ToyPipeline()
159
+ pipeline.set_mode(
160
+ mixin.Training(),
161
+ mixin.Batching(batch_size=2),
162
+ )
163
+ result = pipeline.forward(jnp.arange(4.0)) # [0.6, 2.6]
164
+ ```
165
+
166
+ Use mode objects to centralize runtime semantics instead of scattering ad hoc boolean flags.
167
+
168
+ ## Observe and intercept state access with hooks
169
+
170
+ Source: https://brainx.chaobrain.com/brainstate/how_to/state_hooks.html
171
+
172
+ State hooks run a callback when a State is read, written, restored, or created without editing the model that owns it. They are intended for cross-cutting concerns such as logging changes, validating writes, enforcing invariants, and tracing access patterns while debugging.
173
+
174
+ | Operation | Fires when | Can modify or cancel? |
175
+ |---|---|---|
176
+ | `read` | `state.value` is read | No; inspect only |
177
+ | `write_before` | Just before `state.value = ...` | Yes; transform or cancel |
178
+ | `write_after` | Just after a write completes | No; inspect only |
179
+ | `restore` | `state.restore_value(...)` is called | No |
180
+ | `init` | A State is constructed | No |
181
+
182
+ `brainstate.register_state_hook(...)` registers a global hook that fires for every State. `state.register_hook(...)` scopes the hook to one instance.
183
+
184
+ ### Observe completed writes
185
+
186
+ A `write_after` callback receives a context containing the State, its `old_value`, and the new `value`. The context also exposes `state_name`, `operation`, `timestamp`, and a `metadata` dictionary for passing information between hooks. `ctx.state` is a weak-reference target and returns `None` after the State has been garbage-collected, so long-lived callbacks must guard it.
187
+
188
+ ```python
189
+ import jax.numpy as jnp
190
+ import brainstate
191
+
192
+ brainstate.clear_state_hooks()
193
+ history = []
194
+
195
+
196
+ def record(ctx):
197
+ history.append(
198
+ (ctx.state_name, float(ctx.old_value), float(ctx.value))
199
+ )
200
+
201
+
202
+ handle = brainstate.register_state_hook('write_after', record)
203
+
204
+ weight = brainstate.State(jnp.array(1.0), name='weight')
205
+ weight.value = jnp.array(2.0)
206
+ weight.value = jnp.array(2.5)
207
+ # history == [('weight', 1.0, 2.0), ('weight', 2.0, 2.5)]
208
+ ```
209
+
210
+ ### Transform or reject a pending write
211
+
212
+ A `write_before` hook runs before storage and may set `ctx.transformed_value`. Multiple `write_before` hooks chain in priority order, and each hook sees the previous hook's output.
213
+
214
+ ```python
215
+ brainstate.clear_state_hooks()
216
+
217
+
218
+ def clip_to_unit(ctx):
219
+ current = (
220
+ ctx.transformed_value
221
+ if ctx.transformed_value is not None
222
+ else ctx.value
223
+ )
224
+ ctx.transformed_value = jnp.clip(current, -1.0, 1.0)
225
+
226
+
227
+ clip_handle = brainstate.register_state_hook(
228
+ 'write_before',
229
+ clip_to_unit,
230
+ )
231
+
232
+ gate = brainstate.State(jnp.array(0.0))
233
+ gate.value = jnp.array(5.0) # stored as 1.0
234
+ ```
235
+
236
+ To reject rather than transform, set `ctx.cancel = True`. Assignment then raises `brainstate.HookCancellationError` and preserves the previous value; `ctx.cancel_reason` supplies the reason.
237
+
238
+ ```python
239
+ brainstate.clear_state_hooks()
240
+
241
+
242
+ def reject_negative(ctx):
243
+ value = (
244
+ ctx.transformed_value
245
+ if ctx.transformed_value is not None
246
+ else ctx.value
247
+ )
248
+ if jnp.any(value < 0):
249
+ ctx.cancel = True
250
+ ctx.cancel_reason = 'value must be non-negative'
251
+
252
+
253
+ reject_handle = brainstate.register_state_hook(
254
+ 'write_before',
255
+ reject_negative,
256
+ )
257
+ ```
258
+
259
+ ### Scope and manage hook lifetime
260
+
261
+ Use `state.register_hook(...)` when only one State needs observation or interception; other States are unaffected.
262
+
263
+ ```python
264
+ brainstate.clear_state_hooks()
265
+
266
+ watched = brainstate.State(jnp.array(0.0), name='watched')
267
+ other = brainstate.State(jnp.array(0.0), name='other')
268
+ seen = []
269
+
270
+ handle = watched.register_hook(
271
+ 'write_after',
272
+ lambda ctx: seen.append(float(ctx.value)),
273
+ )
274
+ watched.value = jnp.array(1.0)
275
+ other.value = jnp.array(99.0) # not observed
276
+ ```
277
+
278
+ Every registration returns a `HookHandle`. Use `disable()` to silence it temporarily, `enable()` to reactivate it, `remove()` to remove it permanently, and `is_removed()` to inspect removal status. Use `brainstate.list_state_hooks()` to list registered hooks, optionally filtered by type; `brainstate.has_state_hooks()` to report whether any are active; and `brainstate.clear_state_hooks()` to remove all global hooks.
279
+
280
+ Bound temporary hook lifetimes explicitly:
281
+
282
+ ```python
283
+ handle.disable()
284
+ handle.enable()
285
+ handle.remove()
286
+ assert handle.is_removed()
287
+ ```
288
+
289
+ ### Keep hooks safe under compiled execution
290
+
291
+ Hooks are ordinary Python callbacks. They fire on every concrete `.value` access; inside a `brainstate.transform.jit` step, they fire once per call at runtime and once during the initial trace, when `ctx.value` is an abstract tracer rather than a concrete array.
292
+
293
+ Do not branch in Python on a hooked value's contents, such as `if float(...)`. For NaN guards or bounds assertions that must execute inside compiled code, use the transformation-aware error tools `brainstate.transform.checkify`, `brainstate.transform.check`, or `brainstate.transform.debug_nan`.
@@ -0,0 +1,115 @@
1
+ # Prebuilt activation library
2
+
3
+ Use this reference to choose an exact `brainstate.nn` activation symbol and decide
4
+ between a Module and a functional form. Open
5
+ `prebuilt-layer-library.md` for normalization layers; `standardize` remains here
6
+ because the activation API exports it as a pure array operation.
7
+
8
+ ## Selection map
9
+
10
+ | Choice | Use when | Key constraint |
11
+ |---|---|---|
12
+ | Module class, such as `nn.ReLU()` | The activation must be stored in a Module graph, `Sequential`, or descriptor-based composition. | Instantiate the class; parameterized classes keep their configuration in the graph. |
13
+ | Functional form, such as `nn.relu(x)` | The activation is a stateless operation inside `update()` or another function. | Pass the array directly; do not instantiate the function. |
14
+ | `Softmax`, `LogSoftmax`, `Softmin`, or lowercase equivalents | The output must be normalized across a specified dimension. | Set the dimension or axis deliberately; the default may not match the feature dimension. |
15
+ | `standardize`, `one_hot`, or `logsumexp` | The task is array standardization, encoding, or stable log reduction rather than nonlinear activation. | These are utilities, not activation Modules. |
16
+ | `SpikeBitwise` | The input is a spiking representation requiring the catalog's bitwise-addition behavior. | Do not use it as a general numeric activation. |
17
+
18
+ ## Module activations
19
+
20
+ Use a Module class when graph composition or constructor-held configuration
21
+ matters. The exact class names are case-sensitive.
22
+
23
+ | API | Choose it when | Decision-changing control |
24
+ |---|---|---|
25
+ | `Threshold` | Values on one side of a threshold must be replaced. | `Threshold(threshold, value)` |
26
+ | `ReLU` | Use the standard rectified linear unit. | `ReLU(name=None)` |
27
+ | `RReLU` | Use randomized negative slopes. | `RReLU(lower=0.125, upper=1 / 3)` |
28
+ | `Hardtanh` | Clamp with a hard-tanh response. | `Hardtanh(min_val=-1.0, max_val=1.0)` |
29
+ | `ReLU6` | Clamp ReLU output at six. | No selection-specific constructor control is documented. |
30
+ | `Sigmoid` | Map values through the logistic sigmoid. | No selection-specific constructor control is documented. |
31
+ | `Hardsigmoid` | Use the piecewise-linear sigmoid approximation. | No selection-specific constructor control is documented. |
32
+ | `Tanh` | Map values through hyperbolic tangent. | No selection-specific constructor control is documented. |
33
+ | `SiLU` | Use SiLU, also called swish. | No selection-specific constructor control is documented. |
34
+ | `Mish` | Use the Mish activation. | No selection-specific constructor control is documented. |
35
+ | `Hardswish` | Use the piecewise-linear hard-swish variant. | No selection-specific constructor control is documented. |
36
+ | `ELU` | Use exponential linear units. | `ELU(alpha=1.0)` |
37
+ | `CELU` | Use continuously differentiable ELU. | `CELU(alpha=1.0)` |
38
+ | `SELU` | Use scaled ELU in an architecture designed for self-normalization. | Pair with architecture-appropriate initialization and dropout rather than substituting it blindly. |
39
+ | `GLU` | Split and gate the input along a dimension. | `GLU(dim=-1)` requires a compatible size on the split dimension. |
40
+ | `GELU` | Use Gaussian error linear units. | Check the generated page when an approximation variant matters. |
41
+ | `Hardshrink` | Apply hard shrinkage. | Check the generated page for the threshold control. |
42
+ | `LeakyReLU` | Preserve a fixed negative slope. | `LeakyReLU(negative_slope=0.01)` |
43
+ | `LogSigmoid` | Return the log of sigmoid stably. | No selection-specific constructor control is documented. |
44
+ | `Softplus` | Use a smooth positive rectifier. | The current generated constructor is `Softplus(name=None)`; do not assume PyTorch's `beta` or `threshold` arguments. |
45
+ | `Softshrink` | Apply soft shrinkage. | Check the generated page for the threshold control. |
46
+ | `PReLU` | Learn the negative slope. | `PReLU(num_parameters=1, init=0.25, dtype=None)` creates trainable slope parameters. |
47
+ | `Softsign` | Use the soft-sign response. | No selection-specific constructor control is documented. |
48
+ | `Tanhshrink` | Return the tanh-shrink response. | No selection-specific constructor control is documented. |
49
+ | `Softmin` | Normalize with larger probability on smaller inputs. | Set the normalization dimension explicitly. |
50
+ | `Softmax` | Convert logits to normalized probabilities. | `Softmax(dim=None)`; pass the intended feature dimension. |
51
+ | `Softmax2d` | Normalize features independently at each spatial location. | Use only for the documented 2D spatial layout. |
52
+ | `LogSoftmax` | Return normalized log-probabilities. | Set the normalization dimension explicitly. |
53
+ | `Identity` | Keep a configurable graph slot without changing the input. | It is a placeholder, not an activation. |
54
+ | `SpikeBitwise` | Apply bitwise addition to spiking inputs. | Keep it within spiking-data workflows. |
55
+
56
+ ## Functional activations
57
+
58
+ Use the lowercase form for stateless composition. Prefer the function whose name
59
+ matches the requested operation; aliases are shown explicitly.
60
+
61
+ | API | Distinguishing behavior |
62
+ |---|---|
63
+ | `tanh` | Hyperbolic tangent. |
64
+ | `relu` | Rectified linear unit. |
65
+ | `squareplus` | Smooth squareplus rectifier. |
66
+ | `softplus` | Smooth positive rectifier. |
67
+ | `soft_sign` | Soft-sign response. |
68
+ | `sigmoid` | Logistic sigmoid. |
69
+ | `silu`, `swish` | Equivalent SiLU/swish names. |
70
+ | `log_sigmoid` | Stable log-sigmoid. |
71
+ | `elu`, `celu`, `selu` | ELU-family functions; select by the requested activation contract. |
72
+ | `leaky_relu`, `rrelu`, `prelu` | Fixed, randomized, or supplied negative-slope behavior. |
73
+ | `hard_tanh`, `relu6`, `hard_sigmoid` | Piecewise-linear or clamped responses. |
74
+ | `hard_silu`, `hard_swish` | Equivalent hard-SiLU/hard-swish names. |
75
+ | `gelu`, `mish` | GELU or Mish response. |
76
+ | `glu` | Split-and-gate operation; preserve a compatible split-axis size. |
77
+ | `hard_shrink`, `soft_shrink`, `tanh_shrink` | Shrinkage-family functions. |
78
+ | `softmin`, `softmax`, `log_softmax` | Normalize across `axis`; choose probability, inverse-probability, or log-probability output. |
79
+ | `sparse_plus`, `sparse_sigmoid` | Sparse probability transformations. |
80
+ | `logsumexp` | Stable log of summed exponentials. |
81
+ | `standardize` | Standardize an array, optionally using supplied variance. |
82
+ | `one_hot` | Encode integer indices along a new class axis. |
83
+
84
+ ## Canonical selection workflow
85
+
86
+ Use a Module in a registered layer pipeline and a function for an inline output
87
+ transformation:
88
+
89
+ ```python
90
+ import brainstate
91
+ import brainstate.nn as nn
92
+
93
+ brainstate.random.seed(0)
94
+ feature_block = nn.Sequential(
95
+ nn.Linear(in_size=(8,), out_size=(4,)),
96
+ nn.ReLU(),
97
+ )
98
+
99
+ x = brainstate.random.randn(2, 8)
100
+ logits = feature_block(x)
101
+ probabilities = nn.softmax(logits, axis=-1)
102
+
103
+ assert probabilities.shape == logits.shape
104
+ ```
105
+
106
+ **Invariant:** choose the normalization axis from the tensor layout. A valid
107
+ call on the wrong axis can silently produce the wrong probability semantics.
108
+
109
+ For any parameter not shown above, open the version-matched generated page
110
+ linked from the activation catalog instead of borrowing a signature from JAX,
111
+ PyTorch, or another library.
112
+
113
+ ## Official source
114
+
115
+ - https://brainx.chaobrain.com/brainstate/apis/nn/activation.html
@@ -0,0 +1,143 @@
1
+ # Prebuilt layer library
2
+
3
+ Use this reference to choose a prebuilt `brainstate.nn` layer family and identify
4
+ the constructor controls that change model behavior. Keep ordinary composition
5
+ in `SKILL.md`; open `../size-inference-variations.md` for output-size formulas,
6
+ `prebuilt-activation-library.md` for activations, and
7
+ `../brainstate/randomness-and-reproducibility.md` for stochastic replay.
8
+
9
+ ## Selection map
10
+
11
+ | Family | Use when | Key constraint |
12
+ |---|---|---|
13
+ | Linear and connectivity | Features must be mixed densely, sparsely, by sign, one-to-one, all-to-all, or through low-rank adaptation. | Preserve the requested connectivity structure instead of replacing it with a dense matrix. |
14
+ | Convolution | Local kernels operate over one, two, or three spatial dimensions. | Match the class suffix and `channel_first` setting to the input layout. |
15
+ | Normalization | Activations or weights must be normalized by batch, layer, RMS, group, or weight statistics. | Choose reduction and feature axes from the actual tensor layout. |
16
+ | Pooling and reshaping | Spatial values must be reduced, restored from max indices, or rearranged. | Local pooling and adaptive pooling solve different output-size requirements. |
17
+ | Padding | A boundary condition must be explicit before another spatial operation. | Reflection, replication, circular, constant, and zero padding have different boundary semantics. |
18
+ | Dropout | Training requires elementwise, channelwise, alpha, or time-fixed stochastic masking. | Fitting mode and RNG state determine whether and how the mask is applied. |
19
+
20
+ The forms below show public arguments that affect selection. Open the generated
21
+ class page from the linked family catalog for version-specific initializer
22
+ objects, State subclasses, dtypes, names, and full defaults.
23
+
24
+ ## Linear and connectivity layers
25
+
26
+ | API | Constructor core | Choose it when |
27
+ |---|---|---|
28
+ | `Linear` | `Linear(in_size, out_size, ...)` | Apply a standard dense linear transformation. |
29
+ | `ScaledWSLinear` | `ScaledWSLinear(in_size, out_size, ..., ws_gain=True, eps=1e-4)` | Standardize linear weights during the forward computation. |
30
+ | `SignedWLinear` | `SignedWLinear(in_size, out_size, ..., w_sign=None)` | Enforce a supplied sign pattern over absolute weights. |
31
+ | `SparseLinear` | `SparseLinear(spar_mat, ..., in_size=None)` | Use an existing sparse weight matrix. |
32
+ | `LoRA` | `LoRA(in_features, lora_rank, out_features, *, base_module=None, ...)` | Add a low-rank trainable update, optionally around a base Module. |
33
+ | `AllToAll` | `AllToAll(in_size, out_size, ..., include_self=True)` | Connect every input and output, optionally excluding self-connections. |
34
+ | `OneToOne` | `OneToOne(in_size, ...)` | Give each feature or unit its own scalar connection. |
35
+
36
+ **Invariant:** `SparseLinear`, `LoRA`, `AllToAll`, and `OneToOne` encode model
37
+ structure. Replacing them with `Linear` changes parameterization and often the
38
+ scientific meaning.
39
+
40
+ ## Convolutional layers
41
+
42
+ Choose `1d`, `2d`, or `3d` from the number of spatial axes, excluding batch and
43
+ channel axes.
44
+
45
+ | Exact classes | Constructor family | Choose it when |
46
+ |---|---|---|
47
+ | `Conv1d`, `Conv2d`, `Conv3d` | `ConvNd(in_size, out_channels, kernel_size, stride=1, padding='SAME', lhs_dilation=1, rhs_dilation=1, groups=1, ..., channel_first=False)` | Apply a standard convolution. |
48
+ | `ScaledWSConv1d`, `ScaledWSConv2d`, `ScaledWSConv3d` | `ScaledWSConvNd(..., ws_gain=True, eps=1e-4, channel_first=False)` | Apply convolution with scaled weight standardization. |
49
+ | `ConvTranspose1d`, `ConvTranspose2d`, `ConvTranspose3d` | `ConvTransposeNd(in_size, out_channels, kernel_size, stride=1, padding='SAME', rhs_dilation=1, groups=1, ..., channel_first=False)` | Apply learned transposed-convolution upsampling. |
50
+
51
+ Do not pass `lhs_dilation` to the transposed-convolution family; it is not part
52
+ of its documented constructor. Open `../size-inference-variations.md` before
53
+ predicting shapes affected by stride, padding, dilation, or groups.
54
+
55
+ ## Normalization layers
56
+
57
+ | API | Constructor core | Choose it when |
58
+ |---|---|---|
59
+ | `BatchNorm0d`, `BatchNorm1d`, `BatchNorm2d`, `BatchNorm3d` | `BatchNormNd(in_size, feature_axis=-1, *, track_running_stats=True, epsilon=1e-5, momentum=0.99, affine=True, ...)` | Normalize with batch statistics and optionally maintain running statistics. |
60
+ | `LayerNorm` | `LayerNorm(in_size, reduction_axes=-1, feature_axes=-1, *, epsilon=1e-6, use_bias=True, use_scale=True, ...)` | Normalize selected axes independently for each example. |
61
+ | `RMSNorm` | `RMSNorm(in_size, *, epsilon=1e-6, use_scale=True, reduction_axes=-1, feature_axes=-1, ...)` | Normalize by root mean square without a bias control. |
62
+ | `GroupNorm` | `GroupNorm(in_size, feature_axis=-1, num_groups=32, group_size=None, *, epsilon=1e-6, ...)` | Partition channels into groups; specify `num_groups` or `group_size` coherently. |
63
+ | `weight_standardization` | `weight_standardization(w, eps=1e-4, gain=None, out_axis=-1)` | Standardize a weight array directly rather than selecting a complete layer. |
64
+
65
+ Batch normalization has separate ranks because accepted layouts differ. Do not
66
+ choose a suffix from the total array rank without accounting for batch and
67
+ feature axes.
68
+
69
+ ## Pooling and reshaping
70
+
71
+ | Exact APIs | Constructor family | Choose it when |
72
+ |---|---|---|
73
+ | `Flatten` | `Flatten(start_axis=0, end_axis=-1, in_size=None)` | Collapse a contiguous range of runtime axes. |
74
+ | `Unflatten` | `Unflatten(axis, sizes, name=None, in_size=None)` | Expand one axis into the supplied sizes. |
75
+ | `AvgPool1d`, `AvgPool2d`, `AvgPool3d` | `AvgPoolNd(kernel_size, stride=1, padding='VALID', channel_axis=-1, ...)` | Reduce local windows by their mean. |
76
+ | `MaxPool1d`, `MaxPool2d`, `MaxPool3d` | `MaxPoolNd(kernel_size, stride=None, padding='VALID', channel_axis=-1, return_indices=False, ...)` | Reduce local windows by their maximum; request indices when unpooling follows. |
77
+ | `LPPool1d`, `LPPool2d`, `LPPool3d` | `LPPoolNd(norm_type, kernel_size, stride=None, padding='VALID', channel_axis=-1, ...)` | Apply local Lp pooling with an explicit norm order. |
78
+ | `MaxUnpool1d`, `MaxUnpool2d`, `MaxUnpool3d` | `MaxUnpoolNd(kernel_size, stride=None, padding=0, channel_axis=-1, ...)` | Place pooled maxima back using compatible max-pool indices. |
79
+ | `AdaptiveAvgPool1d`, `AdaptiveAvgPool2d`, `AdaptiveAvgPool3d` | `AdaptiveAvgPoolNd(target_size, channel_axis=-1, ...)` | Produce a fixed target size with average pooling. |
80
+ | `AdaptiveMaxPool1d`, `AdaptiveMaxPool2d`, `AdaptiveMaxPool3d` | `AdaptiveMaxPoolNd(target_size, channel_axis=-1, ...)` | Produce a fixed target size with max pooling. |
81
+
82
+ **Invariant:** `MaxUnpool*` is only a partial inverse. Preserve indices from a
83
+ compatible `MaxPool*` call and do not expect non-maximal values to be recovered.
84
+
85
+ ## Padding layers
86
+
87
+ Choose the boundary behavior first, then the `1d`, `2d`, or `3d` suffix.
88
+
89
+ | Exact class families | Constructor family | Boundary behavior |
90
+ |---|---|---|
91
+ | `ReflectionPad1d`, `ReflectionPad2d`, `ReflectionPad3d` | `ReflectionPadNd(padding, in_size=None, name=None)` | Mirror values at the boundary. |
92
+ | `ReplicationPad1d`, `ReplicationPad2d`, `ReplicationPad3d` | `ReplicationPadNd(padding, in_size=None, name=None)` | Repeat edge values. |
93
+ | `ZeroPad1d`, `ZeroPad2d`, `ZeroPad3d` | `ZeroPadNd(padding, in_size=None, name=None)` | Insert zeros. |
94
+ | `ConstantPad1d`, `ConstantPad2d`, `ConstantPad3d` | `ConstantPadNd(padding, value=0, in_size=None, name=None)` | Insert an explicit constant. |
95
+ | `CircularPad1d`, `CircularPad2d`, `CircularPad3d` | `CircularPadNd(padding, in_size=None, name=None)` | Wrap values from the opposite boundary. |
96
+
97
+ ## Dropout layers
98
+
99
+ | API | Constructor core | Choose it when |
100
+ |---|---|---|
101
+ | `Dropout` | `Dropout(prob=0.5, broadcast_dims=(), name=None)` | Mask individual values, optionally sharing the mask across selected dimensions. |
102
+ | `Dropout1d`, `Dropout2d`, `Dropout3d` | `DropoutNd(prob=0.5, channel_axis=-1, name=None)` | Mask complete feature channels for the matching spatial rank. |
103
+ | `AlphaDropout` | `AlphaDropout(prob=0.5, name=None)` | Preserve self-normalizing-network statistics with elementwise alpha dropout. |
104
+ | `FeatureAlphaDropout` | `FeatureAlphaDropout(prob=0.5, channel_axis=-1, name=None)` | Apply alpha dropout to complete channels. |
105
+ | `DropoutFixed` | `DropoutFixed(in_size, prob=0.5, name=None)` | Reuse a mask along the time axis. |
106
+
107
+ Open `../brainstate/randomness-and-reproducibility.md` when dropout must use an
108
+ independent stream, replay exactly, map across an ensemble, or survive a
109
+ checkpoint.
110
+
111
+ ## Representative composition
112
+
113
+ This example makes layout, spatial rank, normalization axis, and fixed output
114
+ size explicit:
115
+
116
+ ```python
117
+ import brainstate.nn as nn
118
+
119
+ feature_extractor = nn.Sequential(
120
+ nn.Conv2d(
121
+ in_size=(28, 28, 1),
122
+ out_channels=16,
123
+ kernel_size=3,
124
+ padding="SAME",
125
+ channel_first=False,
126
+ ),
127
+ nn.GroupNorm(in_size=(28, 28, 16), feature_axis=-1, num_groups=4),
128
+ nn.ReLU(),
129
+ nn.AdaptiveAvgPool2d(target_size=(1, 1), channel_axis=-1),
130
+ )
131
+ ```
132
+
133
+ Open `skills/brainstate/scripts/modern_cnn.py` for the full convolution,
134
+ normalization, pooling, dropout, and dense workflow.
135
+
136
+ ## Official sources
137
+
138
+ - https://brainx.chaobrain.com/brainstate/apis/nn/linear.html
139
+ - https://brainx.chaobrain.com/brainstate/apis/nn/conv.html
140
+ - https://brainx.chaobrain.com/brainstate/apis/nn/normalization.html
141
+ - https://brainx.chaobrain.com/brainstate/apis/nn/pooling.html
142
+ - https://brainx.chaobrain.com/brainstate/apis/nn/padding.html
143
+ - https://brainx.chaobrain.com/brainstate/apis/nn/dropout.html