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,179 @@
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`
@@ -0,0 +1,183 @@
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`
@@ -0,0 +1,147 @@
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`