brainx-skill 1.0.8 → 1.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -6
- package/manifest.json +3 -2
- package/package.json +2 -1
- package/skills/braincell/SKILL.md +1 -1
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +107 -44
- package/skills/braincell/references/channel-library.md +0 -85
- package/skills/braincell/references/ion-library.md +0 -67
- package/skills/braincell/references/multicompartment/filter-function-library.md +0 -8
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +204 -65
- package/skills/brainmass/SKILL.md +290 -0
- package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
- package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
- package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainmass/references/braintools/cogtask.md +190 -0
- package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
- package/skills/brainmass/references/braintools/metric.md +157 -0
- package/skills/brainmass/references/braintools/optimizer.md +187 -0
- package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
- package/skills/brainmass/references/braintools/surrogate.md +151 -0
- package/skills/brainmass/references/coupling-network-api.md +148 -0
- package/skills/brainmass/references/datasets-api.md +72 -0
- package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
- package/skills/brainmass/references/forward-observation-api.md +131 -0
- package/skills/brainmass/references/horn-task-training.md +199 -0
- package/skills/brainmass/references/modellibrary.md +104 -0
- package/skills/brainmass/references/noiseprocesses.md +121 -0
- package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
- package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
- package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
- package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
- package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
- package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
- package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
- package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
- package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
- package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
- package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
- package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
- package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
- package/skills/brainmass/references/visualization-analysis-api.md +130 -0
- package/skills/brainpy-state/SKILL.md +1 -1
- package/skills/brainx-general-guard/SKILL.md +52 -118
- package/skills/brainx-install/SKILL.md +7 -4
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +0 -303
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +0 -62
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# Braintools cognitive tasks
|
|
2
|
+
|
|
3
|
+
Use this reference to choose a pre-built cognitive paradigm or construct a
|
|
4
|
+
phase-based task that generates time-major training trials. It covers task
|
|
5
|
+
composition, features, value encoders, labels, variable-duration trials, and
|
|
6
|
+
sampling contracts.
|
|
7
|
+
|
|
8
|
+
For BrainMass, use these trials with the direct HORN minibatch workflow in
|
|
9
|
+
`references/horn-task-training.md`; do not send task batches through `Fitter`.
|
|
10
|
+
|
|
11
|
+
## Choose the task path
|
|
12
|
+
|
|
13
|
+
| Decision | Use | Important constraint |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| Standard paradigm | Instantiate a pre-built `Task` subclass | Override parameters, not its phase machinery, unless the paradigm itself changes. |
|
|
16
|
+
| One-off custom task | Construct `Task(phases=..., input_features=..., output_features=..., trial_init=...)` | Put all trial-specific random values in `trial_init`. |
|
|
17
|
+
| Reusable task family | Subclass `Task` and implement `define_features()`, `define_phases()`, and `trial_init()` | Keep feature definitions and phase construction deterministic. |
|
|
18
|
+
| Categorical target | Keep `output_mode='categorical'` and write `outputs={'label': ...}` | Targets have shape `(T,)` per trial. |
|
|
19
|
+
| Continuous or multi-channel target | Set `output_mode='vector'` and write output features by name | Targets have shape `(T, num_outputs)` per trial. |
|
|
20
|
+
| Variable-duration trial | Use `VariableDuration`, `If`, `Switch`, or `While` | Request `return_mask=True` and size computation with `max_trial_duration()`. |
|
|
21
|
+
|
|
22
|
+
## Core task framework
|
|
23
|
+
|
|
24
|
+
`Task` executes a phase tree against one mutable trial-level `Context`, then
|
|
25
|
+
exposes deterministic indexed sampling and vectorized batch sampling.
|
|
26
|
+
|
|
27
|
+
| API | Description |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `Task(phases=None, input_features=None, output_features=None, trial_init=None, name=None, output_mode='categorical', seed=None, num_classes=None, dt=None, **kwargs)` | Use as the dataset-like task owner. It binds the phase tree, feature layout, output mode, seed, and time step. |
|
|
30
|
+
| `Context` | Use as the shared per-trial state. It carries RNG state, input/output buffers, timing, phase history, and values written by `trial_init`. |
|
|
31
|
+
| `Task.sample_trial(index=0, key=None)` | Use when metadata and the uncompiled trial path are needed; it returns `(X, Y, info)`. |
|
|
32
|
+
| `Task.sample(index)` / `task[index]` | Use for one JIT-compiled trial; it returns `(X, Y)`. |
|
|
33
|
+
| `Task.batch_sample(size, time_first=True, return_meta=False, start_index=0, return_mask=False)` | Use for training batches. It folds the trial index into the task seed and returns time-major arrays by default. |
|
|
34
|
+
| `Task.max_trial_duration(ctx=None)` | Use to obtain the static timestep upper bound for variable-length buffers. |
|
|
35
|
+
| `Task.get_trial_meta()` | Override when `batch_sample(..., return_meta=True)` should return task-specific metadata. |
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import brainunit as u
|
|
39
|
+
from braintools.cogtask import (
|
|
40
|
+
Delay,
|
|
41
|
+
Feature,
|
|
42
|
+
Fixation,
|
|
43
|
+
Response,
|
|
44
|
+
Stimulus,
|
|
45
|
+
Task,
|
|
46
|
+
circular,
|
|
47
|
+
concat,
|
|
48
|
+
label,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
fixation = Feature(1, "fixation")
|
|
52
|
+
stimulus = Feature(8, "stimulus")
|
|
53
|
+
choice = Feature(2, "choice")
|
|
54
|
+
|
|
55
|
+
task = Task(
|
|
56
|
+
phases=concat([
|
|
57
|
+
Fixation(100 * u.ms, inputs={"fixation": 1.0}),
|
|
58
|
+
Stimulus(
|
|
59
|
+
500 * u.ms,
|
|
60
|
+
inputs={"stimulus": circular("direction")},
|
|
61
|
+
),
|
|
62
|
+
Delay(500 * u.ms, inputs={"fixation": 1.0}),
|
|
63
|
+
Response(
|
|
64
|
+
100 * u.ms,
|
|
65
|
+
outputs={"label": label("ground_truth")},
|
|
66
|
+
),
|
|
67
|
+
]),
|
|
68
|
+
input_features=fixation + stimulus,
|
|
69
|
+
output_features=fixation + choice,
|
|
70
|
+
trial_init=lambda ctx: ctx.update(
|
|
71
|
+
ground_truth=ctx.rng.choice(2),
|
|
72
|
+
direction=ctx.rng.uniform(0.0, 2.0 * 3.14159),
|
|
73
|
+
),
|
|
74
|
+
seed=0,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
X, Y = task.batch_sample(32)
|
|
78
|
+
assert X.shape[1] == 32
|
|
79
|
+
assert Y.shape[:2] == X.shape[:2]
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**Invariant:** wrap a context-key label with `label("key")`. A bare string is
|
|
83
|
+
treated as a literal value and fails instead of reading from `Context`.
|
|
84
|
+
|
|
85
|
+
## Phases and composition
|
|
86
|
+
|
|
87
|
+
Phases own one trial epoch. Declarative phases fill named feature slices from
|
|
88
|
+
constants or callables with the contract `f(ctx, feature) -> array`.
|
|
89
|
+
|
|
90
|
+
| API | Description |
|
|
91
|
+
|---|---|
|
|
92
|
+
| `Phase` | Subclass only when declarative input/output dictionaries cannot express the epoch. |
|
|
93
|
+
| `DeclarativePhase(duration, inputs=None, outputs=None, noise=None, on_enter=None, on_exit=None, name=None)` | Use for custom named epochs. Input values may be scalar, `(feature.num,)`, or `(duration, feature.num)`. |
|
|
94
|
+
| `Fixation(...)`, `Stimulus(...)`, `Delay(...)`, `Response(...)`, `Cue(...)`, `Blank(...)` | Use these semantic names for ordinary epochs; they share the declarative interface. |
|
|
95
|
+
| `Sample(...)`, `Test(...)`, `Recall(...)`, `Match(...)`, `Comparison(...)` | Use these semantic names for working-memory epochs. |
|
|
96
|
+
| `Sequence(...)` / `a >> b` | Execute phases sequentially. |
|
|
97
|
+
| `Repeat(...)` / `a * n` | Repeat one phase or compound phase a fixed number of times. |
|
|
98
|
+
| `Parallel(...)` / `a \| b` | Execute phase contributions over the same interval. |
|
|
99
|
+
| `concat(phases)` | Build a sequence from a list. |
|
|
100
|
+
| `If(condition, then, else_=None, name='If')` | Select one of two branches from trial state. Packed mode uses `jax.lax.cond`. |
|
|
101
|
+
| `Switch(...)` | Dispatch among several phase branches. The packed selector must return a Python-hashable key, not a tracer. |
|
|
102
|
+
| `While(...)` | Repeat while a condition is true, bounded by `max_iterations`. The packed condition must return a Python `bool`. |
|
|
103
|
+
| `VariableDuration(min_duration, max_duration, ctx_key, ...)` | Reserve `max_duration` but use the per-trial duration in `ctx[ctx_key]`; `min_duration` and `max_duration` must have matching units. |
|
|
104
|
+
|
|
105
|
+
Conditional choices must be derivable from `trial_init` or an earlier phase
|
|
106
|
+
hook. Keep tensor outputs authoritative in compiled code; phase-history metadata
|
|
107
|
+
is best effort when branches are traced.
|
|
108
|
+
|
|
109
|
+
## Features, encoders, and labels
|
|
110
|
+
|
|
111
|
+
`FeatureSet` concatenates fixed-width logical channels into one flat vector and
|
|
112
|
+
assigns each feature a slice through `.i`.
|
|
113
|
+
|
|
114
|
+
| API | Description |
|
|
115
|
+
|---|---|
|
|
116
|
+
| `Feature(num, name=None)` | Define one fixed-width input or output channel. |
|
|
117
|
+
| `FeatureSet` | Collect features and manage their shifted slices. |
|
|
118
|
+
| `CircleFeature` | Define an angular or directional feature with a value range. |
|
|
119
|
+
| `feature_a + feature_b` / `feature_a \| feature_b` | Concatenate copied features without mutating the operands. |
|
|
120
|
+
| `one_hot(...)` | Encode a discrete class as a one-hot feature value. |
|
|
121
|
+
| `identity(...)` | Pass a context value through directly. |
|
|
122
|
+
| `circular(...)` | Encode a direction with cosine tuning. |
|
|
123
|
+
| `von_mises(...)` | Encode a direction with a circular-normal population profile. |
|
|
124
|
+
| `cos_sin(...)` | Encode a direction index as repeated cosine/sine pairs. |
|
|
125
|
+
| `scalar(...)` | Broadcast one scalar across a feature. |
|
|
126
|
+
| `gaussian(...)` | Encode a scalar with a Gaussian bump. |
|
|
127
|
+
| `ctx_value(...)` | Read a dynamic value directly from `Context`. |
|
|
128
|
+
| `label(value)` | Produce a categorical label specification from a literal, callable, or context key. |
|
|
129
|
+
| `match_label(...)` | Produce match/non-match target codes. |
|
|
130
|
+
| `comparison_label(...)` | Produce comparison target codes. |
|
|
131
|
+
|
|
132
|
+
Noise values in a declarative phase map feature names to sigma quantities in
|
|
133
|
+
`ms**0.5`. The runtime samples noise per phase and scales it by
|
|
134
|
+
`1 / sqrt(dt)` so variance is stable when `dt` changes.
|
|
135
|
+
|
|
136
|
+
## Pre-built tasks
|
|
137
|
+
|
|
138
|
+
Use the paradigm whose trial semantics match the experiment.
|
|
139
|
+
|
|
140
|
+
| Family | API | Purpose |
|
|
141
|
+
|---|---|---|
|
|
142
|
+
| Decision making | `PerceptualDecisionMaking(...)` | Perceptual decision making with motion coherence. |
|
|
143
|
+
| Decision making | `PerceptualDecisionMakingDelayResponse(...)` | Perceptual decision making with a response delay. |
|
|
144
|
+
| Decision making | `ContextDecisionMaking(...)` | Context-dependent multimodal decisions. |
|
|
145
|
+
| Decision making | `SingleContextDecisionMaking(...)` | A single-context decision task. |
|
|
146
|
+
| Decision making | `PulseDecisionMaking(...)` | Decisions from discrete evidence pulses. |
|
|
147
|
+
| Working memory | `DelayMatchSample(...)` | Delayed match-to-sample. |
|
|
148
|
+
| Working memory | `DualDelayMatchSample(...)` | Dual delayed match-to-sample. |
|
|
149
|
+
| Working memory | `DelayComparison(...)` | Compare values across a delay. |
|
|
150
|
+
| Working memory | `DelayMatchCategory(...)` | Match stimulus category across a delay. |
|
|
151
|
+
| Working memory | `DelayPairedAssociation(...)` | Delayed paired association. |
|
|
152
|
+
| Working memory | `GoNoGo(...)` | Go/no-go response selection. |
|
|
153
|
+
| Working memory | `IntervalDiscrimination(...)` | Compare or classify time intervals. |
|
|
154
|
+
| Working memory | `PostDecisionWager(...)` | Decision confidence with a wager option. |
|
|
155
|
+
| Working memory | `ReadySetGo(...)` | Timing reproduction from ready/set cues. |
|
|
156
|
+
| Working memory | `DelayDirectionReproduction(...)` | Reproduce a direction after a delay. |
|
|
157
|
+
| Working memory | `ImmediateDirectionReproduction(...)` | Reproduce a direction without a memory delay. |
|
|
158
|
+
| Working memory | `DelayDirectionClassification(...)` | Classify direction after a delay. |
|
|
159
|
+
| Working memory | `ImmediateDirectionClassification(...)` | Classify direction immediately. |
|
|
160
|
+
| Reasoning | `HierarchicalReasoning(...)` | Integrate hierarchical cues or rules. |
|
|
161
|
+
| Reasoning | `ProbabilisticReasoning(...)` | Make decisions under probabilistic evidence. |
|
|
162
|
+
| Motor | `AntiReach(...)` | Produce an anti-reach or anti-saccade response. |
|
|
163
|
+
| Motor | `Reaching1D(...)` | Produce a one-dimensional reaching output. |
|
|
164
|
+
| Motor | `EvidenceAccumulation(...)` | Produce a motor response from accumulated evidence. |
|
|
165
|
+
|
|
166
|
+
## Sampling, masks, and reproducibility
|
|
167
|
+
|
|
168
|
+
For one fixed-length trial, `X` has shape `(T, num_inputs)` and categorical `Y`
|
|
169
|
+
has shape `(T,)`. `batch_sample(B)` returns `(T, B, ...)` unless
|
|
170
|
+
`time_first=False`.
|
|
171
|
+
|
|
172
|
+
For a variable-length task:
|
|
173
|
+
|
|
174
|
+
- `max_trial_duration()` returns a Python `int` suitable for a static buffer
|
|
175
|
+
dimension.
|
|
176
|
+
- `batch_sample(..., return_mask=True)` returns a Boolean mask in the same
|
|
177
|
+
time/batch layout as `X` and `Y`.
|
|
178
|
+
- Trailing buffer positions stay zero and have a false mask.
|
|
179
|
+
- Every traced `step_count(ctx)` must satisfy
|
|
180
|
+
`0 <= step_count(ctx) <= max_steps(ctx)`.
|
|
181
|
+
|
|
182
|
+
A task constructed with `seed=N` derives trial `i` with
|
|
183
|
+
`jax.random.fold_in(PRNGKey(N), i)`. Reusing the same index is deterministic;
|
|
184
|
+
advance `start_index` between batches to avoid overlapping trials. An explicit
|
|
185
|
+
`dt=` overrides the environment; otherwise the task reads
|
|
186
|
+
`brainstate.environ.get_dt()`.
|
|
187
|
+
|
|
188
|
+
## Official source
|
|
189
|
+
|
|
190
|
+
- `https://brainx.chaobrain.com/braintools/apis/cogtask.html`
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Braintools data preprocessing
|
|
2
|
+
|
|
3
|
+
Use this reference to convert continuous values, event streams, or temporal
|
|
4
|
+
features into spike representations and to combine binary spike tensors. Use
|
|
5
|
+
`braintools.cogtask` for phase-structured behavioral trials and
|
|
6
|
+
`braintools.input` for injected-current waveforms.
|
|
7
|
+
|
|
8
|
+
For BrainMass, open this reference only when a custom training workflow must
|
|
9
|
+
encode experimental or task inputs before they enter the model. Ordinary HORN
|
|
10
|
+
feature sequences and `Fitter` targets do not require spike encoding.
|
|
11
|
+
|
|
12
|
+
## Choose an encoder
|
|
13
|
+
|
|
14
|
+
Choose the representation from the information the downstream model must
|
|
15
|
+
preserve.
|
|
16
|
+
|
|
17
|
+
| Encoder family | Use when | Important result |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| Latency | Magnitude should control time to first spike | Larger normalized values spike earlier. |
|
|
20
|
+
| Rate or Poisson | Magnitude should control spike frequency | Returns a time-major spike train whose empirical rate represents the input. |
|
|
21
|
+
| Population | A scalar should activate overlapping receptive fields | Expands each scalar across a neuron population. |
|
|
22
|
+
| Bernoulli | Each time bin should be sampled independently | Converts normalized values into per-bin spike probabilities. |
|
|
23
|
+
| Delta | Only meaningful temporal changes should emit spikes | Detects threshold-crossing differences between successive samples. |
|
|
24
|
+
| Step current | A spiking neuron should receive an analog current level | Returns current values rather than a binary spike code. |
|
|
25
|
+
| Spike count | The window must contain an exact input-dependent count | Places a bounded number of spikes randomly or regularly. |
|
|
26
|
+
| Temporal | A discrete value should select a precise timing pattern | Maps values to synchronized temporal templates. |
|
|
27
|
+
| Rank order | Relative feature ordering matters more than absolute scale | Emits higher-ranked features before lower-ranked features. |
|
|
28
|
+
|
|
29
|
+
## Spike encoders
|
|
30
|
+
|
|
31
|
+
All encoder objects are reusable callables. Pass the input as the first argument
|
|
32
|
+
and the number of encoded timesteps as `n_time=`.
|
|
33
|
+
|
|
34
|
+
| API | Description |
|
|
35
|
+
|---|---|
|
|
36
|
+
| `LatencyEncoder(min_val=None, max_val=None, method='log', threshold=0.01, clip=False, tau=1 * u.ms, normalize=False, first_spk_time=0 * u.ms, epsilon=1e-7)` | Use for time-to-first-spike coding. Normalize inputs when they are not already in `[0, 1]`; larger values produce earlier spikes. |
|
|
37
|
+
| `RateEncoder(gain=100.0, method='linear', min_rate=0.0, max_rate=None, normalize=False, min_val=None, max_val=None)` | Use when firing rate should vary with input intensity. Select the mapping with `method` and constrain rates deliberately. |
|
|
38
|
+
| `PoissonEncoder(time_window=1000.0, normalize=False, max_rate=100.0)` | Use when an input rate should generate Poisson-distributed spikes. Increase the observation window before judging whether empirical counts match the requested rate. |
|
|
39
|
+
| `PopulationEncoder(n_neurons, min_val=0.0, max_val=1.0, sigma=None, max_rate=100.0)` | Use to encode each scalar with overlapping population receptive fields. Set the represented range and population width explicitly. |
|
|
40
|
+
| `BernoulliEncoder(scale=1.0, normalize=True, min_val=None, max_val=None)` | Use for independent Bernoulli sampling at every time step. Ensure the resulting probabilities remain valid after scaling. |
|
|
41
|
+
| `DeltaEncoder(threshold=0.1, positive_only=False, absolute=False, normalize=True)` | Use for change detection in a temporal signal. Configure sign handling so negative changes are either retained, suppressed, or folded by absolute value. |
|
|
42
|
+
| `StepCurrentEncoder(current_scale=10.0, offset=0.0, normalize=True, min_val=None, max_val=None)` | Use to turn features into constant injected-current levels for integrate-and-fire neurons. The result is an analog current code, not a spike tensor. |
|
|
43
|
+
| `SpikeCountEncoder(max_spikes=10, distribution='random', normalize=True)` | Use when input magnitude should determine an exact bounded spike count. Choose random or regular placement with `distribution`. |
|
|
44
|
+
| `TemporalEncoder(n_patterns, pattern_length=10, jitter=0.1)` | Use when values select reusable temporal spike patterns. Set `jitter` according to the timing variability the model should tolerate. |
|
|
45
|
+
| `RankOrderEncoder(use_values=True, normalize=True, invert=False)` | Use when feature rank determines spike order. Use `invert=True` only when low-valued features must spike first. |
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import jax.numpy as jnp
|
|
49
|
+
from braintools import LatencyEncoder
|
|
50
|
+
|
|
51
|
+
values = jnp.array([0.02, 0.5, 1.0])
|
|
52
|
+
encoder = LatencyEncoder(method="linear", normalize=True)
|
|
53
|
+
spikes = encoder(values, n_time=5)
|
|
54
|
+
|
|
55
|
+
assert spikes.shape == (5, 3)
|
|
56
|
+
assert jnp.argmax(spikes[:, 2]) < jnp.argmax(spikes[:, 1])
|
|
57
|
+
assert jnp.argmax(spikes[:, 1]) < jnp.argmax(spikes[:, 0])
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
**Invariant:** treat the leading axis as encoded time. Validate normalization,
|
|
61
|
+
time-window length, and stochastic variability before comparing encoders.
|
|
62
|
+
|
|
63
|
+
## Spike operations
|
|
64
|
+
|
|
65
|
+
Use these element-wise operations only on boolean or binary-compatible spike
|
|
66
|
+
tensors with broadcast-compatible shapes.
|
|
67
|
+
|
|
68
|
+
| API | Description |
|
|
69
|
+
|---|---|
|
|
70
|
+
| `spike_bitwise_or(x, y)` | Return binary OR, implemented as `x + y - x * y`. |
|
|
71
|
+
| `spike_bitwise_and(x, y)` | Return binary AND, implemented as element-wise multiplication. |
|
|
72
|
+
| `spike_bitwise_iand(x, y)` | Return inverse AND, documented as `(NOT x) AND y`. |
|
|
73
|
+
| `spike_bitwise_not(x)` | Invert a binary spike tensor. |
|
|
74
|
+
| `spike_bitwise_xor(x, y)` | Return XOR between two spike tensors. |
|
|
75
|
+
| `spike_bitwise_ixor(x, y)` | Apply the documented inverse-XOR operation. |
|
|
76
|
+
| `spike_bitwise(x, y, op)` | Dispatch by `op` over `'or'`, `'and'`, `'iand'`, `'xor'`, and `'ixor'`. |
|
|
77
|
+
|
|
78
|
+
Do not use these helpers as fuzzy arithmetic on rates or arbitrary continuous
|
|
79
|
+
arrays; their formulas assume binary values.
|
|
80
|
+
|
|
81
|
+
## Official source
|
|
82
|
+
|
|
83
|
+
- `https://brainx.chaobrain.com/braintools/apis/braintools.html`
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# Braintools metrics
|
|
2
|
+
|
|
3
|
+
Use this reference to select supervised losses and neuroscience metrics for
|
|
4
|
+
classification, regression, spike trains, local field potentials, correlation,
|
|
5
|
+
connectivity, and pairwise comparison. Verify input orientation, units, and
|
|
6
|
+
reduction before treating any returned array as a scalar objective.
|
|
7
|
+
|
|
8
|
+
For BrainMass, prefer `brainmass.objectives` for standard `Fitter` time-series,
|
|
9
|
+
FC, and FCD comparisons. Use this reference for HORN supervised losses,
|
|
10
|
+
held-out metrics, or a custom fitting statistic not owned by
|
|
11
|
+
`brainmass.objectives`.
|
|
12
|
+
|
|
13
|
+
## Choose a metric family
|
|
14
|
+
|
|
15
|
+
| Task | Use | Important constraint |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| Independent binary or multilabel classification | Sigmoid binary cross entropy or focal loss | Logits and labels must have broadcast-compatible class structure. |
|
|
18
|
+
| Mutually exclusive classes | Softmax cross entropy | Choose one-hot/probability labels or the integer-label variant explicitly. |
|
|
19
|
+
| Continuous fitting | Squared, absolute, Huber, log-cosh, or cosine losses | Set `reduction` rather than assuming a scalar result. |
|
|
20
|
+
| Spike timing | Victor-Purpura or van Rossum distance | Inputs are spike-time trains, not dense spike matrices. |
|
|
21
|
+
| Population spiking | Firing-rate and synchrony metrics | Dense spike matrices are time-major unless the API says otherwise. |
|
|
22
|
+
| LFP spectrum or coupling | PSD, coherence, PAC, CSD, entropy, or phase coherence | Pass the sample interval as `dt`, not sampling frequency as `fs`. |
|
|
23
|
+
| Functional connectivity | Correlation and connectivity functions | Time series use `(num_time, num_signals)`. |
|
|
24
|
+
|
|
25
|
+
## Classification losses
|
|
26
|
+
|
|
27
|
+
| API | Description |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `sigmoid_binary_cross_entropy(logits, labels)` | Use for independent binary classes; returns element-wise sigmoid cross entropy. |
|
|
30
|
+
| `softmax_cross_entropy(logits, labels)` | Use for mutually exclusive classes represented by one-hot or probability labels. |
|
|
31
|
+
| `softmax_cross_entropy_with_integer_labels(logits, labels)` | Use the more direct integer-index form for mutually exclusive classes. Validate every label yourself. |
|
|
32
|
+
| `hinge_loss(...)` | Use for binary margin classification. |
|
|
33
|
+
| `perceptron_loss(...)` | Use for the binary perceptron objective. |
|
|
34
|
+
| `multiclass_hinge_loss(...)` | Use for a multiclass margin objective. |
|
|
35
|
+
| `multiclass_perceptron_loss(...)` | Use for a multiclass perceptron objective. |
|
|
36
|
+
| `poly_loss_cross_entropy(...)` | Use when the specified method requires PolyLoss cross entropy. |
|
|
37
|
+
| `kl_divergence(...)` | Compare probability distributions. |
|
|
38
|
+
| `kl_divergence_with_log_targets(...)` | Use when predictions and targets are already in log space. |
|
|
39
|
+
| `convex_kl_divergence(...)` | Use when the convex KL variant is required. |
|
|
40
|
+
| `ctc_loss(...)` | Use for sequence alignment without frame-level labels. |
|
|
41
|
+
| `ctc_loss_with_forward_probs(...)` | Use when the CTC forward probabilities are also needed. |
|
|
42
|
+
| `sigmoid_focal_loss(...)` | Use for class imbalance among independent binary targets. |
|
|
43
|
+
| `nll_loss(...)` | Use with log-probability classification outputs. |
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
import jax.numpy as jnp
|
|
47
|
+
from braintools.metric import (
|
|
48
|
+
softmax_cross_entropy_with_integer_labels,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
logits = jnp.array([
|
|
52
|
+
[2.0, 1.0, 0.1],
|
|
53
|
+
[0.5, 2.5, 0.3],
|
|
54
|
+
])
|
|
55
|
+
labels = jnp.array([0, 1])
|
|
56
|
+
|
|
57
|
+
per_example = softmax_cross_entropy_with_integer_labels(logits, labels)
|
|
58
|
+
loss = jnp.mean(per_example)
|
|
59
|
+
assert loss.ndim == 0
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
**Critical exception:** JAX gather silently clamps out-of-range integer labels
|
|
63
|
+
in `softmax_cross_entropy_with_integer_labels`. Validate
|
|
64
|
+
`0 <= labels < logits.shape[-1]`; the function does not raise for invalid
|
|
65
|
+
labels.
|
|
66
|
+
|
|
67
|
+
## Regression and pairwise metrics
|
|
68
|
+
|
|
69
|
+
| API | Description |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `squared_error(predictions, targets=None, axis=None, reduction='none')` | Use for element-wise squared error; choose `mean` or another supported reduction explicitly when a scalar is required. |
|
|
72
|
+
| `absolute_error(...)` | Use for element-wise absolute error. |
|
|
73
|
+
| `l1_loss(...)` | Use for mean absolute-error behavior according to its axis/reduction options. |
|
|
74
|
+
| `l2_loss(...)` | Use for squared L2 loss. |
|
|
75
|
+
| `l2_norm(...)` | Return the L2 norm of prediction error. |
|
|
76
|
+
| `safe_norm(...)` | Use when a differentiable lower bound must prevent an unstable zero norm. |
|
|
77
|
+
| `huber_loss(predictions, targets=None, delta=1.0, axis=None, reduction='none')` | Use for quadratic small residuals and linear large residuals; tune `delta` in target units. |
|
|
78
|
+
| `log_cosh(...)` | Use for a smooth robust regression loss. |
|
|
79
|
+
| `cosine_similarity(...)` | Compare vector direction. |
|
|
80
|
+
| `cosine_distance(...)` | Return the corresponding cosine distance. |
|
|
81
|
+
| `pairwise_cosine_similarity(X, Y, ...)` | Return all pairwise cosine similarities between sample sets. |
|
|
82
|
+
| `pairwise_cosine_distance(X, Y, ...)` | Return all pairwise cosine distances between sample sets. |
|
|
83
|
+
|
|
84
|
+
Do not conflate element-wise loss with final optimization reduction. Preserve
|
|
85
|
+
batch and time axes until the scientific loss definition determines how to
|
|
86
|
+
reduce them.
|
|
87
|
+
|
|
88
|
+
## Correlation and functional connectivity
|
|
89
|
+
|
|
90
|
+
| API | Description |
|
|
91
|
+
|---|---|
|
|
92
|
+
| `cross_correlation(spikes, bin, dt)` | Calculate a cross-correlation synchrony index from a time-major spike matrix. |
|
|
93
|
+
| `voltage_fluctuation(voltages)` | Estimate synchrony from population voltage variance. |
|
|
94
|
+
| `matrix_correlation(a, b)` | Correlate upper-triangular entries of two square matrices. |
|
|
95
|
+
| `weighted_correlation(x, y, weights)` | Compute weighted Pearson correlation for two one-dimensional series. |
|
|
96
|
+
| `functional_connectivity(activities)` | Return the pairwise Pearson correlation matrix for `(num_time, num_signals)` data; NaNs are replaced with zero. |
|
|
97
|
+
| `functional_connectivity_dynamics(activities, window_size, step_size)` | Compare sliding-window connectivity matrices to produce functional-connectivity dynamics. |
|
|
98
|
+
|
|
99
|
+
## Spike-train metrics
|
|
100
|
+
|
|
101
|
+
| API | Description |
|
|
102
|
+
|---|---|
|
|
103
|
+
| `raster_plot(spikes, times)` | Extract neuron indices and spike times from a dense spike matrix; this is a metric/data helper, not the visualization API. |
|
|
104
|
+
| `firing_rate(spikes, width, dt=None)` | Average across neurons and smooth population rate with a rectangular window of physical width. |
|
|
105
|
+
| `victor_purpura_distance(spike_times_1, spike_times_2, cost_factor=1.0)` | Measure edit cost from insertions, deletions, and temporal shifts. |
|
|
106
|
+
| `van_rossum_distance(spike_times_1, spike_times_2, tau=...)` | Compare exponentially filtered spike trains. |
|
|
107
|
+
| `spike_train_synchrony(spikes, window_size, dt=None)` | Compute SPIKE-style synchronization on a population matrix. |
|
|
108
|
+
| `burst_synchrony_index(spikes, dt=None, ...)` | Measure co-occurring burst events. |
|
|
109
|
+
| `phase_locking_value(spikes, reference_freq, dt=None, ...)` | Measure spike phase locking to a reference oscillation. |
|
|
110
|
+
| `spike_time_tiling_coefficient(spikes, dt=None, tau=...)` | Compute STTC within a temporal tolerance. |
|
|
111
|
+
| `correlation_index(spikes, window_size, dt=None)` | Compute a windowed spike-train correlation index. |
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
import brainunit as u
|
|
115
|
+
from braintools.metric import firing_rate, spike_train_synchrony
|
|
116
|
+
|
|
117
|
+
# Shape: (num_time, num_neurons)
|
|
118
|
+
rate = firing_rate(spikes, width=10 * u.ms, dt=1 * u.ms)
|
|
119
|
+
synchrony = spike_train_synchrony(
|
|
120
|
+
spikes,
|
|
121
|
+
window_size=5 * u.ms,
|
|
122
|
+
dt=1 * u.ms,
|
|
123
|
+
)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Keep dense spike matrices and lists of spike times distinct. Distance metrics
|
|
127
|
+
consume event times; population rate and synchrony metrics consume matrices.
|
|
128
|
+
|
|
129
|
+
## Local field potential analysis
|
|
130
|
+
|
|
131
|
+
| API | Description |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `unitary_LFP(times, spikes, neuron_type, seed=None, ...)` | Construct unitary LFP contributions from spikes; use the documented `'exc'` or `'inh'` neuron type. |
|
|
134
|
+
| `power_spectral_density(lfp, dt, nperseg=None, noverlap=None, freq_range=None)` | Return one-sided Welch frequencies and PSD. |
|
|
135
|
+
| `coherence_analysis(signal1, signal2, dt, ...)` | Return frequency-resolved magnitude-squared coherence. |
|
|
136
|
+
| `phase_amplitude_coupling(lfp, dt, phase_freq_range, amplitude_freq_range, ...)` | Return Tort modulation index plus phase-bin details. |
|
|
137
|
+
| `theta_gamma_coupling(lfp, dt, ...)` | Return theta-gamma coupling using standard bands. |
|
|
138
|
+
| `current_source_density(lfp, electrode_spacing, axis=0, ...)` | Estimate laminar CSD along the electrode axis. |
|
|
139
|
+
| `spectral_entropy(lfp, dt, ...)` | Return normalized spectral entropy. |
|
|
140
|
+
| `lfp_phase_coherence(lfp, dt, freq_band, ...)` | Compute pairwise phase coherence across channels. |
|
|
141
|
+
|
|
142
|
+
`power_spectral_density(..., freq_range=...)` uses boolean-mask indexing and
|
|
143
|
+
therefore has a data-dependent output length; that path is not JIT-compatible.
|
|
144
|
+
Compute the full spectrum inside JIT and filter outside when compilation is
|
|
145
|
+
required.
|
|
146
|
+
|
|
147
|
+
## Structured, ranking, and smoothing losses
|
|
148
|
+
|
|
149
|
+
| API | Description |
|
|
150
|
+
|---|---|
|
|
151
|
+
| `make_fenchel_young_loss(max_fun)` | Build a Fenchel-Young loss. `max_fun` must map one score vector to a scalar because it is vectorized with signature `(n)->()`. |
|
|
152
|
+
| `ranking_softmax_loss(scores, labels, ...)` | Use for list-wise learning-to-rank objectives. |
|
|
153
|
+
| `smooth_labels(labels, alpha=...)` | Apply label smoothing to one-hot targets. |
|
|
154
|
+
|
|
155
|
+
## Official source
|
|
156
|
+
|
|
157
|
+
- `https://brainx.chaobrain.com/braintools/apis/metric.html`
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# Braintools optimizer selection
|
|
2
|
+
|
|
3
|
+
Use this reference after the BrainMass fitting or HORN loss, rollout, State
|
|
4
|
+
reset, and gradient target are correct. Select an optimizer interface and
|
|
5
|
+
learning-rate policy without changing the simulation graph or confusing
|
|
6
|
+
gradient-step optimizers with standalone search wrappers.
|
|
7
|
+
|
|
8
|
+
## Choose a gradient optimizer
|
|
9
|
+
|
|
10
|
+
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)`.
|
|
11
|
+
|
|
12
|
+
### General minibatch optimizers
|
|
13
|
+
|
|
14
|
+
Use these optimizers for ordinary repeated gradient steps; establish `Adam` or `SGD` as the baseline before selecting a specialized update rule.
|
|
15
|
+
|
|
16
|
+
| API | Description |
|
|
17
|
+
|---|---|
|
|
18
|
+
| `SGD(...)` | Use for stochastic gradient descent with optional momentum and weight decay when a simple non-adaptive baseline is required. |
|
|
19
|
+
| `Momentum(...)` | Use for momentum updates without selecting the broader `SGD` interface. |
|
|
20
|
+
| `MomentumNesterov(...)` | Use when the optimization method requires Nesterov-accelerated momentum. |
|
|
21
|
+
| `Adam(...)` | Use as the canonical adaptive default after validating finite, nonzero gradients. |
|
|
22
|
+
| `AdamW(...)` | Use when the training policy requires decoupled weight decay; set `weight_decay` deliberately. |
|
|
23
|
+
| `Adagrad(...)` | Use when per-parameter learning rates should accumulate squared-gradient history. |
|
|
24
|
+
| `Adadelta(...)` | Use when the Adadelta extension of Adagrad is explicitly required. |
|
|
25
|
+
| `RMSprop(...)` | Use when the method should scale updates by a moving average of squared gradients. |
|
|
26
|
+
| `Adamax(...)` | Use when the infinity-norm Adam variant is required. |
|
|
27
|
+
| `Nadam(...)` | Use when combining Adam with Nesterov acceleration. |
|
|
28
|
+
| `RAdam(...)` | Use when rectifying adaptive learning-rate variance addresses observed early-step instability. |
|
|
29
|
+
| `Yogi(...)` | Use when the Yogi additive second-moment update is part of the intended method. |
|
|
30
|
+
| `Rprop(...)` | Use when resilient backpropagation should adapt per-parameter step sizes from gradient signs. |
|
|
31
|
+
| `AdaBelief(...)` | Use when adapting step size from the optimizer's belief in the gradient direction is required. |
|
|
32
|
+
| `Lion(...)` | Use when a sign-momentum optimizer is chosen to reduce optimizer-State memory. |
|
|
33
|
+
| `Novograd(...)` | Use when layer-wise gradient normalization with momentum is required. |
|
|
34
|
+
| `Fromage(...)` | Use only when the Free-scale Optimal Method for Adaptive Gradient method is explicitly selected. |
|
|
35
|
+
|
|
36
|
+
### Large-scale and memory-efficient optimizers
|
|
37
|
+
|
|
38
|
+
Use these optimizers only when large-batch scaling or optimizer-State memory is an explicit constraint.
|
|
39
|
+
|
|
40
|
+
| API | Description |
|
|
41
|
+
|---|---|
|
|
42
|
+
| `Lamb(...)` | Use for layer-wise adaptive moments in an explicitly large-batch training regime. |
|
|
43
|
+
| `Lars(...)` | Use for layer-wise adaptive rate scaling in an explicitly large-batch training regime. |
|
|
44
|
+
| `Adafactor(...)` | Use when factorized second-moment estimates are needed to reduce optimizer-State memory. |
|
|
45
|
+
| `SM3(...)` | Use for memory-efficient adaptive updates in a large or sparse model. |
|
|
46
|
+
|
|
47
|
+
### Wrapper and full-batch optimizers
|
|
48
|
+
|
|
49
|
+
Use these variants when the update requires an optimizer composition or a smooth full-batch objective rather than an ordinary standalone minibatch rule.
|
|
50
|
+
|
|
51
|
+
| API | Description |
|
|
52
|
+
|---|---|
|
|
53
|
+
| `Lookahead(...)` | Use when wrapping an inner Optax gradient transformation with periodic slow-weight interpolation. |
|
|
54
|
+
| `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. |
|
|
55
|
+
|
|
56
|
+
### Custom Optax transformations
|
|
57
|
+
|
|
58
|
+
Use the bridge when no named Braintools optimizer expresses the required Optax transformation.
|
|
59
|
+
|
|
60
|
+
| API | Description |
|
|
61
|
+
|---|---|
|
|
62
|
+
| `OptaxOptimizer(tx=..., lr=...)` | Use when supplying a custom Optax transformation while preserving Braintools parameter registration, optimizer State, gradient clipping, weight decay, and scheduler integration. |
|
|
63
|
+
|
|
64
|
+
Do not switch optimizer, scheduler, surrogate, and temporal reduction simultaneously. Establish an `Adam` loss and gradient baseline, then vary one optimization decision.
|
|
65
|
+
|
|
66
|
+
## Gradient-step lifecycle
|
|
67
|
+
|
|
68
|
+
Every ordinary gradient optimizer owns persistent optimizer State and mutates exactly the registered trainable State:
|
|
69
|
+
|
|
70
|
+
| API | Use and result |
|
|
71
|
+
|---|---|
|
|
72
|
+
| `model.states(brainstate.ParamState)` | Select trainable model State; dynamical voltage, conductance, spike, and delay State remain outside the optimizer. |
|
|
73
|
+
| `optimizer.register_trainable_weights(params)` | Register the parameter tree and initialize optimizer State. |
|
|
74
|
+
| `brainstate.transform.grad(loss_fn, params, return_value=True)` | Produce a gradient tree matching `params` and the scalar loss. |
|
|
75
|
+
| `optimizer.update(grads)` | Apply one update to the registered parameters. |
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
params = net.states(brainstate.ParamState)
|
|
79
|
+
optimizer = braintools.optim.Adam(lr=3e-3)
|
|
80
|
+
optimizer.register_trainable_weights(params)
|
|
81
|
+
|
|
82
|
+
@brainstate.transform.jit
|
|
83
|
+
def train_step():
|
|
84
|
+
brainstate.nn.init_all_states(net, batch_size=batch_size)
|
|
85
|
+
grads, loss = brainstate.transform.grad(
|
|
86
|
+
loss_fn,
|
|
87
|
+
params,
|
|
88
|
+
return_value=True,
|
|
89
|
+
)()
|
|
90
|
+
optimizer.update(grads)
|
|
91
|
+
return loss
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Register the same tree passed to `grad`. Do not rebuild or re-register that tree inside every compiled step.
|
|
95
|
+
|
|
96
|
+
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.
|
|
97
|
+
|
|
98
|
+
## Learning-rate schedulers
|
|
99
|
+
|
|
100
|
+
Pass an `LRScheduler` instance as `lr=` to any gradient-based `OptaxOptimizer`. A float is treated as a constant learning rate.
|
|
101
|
+
|
|
102
|
+
| API | Description |
|
|
103
|
+
|---|---|
|
|
104
|
+
| `LRScheduler(...)` | Subclass when implementing a custom schedule; it defines attachment, stepping, current-rate access, and State serialization. |
|
|
105
|
+
| `StepLR(...)` | Use for staircase decay by `gamma` every `step_size` scheduler steps. |
|
|
106
|
+
| `MultiStepLR(...)` | Use for multiplicative decay at explicitly chosen milestones. |
|
|
107
|
+
| `ConstantLR(...)` | Use to multiply the base learning rate by a constant factor for a configured interval. |
|
|
108
|
+
| `LinearLR(...)` | Use to scale the learning rate linearly between configured factors. |
|
|
109
|
+
| `ExponentialLR(...)` | Use for smooth multiplicative decay by `gamma` at every scheduler step. |
|
|
110
|
+
| `PolynomialLR(...)` | Use when the learning rate must follow a polynomial decay. |
|
|
111
|
+
| `ExponentialDecayLR(...)` | Use for exponential decay with explicit step-based control. |
|
|
112
|
+
| `CosineAnnealingLR(...)` | Use for smooth cosine annealing from the base rate toward `eta_min`; match `T_max` to the scheduler-call cadence. |
|
|
113
|
+
| `CosineAnnealingWarmRestarts(...)` | Use for cosine annealing that periodically restarts its cycle. |
|
|
114
|
+
| `WarmupCosineSchedule(...)` | Use when one schedule must warm up first and then anneal by cosine. |
|
|
115
|
+
| `CyclicLR(...)` | Use to oscillate the learning rate between configured bounds. |
|
|
116
|
+
| `OneCycleLR(...)` | Use for a single super-convergence cycle; derive `total_steps` from the actual number of scheduler calls. |
|
|
117
|
+
| `ReduceLROnPlateau(...)` | Use when a validation metric should trigger decay after stalled improvement; call `step(metric=...)`. |
|
|
118
|
+
| `WarmupScheduler(...)` | Use to increase the learning rate linearly during a warmup phase. |
|
|
119
|
+
| `PiecewiseConstantSchedule(...)` | Use for step-wise transitions among explicitly configured constant rates. |
|
|
120
|
+
| `ChainedScheduler(...)` | Use to apply multiple scheduler transformations together. |
|
|
121
|
+
| `SequentialLR(...)` | Use to switch among schedulers at configured epoch milestones. |
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
scheduler = braintools.optim.StepLR(
|
|
125
|
+
base_lr=3e-3,
|
|
126
|
+
step_size=20,
|
|
127
|
+
gamma=0.5,
|
|
128
|
+
)
|
|
129
|
+
optimizer = braintools.optim.Adam(lr=scheduler)
|
|
130
|
+
optimizer.register_trainable_weights(params)
|
|
131
|
+
|
|
132
|
+
# After each epoch, outside the neural time-step transform:
|
|
133
|
+
optimizer.lr.step()
|
|
134
|
+
current_lr = optimizer.lr.get_last_lr()
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
For validation-driven scheduling, use the different call contract:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
scheduler = braintools.optim.ReduceLROnPlateau(
|
|
141
|
+
base_lr=3e-3,
|
|
142
|
+
mode="min",
|
|
143
|
+
factor=0.5,
|
|
144
|
+
patience=5,
|
|
145
|
+
)
|
|
146
|
+
optimizer = braintools.optim.Adam(lr=scheduler)
|
|
147
|
+
|
|
148
|
+
# After validation:
|
|
149
|
+
scheduler.step(metric=float(validation_loss))
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Count scheduler calls explicitly. Stepping an epoch-configured schedule once per batch silently changes its effective timescale.
|
|
153
|
+
|
|
154
|
+
## Standalone and forward-mode optimizers
|
|
155
|
+
|
|
156
|
+
These interfaces own more of the optimization operation than `update(grads)`:
|
|
157
|
+
|
|
158
|
+
| API | Description |
|
|
159
|
+
|---|---|
|
|
160
|
+
| `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. |
|
|
161
|
+
| `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. |
|
|
162
|
+
| `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. |
|
|
163
|
+
| `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. |
|
|
164
|
+
|
|
165
|
+
`ScipyOptimizer` and `NevergradOptimizer` deliberately raise for the State-based register/update methods. Do not place either inside the canonical compiled minibatch train step.
|
|
166
|
+
|
|
167
|
+
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.
|
|
168
|
+
|
|
169
|
+
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.
|
|
170
|
+
|
|
171
|
+
## Routing and official sources
|
|
172
|
+
|
|
173
|
+
Open `references/braintools/metric.md` for loss and reduction choice,
|
|
174
|
+
`references/batch-transform-acceleration.md` for long-rollout control flow and
|
|
175
|
+
checkpointing, and `references/braintools/surrogate.md` only when a custom
|
|
176
|
+
BrainMass path contains a hard threshold or spike operator. Use
|
|
177
|
+
`references/horn-task-training.md` for a complete HORN minibatch workflow or
|
|
178
|
+
`references/fitting-with-objectives-api.md` for `Fitter`.
|
|
179
|
+
|
|
180
|
+
Official sources:
|
|
181
|
+
|
|
182
|
+
- `https://brainx.chaobrain.com/braintools/apis/optim.html`
|
|
183
|
+
- `https://brainx.chaobrain.com/braintools/optim/01_nevergrad_optimizer.html`
|
|
184
|
+
- `https://brainx.chaobrain.com/braintools/optim/02_scipy_optimizer.html`
|
|
185
|
+
- `https://brainx.chaobrain.com/braintools/optim/03_optax_getting_started.html`
|
|
186
|
+
- `https://brainx.chaobrain.com/braintools/optim/04_learning_rate_scheduling.html`
|
|
187
|
+
- `https://brainx.chaobrain.com/braintools/optim/05_advanced_optimizers.html`
|