brainx-skill 1.0.14 → 1.0.16
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/README.md +17 -1
- package/manifest.json +1 -1
- package/mcp-servers/codex/skills.json +1 -1
- package/package.json +1 -1
- package/skills/bio-neuro-lit/SKILL.md +4 -2
- package/skills/bio-neuro-lit/references/required-supplements.md +27 -0
- package/skills/brainx-acceleration/SKILL.md +30 -437
- package/skills/brainx-acceleration/references/audit-and-rewrite-patterns.md +326 -0
- package/skills/brainx-general-guard/SKILL.md +24 -8
- package/skills/brainx-install/SKILL.md +3 -3
- package/skills/brainx-install/references/compatibility-and-release-matching.md +28 -20
- package/skills/brainx-install/references/uninstall-and-cleanup.md +11 -4
- package/skills/brainx-modeling-loop/SKILL.md +143 -36
- package/skills/brainx-modeling-loop/agents/openai.yaml +2 -2
- package/skills/brainx-modeling-loop/references/mechanism-comparison.md +62 -0
- package/skills/brainx-modeling-loop/references/multiscale-coupling.md +16 -0
- package/skills/brainx-modeling-loop/references/paper-reproduction.md +42 -0
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +14 -14
- package/skills/brainx-modeling-loop/references/run-experiment.md +1 -1
- package/skills/brainx-modeling-loop/references/training-workflow.md +10 -8
- package/skills/brainx-visualization/SKILL.md +6 -2
- package/skills/brainx-visualization/references/neural-data-visualization.md +1 -1
- package/skills/brainx-visualization/references/statistical-and-model-visualization.md +1 -1
- package/skills/package-skills/braincell/SKILL.md +23 -14
- package/skills/package-skills/braincell/references/braintools/input-current.md +1 -1
- package/skills/package-skills/braincell/references/braintools/metric.md +72 -46
- package/skills/package-skills/braincell/references/mixions-for-adaptation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/cv-policy-reference.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/filter-function-library.md +3 -3
- package/skills/package-skills/braincell/references/multicompartment/morphology-io-loading-validation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +31 -43
- package/skills/package-skills/braincell/references/multicompartment/network-workflow.md +49 -0
- package/skills/package-skills/braincell/references/multicompartment/probe-reference.md +26 -114
- package/skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md +40 -28
- package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py +13 -17
- package/skills/package-skills/brainevent/SKILL.md +0 -3
- package/skills/package-skills/brainevent/references/synaptic-plasticity.md +1 -1
- package/skills/package-skills/brainmass/SKILL.md +5 -3
- package/skills/package-skills/brainmass/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainmass/references/braintools/data-preprocessing.md +15 -7
- package/skills/package-skills/brainmass/references/braintools/metric.md +72 -46
- package/skills/package-skills/brainmass/references/coupling-network-api.md +3 -1
- package/skills/package-skills/brainmass/references/fitting-with-objectives-api.md +6 -6
- package/skills/package-skills/brainmass/references/horn-task-training.md +9 -9
- package/skills/package-skills/brainmass/references/modellibrary.md +12 -10
- package/skills/package-skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +5 -3
- package/skills/package-skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +10 -6
- package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +3 -1
- package/skills/package-skills/brainmass/references/visualization-analysis-api.md +17 -9
- package/skills/package-skills/brainspike/SKILL.md +201 -0
- package/skills/package-skills/brainspike/references/braintools/connectivity.md +40 -0
- package/skills/package-skills/brainspike/references/braintools/data-preprocessing.md +39 -0
- package/skills/package-skills/brainspike/references/braintools/input-current.md +55 -0
- package/skills/package-skills/brainspike/references/braintools/metric.md +36 -0
- package/skills/package-skills/brainspike/references/braintools/optimizer.md +50 -0
- package/skills/package-skills/brainspike/references/braintools/parameter-initializer.md +43 -0
- package/skills/package-skills/brainspike/references/braintools/surrogate.md +40 -0
- package/skills/package-skills/brainspike/references/migration-boundary.md +38 -0
- package/skills/package-skills/brainspike/references/model-and-readout-selection.md +41 -0
- package/skills/package-skills/brainspike/references/multirate-coupling.md +31 -0
- package/skills/package-skills/brainspike/references/multiscale-composition.md +28 -0
- package/skills/package-skills/brainspike/references/native-composition.md +52 -0
- package/skills/package-skills/brainspike/references/native-delays.md +34 -0
- package/skills/package-skills/brainspike/references/native-projections.md +43 -0
- package/skills/package-skills/brainspike/references/native-training.md +36 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/devices.md +33 -33
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/divergence-and-parity.md +15 -15
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/integration-categories.md +1 -1
- package/skills/package-skills/brainspike/references/nest-compatible/model-library.md +200 -0
- package/skills/package-skills/brainspike/references/nest-compatible/network-building.md +276 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brette_et_al_2007.py +23 -26
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_alpha.py +18 -21
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_delta.py +16 -19
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +11 -12
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +10 -11
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/spatial_gaussex.py +18 -18
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/synapsecollection.py +26 -29
- package/skills/package-skills/brainspike/references/nest-compatible/synapse-and-connectivity.md +166 -0
- package/skills/package-skills/brainspike/references/nest-delay-boundaries.md +31 -0
- package/skills/package-skills/brainspike/references/nonlinear-state-sharing.md +26 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/perturbation-experiment-validity.md +2 -2
- package/skills/package-skills/brainspike/references/simulator-training.md +61 -0
- package/skills/package-skills/brainspike/references/temporal-task-training.md +36 -0
- package/skills/package-skills/brainspike/scripts/advanced_native_patterns.py +76 -0
- package/skills/package-skills/brainspike/scripts/delay_workflow.py +44 -0
- package/skills/package-skills/brainspike/scripts/delayed_cue_training.py +78 -0
- package/skills/package-skills/brainspike/scripts/lif_smoke.py +31 -0
- package/skills/package-skills/brainspike/scripts/multiscale_workflow.py +35 -0
- package/skills/package-skills/brainspike/scripts/native_ei_network.py +47 -0
- package/skills/package-skills/brainspike/scripts/native_workflows.py +77 -0
- package/skills/package-skills/brainspike/scripts/nest_boundary_workflows.py +108 -0
- package/skills/package-skills/brainspike/scripts/train_native_snn.py +65 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator.py +69 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator_two_weights.py +220 -0
- package/skills/package-skills/brainstate/SKILL.md +16 -21
- package/skills/package-skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +1 -138
- package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
- package/skills/package-skills/brainstate/references/brainstate/delay-buffers.md +45 -0
- package/skills/package-skills/brainstate/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md +6 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md +1 -1
- package/skills/package-skills/brainstate/references/braintools-optimizer-reference.md +16 -0
- package/skills/package-skills/brainstate/references/libraries/prebuilt-layer-library.md +1 -1
- package/skills/package-skills/brainstate/references/simulation-environment.md +5 -5
- package/skills/package-skills/braintrace/SKILL.md +17 -38
- package/skills/package-skills/braintrace/references/Drtrl.md +9 -26
- package/skills/package-skills/braintrace/references/algorithm selection.md +7 -12
- package/skills/package-skills/braintrace/references/batching.md +15 -35
- package/skills/package-skills/braintrace/references/compiler_internal.md +1 -1
- package/skills/package-skills/braintrace/references/custom algorithms.md +1 -2
- package/skills/package-skills/braintrace/references/customizing_primitive_transforms.md +26 -15
- package/skills/package-skills/braintrace/references/pp_pprop workflow.md +5 -139
- package/skills/package-skills/brainunit/SKILL.md +7 -2
- package/skills/package-skills/brainunit/references/array-mechanics/functional-structural-api.md +1 -1
- package/skills/package-skills/brainunit/references/math-function-library.md +2 -2
- package/skills/package-skills/brainunit/references/typing-and-runtime-validation.md +5 -2
- package/skills/package-skills/brainevent/references/scripts/102_EI_net_1996.py +0 -107
- package/skills/package-skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +0 -168
- package/skills/package-skills/brainevent/references/scripts/coba_ei_teaching.py +0 -356
- package/skills/package-skills/brainpy-state/SKILL.md +0 -247
- package/skills/package-skills/brainpy-state/references/array-creation.md +0 -158
- package/skills/package-skills/brainpy-state/references/brain-dynamics-delay-protocol.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/analysis.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +0 -373
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +0 -175
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +0 -286
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +0 -111
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -163
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -113
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -136
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -222
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -123
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -185
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/integrators.md +0 -181
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +0 -102
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +0 -159
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +0 -127
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +0 -167
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -186
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +0 -104
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +0 -89
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +0 -253
- package/skills/package-skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +0 -334
- package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +0 -206
- package/skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md +0 -79
- package/skills/package-skills/brainpy-state/references/braintools/input-current.md +0 -199
- package/skills/package-skills/brainpy-state/references/braintools/metric.md +0 -152
- package/skills/package-skills/brainpy-state/references/braintools/optimizer.md +0 -179
- package/skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md +0 -183
- package/skills/package-skills/brainpy-state/references/braintools/surrogate.md +0 -147
- package/skills/package-skills/brainpy-state/references/component-selection.md +0 -288
- package/skills/package-skills/brainpy-state/references/nest-compatible/model-library.md +0 -200
- package/skills/package-skills/brainpy-state/references/nest-compatible/nest-workflow.md +0 -156
- package/skills/package-skills/brainpy-state/references/nest-compatible/network-building.md +0 -264
- package/skills/package-skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +0 -153
- package/skills/package-skills/brainpy-state/references/projection-patterns.md +0 -127
- package/skills/package-skills/brainpy-state/references/scripts/103_COBA_2005.py +0 -86
- package/skills/package-skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +0 -181
- package/skills/package-skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +0 -156
- package/skills/package-skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +0 -111
- package/skills/package-skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -221
- package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +0 -240
- package/skills/package-skills/brainpy-state/references/scripts/training-snn.py +0 -119
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
# Braintools optimizer selection
|
|
2
|
-
|
|
3
|
-
Use this reference after the BrainPy loss, rollout, State reset, and gradient target are correct. Select an optimizer interface and learning-rate policy without changing the simulation graph or confusing gradient-step optimizers with standalone search wrappers.
|
|
4
|
-
|
|
5
|
-
## Choose a gradient optimizer
|
|
6
|
-
|
|
7
|
-
Choose the optimizer family by training regime and resource constraint. Ordinary reverse-mode optimizers register the selected `ParamState` tree once and accept the matching gradient tree through `update(grads)`.
|
|
8
|
-
|
|
9
|
-
### General minibatch optimizers
|
|
10
|
-
|
|
11
|
-
Use these optimizers for ordinary repeated gradient steps; establish `Adam` or `SGD` as the baseline before selecting a specialized update rule.
|
|
12
|
-
|
|
13
|
-
| API | Description |
|
|
14
|
-
|---|---|
|
|
15
|
-
| `SGD(...)` | Use for stochastic gradient descent with optional momentum and weight decay when a simple non-adaptive baseline is required. |
|
|
16
|
-
| `Momentum(...)` | Use for momentum updates without selecting the broader `SGD` interface. |
|
|
17
|
-
| `MomentumNesterov(...)` | Use when the optimization method requires Nesterov-accelerated momentum. |
|
|
18
|
-
| `Adam(...)` | Use as the canonical adaptive default after validating finite, nonzero gradients. |
|
|
19
|
-
| `AdamW(...)` | Use when the training policy requires decoupled weight decay; set `weight_decay` deliberately. |
|
|
20
|
-
| `Adagrad(...)` | Use when per-parameter learning rates should accumulate squared-gradient history. |
|
|
21
|
-
| `Adadelta(...)` | Use when the Adadelta extension of Adagrad is explicitly required. |
|
|
22
|
-
| `RMSprop(...)` | Use when the method should scale updates by a moving average of squared gradients. |
|
|
23
|
-
| `Adamax(...)` | Use when the infinity-norm Adam variant is required. |
|
|
24
|
-
| `Nadam(...)` | Use when combining Adam with Nesterov acceleration. |
|
|
25
|
-
| `RAdam(...)` | Use when rectifying adaptive learning-rate variance addresses observed early-step instability. |
|
|
26
|
-
| `Yogi(...)` | Use when the Yogi additive second-moment update is part of the intended method. |
|
|
27
|
-
| `Rprop(...)` | Use when resilient backpropagation should adapt per-parameter step sizes from gradient signs. |
|
|
28
|
-
| `AdaBelief(...)` | Use when adapting step size from the optimizer's belief in the gradient direction is required. |
|
|
29
|
-
| `Lion(...)` | Use when a sign-momentum optimizer is chosen to reduce optimizer-State memory. |
|
|
30
|
-
| `Novograd(...)` | Use when layer-wise gradient normalization with momentum is required. |
|
|
31
|
-
| `Fromage(...)` | Use only when the Free-scale Optimal Method for Adaptive Gradient method is explicitly selected. |
|
|
32
|
-
|
|
33
|
-
### Large-scale and memory-efficient optimizers
|
|
34
|
-
|
|
35
|
-
Use these optimizers only when large-batch scaling or optimizer-State memory is an explicit constraint.
|
|
36
|
-
|
|
37
|
-
| API | Description |
|
|
38
|
-
|---|---|
|
|
39
|
-
| `Lamb(...)` | Use for layer-wise adaptive moments in an explicitly large-batch training regime. |
|
|
40
|
-
| `Lars(...)` | Use for layer-wise adaptive rate scaling in an explicitly large-batch training regime. |
|
|
41
|
-
| `Adafactor(...)` | Use when factorized second-moment estimates are needed to reduce optimizer-State memory. |
|
|
42
|
-
| `SM3(...)` | Use for memory-efficient adaptive updates in a large or sparse model. |
|
|
43
|
-
|
|
44
|
-
### Wrapper and full-batch optimizers
|
|
45
|
-
|
|
46
|
-
Use these variants when the update requires an optimizer composition or a smooth full-batch objective rather than an ordinary standalone minibatch rule.
|
|
47
|
-
|
|
48
|
-
| API | Description |
|
|
49
|
-
|---|---|
|
|
50
|
-
| `Lookahead(...)` | Use when wrapping an inner Optax gradient transformation with periodic slow-weight interpolation. |
|
|
51
|
-
| `LBFGS(...)` | Use for a small, smooth, full-batch problem suited to limited-memory quasi-Newton updates; verify its step contract before replacing a minibatch optimizer. |
|
|
52
|
-
|
|
53
|
-
### Custom Optax transformations
|
|
54
|
-
|
|
55
|
-
Use the bridge when no named Braintools optimizer expresses the required Optax transformation.
|
|
56
|
-
|
|
57
|
-
| API | Description |
|
|
58
|
-
|---|---|
|
|
59
|
-
| `OptaxOptimizer(tx=..., lr=...)` | Use when supplying a custom Optax transformation while preserving Braintools parameter registration, optimizer State, gradient clipping, weight decay, and scheduler integration. |
|
|
60
|
-
|
|
61
|
-
Do not switch optimizer, scheduler, surrogate, and temporal reduction simultaneously. Establish an `Adam` loss and gradient baseline, then vary one optimization decision.
|
|
62
|
-
|
|
63
|
-
## Gradient-step lifecycle
|
|
64
|
-
|
|
65
|
-
Every ordinary gradient optimizer owns persistent optimizer State and mutates exactly the registered trainable State:
|
|
66
|
-
|
|
67
|
-
| API | Use and result |
|
|
68
|
-
|---|---|
|
|
69
|
-
| `model.states(brainstate.ParamState)` | Select trainable model State; dynamical voltage, conductance, spike, and delay State remain outside the optimizer. |
|
|
70
|
-
| `optimizer.register_trainable_weights(params)` | Register the parameter tree and initialize optimizer State. |
|
|
71
|
-
| `brainstate.transform.grad(loss_fn, params, return_value=True)` | Produce a gradient tree matching `params` and the scalar loss. |
|
|
72
|
-
| `optimizer.update(grads)` | Apply one update to the registered parameters. |
|
|
73
|
-
|
|
74
|
-
```python
|
|
75
|
-
params = net.states(brainstate.ParamState)
|
|
76
|
-
optimizer = braintools.optim.Adam(lr=3e-3)
|
|
77
|
-
optimizer.register_trainable_weights(params)
|
|
78
|
-
|
|
79
|
-
@brainstate.transform.jit
|
|
80
|
-
def train_step():
|
|
81
|
-
brainstate.nn.init_all_states(net, batch_size=batch_size)
|
|
82
|
-
grads, loss = brainstate.transform.grad(
|
|
83
|
-
loss_fn,
|
|
84
|
-
params,
|
|
85
|
-
return_value=True,
|
|
86
|
-
)()
|
|
87
|
-
optimizer.update(grads)
|
|
88
|
-
return loss
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
Register the same tree passed to `grad`. Do not rebuild or re-register that tree inside every compiled step.
|
|
92
|
-
|
|
93
|
-
Use `braintools.optim.UniqueStateManager(...)` only when an arbitrary nested PyTree may contain repeated references to the same `State`; it deduplicates State identity before optimization. An ordinary `model.states(brainstate.ParamState)` collection already expresses the canonical model-owned target.
|
|
94
|
-
|
|
95
|
-
## Learning-rate schedulers
|
|
96
|
-
|
|
97
|
-
Pass an `LRScheduler` instance as `lr=` to any gradient-based `OptaxOptimizer`. A float is treated as a constant learning rate.
|
|
98
|
-
|
|
99
|
-
| API | Description |
|
|
100
|
-
|---|---|
|
|
101
|
-
| `LRScheduler(...)` | Subclass when implementing a custom schedule; it defines attachment, stepping, current-rate access, and State serialization. |
|
|
102
|
-
| `StepLR(...)` | Use for staircase decay by `gamma` every `step_size` scheduler steps. |
|
|
103
|
-
| `MultiStepLR(...)` | Use for multiplicative decay at explicitly chosen milestones. |
|
|
104
|
-
| `ConstantLR(...)` | Use to multiply the base learning rate by a constant factor for a configured interval. |
|
|
105
|
-
| `LinearLR(...)` | Use to scale the learning rate linearly between configured factors. |
|
|
106
|
-
| `ExponentialLR(...)` | Use for smooth multiplicative decay by `gamma` at every scheduler step. |
|
|
107
|
-
| `PolynomialLR(...)` | Use when the learning rate must follow a polynomial decay. |
|
|
108
|
-
| `ExponentialDecayLR(...)` | Use for exponential decay with explicit step-based control. |
|
|
109
|
-
| `CosineAnnealingLR(...)` | Use for smooth cosine annealing from the base rate toward `eta_min`; match `T_max` to the scheduler-call cadence. |
|
|
110
|
-
| `CosineAnnealingWarmRestarts(...)` | Use for cosine annealing that periodically restarts its cycle. |
|
|
111
|
-
| `WarmupCosineSchedule(...)` | Use when one schedule must warm up first and then anneal by cosine. |
|
|
112
|
-
| `CyclicLR(...)` | Use to oscillate the learning rate between configured bounds. |
|
|
113
|
-
| `OneCycleLR(...)` | Use for a single super-convergence cycle; derive `total_steps` from the actual number of scheduler calls. |
|
|
114
|
-
| `ReduceLROnPlateau(...)` | Use when a validation metric should trigger decay after stalled improvement; call `step(metric=...)`. |
|
|
115
|
-
| `WarmupScheduler(...)` | Use to increase the learning rate linearly during a warmup phase. |
|
|
116
|
-
| `PiecewiseConstantSchedule(...)` | Use for step-wise transitions among explicitly configured constant rates. |
|
|
117
|
-
| `ChainedScheduler(...)` | Use to apply multiple scheduler transformations together. |
|
|
118
|
-
| `SequentialLR(...)` | Use to switch among schedulers at configured epoch milestones. |
|
|
119
|
-
|
|
120
|
-
```python
|
|
121
|
-
scheduler = braintools.optim.StepLR(
|
|
122
|
-
base_lr=3e-3,
|
|
123
|
-
step_size=20,
|
|
124
|
-
gamma=0.5,
|
|
125
|
-
)
|
|
126
|
-
optimizer = braintools.optim.Adam(lr=scheduler)
|
|
127
|
-
optimizer.register_trainable_weights(params)
|
|
128
|
-
|
|
129
|
-
# After each epoch, outside the neural time-step transform:
|
|
130
|
-
optimizer.lr.step()
|
|
131
|
-
current_lr = optimizer.lr.get_last_lr()
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
For validation-driven scheduling, use the different call contract:
|
|
135
|
-
|
|
136
|
-
```python
|
|
137
|
-
scheduler = braintools.optim.ReduceLROnPlateau(
|
|
138
|
-
base_lr=3e-3,
|
|
139
|
-
mode="min",
|
|
140
|
-
factor=0.5,
|
|
141
|
-
patience=5,
|
|
142
|
-
)
|
|
143
|
-
optimizer = braintools.optim.Adam(lr=scheduler)
|
|
144
|
-
|
|
145
|
-
# After validation:
|
|
146
|
-
scheduler.step(metric=float(validation_loss))
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
Count scheduler calls explicitly. Stepping an epoch-configured schedule once per batch silently changes its effective timescale.
|
|
150
|
-
|
|
151
|
-
## Standalone and forward-mode optimizers
|
|
152
|
-
|
|
153
|
-
These interfaces own more of the optimization operation than `update(grads)`:
|
|
154
|
-
|
|
155
|
-
| API | Description |
|
|
156
|
-
|---|---|
|
|
157
|
-
| `ScipyOptimizer(loss_fun, bounds, method=...)` | Use for a smooth bounded or constrained objective solved as one optimization problem; match sequence bounds to `loss_fun(*params)` or dict bounds to `loss_fun(**params)`, then call `minimize(n_iter=...)` to obtain a SciPy result whose `x` matches the bounds structure. |
|
|
158
|
-
| `NevergradOptimizer(batched_loss_fun, bounds, n_sample, ...)` | Use when gradients are unavailable or unreliable; accept candidate-stacked parameters, return one loss per candidate, and call `minimize(n_iter=...)` to obtain the best parameter structure. |
|
|
159
|
-
| `SOFO(model, loss_fn, ...)` | Use for a feed-forward model when sampled forward-mode second-order directions are required; register its `ParamState`s, then call `step(inputs, targets)` to compute and apply the direction and return the pre-update loss. |
|
|
160
|
-
| `SOFOScan(rnn_cell, loss_fn, ...)` | Use for a stateful one-step recurrent cell with `(latent, inputs) -> (new_latent, output)`; `step(inputs, targets)` propagates forward-mode tangents through the sequence and applies one update. |
|
|
161
|
-
|
|
162
|
-
`ScipyOptimizer` and `NevergradOptimizer` deliberately raise for the State-based register/update methods. Do not place either inside the canonical compiled minibatch train step.
|
|
163
|
-
|
|
164
|
-
When SciPy bounds carry BrainUnit quantities, the wrapper optimizes numeric mantissas and calls `loss_fun` without units; reconstruct any required physical quantities inside the objective. Nevergrad reattaches units to returned parameters when the corresponding bounds carry units. Apply either optimizer's returned parameters to model State explicitly.
|
|
165
|
-
|
|
166
|
-
For Nevergrad, total objective evaluations are approximately `n_iter * n_sample`. `budget=` configures Nevergrad's internal strategy but does not cap that outer evaluation count.
|
|
167
|
-
|
|
168
|
-
## Routing and official sources
|
|
169
|
-
|
|
170
|
-
Open `references/braintools/surrogate.md` for surrogate gradients, `references/braintools/metric.md` for loss and reduction choice, and `references/braintools/brainstate-control-flow-patterns.md` for BPTT loop choice and checkpointing. Use `references/scripts/training-snn.py` for a complete BrainPy training script.
|
|
171
|
-
|
|
172
|
-
Official sources:
|
|
173
|
-
|
|
174
|
-
- `https://brainx.chaobrain.com/braintools/apis/optim.html`
|
|
175
|
-
- `https://brainx.chaobrain.com/braintools/optim/01_nevergrad_optimizer.html`
|
|
176
|
-
- `https://brainx.chaobrain.com/braintools/optim/02_scipy_optimizer.html`
|
|
177
|
-
- `https://brainx.chaobrain.com/braintools/optim/03_optax_getting_started.html`
|
|
178
|
-
- `https://brainx.chaobrain.com/braintools/optim/04_learning_rate_scheduling.html`
|
|
179
|
-
- `https://brainx.chaobrain.com/braintools/optim/05_advanced_optimizers.html`
|
|
@@ -1,183 +0,0 @@
|
|
|
1
|
-
# Braintools parameter initializers
|
|
2
|
-
|
|
3
|
-
Use this reference to initialize parameters, weights, delays, and spatial
|
|
4
|
-
profiles with unit-aware, reusable strategies. It covers distribution choice,
|
|
5
|
-
variance scaling, orthogonal methods, composition, and distance-based weight
|
|
6
|
-
modulation.
|
|
7
|
-
|
|
8
|
-
## Choose an initializer
|
|
9
|
-
|
|
10
|
-
| Need | Use | Important constraint |
|
|
11
|
-
|---|---|---|
|
|
12
|
-
| Fixed value | `Constant` or `ZeroInit` | Preserve physical units in the value. |
|
|
13
|
-
| Bounded random values | `Uniform`, `TruncatedNormal`, or `Beta` | Choose bounds that match the parameter's domain. |
|
|
14
|
-
| Bell-shaped variability | `Normal` | Negative draws remain possible unless clipped. |
|
|
15
|
-
| Positive skew | `LogNormal`, `Gamma`, `Exponential`, or `Weibull` | Use only when the parameter domain and parameterization match the distribution. |
|
|
16
|
-
| Activation-aware matrix scale | Kaiming, Xavier, or LeCun variants | Match the initializer to the activation and fan mode. |
|
|
17
|
-
| Norm-preserving matrix | `Orthogonal` or `Identity` | Validate the required matrix or convolutional shape. |
|
|
18
|
-
| Heterogeneous population | `Mixture` or `Conditional` | Keep component units and output shapes compatible. |
|
|
19
|
-
| Spatial weight scaling | `DistanceModulated` | This scales existing weights; it does not sample connectivity. |
|
|
20
|
-
|
|
21
|
-
## Resolve initialization specifications
|
|
22
|
-
|
|
23
|
-
An `Initialization` object is a shape-aware callable. Use `param()` at APIs that
|
|
24
|
-
accept an initializer, scalar, array, or quantity through one boundary.
|
|
25
|
-
|
|
26
|
-
| API | Description |
|
|
27
|
-
|---|---|
|
|
28
|
-
| `Initialization` | Subclass when a new reusable initialization strategy is required. |
|
|
29
|
-
| `param(init, sizes, batch_size=None, allow_none=True, allow_scalar=True, **param_kwargs)` | Resolve an initializer or already concrete value into a parameter. It applies the requested shape policy and forwards keywords such as RNG or distances. |
|
|
30
|
-
| `Compose(*steps)` | Apply an initializer followed by one or more transformations. |
|
|
31
|
-
|
|
32
|
-
```python
|
|
33
|
-
import brainunit as u
|
|
34
|
-
import numpy as np
|
|
35
|
-
from braintools.init import Normal, param
|
|
36
|
-
|
|
37
|
-
rng = np.random.default_rng(0)
|
|
38
|
-
initializer = Normal(mean=0.5 * u.nS, std=0.1 * u.nS)
|
|
39
|
-
weights = param(initializer, sizes=100, rng=rng)
|
|
40
|
-
|
|
41
|
-
assert weights.shape == (100,)
|
|
42
|
-
assert weights.unit == u.nS
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
**Invariant:** pass an explicit RNG when reproducibility matters. Do not strip a
|
|
46
|
-
quantity's unit to make an initializer accept it.
|
|
47
|
-
|
|
48
|
-
## Basic distributions
|
|
49
|
-
|
|
50
|
-
| API | Description |
|
|
51
|
-
|---|---|
|
|
52
|
-
| `Constant(value)` | Fill the requested shape with one value. |
|
|
53
|
-
| `ZeroInit(unit=None)` | Fill the requested shape with zero, optionally carrying a unit. |
|
|
54
|
-
| `Uniform(low, high, unit=None)` | Sample uniformly between lower and upper bounds. |
|
|
55
|
-
| `Normal(mean, std, unit=None)` | Sample a Gaussian distribution. |
|
|
56
|
-
| `LogNormal(mean, std, unit=None)` | Sample a positive log-normal distribution. |
|
|
57
|
-
| `TruncatedNormal(mean, std, low, high, unit=None)` | Sample a normal distribution within explicit bounds. |
|
|
58
|
-
| `Gamma(...)` | Sample a gamma distribution for positive skewed values. |
|
|
59
|
-
| `Exponential(...)` | Sample an exponential distribution. |
|
|
60
|
-
| `Beta(...)` | Sample a beta distribution rescaled to a requested range. |
|
|
61
|
-
| `Weibull(...)` | Sample a Weibull distribution. |
|
|
62
|
-
|
|
63
|
-
Use explicit `unit=` only when the distribution parameters themselves do not
|
|
64
|
-
already establish the required unit.
|
|
65
|
-
|
|
66
|
-
## Variance scaling
|
|
67
|
-
|
|
68
|
-
Variance-scaling initializers derive scale from matrix fan dimensions. Use
|
|
69
|
-
`fan_in` to preserve forward variance, `fan_out` to preserve backward variance,
|
|
70
|
-
and `fan_avg` to balance both.
|
|
71
|
-
|
|
72
|
-
| API | Description |
|
|
73
|
-
|---|---|
|
|
74
|
-
| `VarianceScaling(...)` | Use for a custom scale, fan mode, and distribution combination. |
|
|
75
|
-
| `KaimingUniform(...)` | Use uniform Kaiming/He initialization for ReLU-family activations. |
|
|
76
|
-
| `KaimingNormal(scale=None, mode='fan_in', nonlinearity='relu', negative_slope=0.01, unit=None)` | Use normal Kaiming/He initialization and match `nonlinearity` plus `negative_slope` to the layer. |
|
|
77
|
-
| `XavierUniform(...)` | Use uniform Xavier/Glorot initialization for symmetric tanh/sigmoid-style activations. |
|
|
78
|
-
| `XavierNormal(...)` | Use normal Xavier/Glorot initialization. |
|
|
79
|
-
| `LecunUniform(...)` | Use uniform LeCun initialization for SELU-style self-normalizing layers. |
|
|
80
|
-
| `LecunNormal(...)` | Use normal LeCun initialization. |
|
|
81
|
-
|
|
82
|
-
```python
|
|
83
|
-
from braintools.init import KaimingNormal, XavierUniform
|
|
84
|
-
|
|
85
|
-
relu_weights = KaimingNormal(mode="fan_in")((256, 784), rng=rng)
|
|
86
|
-
tanh_weights = XavierUniform()((256, 784), rng=rng)
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
Confirm which axis the consuming layer treats as input before relying on fan
|
|
90
|
-
inference.
|
|
91
|
-
|
|
92
|
-
## Orthogonal methods
|
|
93
|
-
|
|
94
|
-
| API | Description |
|
|
95
|
-
|---|---|
|
|
96
|
-
| `Orthogonal(scale=1.0, unit=None)` | Use QR-based orthogonal initialization for recurrent or deep matrix weights. It supports non-square matrices. |
|
|
97
|
-
| `DeltaOrthogonal(...)` | Use for convolutional kernels whose central spatial slice should be orthogonal. |
|
|
98
|
-
| `Identity(scale=1.0, unit=None)` | Use when the initial transformation should be an optionally scaled identity. |
|
|
99
|
-
|
|
100
|
-
## Composite distributions
|
|
101
|
-
|
|
102
|
-
| API | Description |
|
|
103
|
-
|---|---|
|
|
104
|
-
| `Mixture(distributions, weights=None)` | Select among component distributions per parameter according to mixture weights. |
|
|
105
|
-
| `Conditional(condition_fn, true_dist, false_dist)` | Select one of two initializers from neuron indices or supplied properties. |
|
|
106
|
-
| `Scaled(initializer, scale_factor)` | Multiply another initializer's output. |
|
|
107
|
-
| `Clipped(initializer, min_val, max_val)` | Bound another initializer's output. |
|
|
108
|
-
|
|
109
|
-
```python
|
|
110
|
-
from braintools.init import Conditional, Normal
|
|
111
|
-
|
|
112
|
-
initializer = Conditional(
|
|
113
|
-
condition_fn=lambda indices: indices < 800,
|
|
114
|
-
true_dist=Normal(0.5 * u.nS, 0.1 * u.nS),
|
|
115
|
-
false_dist=Normal(-0.3 * u.nS, 0.05 * u.nS),
|
|
116
|
-
)
|
|
117
|
-
weights = initializer(
|
|
118
|
-
1000,
|
|
119
|
-
neuron_indices=np.arange(1000),
|
|
120
|
-
rng=rng,
|
|
121
|
-
)
|
|
122
|
-
```
|
|
123
|
-
|
|
124
|
-
## Distance-modulated weights
|
|
125
|
-
|
|
126
|
-
A `DistanceProfile` maps distances to both documented probability and
|
|
127
|
-
weight-scaling functions. `DistanceModulated` uses the scaling values only.
|
|
128
|
-
|
|
129
|
-
| API | Description |
|
|
130
|
-
|---|---|
|
|
131
|
-
| `DistanceModulated(base_dist, distance_profile)` | Return `base_weights * distance_profile(distances)` element-wise. Supply `distances` directly or `pre_positions` and `post_positions`. |
|
|
132
|
-
| `GaussianProfile(sigma, max_distance=None)` | Use a Gaussian distance profile. |
|
|
133
|
-
| `ExponentialProfile(decay_constant, max_distance=None)` | Use exponentially decaying distance dependence. |
|
|
134
|
-
| `LinearProfile(...)` | Use a linear distance profile. |
|
|
135
|
-
| `StepProfile(...)` | Use a hard distance threshold or step. |
|
|
136
|
-
| `PowerLawProfile(...)` | Use power-law distance dependence. |
|
|
137
|
-
| `MexicanHatProfile(...)` | Use a Ricker/Mexican-hat profile. |
|
|
138
|
-
| `DoGProfile(...)` | Use a difference-of-Gaussians profile. |
|
|
139
|
-
| `SigmoidProfile(...)` | Use a sigmoid transition with distance. |
|
|
140
|
-
| `BimodalProfile(...)` | Use two distance-dependent modes. |
|
|
141
|
-
| `LogisticProfile(...)` | Use logistic distance dependence. |
|
|
142
|
-
| `ComposedProfile(...)` | Combine two profiles arithmetically. |
|
|
143
|
-
| `ClipProfile(...)` / `profile.clip(...)` | Bound profile output. |
|
|
144
|
-
| `ApplyProfile(...)` / `profile.apply(func)` | Transform profile output with a function. |
|
|
145
|
-
| `PipeProfile(...)` / `profile \| func` | Chain profiles or transformations. |
|
|
146
|
-
|
|
147
|
-
```python
|
|
148
|
-
from braintools.init import DistanceModulated, GaussianProfile, Normal
|
|
149
|
-
|
|
150
|
-
profile = GaussianProfile(sigma=100 * u.um)
|
|
151
|
-
initializer = DistanceModulated(
|
|
152
|
-
base_dist=Normal(1.0 * u.nS, 0.2 * u.nS),
|
|
153
|
-
distance_profile=profile,
|
|
154
|
-
).clip(min_val=0.01 * u.nS)
|
|
155
|
-
|
|
156
|
-
distances = np.random.default_rng(1).uniform(0, 500, 1000) * u.um
|
|
157
|
-
weights = initializer(1000, distances=distances, rng=rng)
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
**Invariant:** a zero profile value creates a present but silent zero-weight
|
|
161
|
-
synapse. Use `braintools.conn.DistanceDependent` when distance must decide
|
|
162
|
-
whether an edge exists.
|
|
163
|
-
|
|
164
|
-
## Functional composition
|
|
165
|
-
|
|
166
|
-
All `Initialization` and `DistanceProfile` objects support arithmetic
|
|
167
|
-
composition. Initializers additionally support `.clip()`, `.add()`,
|
|
168
|
-
`.multiply()`, `.apply()`, and pipe composition with `|`.
|
|
169
|
-
|
|
170
|
-
Build and validate composition incrementally:
|
|
171
|
-
|
|
172
|
-
```python
|
|
173
|
-
base = Normal(0.5 * u.nS, 0.1 * u.nS)
|
|
174
|
-
bounded = base.clip(0.0 * u.nS, 1.0 * u.nS)
|
|
175
|
-
final = bounded * 2.0 + 0.1 * u.nS
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
Keep units compatible at every arithmetic step. Apply clipping through
|
|
179
|
-
composition; `DistanceModulated` does not accept a `min_weight` argument.
|
|
180
|
-
|
|
181
|
-
## Official source
|
|
182
|
-
|
|
183
|
-
- `https://brainx.chaobrain.com/braintools/apis/init.html`
|
|
@@ -1,147 +0,0 @@
|
|
|
1
|
-
# Braintools surrogate gradients
|
|
2
|
-
|
|
3
|
-
Use this reference to select a functional or reusable surrogate-gradient spike
|
|
4
|
-
operator for differentiable spiking neural networks. A surrogate emits a hard
|
|
5
|
-
spike in the forward pass and supplies a smooth derivative in the backward
|
|
6
|
-
pass.
|
|
7
|
-
|
|
8
|
-
## Choose an API style
|
|
9
|
-
|
|
10
|
-
| Style | Use when | Example |
|
|
11
|
-
|---|---|---|
|
|
12
|
-
| Class | A configured surrogate is stored on a neuron or layer and reused | `Sigmoid(alpha=4.0)` |
|
|
13
|
-
| Functional | One direct spike operation is clearer | `sigmoid(x, alpha=4.0)` |
|
|
14
|
-
| Custom class | The research method specifies a derivative absent from the library | Subclass `Surrogate` and implement `surrogate_grad`; optionally implement `surrogate_fun` for analysis. |
|
|
15
|
-
|
|
16
|
-
Corresponding class and functional forms have the same forward and backward
|
|
17
|
-
semantics.
|
|
18
|
-
|
|
19
|
-
## Choose a gradient family
|
|
20
|
-
|
|
21
|
-
| Family | Use when | Main tuning behavior |
|
|
22
|
-
|---|---|---|
|
|
23
|
-
| Sigmoid, soft-sign, arctangent, or ERF | A smooth bounded derivative is preferred | `alpha` controls slope or concentration. |
|
|
24
|
-
| Piecewise quadratic or exponential | A local, inexpensive piecewise derivative is preferred | `alpha` controls scale or sharpness. |
|
|
25
|
-
| ReLU-based | A simple or tailed piecewise derivative is required | Width, leak, and scale control support and tails. |
|
|
26
|
-
| Gaussian | Gradient should be localized around threshold | `sigma` controls support; scale controls magnitude. |
|
|
27
|
-
| Advanced published form | Reproducing a specified SNN method | Preserve the documented parameters and formulation. |
|
|
28
|
-
|
|
29
|
-
Start with `Sigmoid`, `PiecewiseQuadratic`, or `ReluGrad`, confirm finite
|
|
30
|
-
nonzero gradients, then vary one family or parameter at a time.
|
|
31
|
-
|
|
32
|
-
## Smooth bounded surrogates
|
|
33
|
-
|
|
34
|
-
| Functional API | Class API | Description |
|
|
35
|
-
|---|---|---|
|
|
36
|
-
| `sigmoid(x, alpha=4.0)` | `Sigmoid(alpha=4.0)` | Use a sigmoid-shaped backward derivative. |
|
|
37
|
-
| `soft_sign(x, alpha=...)` | `SoftSign(alpha=...)` | Use a soft-sign derivative with different tail decay. |
|
|
38
|
-
| `arctan(x, alpha=...)` | `Arctan(alpha=...)` | Use an arctangent-shaped smooth derivative. |
|
|
39
|
-
| `erf(x, alpha=...)` | `ERF(alpha=...)` | Use an error-function/Gaussian-CDF derivative. |
|
|
40
|
-
|
|
41
|
-
## Piecewise and ReLU-based surrogates
|
|
42
|
-
|
|
43
|
-
| Functional API | Class API | Description |
|
|
44
|
-
|---|---|---|
|
|
45
|
-
| `piecewise_quadratic(x, alpha=1.0)` | `PiecewiseQuadratic(alpha=1.0)` | Use a triangle-like piecewise-quadratic derivative. |
|
|
46
|
-
| `piecewise_exp(x, alpha=1.0)` | `PiecewiseExp(alpha=1.0)` | Use a piecewise-exponential derivative. |
|
|
47
|
-
| `piecewise_leaky_relu(x, c=..., alpha=...)` | `PiecewiseLeakyRelu(c=..., alpha=...)` | Use a piecewise leaky-ReLU derivative. |
|
|
48
|
-
| `leaky_relu(x, alpha=..., beta=...)` | `LeakyRelu(alpha=..., beta=...)` | Use a leaky-ReLU-shaped derivative. |
|
|
49
|
-
| `log_tailed_relu(x, alpha=...)` | `LogTailedRelu(alpha=...)` | Use a ReLU-like center with logarithmic tails. |
|
|
50
|
-
| `relu_grad(x, alpha=0.3, width=1.0)` | `ReluGrad(alpha=0.3, width=1.0)` | Use a constant local derivative within a configured threshold width. |
|
|
51
|
-
|
|
52
|
-
## Gaussian and inverse-square surrogates
|
|
53
|
-
|
|
54
|
-
| Functional API | Class API | Description |
|
|
55
|
-
|---|---|---|
|
|
56
|
-
| `gaussian_grad(x, sigma=0.5, alpha=0.5)` | `GaussianGrad(sigma=0.5, alpha=0.5)` | Use one Gaussian derivative peak around threshold. |
|
|
57
|
-
| `multi_gaussian_grad(x, h=0.15, s=6.0, sigma=0.5, scale=0.5)` | `MultiGaussianGrad(h=0.15, s=6.0, sigma=0.5, scale=0.5)` | Use the documented multi-Gaussian combination. |
|
|
58
|
-
| `inv_square_grad(x, alpha=...)` | `InvSquareGrad(alpha=...)` | Use an inverse-square derivative profile. |
|
|
59
|
-
|
|
60
|
-
## Advanced surrogates
|
|
61
|
-
|
|
62
|
-
| Functional API | Class API | Description |
|
|
63
|
-
|---|---|---|
|
|
64
|
-
| `squarewave_fourier_series(x, ...)` | `SquarewaveFourierSeries(...)` | Use a truncated Fourier approximation to a square wave. |
|
|
65
|
-
| `s2nn(x, alpha=4.0, beta=1.0, epsilon=1e-8)` | `S2NN(alpha=4.0, beta=1.0, epsilon=1e-8)` | Use the S2NN formulation. |
|
|
66
|
-
| `q_pseudo_spike(x, alpha=2.0)` | `QPseudoSpike(alpha=2.0)` | Use the q-pseudo-spike formulation. |
|
|
67
|
-
| `slayer_grad(x, alpha=1.0)` | `SlayerGrad(alpha=1.0)` | Use the SLAYER surrogate formulation. |
|
|
68
|
-
| `nonzero_sign_log(x, alpha=...)` | `NonzeroSignLog(alpha=...)` | Use nonzero sign with logarithmic damping. |
|
|
69
|
-
|
|
70
|
-
## Canonical neuron integration
|
|
71
|
-
|
|
72
|
-
Store the configured surrogate on the neuron and apply it to membrane state
|
|
73
|
-
relative to threshold.
|
|
74
|
-
|
|
75
|
-
```python
|
|
76
|
-
import brainstate as bst
|
|
77
|
-
import jax.numpy as jnp
|
|
78
|
-
from braintools.surrogate import Sigmoid
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
class LIFLayer(bst.nn.Module):
|
|
82
|
-
def __init__(self, in_size, out_size):
|
|
83
|
-
super().__init__()
|
|
84
|
-
self.linear = bst.nn.Linear(in_size, out_size)
|
|
85
|
-
self.v = bst.State(jnp.zeros(out_size))
|
|
86
|
-
self.spike = Sigmoid(alpha=4.0)
|
|
87
|
-
|
|
88
|
-
def __call__(self, x):
|
|
89
|
-
self.v.value = 0.9 * self.v.value + self.linear(x)
|
|
90
|
-
spikes = self.spike(self.v.value - 1.0)
|
|
91
|
-
self.v.value = jnp.where(spikes > 0, 0.0, self.v.value)
|
|
92
|
-
return spikes
|
|
93
|
-
```
|
|
94
|
-
|
|
95
|
-
**Invariant:** the forward value remains the discrete threshold event. The
|
|
96
|
-
surrogate changes only the derivative seen by automatic differentiation.
|
|
97
|
-
|
|
98
|
-
## Validate the chosen surrogate
|
|
99
|
-
|
|
100
|
-
Inspect representative gradients before a training run:
|
|
101
|
-
|
|
102
|
-
```python
|
|
103
|
-
import jax
|
|
104
|
-
import jax.numpy as jnp
|
|
105
|
-
from braintools.surrogate import Sigmoid
|
|
106
|
-
|
|
107
|
-
spike = Sigmoid(alpha=4.0)
|
|
108
|
-
x = jnp.linspace(-2.0, 2.0, 101)
|
|
109
|
-
gradient = jax.vmap(jax.grad(lambda value: spike(value)))(x)
|
|
110
|
-
|
|
111
|
-
assert jnp.all(jnp.isfinite(gradient))
|
|
112
|
-
assert jnp.any(gradient != 0)
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
If learning fails, first verify reset timing, loss reduction, gradient target,
|
|
116
|
-
and temporal rollout. Do not change the surrogate, optimizer, and loss
|
|
117
|
-
simultaneously.
|
|
118
|
-
|
|
119
|
-
## Custom surrogate
|
|
120
|
-
|
|
121
|
-
Subclass `Surrogate` only when the required derivative is not already
|
|
122
|
-
represented:
|
|
123
|
-
|
|
124
|
-
```python
|
|
125
|
-
import jax.numpy as jnp
|
|
126
|
-
from braintools.surrogate import Surrogate
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
class TanhSurrogate(Surrogate):
|
|
130
|
-
def __init__(self, alpha=1.0):
|
|
131
|
-
super().__init__()
|
|
132
|
-
self.alpha = alpha
|
|
133
|
-
|
|
134
|
-
def surrogate_fun(self, x):
|
|
135
|
-
return 0.5 * jnp.tanh(self.alpha * x) + 0.5
|
|
136
|
-
|
|
137
|
-
def surrogate_grad(self, x):
|
|
138
|
-
tanh_x = jnp.tanh(self.alpha * x)
|
|
139
|
-
return 0.5 * self.alpha * (1.0 - tanh_x**2)
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
Keep `surrogate_grad` pure, shape preserving, JAX traceable, and finite near
|
|
143
|
-
threshold.
|
|
144
|
-
|
|
145
|
-
## Official source
|
|
146
|
-
|
|
147
|
-
- `https://brainx.chaobrain.com/braintools/apis/surrogate.html`
|