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.
Files changed (171) hide show
  1. package/README.md +17 -1
  2. package/manifest.json +1 -1
  3. package/mcp-servers/codex/skills.json +1 -1
  4. package/package.json +1 -1
  5. package/skills/bio-neuro-lit/SKILL.md +4 -2
  6. package/skills/bio-neuro-lit/references/required-supplements.md +27 -0
  7. package/skills/brainx-acceleration/SKILL.md +30 -437
  8. package/skills/brainx-acceleration/references/audit-and-rewrite-patterns.md +326 -0
  9. package/skills/brainx-general-guard/SKILL.md +24 -8
  10. package/skills/brainx-install/SKILL.md +3 -3
  11. package/skills/brainx-install/references/compatibility-and-release-matching.md +28 -20
  12. package/skills/brainx-install/references/uninstall-and-cleanup.md +11 -4
  13. package/skills/brainx-modeling-loop/SKILL.md +143 -36
  14. package/skills/brainx-modeling-loop/agents/openai.yaml +2 -2
  15. package/skills/brainx-modeling-loop/references/mechanism-comparison.md +62 -0
  16. package/skills/brainx-modeling-loop/references/multiscale-coupling.md +16 -0
  17. package/skills/brainx-modeling-loop/references/paper-reproduction.md +42 -0
  18. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +14 -14
  19. package/skills/brainx-modeling-loop/references/run-experiment.md +1 -1
  20. package/skills/brainx-modeling-loop/references/training-workflow.md +10 -8
  21. package/skills/brainx-visualization/SKILL.md +6 -2
  22. package/skills/brainx-visualization/references/neural-data-visualization.md +1 -1
  23. package/skills/brainx-visualization/references/statistical-and-model-visualization.md +1 -1
  24. package/skills/package-skills/braincell/SKILL.md +23 -14
  25. package/skills/package-skills/braincell/references/braintools/input-current.md +1 -1
  26. package/skills/package-skills/braincell/references/braintools/metric.md +72 -46
  27. package/skills/package-skills/braincell/references/mixions-for-adaptation.md +1 -1
  28. package/skills/package-skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +1 -1
  29. package/skills/package-skills/braincell/references/multicompartment/cv-policy-reference.md +1 -1
  30. package/skills/package-skills/braincell/references/multicompartment/filter-function-library.md +3 -3
  31. package/skills/package-skills/braincell/references/multicompartment/morphology-io-loading-validation.md +1 -1
  32. package/skills/package-skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +31 -43
  33. package/skills/package-skills/braincell/references/multicompartment/network-workflow.md +49 -0
  34. package/skills/package-skills/braincell/references/multicompartment/probe-reference.md +26 -114
  35. package/skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md +40 -28
  36. package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py +13 -17
  37. package/skills/package-skills/brainevent/SKILL.md +0 -3
  38. package/skills/package-skills/brainevent/references/synaptic-plasticity.md +1 -1
  39. package/skills/package-skills/brainmass/SKILL.md +5 -3
  40. package/skills/package-skills/brainmass/references/brainstate/parameter-constraints-regularization.md +9 -7
  41. package/skills/package-skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
  42. package/skills/package-skills/brainmass/references/braintools/data-preprocessing.md +15 -7
  43. package/skills/package-skills/brainmass/references/braintools/metric.md +72 -46
  44. package/skills/package-skills/brainmass/references/coupling-network-api.md +3 -1
  45. package/skills/package-skills/brainmass/references/fitting-with-objectives-api.md +6 -6
  46. package/skills/package-skills/brainmass/references/horn-task-training.md +9 -9
  47. package/skills/package-skills/brainmass/references/modellibrary.md +12 -10
  48. package/skills/package-skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +5 -3
  49. package/skills/package-skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +10 -6
  50. package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +3 -1
  51. package/skills/package-skills/brainmass/references/visualization-analysis-api.md +17 -9
  52. package/skills/package-skills/brainspike/SKILL.md +201 -0
  53. package/skills/package-skills/brainspike/references/braintools/connectivity.md +40 -0
  54. package/skills/package-skills/brainspike/references/braintools/data-preprocessing.md +39 -0
  55. package/skills/package-skills/brainspike/references/braintools/input-current.md +55 -0
  56. package/skills/package-skills/brainspike/references/braintools/metric.md +36 -0
  57. package/skills/package-skills/brainspike/references/braintools/optimizer.md +50 -0
  58. package/skills/package-skills/brainspike/references/braintools/parameter-initializer.md +43 -0
  59. package/skills/package-skills/brainspike/references/braintools/surrogate.md +40 -0
  60. package/skills/package-skills/brainspike/references/migration-boundary.md +38 -0
  61. package/skills/package-skills/brainspike/references/model-and-readout-selection.md +41 -0
  62. package/skills/package-skills/brainspike/references/multirate-coupling.md +31 -0
  63. package/skills/package-skills/brainspike/references/multiscale-composition.md +28 -0
  64. package/skills/package-skills/brainspike/references/native-composition.md +52 -0
  65. package/skills/package-skills/brainspike/references/native-delays.md +34 -0
  66. package/skills/package-skills/brainspike/references/native-projections.md +43 -0
  67. package/skills/package-skills/brainspike/references/native-training.md +36 -0
  68. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/devices.md +33 -33
  69. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/divergence-and-parity.md +15 -15
  70. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/integration-categories.md +1 -1
  71. package/skills/package-skills/brainspike/references/nest-compatible/model-library.md +200 -0
  72. package/skills/package-skills/brainspike/references/nest-compatible/network-building.md +276 -0
  73. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brette_et_al_2007.py +23 -26
  74. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_alpha.py +18 -21
  75. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_delta.py +16 -19
  76. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +11 -12
  77. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +10 -11
  78. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/spatial_gaussex.py +18 -18
  79. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/synapsecollection.py +26 -29
  80. package/skills/package-skills/brainspike/references/nest-compatible/synapse-and-connectivity.md +166 -0
  81. package/skills/package-skills/brainspike/references/nest-delay-boundaries.md +31 -0
  82. package/skills/package-skills/brainspike/references/nonlinear-state-sharing.md +26 -0
  83. package/skills/package-skills/{brainpy-state → brainspike}/references/perturbation-experiment-validity.md +2 -2
  84. package/skills/package-skills/brainspike/references/simulator-training.md +61 -0
  85. package/skills/package-skills/brainspike/references/temporal-task-training.md +36 -0
  86. package/skills/package-skills/brainspike/scripts/advanced_native_patterns.py +76 -0
  87. package/skills/package-skills/brainspike/scripts/delay_workflow.py +44 -0
  88. package/skills/package-skills/brainspike/scripts/delayed_cue_training.py +78 -0
  89. package/skills/package-skills/brainspike/scripts/lif_smoke.py +31 -0
  90. package/skills/package-skills/brainspike/scripts/multiscale_workflow.py +35 -0
  91. package/skills/package-skills/brainspike/scripts/native_ei_network.py +47 -0
  92. package/skills/package-skills/brainspike/scripts/native_workflows.py +77 -0
  93. package/skills/package-skills/brainspike/scripts/nest_boundary_workflows.py +108 -0
  94. package/skills/package-skills/brainspike/scripts/train_native_snn.py +65 -0
  95. package/skills/package-skills/brainspike/scripts/train_nest_simulator.py +69 -0
  96. package/skills/package-skills/brainspike/scripts/train_nest_simulator_two_weights.py +220 -0
  97. package/skills/package-skills/brainstate/SKILL.md +16 -21
  98. package/skills/package-skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +1 -138
  99. package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  100. package/skills/package-skills/brainstate/references/brainstate/delay-buffers.md +45 -0
  101. package/skills/package-skills/brainstate/references/brainstate/parameter-constraints-regularization.md +9 -7
  102. package/skills/package-skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
  103. package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md +6 -4
  104. package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md +4 -4
  105. package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md +1 -1
  106. package/skills/package-skills/brainstate/references/braintools-optimizer-reference.md +16 -0
  107. package/skills/package-skills/brainstate/references/libraries/prebuilt-layer-library.md +1 -1
  108. package/skills/package-skills/brainstate/references/simulation-environment.md +5 -5
  109. package/skills/package-skills/braintrace/SKILL.md +17 -38
  110. package/skills/package-skills/braintrace/references/Drtrl.md +9 -26
  111. package/skills/package-skills/braintrace/references/algorithm selection.md +7 -12
  112. package/skills/package-skills/braintrace/references/batching.md +15 -35
  113. package/skills/package-skills/braintrace/references/compiler_internal.md +1 -1
  114. package/skills/package-skills/braintrace/references/custom algorithms.md +1 -2
  115. package/skills/package-skills/braintrace/references/customizing_primitive_transforms.md +26 -15
  116. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +5 -139
  117. package/skills/package-skills/brainunit/SKILL.md +7 -2
  118. package/skills/package-skills/brainunit/references/array-mechanics/functional-structural-api.md +1 -1
  119. package/skills/package-skills/brainunit/references/math-function-library.md +2 -2
  120. package/skills/package-skills/brainunit/references/typing-and-runtime-validation.md +5 -2
  121. package/skills/package-skills/brainevent/references/scripts/102_EI_net_1996.py +0 -107
  122. package/skills/package-skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +0 -168
  123. package/skills/package-skills/brainevent/references/scripts/coba_ei_teaching.py +0 -356
  124. package/skills/package-skills/brainpy-state/SKILL.md +0 -247
  125. package/skills/package-skills/brainpy-state/references/array-creation.md +0 -158
  126. package/skills/package-skills/brainpy-state/references/brain-dynamics-delay-protocol.md +0 -147
  127. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/analysis.md +0 -150
  128. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +0 -373
  129. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -150
  130. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +0 -175
  131. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +0 -286
  132. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +0 -111
  133. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -163
  134. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -113
  135. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -136
  136. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -222
  137. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -123
  138. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +0 -107
  139. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -185
  140. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/integrators.md +0 -181
  141. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +0 -102
  142. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +0 -147
  143. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +0 -159
  144. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +0 -127
  145. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +0 -167
  146. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +0 -107
  147. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -186
  148. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +0 -104
  149. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +0 -89
  150. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +0 -253
  151. package/skills/package-skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +0 -334
  152. package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +0 -206
  153. package/skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md +0 -79
  154. package/skills/package-skills/brainpy-state/references/braintools/input-current.md +0 -199
  155. package/skills/package-skills/brainpy-state/references/braintools/metric.md +0 -152
  156. package/skills/package-skills/brainpy-state/references/braintools/optimizer.md +0 -179
  157. package/skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md +0 -183
  158. package/skills/package-skills/brainpy-state/references/braintools/surrogate.md +0 -147
  159. package/skills/package-skills/brainpy-state/references/component-selection.md +0 -288
  160. package/skills/package-skills/brainpy-state/references/nest-compatible/model-library.md +0 -200
  161. package/skills/package-skills/brainpy-state/references/nest-compatible/nest-workflow.md +0 -156
  162. package/skills/package-skills/brainpy-state/references/nest-compatible/network-building.md +0 -264
  163. package/skills/package-skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +0 -153
  164. package/skills/package-skills/brainpy-state/references/projection-patterns.md +0 -127
  165. package/skills/package-skills/brainpy-state/references/scripts/103_COBA_2005.py +0 -86
  166. package/skills/package-skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +0 -181
  167. package/skills/package-skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +0 -156
  168. package/skills/package-skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +0 -111
  169. package/skills/package-skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -221
  170. package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +0 -240
  171. package/skills/package-skills/brainpy-state/references/scripts/training-snn.py +0 -119
@@ -1,167 +0,0 @@
1
- # Legacy BrainPy optimizers
2
-
3
- Use this reference after a legacy BrainPy loss and gradient target are correct.
4
- It covers `brainpy.optim` optimizers and schedulers that mutate named
5
- `bm.Variable` objects; do not substitute Braintools optimizers or BrainState
6
- `ParamState` trees in this workflow.
7
-
8
- ## Apply a gradient update
9
-
10
- A legacy optimizer owns a named dictionary of trainable variables, scheduler
11
- State, and any algorithm-specific moment or velocity variables. The gradient
12
- dictionary passed to `update()` must have the same keys and compatible shapes.
13
-
14
- | API | Description |
15
- |---|---|
16
- | `bp.optim.Optimizer(lr, train_vars=None, name=None)` | Subclass only for a custom update rule; it normalizes `lr` to a scheduler and owns the registered trainable variables. |
17
- | `bm.grad(func, grad_vars=train_vars, return_value=True)` | Differentiate a scalar loss with respect to the same named variable dictionary. |
18
- | `optimizer.update(grads)` | Mutate the registered variables and advance optimizer-owned State from a matching gradient dictionary. |
19
- | `optimizer.vars()` | Inspect scheduler, step, velocity, and moment variables that must remain visible to object-aware transformations. |
20
-
21
- ```python
22
- import brainpy as bp
23
- import brainpy.math as bm
24
-
25
-
26
- class Objective(bp.BrainPyObject):
27
- def __init__(self):
28
- super().__init__()
29
- self.weight = bm.TrainVar(bm.array([1.0]))
30
-
31
- def __call__(self):
32
- return bm.mean((self.weight - 3.0) ** 2)
33
-
34
-
35
- objective = Objective()
36
- train_vars = {'weight': objective.weight}
37
- optimizer = bp.optim.Adam(lr=0.05, train_vars=train_vars)
38
- value_and_grad = bm.grad(
39
- objective,
40
- grad_vars=train_vars,
41
- return_value=True,
42
- )
43
-
44
- grads, loss = value_and_grad()
45
- optimizer.update(grads)
46
-
47
- assert grads.keys() == train_vars.keys()
48
- assert loss.ndim == 0
49
- ```
50
-
51
- Process gradients between differentiation and `update()` when clipping or
52
- another explicit transform is required. Do not rename, drop, or add keys while
53
- doing so.
54
-
55
- ## Choose an optimizer
56
-
57
- Establish `Adam` or `SGD` as the baseline, then select a specialized rule only
58
- when its behavior matches the training regime.
59
-
60
- | API | Description |
61
- |---|---|
62
- | `bp.optim.SGD(lr, train_vars=None, weight_decay=None, name=None)` | Use for plain stochastic gradient descent and as the simplest update baseline. |
63
- | `bp.optim.Momentum(lr, train_vars=None, momentum=0.9, weight_decay=None, name=None)` | Use when velocity-based momentum is required. |
64
- | `bp.optim.MomentumNesterov(lr, train_vars=None, weight_decay=None, momentum=0.9, name=None)` | Use for Nesterov accelerated momentum. |
65
- | `bp.optim.Adagrad(lr, train_vars=None, weight_decay=None, epsilon=1e-6, name=None)` | Use when accumulated squared gradients should adapt each parameter's rate. |
66
- | `bp.optim.Adadelta(lr=1.0, train_vars=None, weight_decay=None, epsilon=1e-6, rho=0.95, name=None)` | Use for the Adadelta extension with decaying accumulated statistics. |
67
- | `bp.optim.RMSProp(lr, train_vars=None, weight_decay=None, epsilon=1e-6, rho=0.9, name=None)` | Use for a moving average of squared gradients. Preserve the legacy capitalization `RMSProp`. |
68
- | `bp.optim.Adam(lr, train_vars=None, beta1=0.9, beta2=0.999, eps=1e-8, weight_decay=None, name=None)` | Use as the canonical adaptive baseline after verifying finite, nonzero gradients. |
69
- | `bp.optim.AdamW(lr, train_vars=None, beta1=0.9, beta2=0.999, eps=1e-8, weight_decay=0.01, amsgrad=False, name=None)` | Use when decoupled weight decay is required. |
70
- | `bp.optim.LARS(lr, train_vars=None, momentum=0.9, weight_decay=0.0001, tc=0.001, eps=1e-5, name=None)` | Use for layer-wise adaptive rate scaling in an explicitly large-batch regime. |
71
- | `bp.optim.Adan(lr=0.001, train_vars=None, betas=(0.02, 0.08, 0.01), eps=1e-8, weight_decay=0.02, no_prox=False, name=None)` | Use only when the Adan adaptive Nesterov method is intentionally selected. |
72
-
73
- Optimizer classes create different auxiliary State. `SGD` may only expose
74
- scheduler step State; `Momentum` adds velocity variables; `Adam` adds step and
75
- first- and second-moment variables. Preserve all of them across checkpoints and
76
- compiled updates.
77
-
78
- ## Choose a learning-rate schedule
79
-
80
- Every optimizer `lr` becomes a `bp.optim.Scheduler`. A scalar or `bm.Variable`
81
- is normalized to `bp.optim.Constant` by `make_schedule()`.
82
-
83
- | API | Description |
84
- |---|---|
85
- | `bp.optim.make_schedule(scalar_or_schedule)` | Normalize a scalar, variable, or existing scheduler to the scheduler interface. |
86
- | `bp.optim.Constant(lr, last_epoch=-1)` | Use for an unchanging learning rate. |
87
- | `bp.optim.StepLR(lr, step_size, gamma=0.1, last_epoch=-1)` | Multiply the rate by `gamma` every `step_size` epochs. |
88
- | `bp.optim.MultiStepLR(lr, milestones, gamma=0.1, last_epoch=-1)` | Decay at explicitly listed epoch milestones. |
89
- | `bp.optim.CosineAnnealingLR(lr, T_max, eta_min=0.0, last_epoch=-1)` | Anneal from the initial rate to `eta_min` over the configured cosine horizon. |
90
- | `bp.optim.CosineAnnealingWarmRestarts(lr, num_call_per_epoch, T_0, T_mult=1, eta_min=0.0, last_epoch=-1, last_call=-1)` | Use cosine annealing with expanding or fixed restart periods; match calls per epoch to the actual update cadence. |
91
- | `bp.optim.ExponentialLR(lr, gamma, last_epoch=-1)` | Multiply the rate by `gamma` every epoch. |
92
- | `bp.optim.ExponentialDecayLR(lr, decay_steps, decay_rate, last_epoch=-1, last_call=-1)` | Apply call-count-based exponential decay over `decay_steps`. |
93
- | `bp.optim.InverseTimeDecayLR(lr, decay_steps, decay_rate, staircase=False, last_epoch=-1, last_call=-1)` | Apply inverse-time decay, optionally in staircase form. |
94
- | `bp.optim.PolynomialDecayLR(lr, decay_steps, final_lr, power=1.0, last_epoch=-1, last_call=-1)` | Decay polynomially toward `final_lr`. |
95
- | `bp.optim.PiecewiseConstantLR(boundaries, values, last_epoch=-1, last_call=-1)` | Use explicit piecewise-constant rates over call-count boundaries. |
96
-
97
- ```python
98
- scheduler = bp.optim.ExponentialDecayLR(
99
- lr=0.1,
100
- decay_steps=100,
101
- decay_rate=0.99,
102
- )
103
- optimizer = bp.optim.Adam(
104
- lr=scheduler,
105
- train_vars=train_vars,
106
- )
107
-
108
- initial_rate = optimizer.lr(0)
109
- later_rate = optimizer.lr(100)
110
- assert later_rate < initial_rate
111
- ```
112
-
113
- Calling a scheduler with an explicit index evaluates that step. Calling without
114
- an index evaluates its built-in training step. Count optimizer and scheduler
115
- calls against the intended epoch or batch timescale; a schedule configured in
116
- epochs decays too quickly if advanced once per batch.
117
-
118
- To change a constant schedule intentionally, use `optimizer.lr.lr = value` or
119
- `optimizer.lr.set_value(value)`. Do not replace the scheduler object during a
120
- compiled training run.
121
-
122
- ## JIT and checkpoint optimizer State
123
-
124
- If an update is wrapped in `bm.jit`, include the variables returned by
125
- `optimizer.vars()` in the transformation's dynamic-variable set when they are
126
- not already discoverable through the transformed object. Omitting them can
127
- freeze or lose step, velocity, and moment updates.
128
-
129
- Checkpoint all of the following together:
130
-
131
- | State | Why it matters |
132
- |---|---|
133
- | `train_vars` | Contains the parameters being optimized. |
134
- | `optimizer.vars()` | Contains schedule position and algorithm-specific accumulated State. |
135
- | Model dynamical State when resuming mid-rollout | Determines the next simulation and gradient result. |
136
-
137
- For a new independent training run, reset model State and construct a new
138
- optimizer when moment and scheduler histories must also restart. Resetting only
139
- neuronal State does not restart Adam moments or scheduler time.
140
-
141
- ## Customize only the missing mechanism
142
-
143
- Subclass `bp.optim.Optimizer` when a required update rule is absent. Accept
144
- `lr` and `train_vars`, register every dynamically changing auxiliary variable,
145
- and implement `update(grads)` with the same named-gradient contract.
146
-
147
- Subclass `bp.optim.Scheduler` when the learning-rate policy is absent. Implement
148
- `__call__(i=None)` so explicit indices and the built-in step have clear,
149
- consistent semantics.
150
-
151
- ## Source-backed failures
152
-
153
- - Pass a dictionary of legacy `bm.Variable` or `bm.TrainVar` objects as
154
- `train_vars`; do not pass BrainState `ParamState` collections.
155
- - Make the differentiated objective scalar and validate gradient finiteness
156
- before changing optimizer families.
157
- - Keep gradient keys and shapes identical to the registered trainable-variable
158
- dictionary.
159
- - Preserve optimizer-owned variables through JIT and checkpointing.
160
- - Change one of loss, optimizer, schedule, or gradient processing at a time so a
161
- training regression remains diagnosable.
162
-
163
- ## Official sources
164
-
165
- - `https://brainpy.readthedocs.io/apis/optim.html`
166
- - `https://brainpy.readthedocs.io/tutorial_toolbox/optimizers.html`
167
- - Generated optimizer and scheduler pages linked from the official API index.
@@ -1,107 +0,0 @@
1
- # Parameter initializers
2
-
3
- Use this reference to choose and apply a legacy `brainpy.initialize` initializer for state arrays, trainable matrices, convolution kernels, or distance-dependent within-population weights. Keep these APIs separate from `brainpy.state` and from newer initializer packages.
4
-
5
- ## Selection map
6
-
7
- | Need | Use | Key constraint |
8
- |---|---|---|
9
- | Zeros, ones, a constant, or an identity matrix | Fixed and direct initializers | Check whether the consumer needs a scalar-filled array or a matrix with identity structure. |
10
- | Values from a named distribution | Random initializers | Set the distribution parameters and pass `seed` when the random sequence must be reproducible. |
11
- | Fan-scaled neural-network weights | Variance-scaling presets | Preserve the initializer's `in_axis` and `out_axis` interpretation for the actual weight layout. |
12
- | Orthogonal dense or convolutional weights | Orthogonal initializers | `DeltaOrthogonal` accepts only 3-D, 4-D, or 5-D shapes. |
13
- | Spatially decaying recurrent weights | Decay initializers | Define encoded ranges and periodic boundaries from the modeled space, not from array shape alone. |
14
-
15
- ## Initializer contract
16
-
17
- An initializer stores an initialization policy; calling it with a shape creates the concrete BrainPy array.
18
-
19
- | API | Description |
20
- |---|---|
21
- | `Initializer.__call__(shape, dtype=None)` | Implement this contract for a custom reusable initializer; it receives the requested shape and returns initialized values. |
22
-
23
- Pass an initializer object to a BrainPy API that accepts an initialization policy. Call it directly only when the concrete array is needed immediately.
24
-
25
- ## Fixed and direct initializers
26
-
27
- Use these when initialization is deterministic and does not depend on fan statistics.
28
-
29
- | API | Description |
30
- |---|---|
31
- | `ZeroInit()` | Fill the requested shape with zeros. |
32
- | `Constant(value=1.0)` | Fill the requested shape with `value`. |
33
- | `OneInit(value=1.0)` | Initialize with ones, optionally scaled by `value`. |
34
- | `Identity(value=1.0)` | Return an identity matrix scaled by `value`; use for matrix-shaped recurrent or linear weights. |
35
-
36
- ## Random initializers
37
-
38
- Use a direct distribution when its location, scale, or bounds are part of the model specification.
39
-
40
- | API | Description |
41
- |---|---|
42
- | `Normal(mean=0.0, scale=1.0, seed=None)` | Draw normally distributed values with the requested mean and scale. |
43
- | `Uniform(min_val=0.0, max_val=1.0, seed=None)` | Draw values uniformly from the requested interval. |
44
- | `TruncatedNormal(loc=0.0, scale=1.0, lower=-2.0, upper=2.0, seed=None)` | Draw from a normal distribution restricted to the supplied bounds. |
45
-
46
- Do not substitute a truncated normal for an ordinary normal silently; truncation changes both the support and the realized distribution.
47
-
48
- ## Variance-scaled initializers
49
-
50
- Use these for dense or convolutional weights whose scale must depend on fan-in, fan-out, or their average.
51
-
52
- | API | Description |
53
- |---|---|
54
- | `VarianceScaling(scale, mode, distribution, in_axis=-2, out_axis=-1, seed=None)` | Configure the scale, fan mode, distribution, and weight axes explicitly. |
55
- | `KaimingUniform(scale=2.0, mode='fan_in', distribution='uniform', in_axis=-2, out_axis=-1, seed=None)` | Use the Kaiming uniform preset. |
56
- | `KaimingNormal(scale=2.0, mode='fan_in', distribution='truncated_normal', in_axis=-2, out_axis=-1, seed=None)` | Use the Kaiming truncated-normal preset. |
57
- | `XavierUniform(scale=1.0, mode='fan_avg', distribution='uniform', in_axis=-2, out_axis=-1, seed=None)` | Use the Xavier uniform preset. |
58
- | `XavierNormal(scale=1.0, mode='fan_avg', distribution='truncated_normal', in_axis=-2, out_axis=-1, seed=None)` | Use the Xavier truncated-normal preset. |
59
- | `LecunUniform(scale=1.0, mode='fan_in', distribution='uniform', in_axis=-2, out_axis=-1, seed=None)` | Use the LeCun uniform preset. |
60
- | `LecunNormal(scale=1.0, mode='fan_in', distribution='truncated_normal', in_axis=-2, out_axis=-1, seed=None)` | Use the LeCun truncated-normal preset. |
61
-
62
- **Invariant:** `in_axis` and `out_axis` determine the fan calculation. Do not copy their defaults to a weight layout whose input and output axes differ.
63
-
64
- ## Orthogonal initializers
65
-
66
- Use orthogonal structure when the model or training method requires norm-preserving rows or columns.
67
-
68
- | API | Description |
69
- |---|---|
70
- | `Orthogonal(scale=1.0, axis=-1, seed=None)` | Construct a uniformly distributed orthogonal matrix; a non-square shape receives orthonormal rows or columns according to its smaller side. |
71
- | `DeltaOrthogonal(scale=1.0, axis=-1)` | Construct a delta-orthogonal convolution kernel; the requested shape must be 3-D, 4-D, or 5-D. |
72
-
73
- ## Distance-decay initializers
74
-
75
- Use these to build within-population weight patterns from encoded positions.
76
-
77
- | API | Description |
78
- |---|---|
79
- | `GaussianDecay(sigma, max_w, min_w=None, encoding_values=None, periodic_boundary=False, include_self=True, normalize=False)` | Build Gaussian-decaying weights; use `min_w` to suppress small weights and configure self-connections, normalization, encoded ranges, and periodic boundaries explicitly. |
80
- | `DOGDecay(sigmas, max_ws, min_w=None, encoding_values=None, periodic_boundary=False, normalize=True, include_self=True)` | Build a difference-of-Gaussians pattern from the positive and negative widths and amplitudes. |
81
-
82
- `encoding_values` defines the value range represented along each population axis. Set `periodic_boundary=True` only for a genuinely periodic represented variable such as an angle.
83
-
84
- ## Canonical workflow
85
-
86
- Create reusable policies first, then let each policy materialize the shape required by the consuming model:
87
-
88
- ```python
89
- import brainpy.initialize as init
90
-
91
- voltage_initializer = init.Normal(mean=-60.0, scale=2.0, seed=7)
92
- weight_initializer = init.XavierNormal(seed=11)
93
-
94
- initial_voltage = voltage_initializer((4,))
95
- weights = weight_initializer((4, 3))
96
- recurrent_identity = init.Identity(value=0.5)((3, 3))
97
-
98
- assert initial_voltage.shape == (4,)
99
- assert weights.shape == (4, 3)
100
- assert recurrent_identity.shape == (3, 3)
101
- ```
102
-
103
- Keep the initializer object when several components should share one policy. Construct separate seeded initializer objects when independent reproducible random sequences are required.
104
-
105
- ## Sources
106
-
107
- - https://brainpy.readthedocs.io/apis/initialize.html
@@ -1,186 +0,0 @@
1
- # Prebuilt neural network layers
2
-
3
- Use this reference to choose and compose legacy `brainpy.dnn` activations, convolutions, connection operators, normalization, pooling, interoperability wrappers, and utility layers. These are `brainpy.dnn` dynamical-system layers, not `brainpy.state` or `brainstate.nn` modules.
4
-
5
- ## Selection map
6
-
7
- | Family | Use when | Key constraint |
8
- |---|---|---|
9
- | Activations | A layer graph needs a stored nonlinear transformation. | Set the normalization dimension explicitly for softmax-family layers. |
10
- | Convolutions | Local kernels operate over one, two, or three spatial dimensions. | Legacy BrainPy convolution inputs place channels last. |
11
- | Dense and connectivity layers | Features or neural activity must be routed through dense, explicit sparse, masked, or implicit random connectivity. | Preserve event semantics and connection structure instead of replacing every operator with `Dense`. |
12
- | Normalization | Activations must be normalized over batch, layer, group, or instance statistics. | Match the documented axes and expected tensor layout. |
13
- | Pooling | Spatial values must be reduced locally or to a target shape. | Match the class suffix to the number of spatial dimensions and preserve `channel_axis`. |
14
- | Flax interoperability | A Flax module and a legacy BrainPy dynamical system must cross framework boundaries. | Use the wrapper in the direction required by the owning runtime. |
15
- | Utilities | A graph needs dropout, reshaping, or a function adapter. | Dropout's `prob` is the probability to keep a value and is active only in training mode. |
16
-
17
- ## Activation layers
18
-
19
- Use an activation class when the operation belongs in a stored BrainPy layer graph. Use `Activation(...)` to wrap a callable that has no dedicated class.
20
-
21
- | API | Choose it when |
22
- |---|---|
23
- | `Activation(activate_fun, name=None, mode=None, **kwargs)` | Wrap an arbitrary activation callable and retain its keyword arguments. |
24
- | `Threshold(threshold, value, inplace=False)` | Replace values on the thresholded side with a fixed value. |
25
- | `ReLU(inplace=False)` | Apply the standard rectified linear unit. |
26
- | `RReLU(lower=0.125, upper=1 / 3, inplace=False)` | Randomize the negative slope within the supplied bounds. |
27
- | `Hardtanh(min_val=-1.0, max_val=1.0, inplace=False)` | Clamp through a hard-tanh response. |
28
- | `ReLU6(inplace=False)` | Use ReLU capped at six. |
29
- | `Sigmoid(name=None, mode=None)` | Apply the logistic sigmoid. |
30
- | `Hardsigmoid(inplace=False)` | Use the piecewise-linear sigmoid approximation. |
31
- | `Tanh(name=None, mode=None)` | Apply hyperbolic tangent. |
32
- | `SiLU(inplace=False)` | Apply the sigmoid linear unit. |
33
- | `Mish(inplace=False)` | Apply Mish. |
34
- | `Hardswish(inplace=False)` | Apply hard-swish. |
35
- | `ELU(alpha=1.0, inplace=False)` | Apply an exponential linear unit with the selected negative scale. |
36
- | `CELU(alpha=1.0, inplace=False)` | Apply the continuously differentiable ELU form. |
37
- | `SELU(inplace=False)` | Apply scaled ELU in a self-normalizing architecture. |
38
- | `GLU(dim=-1)` | Split the selected dimension and gate one half with the other; the dimension size must be even. |
39
- | `GELU(approximate=False)` | Apply GELU and optionally select its approximation. |
40
- | `Hardshrink(lambd=0.5)` | Apply hard shrinkage around the configured threshold. |
41
- | `LeakyReLU(negative_slope=0.01, inplace=False)` | Preserve a fixed slope for negative values. |
42
- | `LogSigmoid(name=None, mode=None)` | Return log-sigmoid values. |
43
- | `Softplus(beta=1, threshold=20.0)` | Apply a smooth positive rectifier with explicit beta and numerical threshold. |
44
- | `Softshrink(lambd=0.5)` | Apply soft shrinkage around the configured threshold. |
45
- | `PReLU(num_parameters=1, init=0.25, dtype=None)` | Learn one negative slope globally or one slope per input channel. |
46
- | `Softsign(name=None, mode=None)` | Apply the soft-sign response. |
47
- | `Tanhshrink(name=None, mode=None)` | Apply tanh shrinkage. |
48
- | `Softmin(dim=None)` | Normalize so smaller inputs receive larger probabilities. |
49
- | `Softmax(dim=None)` | Normalize values into probabilities along `dim`. |
50
- | `Softmax2d(name=None, mode=None)` | Apply softmax over features at each spatial location. |
51
- | `LogSoftmax(dim=None)` | Return log-probabilities normalized along `dim`. |
52
-
53
- **Invariant:** set `dim` from the actual feature layout for `Softmin`, `Softmax`, and `LogSoftmax`. A call can succeed on the wrong dimension while producing the wrong probability semantics.
54
-
55
- ## Convolutional layers
56
-
57
- Choose the suffix from the number of spatial dimensions. Inputs use channel-last layouts such as `[H, W, C]` or `[B, H, W, C]` for `Conv2d`.
58
-
59
- | API | Constructor core and use |
60
- |---|---|
61
- | `Conv1d` | `Conv1d(in_channels, out_channels, kernel_size, stride=None, padding='SAME', lhs_dilation=1, rhs_dilation=1, groups=1, ...)` for one spatial dimension. |
62
- | `Conv2d` | `Conv2d(in_channels, out_channels, kernel_size, stride=None, padding='SAME', lhs_dilation=1, rhs_dilation=1, groups=1, ...)` for two spatial dimensions. |
63
- | `Conv3d` | `Conv3d(in_channels, out_channels, kernel_size, stride=None, padding='SAME', lhs_dilation=1, rhs_dilation=1, groups=1, ...)` for three spatial dimensions. |
64
- | `ConvTranspose1d` | `ConvTranspose1d(in_channels, out_channels, kernel_size, stride=1, padding='SAME', ...)` for learned one-dimensional upsampling. |
65
- | `ConvTranspose2d` | `ConvTranspose2d(in_channels, out_channels, kernel_size, stride=1, padding='SAME', ...)` for learned two-dimensional upsampling. |
66
- | `ConvTranspose3d` | `ConvTranspose3d(in_channels, out_channels, kernel_size, stride=1, padding='SAME', ...)` for learned three-dimensional upsampling. |
67
-
68
- `Conv1D`, `Conv2D`, and `Conv3D` are aliases of `Conv1d`, `Conv2d`, and `Conv3d`. Prefer the lowercase final suffix used by the canonical class names.
69
-
70
- The standard convolution family also accepts weight and bias initializers and an optional weight mask. Preserve `groups`, padding, stride, and dilation because they change the operator rather than merely tuning performance.
71
-
72
- ## Dense and connectivity layers
73
-
74
- Choose a dense feature transform only when connectivity structure is not itself part of the model.
75
-
76
- | API | Description |
77
- |---|---|
78
- | `Dense(num_in, num_out, W_initializer=..., b_initializer=..., mode=None, name=None)` | Apply a learned dense transform over the last input dimension. |
79
- | `Linear` | Alias of `Dense`. |
80
- | `Identity(*args, **kwargs)` | Keep a graph position without changing the input. |
81
- | `AllToAll(num_pre, num_post, weight, sharding=None, include_self=True, mode=None, name=None)` | Route activity through all-to-all synaptic weights and explicitly choose self-connections. |
82
- | `OneToOne(num, weight, sharding=None, mode=None, name=None)` | Apply one independent weight per matched pre/post index. |
83
- | `MaskedLinear(conn, weight, mask_fun=..., sharding=None, mode=None, name=None)` | Materialize a connector as a masked dense computation. |
84
- | `CSRLinear(conn, weight, sharding=None, mode=None, name=None, method=None, transpose=True)` | Apply ordinary values through explicit CSR sparse connectivity. |
85
- | `EventCSRLinear(conn, weight, sharding=None, mode=None, name=None, transpose=True)` | Apply spike or event input through explicit CSR sparse connectivity. |
86
- | `JitFPHomoLinear(num_in, num_out, prob, weight, seed=None, ..., transpose=False, atomic=False)` | Generate fixed-probability connectivity during multiplication with one homogeneous weight. |
87
- | `JitFPUniformLinear(num_in, num_out, prob, w_low, w_high, seed=None, ..., transpose=False, atomic=False)` | Generate fixed-probability connectivity with uniformly distributed weights. |
88
- | `JitFPNormalLinear(num_in, num_out, prob, w_mu, w_sigma, seed=None, ..., transpose=False, atomic=False)` | Generate fixed-probability connectivity with normally distributed weights. |
89
- | `EventJitFPHomoLinear(num_in, num_out, prob, weight, seed=None, ..., transpose=False, atomic=True)` | Use event input with implicit fixed-probability connectivity and one weight. |
90
- | `EventJitFPUniformLinear(num_in, num_out, prob, w_low, w_high, seed=None, ..., transpose=False, atomic=True)` | Use event input with implicit fixed-probability connectivity and uniform weights. |
91
- | `EventJitFPNormalLinear(num_in, num_out, prob, w_mu, w_sigma, seed=None, ..., transpose=False, atomic=True)` | Use event input with implicit fixed-probability connectivity and normal weights. |
92
-
93
- **Invariant:** `MaskedLinear`, CSR layers, and JIT fixed-probability layers encode different storage and execution choices. Select from the known connectivity representation and input type; converting all of them to `Dense` changes memory use and may change event semantics.
94
-
95
- ## Normalization layers
96
-
97
- Use batch normalization when batch statistics and running statistics are required; use layer, group, or instance normalization when the reduction domain follows feature structure instead.
98
-
99
- | API | Description |
100
- |---|---|
101
- | `BatchNorm1d(num_features, axis=(0, 1), epsilon=1e-5, momentum=0.99, affine=True, ..., mode=None)` | Normalize `[B, L, C]` data while excluding the channel axis from the reduction. |
102
- | `BatchNorm2d(num_features, axis=(0, 1, 2), epsilon=1e-5, momentum=0.99, affine=True, ..., mode=None)` | Normalize batch plus two spatial dimensions for channel-last data. |
103
- | `BatchNorm3d(num_features, axis=(0, 1, 2, 3), epsilon=1e-5, momentum=0.99, affine=True, ..., mode=None)` | Normalize batch plus three spatial dimensions for channel-last data. |
104
- | `LayerNorm(normalized_shape, epsilon=1e-5, ..., elementwise_affine=True, mode=None, name=None)` | Normalize the supplied trailing shape for each example. |
105
- | `GroupNorm(num_groups, num_channels, epsilon=1e-5, affine=True, ..., mode=None, name=None)` | Partition channels into the requested number of groups. |
106
- | `InstanceNorm(num_channels, epsilon=1e-5, affine=True, ..., mode=None, name=None)` | Normalize each instance independently over its non-channel dimensions. |
107
-
108
- `BatchNorm1D`, `BatchNorm2D`, and `BatchNorm3D` are aliases of their lowercase-suffix counterparts.
109
-
110
- Batch-normalization behavior depends on computation mode. Keep training and inference modes explicit when running the same layer in both workflows, and preserve any `axis_name` configuration used to aggregate statistics across mapped replicas.
111
-
112
- ## Pooling layers
113
-
114
- Use local pooling for a fixed window and adaptive pooling when the output spatial shape is specified directly.
115
-
116
- | API | Description |
117
- |---|---|
118
- | `MaxPool(kernel_size, stride=1, padding='VALID', channel_axis=None, mode=None, name=None)` | Take local maxima for a general window specification. |
119
- | `MaxPool1d(kernel_size, stride=None, padding='VALID', channel_axis=-1, mode=None, name=None)` | Apply one-dimensional max pooling. |
120
- | `MaxPool2d(kernel_size, stride=None, padding='VALID', channel_axis=-1, mode=None, name=None)` | Apply two-dimensional max pooling. |
121
- | `MaxPool3d(kernel_size, stride=None, padding='VALID', channel_axis=-1, mode=None, name=None)` | Apply three-dimensional max pooling. |
122
- | `MinPool(kernel_size, stride=1, padding='VALID', channel_axis=None, mode=None, name=None)` | Take local minima. |
123
- | `AvgPool(kernel_size, stride=1, padding='VALID', channel_axis=None, mode=None, name=None)` | Take local averages for a general window specification. |
124
- | `AvgPool1d(kernel_size, stride=1, padding='VALID', channel_axis=-1, mode=None, name=None)` | Apply one-dimensional average pooling. |
125
- | `AvgPool2d(kernel_size, stride=1, padding='VALID', channel_axis=-1, mode=None, name=None)` | Apply two-dimensional average pooling. |
126
- | `AvgPool3d(kernel_size, stride=1, padding='VALID', channel_axis=-1, mode=None, name=None)` | Apply three-dimensional average pooling. |
127
- | `AdaptiveAvgPool1d(target_shape, channel_axis=-1, name=None, mode=None)` | Average-pool one spatial dimension to `target_shape`. |
128
- | `AdaptiveAvgPool2d(target_shape, channel_axis=-1, name=None, mode=None)` | Average-pool two spatial dimensions to `target_shape`. |
129
- | `AdaptiveAvgPool3d(target_shape, channel_axis=-1, name=None, mode=None)` | Average-pool three spatial dimensions to `target_shape`. |
130
- | `AdaptiveMaxPool1d(target_shape, channel_axis=-1, name=None, mode=None)` | Max-pool one spatial dimension to `target_shape`. |
131
- | `AdaptiveMaxPool2d(target_shape, channel_axis=-1, name=None, mode=None)` | Max-pool two spatial dimensions to `target_shape`. |
132
- | `AdaptiveMaxPool3d(target_shape, channel_axis=-1, name=None, mode=None)` | Max-pool three spatial dimensions to `target_shape`. |
133
-
134
- ## Flax interoperability
135
-
136
- Keep ownership clear when crossing the framework boundary.
137
-
138
- | API | Description |
139
- |---|---|
140
- | `FromFlax(flax_module, *module_args, **module_kwargs)` | Wrap a Flax module as a legacy BrainPy `DynamicalSystem`. |
141
- | `ToFlaxRNNCell(*args, **kwargs)` | Wrap a BrainPy `DynamicalSystem` as a Flax recurrent module. |
142
- | `ToFlax` | Alias of `ToFlaxRNNCell`. |
143
-
144
- ## Utility layers
145
-
146
- | API | Description |
147
- |---|---|
148
- | `Dropout(prob, mode=None, name=None)` | Keep each value with probability `prob`; during training, scale survivors by `1 / prob`, and outside training mode act as a no-op. |
149
- | `Flatten(start_dim=0, end_dim=-1, name=None, mode=None)` | Flatten a contiguous dimension range; account for BrainPy batching mode when choosing `start_dim`. |
150
- | `Unflatten(dim, sizes, mode=None, name=None)` | Expand one dimension into `sizes`, whose product must match the original dimension. |
151
- | `FunAsLayer(fun, name=None, mode=None, **kwargs)` | Wrap an ordinary callable as a BrainPy layer and retain its keyword arguments. |
152
-
153
- **Invariant:** the documented `Dropout.prob` is a keep probability, not a drop rate. Do not translate it directly from an API whose parameter means the probability to discard.
154
-
155
- ## Canonical composition
156
-
157
- This example keeps the legacy channel-last layout explicit from convolution through pooling and dense readout:
158
-
159
- ```python
160
- import brainpy as bp
161
- import brainpy.math as bm
162
-
163
- conv = bp.dnn.Conv2d(
164
- in_channels=1,
165
- out_channels=8,
166
- kernel_size=(3, 3),
167
- padding="SAME",
168
- )
169
- activation = bp.dnn.ReLU()
170
- pool = bp.dnn.MaxPool2d(kernel_size=2, stride=2, channel_axis=-1)
171
-
172
- x = bm.ones((4, 28, 28, 1))
173
- features = pool(activation(conv(x)))
174
- flat = bm.reshape(features, (features.shape[0], -1))
175
- readout = bp.dnn.Dense(num_in=flat.shape[-1], num_out=10)
176
- logits = readout(flat)
177
-
178
- assert features.shape == (4, 14, 14, 8)
179
- assert logits.shape == (4, 10)
180
- ```
181
-
182
- Use a connection-specific linear layer instead of `Dense` when the input represents neural events or when explicit sparse, masked, or implicit random connectivity is part of the model.
183
-
184
- ## Sources
185
-
186
- - https://brainpy.readthedocs.io/apis/dnn.html
@@ -1,104 +0,0 @@
1
- # Surrogate gradients
2
-
3
- Use this reference when legacy `brainpy.math.surrogate` code must emit discrete spikes in the forward pass while supplying a smooth derivative for gradient-based spiking-neural-network training. Keep the import and examples on the legacy BrainPy surface; do not replace them with `brainpy.state` APIs.
4
-
5
- ## Core contract
6
-
7
- A surrogate spike function applies the Heaviside step in the forward pass and substitutes its configured surrogate derivative during backpropagation.
8
-
9
- | API | Description |
10
- |---|---|
11
- | `Surrogate()` | Base object for reusable class-style surrogate functions; use a concrete subclass for normal workflows. |
12
- | Class form, such as `Sigmoid(alpha=4.0)` | Store the derivative-shape parameters once and call the object repeatedly. |
13
- | Functional form, such as `sigmoid(x, alpha=4.0)` | Apply one surrogate operation inline without storing configuration. |
14
-
15
- **Invariant:** changing the surrogate family or its shape parameters changes the backward gradient, not the binary forward spike rule. Tune it as an optimization choice and verify gradients separately from spike outputs.
16
-
17
- ## Selection map
18
-
19
- | Family | Use when | Main controls |
20
- |---|---|---|
21
- | Smooth sigmoid-like | A smooth, centered surrogate is required. | Usually `alpha`; `ERF` uses the same centered family interface. |
22
- | Piecewise | A piecewise polynomial, exponential, or leaky response is required. | `alpha`, or the piecewise constants `c` and `w`. |
23
- | Fourier or literature-specific | The training method specifies a named estimator. | Preserve the estimator-specific parameters instead of translating them to a generic slope. |
24
- | ReLU-shaped | A rectangular, leaky, or tailed derivative is required. | Slope, width, and tail parameters. |
25
- | Gaussian-shaped | A Gaussian or multi-Gaussian derivative is required. | Width, height, scale, and side-lobe parameters. |
26
-
27
- ## Smooth surrogate families
28
-
29
- Choose between reusable class and inline functional forms without changing the mathematical family.
30
-
31
- | Class form | Functional form | Distinguishing behavior |
32
- |---|---|---|
33
- | `Sigmoid(alpha=...)` | `sigmoid(x, alpha=...)` | Sigmoid-shaped surrogate gradient. |
34
- | `SoftSign(alpha=...)` | `soft_sign(x, alpha=...)` | Soft-sign surrogate gradient. |
35
- | `Arctan(alpha=...)` | `arctan(x, alpha=...)` | Arctangent surrogate gradient. |
36
- | `NonzeroSignLog(alpha=...)` | `nonzero_sign_log(x, alpha=...)` | Nonzero-sign logarithmic surrogate gradient. |
37
- | `ERF(alpha=...)` | `erf(x, alpha=...)` | Error-function surrogate gradient. |
38
-
39
- ## Piecewise surrogate families
40
-
41
- Use these when the selected training formulation calls for a piecewise derivative.
42
-
43
- | Class form | Functional form | Distinguishing behavior |
44
- |---|---|---|
45
- | `PiecewiseQuadratic(alpha=...)` | `piecewise_quadratic(x, alpha=...)` | Piecewise-quadratic surrogate gradient. |
46
- | `PiecewiseExp(alpha=...)` | `piecewise_exp(x, alpha=...)` | Piecewise-exponential surrogate gradient. |
47
- | `PiecewiseLeakyRelu(c=..., w=...)` | `piecewise_leaky_relu(x, c=..., w=...)` | Piecewise leaky-ReLU surrogate controlled by its constant and width. |
48
-
49
- ## Fourier and named estimators
50
-
51
- Use a named estimator when reproducing a method that specifies it explicitly.
52
-
53
- | Class form | Functional form | Distinguishing behavior |
54
- |---|---|---|
55
- | `SquarewaveFourierSeries(n=..., t_period=...)` | `squarewave_fourier_series(x, n=..., t_period=...)` | Square-wave Fourier-series surrogate. |
56
- | `S2NN(alpha=..., beta=..., epsilon=...)` | `s2nn(x, alpha=..., beta=..., epsilon=...)` | S2NN surrogate spiking function. |
57
- | `QPseudoSpike(alpha=...)` | `q_pseudo_spike(x, alpha=...)` | q-PseudoSpike surrogate function. |
58
-
59
- ## ReLU-shaped surrogate families
60
-
61
- Use these when slope, width, or tail behavior must follow a ReLU-like estimator.
62
-
63
- | Class form | Functional form | Distinguishing behavior |
64
- |---|---|---|
65
- | `LeakyRelu(alpha=..., beta=...)` | `leaky_relu(x, alpha=..., beta=...)` | Leaky-ReLU surrogate gradient. |
66
- | `LogTailedRelu(alpha=...)` | `log_tailed_relu(x, alpha=...)` | Log-tailed ReLU surrogate gradient. |
67
- | `ReluGrad(alpha=..., width=...)` | `relu_grad(x, alpha=..., width=...)` | Finite-width ReLU-gradient surrogate. |
68
-
69
- ## Gaussian and other gradient families
70
-
71
- Use these when the chosen method specifies Gaussian lobes, inverse-square decay, or the SLAYER estimator.
72
-
73
- | Class form | Functional form | Distinguishing behavior |
74
- |---|---|---|
75
- | `GaussianGrad(sigma=..., alpha=...)` | `gaussian_grad(x, sigma=..., alpha=...)` | Gaussian surrogate gradient. |
76
- | `MultiGaussianGrad(h=..., s=..., sigma=..., scale=...)` | `multi_gaussian_grad(x, h=..., s=..., sigma=..., scale=...)` | Multi-Gaussian surrogate with configurable lobes and scale. |
77
- | `InvSquareGrad(alpha=...)` | `inv_square_grad(x, alpha=...)` | Inverse-square surrogate gradient. |
78
- | `SlayerGrad(alpha=...)` | `slayer_grad(x, alpha=...)` | SLAYER surrogate gradient. |
79
-
80
- ## Canonical workflow
81
-
82
- Use the class form for a spike rule stored by a model and verify both the discrete forward result and the differentiable backward path:
83
-
84
- ```python
85
- import brainpy.math as bm
86
- import jax.numpy as jnp
87
-
88
- spike_fn = bm.surrogate.Sigmoid(alpha=4.0)
89
- x = jnp.asarray([-1.0, 0.0, 1.0])
90
-
91
- class_spikes = spike_fn(x)
92
- functional_spikes = bm.surrogate.sigmoid(x, alpha=4.0)
93
- gradient = bm.grad(lambda value: bm.sum(spike_fn(value)))(x)
94
-
95
- assert bm.allclose(class_spikes, jnp.asarray([0.0, 1.0, 1.0]))
96
- assert bm.allclose(functional_spikes, class_spikes)
97
- assert gradient.shape == x.shape
98
- ```
99
-
100
- Do not validate a surrogate only by plotting its forward output; every family has the same step-like spike role. Inspect the gradient magnitude and support around the threshold because those determine the training signal.
101
-
102
- ## Sources
103
-
104
- - https://brainpy.readthedocs.io/apis/brainpy.math.surrogate.html
@@ -1,89 +0,0 @@
1
- # Trainer library
2
-
3
- Use this reference to select a trainer from the top-level legacy `brainpy`
4
- module. Choose from temporal credit assignment, feedforward backpropagation,
5
- incremental recurrent fitting, and whole-sequence regression. Open
6
- `trainingworkflows.md` after selecting the trainer for canonical fit, warm-up,
7
- prediction, and validation patterns.
8
-
9
- ## Trainer selection
10
-
11
- | Training requirement | Use | Key constraint |
12
- |---|---|---|
13
- | Reuse simulation and prediction mechanics in a custom trainer | `DSTrainer` | It is the structural trainer base; it does not select a learning algorithm. |
14
- | Differentiate through recurrent time steps | `BPTT` | Supply a loss and a legacy BrainPy optimizer; training data is an iterable or callable that yields input-target batches. |
15
- | Backpropagate through a feedforward model | `BPFF` | Use for feedforward networks; do not pay the recurrent unrolling cost of BPTT. |
16
- | Update a recurrent readout as samples arrive | `OnlineTrainer` | Supply an online algorithm such as RLS; fit data must be an `(X, Y)` pair. |
17
- | Use the FORCE convenience interface | `ForceTrainer` | It is the specialized online FORCE path. |
18
- | Fit a recurrent readout from a collected sequence | `OfflineTrainer` | Supply an offline algorithm; fit data must be an `(X, Y)` pair. |
19
- | Use ridge regression without configuring an offline algorithm | `RidgeTrainer` | It is the specialized offline ridge path. |
20
-
21
- ## Trainer constructors
22
-
23
- | API | Description |
24
- |---|---|
25
- | `DSTrainer(target, **kwargs)` | Use as the base for a custom dynamical-system trainer; it inherits runner configuration and provides prediction over the target. |
26
- | `BPTT(target, loss_fun, optimizer=None, loss_has_aux=False, loss_auto_run=True, seed=None, shuffle_data=None, **kwargs)` | Use for backpropagation through time; `loss_fun` may name a `brainpy.losses` function or accept `(predictions, targets)`. |
27
- | `BPFF(target, loss_fun, optimizer=None, loss_has_aux=False, loss_auto_run=True, seed=None, shuffle_data=None, **kwargs)` | Use for ordinary feedforward backpropagation with the same loss and optimizer contract. |
28
- | `OnlineTrainer(target, fit_method=None, **kwargs)` | Use for recurrent online fitting; `fit_method` may be a supported name, a configuration dictionary, an online-algorithm instance, or a callable. |
29
- | `ForceTrainer(target, alpha=1.0, **kwargs)` | Use for FORCE learning with regularization parameter `alpha`. |
30
- | `OfflineTrainer(target, fit_method=None, **kwargs)` | Use for whole-sequence recurrent fitting; `fit_method` may be a supported name, a configuration dictionary, an offline-algorithm instance, or a callable. |
31
- | `RidgeTrainer(target, alpha=1e-7, **kwargs)` | Use for ridge regression with Tikhonov regularization coefficient `alpha`. |
32
-
33
- Use explicit algorithm objects when the method has parameters that affect the
34
- experiment:
35
-
36
- ```python
37
- online = bp.OnlineTrainer(model, fit_method=bp.algorithms.RLS(alpha=1e-5))
38
- offline = bp.OfflineTrainer(
39
- model,
40
- fit_method=bp.algorithms.RidgeRegression(alpha=0.1),
41
- )
42
- ```
43
-
44
- String shortcuts such as `fit_method='rls'` and `fit_method='ridge'` are useful
45
- only when their defaults are intentional. A dictionary such as
46
- `{'name': 'ridge', 'alpha': 0.1}` selects and configures the method together.
47
-
48
- ## Fit and prediction lifecycle
49
-
50
- | API | Description |
51
- |---|---|
52
- | `DSTrainer.predict(inputs, reset_state=False, shared_args=None, eval_time=False)` | Use for prediction with runner semantics; it returns model output and optionally evaluation time. |
53
- | `OnlineTrainer.fit((X, Y), reset_state=False, shared_args=None)` | Use to update the fitted parameters incrementally while traversing a paired sequence. It rejects data that is not a two-item list or tuple. |
54
- | `OfflineTrainer.fit((X, Y), reset_state=False, shared_args=None)` | Use to collect the sequence and solve the selected offline fit; it returns the modeled output. |
55
- | `BPTT.fit(train_data, test_data=None, num_epoch=100, num_report=-1, reset_state=True, shared_args=None, ...)` | Use to run epoch-based gradient training from an iterable or callable batch source; it resets state by default. |
56
- | `BPTT.predict(inputs, reset_state=False, shared_args=None, eval_time=False)` | Use after fitting to run a time series; reset explicitly when the prediction is an independent trajectory. |
57
- | `BPTT.get_hist_metric(phase='fit', metric='loss', which='report')` | Use to retrieve reported or detailed fit/test metrics after training. |
58
-
59
- Online and offline trainers treat inputs as batched by default. Their canonical
60
- input has shape `(num_sample, num_time, num_feature)`. Preserve this batch-major
61
- layout unless the trainer is explicitly configured otherwise.
62
-
63
- ## Boundaries and common failures
64
-
65
- - Do not select `BPTT` for a feedforward-only model; use `BPFF`.
66
- - Do not select `OnlineTrainer` when the algorithm needs the complete feature
67
- matrix before solving; use `OfflineTrainer`.
68
- - Do not pass a bare `X` array to online or offline `fit()`; pass `(X, Y)` as a
69
- list or tuple.
70
- - Do not omit a reservoir warm-up when delayed or recurrent state must settle
71
- before fitting.
72
- - Do not assume prediction starts from a fresh trajectory. The base, BPTT,
73
- online, and offline prediction paths preserve model state by default.
74
- - Do not import these trainers from another BrainPy implementation. This is the
75
- legacy top-level `brainpy` trainer library.
76
-
77
- ## Routing
78
-
79
- - Open `trainingworkflows.md` for offline ridge, online RLS, BPTT, and custom
80
- gradient-loop execution order.
81
- - Open `loss library.md` when selecting built-in loss functions.
82
- - Open `optimizers.md` when selecting learning-rate schedules or gradient
83
- optimizers for `BPTT` and `BPFF`.
84
- - Open `prebuilt neural network layers.md` when the trainable model requires
85
- legacy `brainpy.dnn` layers.
86
-
87
- ## Sources
88
-
89
- - `brainpy` module API: https://brainpy.readthedocs.io/apis/brainpy.html