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.
- package/LICENSE +1 -1
- package/README.md +24 -56
- package/{lib → installation/lib}/installer.js +4 -4
- package/manifest.json +3 -1
- package/package.json +19 -9
- package/skills/brainstate/SKILL.md +399 -0
- package/skills/brainstate/agents/openai.yaml +4 -0
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +483 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +176 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +199 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +166 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +210 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +450 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +157 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +286 -0
- package/skills/brainstate/references/braintools-optimizer-reference.md +133 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +282 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +217 -0
- package/skills/brainstate/references/libraries/solver-library-with-effects.md +85 -0
- package/skills/brainstate/references/model-interop-and-migration.md +295 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +268 -0
- package/skills/brainstate/references/state-graph-operations.md +218 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +224 -0
- package/skills/brainstate/scripts/integrator_rnn.py +359 -0
- package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
- package/skills/brainstate/scripts/modern_cnn.py +73 -0
- package/skills/brainstate/scripts/resnet.py +130 -0
- package/skills/brainunit/SKILL.md +287 -0
- package/skills/brainunit/references/array-creation.md +158 -0
- package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
- package/skills/brainunit/references/array-mechanics.md +165 -0
- package/skills/brainunit/references/math-function-library.md +433 -0
- package/skills/brainunit/references/physical-constant-library.md +58 -0
- package/skills/brainunit/references/prefix-library.md +116 -0
- package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
- package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
- package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
- package/skills/brainx-install/SKILL.md +21 -13
- package/skills/brainx-install/references/compatibility-and-release-matching.md +12 -10
- package/skills/brainx-install/references/uninstall-and-cleanup.md +186 -0
- /package/{bin → installation/bin}/brainx.js +0 -0
- /package/{lib → installation/lib}/adapter-transaction.js +0 -0
- /package/{lib → installation/lib}/bundle.js +0 -0
- /package/{lib → installation/lib}/cli.js +0 -0
- /package/{lib → installation/lib}/constants.js +0 -0
- /package/{lib → installation/lib}/hash.js +0 -0
- /package/{lib → installation/lib}/paths.js +0 -0
- /package/{lib → installation/lib}/prompts.js +0 -0
- /package/{lib → installation/lib}/receipt.js +0 -0
|
@@ -0,0 +1,282 @@
|
|
|
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
|
+
## Mixin system
|
|
6
|
+
|
|
7
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/custom_states_and_mixins.html
|
|
8
|
+
|
|
9
|
+
### Reuse focused behavior with `Mixin`
|
|
10
|
+
|
|
11
|
+
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`.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import datetime
|
|
15
|
+
|
|
16
|
+
import brainstate
|
|
17
|
+
from brainstate import mixin
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class LoggingMixin(mixin.Mixin):
|
|
21
|
+
"""Attach timestamped logging without touching the host constructor."""
|
|
22
|
+
|
|
23
|
+
def log(self, message: str) -> None:
|
|
24
|
+
stamp = datetime.datetime.now().strftime('%H:%M:%S')
|
|
25
|
+
print(f'[LOG {stamp}] {self.__class__.__name__}: {message}')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Accumulator(brainstate.nn.Module, LoggingMixin):
|
|
29
|
+
def __init__(self):
|
|
30
|
+
super().__init__()
|
|
31
|
+
self.total = 0.0
|
|
32
|
+
|
|
33
|
+
def add(self, value):
|
|
34
|
+
self.total += float(value)
|
|
35
|
+
self.log(f'updated running total to {self.total:.2f}')
|
|
36
|
+
return self.total
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
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.
|
|
40
|
+
|
|
41
|
+
### Capture constructor presets with `ParamDesc`
|
|
42
|
+
|
|
43
|
+
`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.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from brainstate import mixin
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class DenseBlock(mixin.ParamDesc):
|
|
50
|
+
def __init__(self, in_features, out_features, *, activation='relu'):
|
|
51
|
+
self.in_features = in_features
|
|
52
|
+
self.out_features = out_features
|
|
53
|
+
self.activation = activation
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
encoder_block = DenseBlock.desc(256, 128, activation='gelu')
|
|
57
|
+
|
|
58
|
+
gelu_block = encoder_block()
|
|
59
|
+
relu_block = encoder_block(activation='relu') # override at call time
|
|
60
|
+
cache_key = encoder_block.identifier
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
For a class that does not inherit from `ParamDesc`, construct `ParamDescriber` directly:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from dataclasses import dataclass
|
|
67
|
+
|
|
68
|
+
from brainstate import mixin
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class OptimConfig:
|
|
73
|
+
lr: float
|
|
74
|
+
beta1: float = 0.9
|
|
75
|
+
beta2: float = 0.999
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
adam_template = mixin.ParamDescriber(
|
|
79
|
+
OptimConfig,
|
|
80
|
+
lr=1e-3,
|
|
81
|
+
beta1=0.95,
|
|
82
|
+
)
|
|
83
|
+
opt_a = adam_template()
|
|
84
|
+
opt_b = adam_template(lr=5e-4)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Express runtime type expectations
|
|
88
|
+
|
|
89
|
+
`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.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from brainstate import mixin
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Persistable:
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class Visualisable:
|
|
100
|
+
pass
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Report(Persistable, Visualisable):
|
|
104
|
+
pass
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
FullFeatureType = mixin.JointTypes[Persistable, Visualisable]
|
|
108
|
+
OptionalNumber = mixin.OneOfTypes[int, float, type(None)]
|
|
109
|
+
|
|
110
|
+
assert isinstance(Report(), FullFeatureType)
|
|
111
|
+
assert isinstance(3.14, OptionalNumber)
|
|
112
|
+
assert isinstance(None, OptionalNumber)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
These helpers make interface expectations explicit; they are used with `isinstance` in the official example.
|
|
116
|
+
|
|
117
|
+
### Centralize runtime behavior with modes
|
|
118
|
+
|
|
119
|
+
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=...)`.
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
import jax.numpy as jnp
|
|
123
|
+
from brainstate import mixin
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class ToyPipeline:
|
|
127
|
+
def __init__(self):
|
|
128
|
+
self.mode: mixin.Mode = mixin.Mode()
|
|
129
|
+
|
|
130
|
+
def set_mode(self, *modes: mixin.Mode):
|
|
131
|
+
if not modes:
|
|
132
|
+
self.mode = mixin.Mode()
|
|
133
|
+
elif len(modes) == 1:
|
|
134
|
+
self.mode = modes[0]
|
|
135
|
+
else:
|
|
136
|
+
self.mode = mixin.JointMode(*modes)
|
|
137
|
+
|
|
138
|
+
def forward(self, values):
|
|
139
|
+
x = jnp.asarray(values, dtype=jnp.float32)
|
|
140
|
+
if self.mode.has(mixin.Training):
|
|
141
|
+
x = x + 0.1
|
|
142
|
+
if self.mode.has(mixin.Batching):
|
|
143
|
+
x = x.reshape((self.mode.batch_size, -1)).mean(axis=1)
|
|
144
|
+
return x
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
pipeline = ToyPipeline()
|
|
148
|
+
pipeline.set_mode(
|
|
149
|
+
mixin.Training(),
|
|
150
|
+
mixin.Batching(batch_size=2),
|
|
151
|
+
)
|
|
152
|
+
result = pipeline.forward(jnp.arange(4.0)) # [0.6, 2.6]
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Use mode objects to centralize runtime semantics instead of scattering ad hoc boolean flags.
|
|
156
|
+
|
|
157
|
+
## Observe and intercept state access with hooks
|
|
158
|
+
|
|
159
|
+
Source: https://brainx.chaobrain.com/brainstate/how_to/state_hooks.html
|
|
160
|
+
|
|
161
|
+
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.
|
|
162
|
+
|
|
163
|
+
| Operation | Fires when | Can modify or cancel? |
|
|
164
|
+
|---|---|---|
|
|
165
|
+
| `read` | `state.value` is read | No; inspect only |
|
|
166
|
+
| `write_before` | Just before `state.value = ...` | Yes; transform or cancel |
|
|
167
|
+
| `write_after` | Just after a write completes | No; inspect only |
|
|
168
|
+
| `restore` | `state.restore_value(...)` is called | No |
|
|
169
|
+
| `init` | A State is constructed | No |
|
|
170
|
+
|
|
171
|
+
`brainstate.register_state_hook(...)` registers a global hook that fires for every State. `state.register_hook(...)` scopes the hook to one instance.
|
|
172
|
+
|
|
173
|
+
### Observe completed writes
|
|
174
|
+
|
|
175
|
+
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.
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
import jax.numpy as jnp
|
|
179
|
+
import brainstate
|
|
180
|
+
|
|
181
|
+
brainstate.clear_state_hooks()
|
|
182
|
+
history = []
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def record(ctx):
|
|
186
|
+
history.append(
|
|
187
|
+
(ctx.state_name, float(ctx.old_value), float(ctx.value))
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
handle = brainstate.register_state_hook('write_after', record)
|
|
192
|
+
|
|
193
|
+
weight = brainstate.State(jnp.array(1.0), name='weight')
|
|
194
|
+
weight.value = jnp.array(2.0)
|
|
195
|
+
weight.value = jnp.array(2.5)
|
|
196
|
+
# history == [('weight', 1.0, 2.0), ('weight', 2.0, 2.5)]
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Transform or reject a pending write
|
|
200
|
+
|
|
201
|
+
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.
|
|
202
|
+
|
|
203
|
+
```python
|
|
204
|
+
brainstate.clear_state_hooks()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def clip_to_unit(ctx):
|
|
208
|
+
current = (
|
|
209
|
+
ctx.transformed_value
|
|
210
|
+
if ctx.transformed_value is not None
|
|
211
|
+
else ctx.value
|
|
212
|
+
)
|
|
213
|
+
ctx.transformed_value = jnp.clip(current, -1.0, 1.0)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
clip_handle = brainstate.register_state_hook(
|
|
217
|
+
'write_before',
|
|
218
|
+
clip_to_unit,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
gate = brainstate.State(jnp.array(0.0))
|
|
222
|
+
gate.value = jnp.array(5.0) # stored as 1.0
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
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.
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
brainstate.clear_state_hooks()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def reject_negative(ctx):
|
|
232
|
+
value = (
|
|
233
|
+
ctx.transformed_value
|
|
234
|
+
if ctx.transformed_value is not None
|
|
235
|
+
else ctx.value
|
|
236
|
+
)
|
|
237
|
+
if jnp.any(value < 0):
|
|
238
|
+
ctx.cancel = True
|
|
239
|
+
ctx.cancel_reason = 'value must be non-negative'
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
reject_handle = brainstate.register_state_hook(
|
|
243
|
+
'write_before',
|
|
244
|
+
reject_negative,
|
|
245
|
+
)
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### Scope and manage hook lifetime
|
|
249
|
+
|
|
250
|
+
Use `state.register_hook(...)` when only one State needs observation or interception; other States are unaffected.
|
|
251
|
+
|
|
252
|
+
```python
|
|
253
|
+
brainstate.clear_state_hooks()
|
|
254
|
+
|
|
255
|
+
watched = brainstate.State(jnp.array(0.0), name='watched')
|
|
256
|
+
other = brainstate.State(jnp.array(0.0), name='other')
|
|
257
|
+
seen = []
|
|
258
|
+
|
|
259
|
+
handle = watched.register_hook(
|
|
260
|
+
'write_after',
|
|
261
|
+
lambda ctx: seen.append(float(ctx.value)),
|
|
262
|
+
)
|
|
263
|
+
watched.value = jnp.array(1.0)
|
|
264
|
+
other.value = jnp.array(99.0) # not observed
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
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.
|
|
268
|
+
|
|
269
|
+
Bound temporary hook lifetimes explicitly:
|
|
270
|
+
|
|
271
|
+
```python
|
|
272
|
+
handle.disable()
|
|
273
|
+
handle.enable()
|
|
274
|
+
handle.remove()
|
|
275
|
+
assert handle.is_removed()
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
### Keep hooks safe under compiled execution
|
|
279
|
+
|
|
280
|
+
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.
|
|
281
|
+
|
|
282
|
+
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,106 @@
|
|
|
1
|
+
# Prebuilt activation library
|
|
2
|
+
|
|
3
|
+
Use this reference to select an exact `brainstate.nn` activation symbol. The routed catalog provides symbol names and descriptions, but not constructor or callable signatures; do not invent argument lists from similarly named APIs in another library. It distinguishes stateful layer modules from pure functions, but leaves basic activation use and `Module` composition to `SKILL.md`.
|
|
4
|
+
|
|
5
|
+
Normalization layers are not present on this page. Select `BatchNorm*`, `LayerNorm`, `RMSNorm`, or `GroupNorm` from `prebuilt-layer-library.md`. The functional `standardize` entry below remains here because it is part of the activation catalog and is described as standardizing an array; it is not a normalization-layer API.
|
|
6
|
+
|
|
7
|
+
## Element-wise layers
|
|
8
|
+
|
|
9
|
+
Source URL: https://brainx.chaobrain.com/brainstate/apis/nn/activation.html
|
|
10
|
+
|
|
11
|
+
The official page describes these as non-linear activation layers that operate element-wise on input tensors. Its catalog includes rectified linear units and variants, sigmoid functions, hyperbolic tangent, softmax for probability distributions, and specialized activations for specific architectures such as SELU, GELU, SiLU, and Mish.
|
|
12
|
+
|
|
13
|
+
| Exact symbol | Official catalog description |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `Threshold` | Thresholds each element of the input Tensor. |
|
|
16
|
+
| `ReLU` | Applies the rectified linear unit function element-wise. |
|
|
17
|
+
| `RReLU` | Applies the randomized leaky rectified liner unit function, element-wise. |
|
|
18
|
+
| `Hardtanh` | Applies the HardTanh function element-wise. |
|
|
19
|
+
| `ReLU6` | Applies the element-wise function. |
|
|
20
|
+
| `Sigmoid` | Applies the element-wise function. |
|
|
21
|
+
| `Hardsigmoid` | Applies the Hardsigmoid function element-wise. |
|
|
22
|
+
| `Tanh` | Applies the Hyperbolic Tangent (Tanh) function element-wise. |
|
|
23
|
+
| `SiLU` | Applies the Sigmoid Linear Unit (SiLU) function, element-wise. |
|
|
24
|
+
| `Mish` | Applies the Mish function, element-wise. |
|
|
25
|
+
| `Hardswish` | Applies the Hardswish function, element-wise. |
|
|
26
|
+
| `ELU` | Applies the Exponential Linear Unit (ELU) function, element-wise. |
|
|
27
|
+
| `CELU` | Applies the element-wise function. |
|
|
28
|
+
| `SELU` | Applied element-wise. |
|
|
29
|
+
| `GLU` | Applies the gated linear unit function. |
|
|
30
|
+
| `GELU` | Applies the Gaussian Error Linear Units function. |
|
|
31
|
+
| `Hardshrink` | Applies the Hard Shrinkage (Hardshrink) function element-wise. |
|
|
32
|
+
| `LeakyReLU` | Applies the element-wise function. |
|
|
33
|
+
| `LogSigmoid` | Applies the element-wise function. |
|
|
34
|
+
| `Softplus` | Applies the Softplus function element-wise. |
|
|
35
|
+
| `Softshrink` | Applies the soft shrinkage function elementwise. |
|
|
36
|
+
| `PReLU` | Applies the element-wise function. |
|
|
37
|
+
| `Softsign` | Applies the element-wise function. |
|
|
38
|
+
| `Tanhshrink` | Applies the element-wise function. |
|
|
39
|
+
| `Softmin` | Applies the Softmin function to an n-dimensional input Tensor. |
|
|
40
|
+
| `Softmax` | Applies the Softmax function to an n-dimensional input Tensor. |
|
|
41
|
+
| `Softmax2d` | Applies SoftMax over features to each spatial location. |
|
|
42
|
+
| `LogSoftmax` | Applies the `log(Softmax(x))` function to an n-dimensional input Tensor. |
|
|
43
|
+
| `Identity` | A placeholder identity operator that is argument-insensitive. |
|
|
44
|
+
| `SpikeBitwise` | Bitwise addition for the spiking inputs. |
|
|
45
|
+
|
|
46
|
+
Selection cues supplied by the catalog:
|
|
47
|
+
|
|
48
|
+
- Use `Softmin`, `Softmax`, or `LogSoftmax` when the requested operation names that distribution transform; use `Softmax2d` when the request specifically calls for SoftMax over features at each spatial location.
|
|
49
|
+
- Use `Identity` when an argument-insensitive placeholder identity operator is required.
|
|
50
|
+
- Use `SpikeBitwise` only for the page's stated spiking-input bitwise addition role.
|
|
51
|
+
- Treat the remaining entries according to their exact named activation. The catalog does not expose parameters here, even for parameterized, thresholded, randomized, gated, or shrinkage variants.
|
|
52
|
+
|
|
53
|
+
## Functional activations
|
|
54
|
+
|
|
55
|
+
Source URL: https://brainx.chaobrain.com/brainstate/apis/nn/activation.html
|
|
56
|
+
|
|
57
|
+
The official page describes these as functional, non-module activation functions for flexible composition. They are pure functions that may be used directly in `update()` methods or combined with JAX transformations, and provide activation behavior without state or module overhead.
|
|
58
|
+
|
|
59
|
+
| Exact symbol | Official catalog description |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `tanh` | Hyperbolic tangent activation function. |
|
|
62
|
+
| `relu` | Rectified Linear Unit activation function. |
|
|
63
|
+
| `squareplus` | Squareplus activation function. |
|
|
64
|
+
| `softplus` | Softplus activation function. |
|
|
65
|
+
| `soft_sign` | Soft-sign activation function. |
|
|
66
|
+
| `sigmoid` | Sigmoid activation function. |
|
|
67
|
+
| `silu` | SiLU (Sigmoid Linear Unit) activation function. |
|
|
68
|
+
| `swish` | SiLU (Sigmoid Linear Unit) activation function. |
|
|
69
|
+
| `log_sigmoid` | Log-sigmoid activation function. |
|
|
70
|
+
| `elu` | Exponential Linear Unit activation function. |
|
|
71
|
+
| `leaky_relu` | Leaky Rectified Linear Unit activation function. |
|
|
72
|
+
| `hard_tanh` | Hard hyperbolic tangent activation function. |
|
|
73
|
+
| `celu` | Continuously-differentiable Exponential Linear Unit activation. |
|
|
74
|
+
| `selu` | Scaled Exponential Linear Unit activation. |
|
|
75
|
+
| `gelu` | Gaussian Error Linear Unit activation function. |
|
|
76
|
+
| `glu` | Gated Linear Unit activation function. |
|
|
77
|
+
| `logsumexp` | No description is supplied in the routed catalog. |
|
|
78
|
+
| `log_softmax` | Log-Softmax function. |
|
|
79
|
+
| `softmax` | Softmax activation function. |
|
|
80
|
+
| `standardize` | Standardize (normalize) an array. |
|
|
81
|
+
| `one_hot` | One-hot encode the given indices. |
|
|
82
|
+
| `relu6` | Rectified Linear Unit 6 activation function. |
|
|
83
|
+
| `hard_sigmoid` | Hard Sigmoid activation function. |
|
|
84
|
+
| `hard_silu` | Hard SiLU (Swish) activation function. |
|
|
85
|
+
| `hard_swish` | Hard SiLU (Swish) activation function. |
|
|
86
|
+
| `hard_shrink` | Hard shrinkage activation function. |
|
|
87
|
+
| `rrelu` | Randomized Leaky Rectified Linear Unit activation function. |
|
|
88
|
+
| `mish` | Mish activation function. |
|
|
89
|
+
| `soft_shrink` | Soft shrinkage activation function. |
|
|
90
|
+
| `prelu` | Parametric Rectified Linear Unit activation function. |
|
|
91
|
+
| `tanh_shrink` | Tanh shrink activation function. |
|
|
92
|
+
| `softmin` | Softmin activation function. |
|
|
93
|
+
| `sparse_plus` | Sparse plus activation function. |
|
|
94
|
+
| `sparse_sigmoid` | Sparse sigmoid activation function. |
|
|
95
|
+
|
|
96
|
+
Selection cues supplied by the catalog:
|
|
97
|
+
|
|
98
|
+
- Choose the lowercase functional form when the operation should remain a pure function inside `update()` or a JAX transformation rather than a layer module.
|
|
99
|
+
- `silu` and `swish` share the same catalog description; likewise, `hard_silu` and `hard_swish` share the same description.
|
|
100
|
+
- `standardize` is the page's functional array-standardization choice. Route stateful or configurable normalization-layer selection to `prebuilt-layer-library.md`.
|
|
101
|
+
- `one_hot` is an encoding utility listed in this catalog, not a nonlinear layer.
|
|
102
|
+
- The routed page gives no description or signature for `logsumexp`; use the exact symbol only when that operation is explicitly requested, and consult a version-matched generated API page before supplying arguments.
|
|
103
|
+
|
|
104
|
+
## Source
|
|
105
|
+
|
|
106
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/activation.html
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
# Brainstate prebuilt layer library
|
|
2
|
+
|
|
3
|
+
Use this reference only to select a prebuilt `brainstate.nn` layer and recover its constructor form. The canonical layer example, `Module` composition, and `.desc()` workflow stay in `SKILL.md`. Route convolution, pooling, padding, and flatten output formulas to `../size-inference-variations.md`; route activation functions to `prebuilt-activation-library.md`; route dropout randomness, reproducibility, and fitting-mode work to `../brainstate/randomness-and-reproducibility.md`.
|
|
4
|
+
|
|
5
|
+
The constructor forms below preserve the documented public parameter order and defaults. To keep the catalog readable, these aliases compress only verbose initializer and State-type representations:
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
P = brainstate.ParamState
|
|
9
|
+
NP = brainstate.nn._normalizations.NormalizationParamState
|
|
10
|
+
MS = brainstate.BatchState
|
|
11
|
+
WK = KaimingNormal(scale=2.0, mode='fan_in', in_axis=-2,
|
|
12
|
+
out_axis=-1, distribution='truncated_normal', ...)
|
|
13
|
+
WX = XavierNormal(scale=1.0, mode='fan_avg', in_axis=-2,
|
|
14
|
+
out_axis=-1, distribution='truncated_normal', ...)
|
|
15
|
+
WL = LecunNormal(scale=1.0, mode='fan_in', in_axis=-2,
|
|
16
|
+
out_axis=-1, distribution='truncated_normal', ...)
|
|
17
|
+
WN = Normal(scale=1.0, mean=0.0, ...)
|
|
18
|
+
Z = ZeroInit(unit=Unit("1"))
|
|
19
|
+
C0 = Constant(value=0.0)
|
|
20
|
+
C1 = Constant(value=1.0)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The `...` inside an initializer alias stands only for its rendered RNG and unit representation, not for omitted layer arguments.
|
|
24
|
+
|
|
25
|
+
## Linear and connectivity layers
|
|
26
|
+
|
|
27
|
+
Source URL: https://brainx.chaobrain.com/brainstate/apis/nn/linear.html
|
|
28
|
+
|
|
29
|
+
The official catalog includes standard dense, weight-standardized, signed-absolute-weight, sparse, low-rank-adaptation, all-to-all, and one-to-one forms.
|
|
30
|
+
|
|
31
|
+
| API | Constructor | Select when |
|
|
32
|
+
|---|---|---|
|
|
33
|
+
| `Linear` | `Linear(in_size, out_size, w_init=WK, b_init=Z, w_mask=None, name=None, param_type=P)` | A standard linear transformation is required. |
|
|
34
|
+
| `ScaledWSLinear` | `ScaledWSLinear(in_size, out_size, w_init=WK, b_init=Z, w_mask=None, ws_gain=True, eps=0.0001, name=None, param_type=P)` | The linear weights should use scaled weight standardization. |
|
|
35
|
+
| `SignedWLinear` | `SignedWLinear(in_size, out_size, w_init=WK, w_sign=None, name=None, param_type=P)` | The transformation should use signed absolute weights. |
|
|
36
|
+
| `SparseLinear` | `SparseLinear(spar_mat, b_init=None, in_size=None, name=None, param_type=P)` | The weight matrix is sparse. Supply the sparse matrix as `spar_mat`. |
|
|
37
|
+
| `LoRA` | `LoRA(in_features, lora_rank, out_features, *, base_module=None, kernel_init=WL, param_type=P, in_size=None)` | Low-rank adaptation is needed for parameter-efficient fine-tuning, optionally around `base_module`. |
|
|
38
|
+
| `AllToAll` | `AllToAll(in_size, out_size, w_init=WK, b_init=None, include_self=True, name=None, param_type=P)` | An all-to-all connection layer is required; use `include_self` to retain or exclude self-connections. |
|
|
39
|
+
| `OneToOne` | `OneToOne(in_size, w_init=WN, b_init=None, name=None, param_type=P)` | A one-to-one connection layer is required. |
|
|
40
|
+
|
|
41
|
+
Do not replace `SparseLinear`, `LoRA`, `AllToAll`, or `OneToOne` with a hand-written dense layer when the corresponding connection structure is the requirement.
|
|
42
|
+
|
|
43
|
+
## Convolutional layers
|
|
44
|
+
|
|
45
|
+
Source URL: https://brainx.chaobrain.com/brainstate/apis/nn/conv.html
|
|
46
|
+
|
|
47
|
+
Choose the suffix by spatial rank: `1d` for one spatial dimension, `2d` for two, and `3d` for three. The catalog provides the same three ranks for standard convolution, scaled weight-standardized convolution, and transposed convolution.
|
|
48
|
+
|
|
49
|
+
### Standard convolution
|
|
50
|
+
|
|
51
|
+
Exact classes: `Conv1d`, `Conv2d`, `Conv3d`.
|
|
52
|
+
|
|
53
|
+
```text
|
|
54
|
+
ConvNd(
|
|
55
|
+
in_size, out_channels, kernel_size,
|
|
56
|
+
stride=1, padding='SAME', lhs_dilation=1, rhs_dilation=1, groups=1,
|
|
57
|
+
w_init=WX, b_init=None, w_mask=None, channel_first=False,
|
|
58
|
+
name=None, param_type=P,
|
|
59
|
+
)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Use the matching concrete class name in place of `ConvNd`. `channel_first=False` is the documented default; make layout choice explicit when selecting the non-default layout. Size outcomes for `stride`, `padding`, dilation, and groups belong in the size-inference reference.
|
|
63
|
+
|
|
64
|
+
### Scaled weight-standardized convolution
|
|
65
|
+
|
|
66
|
+
Exact classes: `ScaledWSConv1d`, `ScaledWSConv2d`, `ScaledWSConv3d`.
|
|
67
|
+
|
|
68
|
+
```text
|
|
69
|
+
ScaledWSConvNd(
|
|
70
|
+
in_size, out_channels, kernel_size,
|
|
71
|
+
stride=1, padding='SAME', lhs_dilation=1, rhs_dilation=1, groups=1,
|
|
72
|
+
ws_gain=True, eps=0.0001,
|
|
73
|
+
w_init=WX, b_init=None, w_mask=None, channel_first=False,
|
|
74
|
+
name=None, param_type=P,
|
|
75
|
+
)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Select this family when convolution with weight standardization is required. `ws_gain` and `eps` are the family-specific constructor controls.
|
|
79
|
+
|
|
80
|
+
### Transposed convolution
|
|
81
|
+
|
|
82
|
+
Exact classes: `ConvTranspose1d`, `ConvTranspose2d`, `ConvTranspose3d`.
|
|
83
|
+
|
|
84
|
+
```text
|
|
85
|
+
ConvTransposeNd(
|
|
86
|
+
in_size, out_channels, kernel_size,
|
|
87
|
+
stride=1, padding='SAME', rhs_dilation=1, groups=1,
|
|
88
|
+
w_init=WX, b_init=None, w_mask=None, channel_first=False,
|
|
89
|
+
name=None, param_type=P,
|
|
90
|
+
)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Select this family for the catalog's transposed-convolution, or deconvolution, upsampling operation. Unlike the standard and scaled-WS forms, its documented constructor has no `lhs_dilation` argument.
|
|
94
|
+
|
|
95
|
+
## Normalization layers
|
|
96
|
+
|
|
97
|
+
Source URL: https://brainx.chaobrain.com/brainstate/apis/nn/normalization.html
|
|
98
|
+
|
|
99
|
+
This section inventories normalization APIs only. Activation-function selection remains in `prebuilt-activation-library.md`.
|
|
100
|
+
|
|
101
|
+
### Batch normalization ranks
|
|
102
|
+
|
|
103
|
+
Exact classes: `BatchNorm0d`, `BatchNorm1d`, `BatchNorm2d`, `BatchNorm3d`.
|
|
104
|
+
|
|
105
|
+
```text
|
|
106
|
+
BatchNormNd(
|
|
107
|
+
in_size, feature_axis=-1, *,
|
|
108
|
+
track_running_stats=True, epsilon=1e-05, momentum=0.99, affine=True,
|
|
109
|
+
bias_initializer=C0, scale_initializer=C1,
|
|
110
|
+
axis_name=None, axis_index_groups=None, use_fast_variance=True,
|
|
111
|
+
name=None, dtype=None, param_type=NP, mean_type=MS,
|
|
112
|
+
)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Choose `0d`, `1d`, `2d`, or `3d` to match the required batch-normalization rank. Running-statistics and affine behavior are constructor choices through `track_running_stats` and `affine`; do not silently change their documented defaults.
|
|
116
|
+
|
|
117
|
+
### Axis- and group-based normalization
|
|
118
|
+
|
|
119
|
+
| API | Constructor | Selection distinction |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| `LayerNorm` | `LayerNorm(in_size, reduction_axes=-1, feature_axes=-1, *, epsilon=1e-06, use_bias=True, use_scale=True, bias_init=Z, scale_init=C1, axis_name=None, axis_index_groups=None, use_fast_variance=True, dtype=None, param_type=NP)` | Layer normalization with explicit reduction and feature axes. |
|
|
122
|
+
| `RMSNorm` | `RMSNorm(in_size, *, epsilon=1e-06, dtype=None, use_scale=True, scale_init=C1, reduction_axes=-1, feature_axes=-1, axis_name=None, axis_index_groups=None, use_fast_variance=True, param_type=NP)` | Root Mean Square Layer Normalization; it exposes scale but no bias argument. |
|
|
123
|
+
| `GroupNorm` | `GroupNorm(in_size, feature_axis=-1, num_groups=32, group_size=None, *, epsilon=1e-06, dtype=None, use_bias=True, use_scale=True, bias_init=Z, scale_init=C1, reduction_axes=None, axis_name=None, axis_index_groups=None, use_fast_variance=True, param_type=NP)` | Group Normalization; choose the grouping with `num_groups` or `group_size`. |
|
|
124
|
+
|
|
125
|
+
The catalog also exposes the functional primitive:
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
brainstate.nn.weight_standardization(w, eps=0.0001, gain=None, out_axis=-1)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Use it when standardizing a weight value directly; prefer the prebuilt `ScaledWSLinear` or `ScaledWSConv*` families when the whole layer already matches the task.
|
|
132
|
+
|
|
133
|
+
## Pooling and reshaping
|
|
134
|
+
|
|
135
|
+
Source URL: https://brainx.chaobrain.com/brainstate/apis/nn/pooling.html
|
|
136
|
+
|
|
137
|
+
The catalog covers shape conversion, local average/max/Lp pooling, max unpooling, and adaptive pooling. It does not own output-size formulas.
|
|
138
|
+
|
|
139
|
+
### Shape conversion
|
|
140
|
+
|
|
141
|
+
| API | Constructor | Select when |
|
|
142
|
+
|---|---|---|
|
|
143
|
+
| `Flatten` | `Flatten(start_axis=0, end_axis=-1, in_size=None)` | A contiguous range of axes should be flattened. |
|
|
144
|
+
| `Unflatten` | `Unflatten(axis, sizes, name=None, in_size=None)` | One axis should be expanded to `sizes`. |
|
|
145
|
+
|
|
146
|
+
### Local pooling
|
|
147
|
+
|
|
148
|
+
| Exact classes | Constructor family | Selection distinction |
|
|
149
|
+
|---|---|---|
|
|
150
|
+
| `AvgPool1d`, `AvgPool2d`, `AvgPool3d` | `AvgPoolNd(kernel_size, stride=1, padding='VALID', channel_axis=-1, name=None, in_size=None)` | Average pooling for the matching spatial rank. |
|
|
151
|
+
| `MaxPool1d`, `MaxPool2d`, `MaxPool3d` | `MaxPoolNd(kernel_size, stride=None, padding='VALID', channel_axis=-1, return_indices=False, name=None, in_size=None)` | Max pooling; request indices only through `return_indices`. |
|
|
152
|
+
| `LPPool1d`, `LPPool2d`, `LPPool3d` | `LPPoolNd(norm_type, kernel_size, stride=None, padding='VALID', channel_axis=-1, name=None, in_size=None)` | Power-average pooling with the required `norm_type`. |
|
|
153
|
+
|
|
154
|
+
Keep the default distinction exact: average pooling defaults to `stride=1`; max and Lp pooling default to `stride=None`.
|
|
155
|
+
|
|
156
|
+
### Max unpooling
|
|
157
|
+
|
|
158
|
+
Exact classes: `MaxUnpool1d`, `MaxUnpool2d`, `MaxUnpool3d`.
|
|
159
|
+
|
|
160
|
+
```text
|
|
161
|
+
MaxUnpoolNd(
|
|
162
|
+
kernel_size, stride=None, padding=0,
|
|
163
|
+
channel_axis=-1, name=None, in_size=None,
|
|
164
|
+
)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Select the matching rank when the partial inverse of the corresponding `MaxPoolNd` operation is required.
|
|
168
|
+
|
|
169
|
+
### Adaptive pooling
|
|
170
|
+
|
|
171
|
+
| Exact classes | Constructor family | Selection distinction |
|
|
172
|
+
|---|---|---|
|
|
173
|
+
| `AdaptiveAvgPool1d`, `AdaptiveAvgPool2d`, `AdaptiveAvgPool3d` | `AdaptiveAvgPoolNd(target_size, channel_axis=-1, name=None, in_size=None)` | Adaptive average pooling to a fixed target size. |
|
|
174
|
+
| `AdaptiveMaxPool1d`, `AdaptiveMaxPool2d`, `AdaptiveMaxPool3d` | `AdaptiveMaxPoolNd(target_size, channel_axis=-1, name=None, in_size=None)` | Adaptive max pooling to a fixed target size. |
|
|
175
|
+
|
|
176
|
+
## Padding layers
|
|
177
|
+
|
|
178
|
+
Source URL: https://brainx.chaobrain.com/brainstate/apis/nn/padding.html
|
|
179
|
+
|
|
180
|
+
All five boundary-condition families are available in 1D, 2D, and 3D. Choose the family first, then the suffix matching the spatial rank.
|
|
181
|
+
|
|
182
|
+
| Exact classes | Constructor family | Boundary behavior |
|
|
183
|
+
|---|---|---|
|
|
184
|
+
| `ReflectionPad1d`, `ReflectionPad2d`, `ReflectionPad3d` | `ReflectionPadNd(padding, in_size=None, name=None)` | Reflect the input boundary. |
|
|
185
|
+
| `ReplicationPad1d`, `ReplicationPad2d`, `ReplicationPad3d` | `ReplicationPadNd(padding, in_size=None, name=None)` | Replicate the input boundary. |
|
|
186
|
+
| `ZeroPad1d`, `ZeroPad2d`, `ZeroPad3d` | `ZeroPadNd(padding, in_size=None, name=None)` | Pad with zeros. |
|
|
187
|
+
| `ConstantPad1d`, `ConstantPad2d`, `ConstantPad3d` | `ConstantPadNd(padding, value=0, in_size=None, name=None)` | Pad with `value`; the documented default is zero. |
|
|
188
|
+
| `CircularPad1d`, `CircularPad2d`, `CircularPad3d` | `CircularPadNd(padding, in_size=None, name=None)` | Wrap around with circular padding. |
|
|
189
|
+
|
|
190
|
+
Do not derive output dimensions here. Open `../size-inference-variations.md` when `padding` interacts with convolution, pooling, stride, dilation, or flattening.
|
|
191
|
+
|
|
192
|
+
## Dropout layers
|
|
193
|
+
|
|
194
|
+
Source URL: https://brainx.chaobrain.com/brainstate/apis/nn/dropout.html
|
|
195
|
+
|
|
196
|
+
The official catalog distinguishes elementwise dropout, channelwise spatial dropout, alpha-dropout variants, and a fixed mask along the time axis.
|
|
197
|
+
|
|
198
|
+
| API | Constructor | Select when |
|
|
199
|
+
|---|---|---|
|
|
200
|
+
| `Dropout` | `Dropout(prob=0.5, broadcast_dims=(), name=None)` | A subset of inputs should be ignored stochastically each training step; `broadcast_dims` controls mask broadcasting. |
|
|
201
|
+
| `Dropout1d` | `Dropout1d(prob=0.5, channel_axis=-1, name=None)` | Entire channels of 1D feature maps should be zeroed. |
|
|
202
|
+
| `Dropout2d` | `Dropout2d(prob=0.5, channel_axis=-1, name=None)` | Entire channels of 2D feature maps should be zeroed. |
|
|
203
|
+
| `Dropout3d` | `Dropout3d(prob=0.5, channel_axis=-1, name=None)` | Entire channels of 3D feature maps should be zeroed. |
|
|
204
|
+
| `AlphaDropout` | `AlphaDropout(prob=0.5, name=None)` | Alpha Dropout is required. |
|
|
205
|
+
| `FeatureAlphaDropout` | `FeatureAlphaDropout(prob=0.5, channel_axis=-1, name=None)` | Entire channels should be masked with Alpha Dropout properties. |
|
|
206
|
+
| `DropoutFixed` | `DropoutFixed(in_size, prob=0.5, name=None)` | A dropout mask fixed along the time axis is required. |
|
|
207
|
+
|
|
208
|
+
After selecting the class, route RNG streams, deterministic replay, mapped randomness, checkpoint behavior, or training/evaluation mode to `../brainstate/randomness-and-reproducibility.md`; those concerns are deliberately not duplicated here.
|
|
209
|
+
|
|
210
|
+
## Exact official sources
|
|
211
|
+
|
|
212
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/linear.html
|
|
213
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/conv.html
|
|
214
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/normalization.html
|
|
215
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/pooling.html
|
|
216
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/padding.html
|
|
217
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/dropout.html
|