braindecode 2.1.0.dev181714115__py3-none-any.whl → 2.1.0.dev182154342__py3-none-any.whl
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.
- braindecode/augmentation/functional.py +1 -1
- braindecode/augmentation/transforms.py +1 -1
- braindecode/datasets/base.py +17 -12
- braindecode/datasets/bids/hub.py +13 -1
- braindecode/datautil/serialization.py +7 -0
- braindecode/functional/__init__.py +10 -0
- braindecode/functional/attention.py +4 -14
- braindecode/functional/channels.py +282 -0
- braindecode/models/__init__.py +6 -0
- braindecode/models/attn_sleep.py +40 -6
- braindecode/models/base.py +50 -13
- braindecode/models/biot.py +10 -8
- braindecode/models/brainmodule.py +1 -13
- braindecode/models/codebrain.py +14 -19
- braindecode/models/eegpt.py +1 -1
- braindecode/models/eegtcnet.py +31 -4
- braindecode/models/emg2qwerty.py +8 -2
- braindecode/models/fnirs4d.py +761 -0
- braindecode/models/fnirs_cnn1d.py +339 -0
- braindecode/models/fnirs_t.py +785 -0
- braindecode/models/fnirsnet.py +268 -86
- braindecode/models/geonirs.py +1545 -0
- braindecode/models/guetschel2026.py +1 -1
- braindecode/models/jung_mae.py +596 -0
- braindecode/models/luna.py +43 -33
- braindecode/models/mapa.py +4 -5
- braindecode/models/model.html.jinja +24 -9
- braindecode/models/msvtnet.py +1 -2
- braindecode/models/mtrenirs.py +1053 -0
- braindecode/models/patchedtransformer.py +26 -15
- braindecode/models/reve.py +1 -4
- braindecode/models/signal_jepa.py +5 -6
- braindecode/models/sleepfm.py +98 -23
- braindecode/models/summary.csv +7 -0
- braindecode/models/util.py +139 -1
- braindecode/models/zuna.py +11 -24
- braindecode/modules/attention.py +9 -8
- braindecode/modules/channels.py +170 -30
- braindecode/modules/layers.py +2 -8
- braindecode/preprocessing/preprocess.py +4 -0
- braindecode/preprocessing/windowers.py +14 -6
- braindecode/util.py +21 -28
- braindecode/version.py +1 -1
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/METADATA +25 -9
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/RECORD +49 -42
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/NOTICE.txt +6 -0
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/WHEEL +0 -0
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/LICENSE.txt +0 -0
- {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,1053 @@
|
|
|
1
|
+
# Authors: Bruno Aristimunha <b.aristimunha@gmail.com>
|
|
2
|
+
#
|
|
3
|
+
# License: MIT
|
|
4
|
+
#
|
|
5
|
+
# Adapted from https://github.com/microsoft/MtReNIRS (MIT).
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from collections import OrderedDict
|
|
11
|
+
from typing import List, Literal, Optional
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import torch
|
|
15
|
+
import torch.nn as nn
|
|
16
|
+
from einops.layers.torch import Rearrange
|
|
17
|
+
|
|
18
|
+
from braindecode.functional import (
|
|
19
|
+
apply_rotary,
|
|
20
|
+
check_ch_mask,
|
|
21
|
+
pad_or_crop_to_patches,
|
|
22
|
+
patch_count,
|
|
23
|
+
rotary_angles,
|
|
24
|
+
rotary_frequencies,
|
|
25
|
+
scaled_dot_product_attention,
|
|
26
|
+
)
|
|
27
|
+
from braindecode.functional.patches import _check_on_non_divisible
|
|
28
|
+
from braindecode.models.base import EEGModuleMixin
|
|
29
|
+
from braindecode.models.util import (
|
|
30
|
+
extract_channel_locations_from_chs_info,
|
|
31
|
+
fnirs_chromophores_from_chs_info,
|
|
32
|
+
)
|
|
33
|
+
from braindecode.modules import FeedForwardBlock
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class MtReNIRS(EEGModuleMixin, nn.Module, license="mit"):
|
|
37
|
+
r"""MtReNIRS from Chae et al. (2026).
|
|
38
|
+
|
|
39
|
+
:bdg-info:`Attention/Transformer` :bdg-dark-line:`Channel` :bdg-danger:`Foundation Model`
|
|
40
|
+
|
|
41
|
+
.. figure:: https://braindecode.org/dev/_static/model/mtrenirs.png
|
|
42
|
+
:align: center
|
|
43
|
+
:alt: MtReNIRS preprocessing, montage harmonization, token embedding and pretraining
|
|
44
|
+
|
|
45
|
+
Fig. 2 of Chae et al. (2026), arXiv:2610.36159 (`CC BY 4.0
|
|
46
|
+
<https://creativecommons.org/licenses/by/4.0/>`_). This class is the
|
|
47
|
+
encoder of panels (C)-(D) with a linear head.
|
|
48
|
+
|
|
49
|
+
MtReNIRS (Montage-aligned transferable Representations for fNIRS) is the
|
|
50
|
+
fNIRS foundation model of Chae et al. :footcite:`microsoft2026mtrenirs`:
|
|
51
|
+
"a montage-aware masked autoencoder, pretrained on 12 public fNIRS
|
|
52
|
+
datasets spanning 268 subjects and 567 recording hours". It "jointly
|
|
53
|
+
encodes the slow hemodynamic nature of fNIRS, chromophore identity and
|
|
54
|
+
cortical location by mapping heterogeneous montages onto a shared
|
|
55
|
+
anatomical reference". A token is one 10-s window of one chromophore
|
|
56
|
+
channel, tagged with the canonical 10-05 position
|
|
57
|
+
:footcite:`oostenveld2001five` of its source-detector (S-D) pair and with
|
|
58
|
+
its chromophore; six Transformer blocks mix all tokens, with the window
|
|
59
|
+
index as their only time code.
|
|
60
|
+
|
|
61
|
+
.. rubric:: Architectural Overview
|
|
62
|
+
|
|
63
|
+
With ``W = n_times // window_samples`` windows, ``C = n_chans`` HbO/HbR
|
|
64
|
+
rows and ``D = embed_dim``:
|
|
65
|
+
|
|
66
|
+
1. **Windowing**: ``(batch, C, n_times)`` is cut into non-overlapping
|
|
67
|
+
10-s windows :math:`x_{c,t}`, ``(batch, W, C, window_samples)``; a
|
|
68
|
+
short last window is cropped (``on_non_divisible``).
|
|
69
|
+
2. **Token embedding**: each window becomes a token :math:`z_{c,t}`, the
|
|
70
|
+
sum of its signal embedding and of the spatio-chromophore embedding of
|
|
71
|
+
its channel, ``(batch, W * C, D)``.
|
|
72
|
+
3. **Transformer encoder**: ``depth`` pre-norm blocks attend over all
|
|
73
|
+
channels and windows jointly, then a final LayerNorm; invalid tokens
|
|
74
|
+
are never attended and are zeroed, ``(batch, W, C, D)``.
|
|
75
|
+
4. **Readout and head**: ``pool`` reduces the tokens to
|
|
76
|
+
``(batch, feature_dim)`` and ``final_layer`` gives
|
|
77
|
+
``(batch, n_outputs)``.
|
|
78
|
+
|
|
79
|
+
.. rubric:: Macro Components
|
|
80
|
+
|
|
81
|
+
- **Token embedding** (``embed``, ``_TokenEmbedding``).
|
|
82
|
+
|
|
83
|
+
- **Operations.** Signal embedding ``embed.signal.proj``,
|
|
84
|
+
``nn.Linear(100, 128)``: "Each 10-s signal segment :math:`x_{c,t} \in
|
|
85
|
+
\mathbb{R}^{100}` was projected by a linear layer to a 128-dimensional
|
|
86
|
+
signal embedding". Spatio-chromophore embedding ``embed.spatial.mlp``,
|
|
87
|
+
``nn.Linear(48, 128)``, GELU, ``nn.Linear(128, 128)``, on six bands of
|
|
88
|
+
Fourier features :footcite:`tancik2020fourier` of :math:`u_c =
|
|
89
|
+
[q_c^\top, b_c]^\top \in \mathbb{R}^4`, the canonical coordinate
|
|
90
|
+
:math:`q_c` of the S-D pair and the chromophore :math:`b_c` (0 HbO,
|
|
91
|
+
1 HbR):
|
|
92
|
+
|
|
93
|
+
.. math::
|
|
94
|
+
|
|
95
|
+
\phi(u_c) = \left[\sin(2^k \pi u_{c,j}),\, \cos(2^k \pi u_{c,j})
|
|
96
|
+
\right]_{j = 1, \dots, 4}^{k = 0, \dots, 5} \in \mathbb{R}^{48},
|
|
97
|
+
\qquad z_{c,t} = W_x x_{c,t} + b_x + \mathrm{MLP}(\phi(u_c)).
|
|
98
|
+
|
|
99
|
+
- *Role.* "This embedding lets the encoder distinguish region-specific
|
|
100
|
+
activity while modeling coupled, often opposing HbO/HbR dynamics."
|
|
101
|
+
There is no CLS token and no per-channel table.
|
|
102
|
+
|
|
103
|
+
- **Canonical coordinates** (``default_coordinates``, or the
|
|
104
|
+
``coordinates`` argument of :meth:`forward`).
|
|
105
|
+
|
|
106
|
+
- **Operations.** :math:`\hat{q}_c = (q_c - \mu) / \sigma` with
|
|
107
|
+
:math:`\mu` = ``coordinate_center`` and :math:`\sigma` =
|
|
108
|
+
``coordinate_scale``: "We normalized all available canonical
|
|
109
|
+
coordinates with one center and RMS scale computed from the
|
|
110
|
+
pretraining corpus."
|
|
111
|
+
- *Role.* Before the model, the paper maps every montage to the 10-05
|
|
112
|
+
system (Sec. III-B, Eq. 1) and uses "the fixed coordinate
|
|
113
|
+
:math:`q_{s_i}` of assigned slot :math:`s_i`". That alignment and slot
|
|
114
|
+
assignment (the authors' ``mtrenirs.alignment.align``) stay outside
|
|
115
|
+
this class, which reads :math:`q_c` from ``loc[:3]`` of ``chs_info``.
|
|
116
|
+
|
|
117
|
+
- **Transformer encoder** (``encoder.blocks``, ``encoder.norm``;
|
|
118
|
+
``_TransformerBlock``, ``_RotarySelfAttention``).
|
|
119
|
+
|
|
120
|
+
- **Operations.** "The encoder contained six pre-layer-normalized
|
|
121
|
+
Transformer blocks with a 128-dimensional state, four attention heads,
|
|
122
|
+
a 512-dimensional MLP, and 0.1 dropout. Per-head layer normalization
|
|
123
|
+
stabilized queries and keys." With :math:`y` the normalized input, a
|
|
124
|
+
block computes
|
|
125
|
+
|
|
126
|
+
.. math::
|
|
127
|
+
|
|
128
|
+
h = z + \mathrm{Drop}\big(\mathrm{Attn}(\mathrm{LN}_1(z))\big),
|
|
129
|
+
\qquad z' = h + \mathrm{MLP}(\mathrm{LN}_2(h)),
|
|
130
|
+
|
|
131
|
+
.. math::
|
|
132
|
+
|
|
133
|
+
\mathrm{Attn}_n = \sum_m \mathrm{softmax}_m\!\left(
|
|
134
|
+
\frac{(\mathcal{R}_{t_n} \mathrm{LN}_q(W_q y_n))^\top
|
|
135
|
+
\mathcal{R}_{t_m} \mathrm{LN}_k(W_k y_m)}{\sqrt{d_h}} + M_m
|
|
136
|
+
\right) W_v y_m,
|
|
137
|
+
|
|
138
|
+
where :math:`\mathcal{R}_t` is the rotary rotation
|
|
139
|
+
:footcite:`su2024roformer` of the window index :math:`t` with
|
|
140
|
+
frequencies :math:`\beta^{-2j/d_h}`, :math:`\beta` = ``rope_base``,
|
|
141
|
+
and :math:`M_m = 0` for a valid key and :math:`-\infty` otherwise.
|
|
142
|
+
- *Role.* "To preserve cross-window order without conflating time with
|
|
143
|
+
spatial identity, rotary position encoding (RoPE) with base 500
|
|
144
|
+
encoded the temporal-window index. All S-D pairs from the same window
|
|
145
|
+
shared that index; spatial identity entered only through the canonical
|
|
146
|
+
coordinate embedding."
|
|
147
|
+
|
|
148
|
+
- **Readout and head** (``pool``, ``final_layer``).
|
|
149
|
+
|
|
150
|
+
- **Operations.** ``"temporal_mean"`` (default): mean over the valid
|
|
151
|
+
windows, one ``embed_dim`` vector per channel, concatenated;
|
|
152
|
+
``"channel_temporal_mean"``: mean over the valid windows and
|
|
153
|
+
channels; ``"flatten"``: all tokens. Then ``nn.Linear``.
|
|
154
|
+
- *Role.* The paper's linear probe on frozen features (Sec. III-D): "we
|
|
155
|
+
temporally averaged encoder outputs before classification so that the
|
|
156
|
+
feature dimensionality remained fixed."
|
|
157
|
+
|
|
158
|
+
.. rubric:: Temporal, Spatial, and Spectral Encoding
|
|
159
|
+
|
|
160
|
+
- *Temporal:* within a window, the 100 input weights of the signal
|
|
161
|
+
projection (no convolution); across windows, RoPE of the window index
|
|
162
|
+
only. The weights expect 10 Hz and 10-s windows.
|
|
163
|
+
- *Spatial:* every row of ``x`` is one chromophore channel, in any order
|
|
164
|
+
and number; the HbO and HbR rows of one S-D pair share :math:`q_c`.
|
|
165
|
+
Rows without a location (NaN or all-zero ``loc``) are left out of the
|
|
166
|
+
attention and the pooling.
|
|
167
|
+
- *Chromophore:* read from MNE's ``coil_type`` or the ``" hbo"`` /
|
|
168
|
+
``" hbr"`` name suffix; any other channel (e.g. HbT) raises.
|
|
169
|
+
|
|
170
|
+
.. rubric:: Additional Mechanisms
|
|
171
|
+
|
|
172
|
+
- **Masked pretraining** (Fig. 2D, Sec. III-C; not part of this class):
|
|
173
|
+
"we randomly masked 25% of valid tokens and passed only visible tokens
|
|
174
|
+
to the encoder. A two-block lightweight Transformer decoder
|
|
175
|
+
reconstructed each masked 10-s waveform", with a mean squared error
|
|
176
|
+
over the masked tokens (Eq. 3).
|
|
177
|
+
|
|
178
|
+
.. rubric:: Pretrained Weights
|
|
179
|
+
|
|
180
|
+
``mtrenirs_10s.pt`` of `microsoft/MtReNIRS
|
|
181
|
+
<https://github.com/microsoft/MtReNIRS>`_ (commit 16c3082, MIT), the
|
|
182
|
+
paper's epoch-95 checkpoint of the 10-s model, is mirrored unchanged at
|
|
183
|
+
`braindecode/mtrenirs-pretrained
|
|
184
|
+
<https://huggingface.co/braindecode/mtrenirs-pretrained>`_. It holds the
|
|
185
|
+
inference encoder only. :meth:`load_state_dict` takes this payload
|
|
186
|
+
strictly with the authors' key names; ``final_layer`` keeps its
|
|
187
|
+
initialization. It expects 10 Hz HbO/HbR, preprocessed as in Notes, in
|
|
188
|
+
100-sample windows, with positions on 10-05 slots:
|
|
189
|
+
|
|
190
|
+
.. code-block:: python
|
|
191
|
+
|
|
192
|
+
path = hf_hub_download(
|
|
193
|
+
"braindecode/mtrenirs-pretrained",
|
|
194
|
+
"mtrenirs_10s.pt",
|
|
195
|
+
revision="bbc68ce5e00a4515081d900227fc06d111858e75",
|
|
196
|
+
)
|
|
197
|
+
payload = torch.load(path, map_location="cpu", weights_only=True)
|
|
198
|
+
# raw: MNE Raw with the 10-05 slot positions in loc[:3]
|
|
199
|
+
model = MtReNIRS(chs_info=raw.info["chs"], n_outputs=3, n_times=100, sfreq=10.0)
|
|
200
|
+
model.load_state_dict(payload)
|
|
201
|
+
|
|
202
|
+
.. versionadded:: 2.1
|
|
203
|
+
|
|
204
|
+
`License <https://github.com/microsoft/MtReNIRS/blob/main/LICENSE.txt>`_
|
|
205
|
+
|
|
206
|
+
Parameters
|
|
207
|
+
----------
|
|
208
|
+
window_samples : int, default=100
|
|
209
|
+
Samples per token window :math:`x_{c,t}`; the paper's "10-s
|
|
210
|
+
(100-sample) windows" at 10 Hz.
|
|
211
|
+
embed_dim : int, default=128
|
|
212
|
+
Token and Transformer width, the paper's "128-dimensional state".
|
|
213
|
+
depth : int, default=6
|
|
214
|
+
Number of Transformer blocks.
|
|
215
|
+
num_heads : int, default=4
|
|
216
|
+
Attention heads; ``embed_dim // num_heads`` must be even for RoPE.
|
|
217
|
+
mlp_dim : int, default=512
|
|
218
|
+
Hidden width of each block's feed-forward network.
|
|
219
|
+
n_fourier_bands : int, default=6
|
|
220
|
+
Fourier bands :math:`2^k \pi` per coordinate of :math:`u_c` ("six
|
|
221
|
+
bands of Fourier features", 48 features).
|
|
222
|
+
spatial_hidden_dim : int, default=128
|
|
223
|
+
Hidden width of the spatio-chromophore MLP (48 -> 128 -> 128).
|
|
224
|
+
rope_base : float, default=500.0
|
|
225
|
+
RoPE base :math:`\beta` of the window index.
|
|
226
|
+
qk_norm : bool, default=True
|
|
227
|
+
Per-head LayerNorm of queries and keys.
|
|
228
|
+
pool : {"temporal_mean", "channel_temporal_mean", "flatten"}, default="temporal_mean"
|
|
229
|
+
Readout of the ``(batch, n_windows, n_chans, embed_dim)`` tokens:
|
|
230
|
+
mean over the valid windows (the paper's temporal averaging); mean
|
|
231
|
+
over the valid windows and channels (takes ``ch_mask``); or all
|
|
232
|
+
tokens flattened.
|
|
233
|
+
on_non_divisible : {"crop", "pad", "error"}, default="crop"
|
|
234
|
+
A short last window is dropped (the reference's ``remainder="drop"``),
|
|
235
|
+
zero-padded or refused.
|
|
236
|
+
coordinate_center : tuple of float
|
|
237
|
+
Centre :math:`\mu` (m) subtracted from :math:`q_c`; the checkpoint's
|
|
238
|
+
``data.pos_center``.
|
|
239
|
+
coordinate_scale : float
|
|
240
|
+
RMS scale :math:`\sigma` (m) dividing the centred :math:`q_c`; the
|
|
241
|
+
checkpoint's ``data.pos_scale``.
|
|
242
|
+
drop_prob : float, default=0.1
|
|
243
|
+
Dropout of attention weights, attention output and MLP.
|
|
244
|
+
activation : type[nn.Module], default=nn.GELU
|
|
245
|
+
Activation of the spatio-chromophore MLP and the feed-forward blocks.
|
|
246
|
+
|
|
247
|
+
Notes
|
|
248
|
+
-----
|
|
249
|
+
Preprocessing (Sec. III-B, Fig. 2A): optical density, temporal derivative
|
|
250
|
+
distribution repair, modified Beer-Lambert law; "We then band-pass
|
|
251
|
+
filtered each run from 0.01 to 0.5 Hz, resampled to 10 Hz, and removed
|
|
252
|
+
flat or abnormally low-variance chromophore channels"; z-score of each
|
|
253
|
+
chromophore channel over its run, clipped to :math:`[-6, 6]`; downstream
|
|
254
|
+
windows "[onset, onset + 10 s) without a hemodynamic-response shift".
|
|
255
|
+
|
|
256
|
+
Band-pass: the paper gives the band, 0.01 to 0.5 Hz. The released
|
|
257
|
+
``from_mne_raw`` uses MNE's default FIR for it; the replication below
|
|
258
|
+
used a zero-phase third-order Butterworth,
|
|
259
|
+
``raw.filter(0.01, 0.5, method="iir", iir_params=dict(order=3, ftype="butter"))``,
|
|
260
|
+
and reproduces the paper's numbers (:gh:`1564`). With MNE's default FIR,
|
|
261
|
+
43.8 % of the window power stays above 0.5 Hz, against 1.1 % with that
|
|
262
|
+
Butterworth.
|
|
263
|
+
|
|
264
|
+
Differences from the reference implementation: the input is a
|
|
265
|
+
``(batch, n_chans, n_times)`` tensor with the montage in ``chs_info``;
|
|
266
|
+
``final_layer`` and ``pool="channel_temporal_mean"`` are added (the
|
|
267
|
+
reference returns features only); a window with a NaN sample is left out
|
|
268
|
+
of the attention and of the average; the reference's ``remainder="overlap"``
|
|
269
|
+
is not offered. On the released checkpoint, the encoder features equal the
|
|
270
|
+
authors' ``MtReNIRSEncoder`` (MtReNIRS@16c3082) with max-abs difference
|
|
271
|
+
0.0.
|
|
272
|
+
|
|
273
|
+
Replication on SujinBak 2019 :footcite:`bak2019ufft` (30 subjects, left-
|
|
274
|
+
hand, right-hand and foot tapping) with this port and ``mtrenirs_10s.pt``
|
|
275
|
+
(macro-F1, %), under the paper's protocol: leave-one-subject-out with a
|
|
276
|
+
linear probe (LP), MLP probe, LoRA, full fine-tuning (Full-FT) and random
|
|
277
|
+
initialization (Scratch-FT), and within-subject few-shot linear probes.
|
|
278
|
+
|
|
279
|
+
========= ===== ==== ==== ======= ========== ====== ====== ====== ======
|
|
280
|
+
\ LP MLP LoRA Full-FT Scratch-FT 2-shot 4-shot 6-shot 8-shot
|
|
281
|
+
========= ===== ==== ==== ======= ========== ====== ====== ====== ======
|
|
282
|
+
Paper 67.9 67.2 70.3 70.2 66.7 40.4 46.2 50.0 53.0
|
|
283
|
+
Paper SD 17.7 18.6 18.6 19.1 16.2 8.1 11.9 14.2 15.1
|
|
284
|
+
Port 68.3 67.4 69.3 69.6 67.8 40.3 46.6 50.4 53.0
|
|
285
|
+
========= ===== ==== ==== ======= ========== ====== ====== ====== ======
|
|
286
|
+
|
|
287
|
+
References
|
|
288
|
+
----------
|
|
289
|
+
.. footbibliography::
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
def __init__(
|
|
293
|
+
self,
|
|
294
|
+
# Braindecode parameters
|
|
295
|
+
n_outputs: int | None = None,
|
|
296
|
+
n_chans: int | None = None,
|
|
297
|
+
chs_info: list[dict] | None = None,
|
|
298
|
+
n_times: int | None = None,
|
|
299
|
+
input_window_seconds: float | None = None,
|
|
300
|
+
sfreq: float | None = None,
|
|
301
|
+
*,
|
|
302
|
+
# Model-specific parameters
|
|
303
|
+
window_samples: int = 100,
|
|
304
|
+
embed_dim: int = 128,
|
|
305
|
+
depth: int = 6,
|
|
306
|
+
num_heads: int = 4,
|
|
307
|
+
mlp_dim: int = 512,
|
|
308
|
+
n_fourier_bands: int = 6,
|
|
309
|
+
spatial_hidden_dim: int = 128,
|
|
310
|
+
rope_base: float = 500.0,
|
|
311
|
+
qk_norm: bool = True,
|
|
312
|
+
pool: Literal[
|
|
313
|
+
"temporal_mean", "channel_temporal_mean", "flatten"
|
|
314
|
+
] = "temporal_mean",
|
|
315
|
+
on_non_divisible: Literal["crop", "pad", "error"] = "crop",
|
|
316
|
+
coordinate_center: tuple[float, float, float] = (
|
|
317
|
+
0.00021245056996122003,
|
|
318
|
+
-0.022675372660160065,
|
|
319
|
+
0.020025914534926414,
|
|
320
|
+
),
|
|
321
|
+
coordinate_scale: float = 0.09265176206827164,
|
|
322
|
+
drop_prob: float = 0.1,
|
|
323
|
+
activation: type[nn.Module] = nn.GELU,
|
|
324
|
+
) -> None:
|
|
325
|
+
super().__init__(
|
|
326
|
+
n_outputs=n_outputs,
|
|
327
|
+
n_chans=n_chans,
|
|
328
|
+
chs_info=chs_info,
|
|
329
|
+
n_times=n_times,
|
|
330
|
+
input_window_seconds=input_window_seconds,
|
|
331
|
+
sfreq=sfreq,
|
|
332
|
+
)
|
|
333
|
+
del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
|
|
334
|
+
|
|
335
|
+
# Checkers
|
|
336
|
+
# RoPE rotates pairs of features of each head, so every head needs an
|
|
337
|
+
# even number of features.
|
|
338
|
+
if embed_dim % num_heads or (embed_dim // num_heads) % 2:
|
|
339
|
+
raise ValueError(
|
|
340
|
+
f"embed_dim ({embed_dim}) must be divisible by num_heads "
|
|
341
|
+
f"({num_heads}) with an even head_dim for rotary position "
|
|
342
|
+
"embeddings."
|
|
343
|
+
)
|
|
344
|
+
# The readout is one of the three the paper's heads use; any other
|
|
345
|
+
# name has no defined feature size.
|
|
346
|
+
pools = ("temporal_mean", "channel_temporal_mean", "flatten")
|
|
347
|
+
if pool not in pools:
|
|
348
|
+
raise ValueError(f"pool must be one of {pools}, got {pool!r}.")
|
|
349
|
+
_check_on_non_divisible(on_non_divisible)
|
|
350
|
+
|
|
351
|
+
# Parameters
|
|
352
|
+
self.window_samples = window_samples
|
|
353
|
+
self.pool = pool
|
|
354
|
+
self.on_non_divisible = on_non_divisible
|
|
355
|
+
# Number of temporal windows T cut from the recording
|
|
356
|
+
self.n_windows = patch_count(self.n_times, window_samples, on_non_divisible)
|
|
357
|
+
# u_c = (x, y, z, chromophore): three standardized optode coordinates
|
|
358
|
+
# and the HbO/HbR flag
|
|
359
|
+
self.n_coordinates = 4
|
|
360
|
+
# Size of the feature vector that each readout hands to the head
|
|
361
|
+
self.feature_dim = {
|
|
362
|
+
"temporal_mean": self.n_chans * embed_dim,
|
|
363
|
+
"channel_temporal_mean": embed_dim,
|
|
364
|
+
"flatten": self.n_windows * self.n_chans * embed_dim,
|
|
365
|
+
}[pool]
|
|
366
|
+
drop_prob = float(drop_prob)
|
|
367
|
+
|
|
368
|
+
# Layers
|
|
369
|
+
# Following paper nomenclature
|
|
370
|
+
|
|
371
|
+
# Token embedding: z_{c,t} = signal embedding of the window x_{c,t}
|
|
372
|
+
# plus the spatio-chromophore embedding of u_c. One token per
|
|
373
|
+
# (channel, window), so any montage is a variable-length token set.
|
|
374
|
+
self.embed = _TokenEmbedding(
|
|
375
|
+
window_samples=window_samples,
|
|
376
|
+
embed_dim=embed_dim,
|
|
377
|
+
n_coordinates=self.n_coordinates,
|
|
378
|
+
n_fourier_bands=n_fourier_bands,
|
|
379
|
+
spatial_hidden_dim=spatial_hidden_dim,
|
|
380
|
+
activation=activation,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
# Transformer encoder: ``depth`` pre-norm blocks whose attention spans
|
|
384
|
+
# all channels and windows jointly, with QK-norm and a rotary embedding
|
|
385
|
+
# of the window index (the only place where time order enters).
|
|
386
|
+
blocks = [
|
|
387
|
+
_TransformerBlock(
|
|
388
|
+
embed_dim=embed_dim,
|
|
389
|
+
num_heads=num_heads,
|
|
390
|
+
mlp_dim=mlp_dim,
|
|
391
|
+
drop_prob=drop_prob,
|
|
392
|
+
rope_base=rope_base,
|
|
393
|
+
qk_norm=qk_norm,
|
|
394
|
+
activation=activation,
|
|
395
|
+
)
|
|
396
|
+
for _ in range(depth)
|
|
397
|
+
]
|
|
398
|
+
self.encoder = _Encoder(blocks=blocks, embed_dim=embed_dim)
|
|
399
|
+
|
|
400
|
+
# u_c of the channels in chs_info, standardized with the pretraining
|
|
401
|
+
# statistics; not persistent, so a checkpoint carries no montage.
|
|
402
|
+
default_coordinates = _coordinates(
|
|
403
|
+
self._chs_info, coordinate_center, coordinate_scale
|
|
404
|
+
)
|
|
405
|
+
self.register_buffer(
|
|
406
|
+
"default_coordinates",
|
|
407
|
+
torch.from_numpy(default_coordinates),
|
|
408
|
+
persistent=False,
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
# Shape layers of the tokenization: windows of one channel become
|
|
412
|
+
# tokens, and masks and coordinates are broadcast to the same layout.
|
|
413
|
+
self.split_windows = Rearrange(
|
|
414
|
+
"batch chans (windows samples) -> batch windows chans samples",
|
|
415
|
+
samples=window_samples,
|
|
416
|
+
)
|
|
417
|
+
self.chan_over_coordinates = Rearrange("batch chans -> batch chans 1")
|
|
418
|
+
self.chan_over_windows = Rearrange("batch chans -> batch 1 chans")
|
|
419
|
+
self.merge_tokens = Rearrange(
|
|
420
|
+
"batch windows chans samples -> batch (windows chans) samples"
|
|
421
|
+
)
|
|
422
|
+
self.merge_token_mask = Rearrange(
|
|
423
|
+
"batch windows chans -> batch (windows chans)"
|
|
424
|
+
)
|
|
425
|
+
self.coordinates_over_windows = Rearrange(
|
|
426
|
+
"batch chans coords -> batch 1 chans coords"
|
|
427
|
+
)
|
|
428
|
+
self.merge_coordinates = Rearrange(
|
|
429
|
+
"batch windows chans coords -> batch (windows chans) coords"
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
# Shape layers of the readout
|
|
433
|
+
self.token_over_features = Rearrange("batch tokens -> batch tokens 1")
|
|
434
|
+
self.valid_over_features = Rearrange(
|
|
435
|
+
"batch windows chans -> batch windows chans 1"
|
|
436
|
+
)
|
|
437
|
+
self.flatten_channels = Rearrange("batch chans dim -> batch (chans dim)")
|
|
438
|
+
self.flatten_tokens = Rearrange(
|
|
439
|
+
"batch windows chans dim -> batch (windows chans dim)"
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
# Classification head: one linear layer on the pooled features
|
|
443
|
+
self.final_layer = nn.Linear(self.feature_dim, self.n_outputs)
|
|
444
|
+
|
|
445
|
+
def encode_windows(
|
|
446
|
+
self,
|
|
447
|
+
x: torch.Tensor,
|
|
448
|
+
coordinates: Optional[torch.Tensor] = None,
|
|
449
|
+
ch_mask: Optional[torch.Tensor] = None,
|
|
450
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
451
|
+
"""Tokenize the recording and encode its (channel, window) tokens.
|
|
452
|
+
|
|
453
|
+
Parameters
|
|
454
|
+
----------
|
|
455
|
+
x : torch.Tensor
|
|
456
|
+
Hemoglobin concentrations, ``(batch, n_chans, n_times)``. A NaN
|
|
457
|
+
sample masks its window.
|
|
458
|
+
coordinates : torch.Tensor or None
|
|
459
|
+
:math:`u_c` of the channels of ``x``, ``(n_chans, 4)`` or
|
|
460
|
+
``(batch, n_chans, 4)``: standardized position and chromophore
|
|
461
|
+
(0 HbO, 1 HbR). NaN positions mark channels without a location.
|
|
462
|
+
``None`` uses the coordinates built from ``chs_info``.
|
|
463
|
+
ch_mask : torch.Tensor or None
|
|
464
|
+
``True`` for real channels, ``(batch, n_chans)``.
|
|
465
|
+
|
|
466
|
+
Returns
|
|
467
|
+
-------
|
|
468
|
+
encoded : torch.Tensor
|
|
469
|
+
Encoded tokens, ``(batch, n_windows, n_chans, embed_dim)``; zero
|
|
470
|
+
where a token is not valid.
|
|
471
|
+
valid : torch.Tensor
|
|
472
|
+
Validity of each token, ``(batch, n_windows, n_chans)``.
|
|
473
|
+
"""
|
|
474
|
+
batch_size, n_chans, _ = x.shape
|
|
475
|
+
|
|
476
|
+
# Spatio-chromophore coordinates u_c: from chs_info unless given. The
|
|
477
|
+
# model has no channel table, so it cannot run without positions.
|
|
478
|
+
if coordinates is None:
|
|
479
|
+
coord = self.default_coordinates
|
|
480
|
+
if coord.numel() == 0:
|
|
481
|
+
raise ValueError(
|
|
482
|
+
"MtReNIRS needs channel positions and chromophores: chs_info "
|
|
483
|
+
"with channel locations (loc[:3]) or the coordinates argument."
|
|
484
|
+
)
|
|
485
|
+
if coord.shape[0] != n_chans:
|
|
486
|
+
raise ValueError(
|
|
487
|
+
"x and chs_info have different channel counts: pass the "
|
|
488
|
+
"coordinates of the channels of x."
|
|
489
|
+
)
|
|
490
|
+
else:
|
|
491
|
+
coord = coordinates
|
|
492
|
+
if coord.shape[-2] != n_chans:
|
|
493
|
+
raise ValueError(
|
|
494
|
+
"coordinates and x have different channel counts: pass one "
|
|
495
|
+
"row per channel of x."
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
# Temporal windowing: the recording is cut into T non-overlapping
|
|
499
|
+
# windows of window_samples; a partial last window is cropped or padded
|
|
500
|
+
# (batch, n_chans, n_times) -> (batch, n_chans, n_windows * window_samples)
|
|
501
|
+
x = pad_or_crop_to_patches(x, self.window_samples, self.on_non_divisible)
|
|
502
|
+
# Windows x_{c,t}, one per channel c and window t
|
|
503
|
+
# -> (batch, n_windows, n_chans, window_samples)
|
|
504
|
+
windows = self.split_windows(x)
|
|
505
|
+
n_windows = windows.shape[1]
|
|
506
|
+
|
|
507
|
+
# Validity of each window: a NaN sample (missing or bad segment) masks
|
|
508
|
+
# the whole window
|
|
509
|
+
# (batch, n_windows, n_chans, window_samples)
|
|
510
|
+
finite = torch.isfinite(windows)
|
|
511
|
+
# -> (batch, n_windows, n_chans)
|
|
512
|
+
valid = finite.all(dim=-1)
|
|
513
|
+
|
|
514
|
+
# u_c for every sample of the batch
|
|
515
|
+
# (n_chans, 4) or (batch, n_chans, 4) -> (batch, n_chans, 4)
|
|
516
|
+
coord = coord.to(device=x.device, dtype=windows.dtype)
|
|
517
|
+
coord = coord.expand(batch_size, -1, -1)
|
|
518
|
+
|
|
519
|
+
# A channel without a location (NaN position) is masked; its u_c is
|
|
520
|
+
# set to 0 so that the Fourier features stay finite
|
|
521
|
+
# (batch, n_chans, 3)
|
|
522
|
+
positions = coord[..., :3]
|
|
523
|
+
positions_finite = torch.isfinite(positions)
|
|
524
|
+
# -> (batch, n_chans)
|
|
525
|
+
located = positions_finite.all(dim=-1)
|
|
526
|
+
# -> (batch, n_chans, 1)
|
|
527
|
+
located_over_coordinates = self.chan_over_coordinates(located)
|
|
528
|
+
coord_zeros = torch.zeros_like(coord)
|
|
529
|
+
# (batch, n_chans, 4)
|
|
530
|
+
coord = torch.where(located_over_coordinates, coord, coord_zeros)
|
|
531
|
+
# (batch, n_chans) -> (batch, 1, n_chans)
|
|
532
|
+
located_over_windows = self.chan_over_windows(located)
|
|
533
|
+
# (batch, n_windows, n_chans)
|
|
534
|
+
valid = valid & located_over_windows
|
|
535
|
+
|
|
536
|
+
# Padded channels of a batch that mixes montages are masked too
|
|
537
|
+
if ch_mask is not None:
|
|
538
|
+
# (batch, n_chans) -> (batch, 1, n_chans)
|
|
539
|
+
ch_mask = self.chan_over_windows(ch_mask)
|
|
540
|
+
ch_mask = ch_mask.to(torch.bool)
|
|
541
|
+
# (batch, n_windows, n_chans)
|
|
542
|
+
valid = valid & ch_mask
|
|
543
|
+
|
|
544
|
+
# Token set: every (window, channel) pair is one token, windows first
|
|
545
|
+
# (batch, n_windows, n_chans) -> (batch, n_windows * n_chans)
|
|
546
|
+
valid_tokens = self.merge_token_mask(valid)
|
|
547
|
+
# NaN samples are replaced by 0 so that masked tokens stay finite
|
|
548
|
+
# (batch, n_windows, n_chans, window_samples)
|
|
549
|
+
window_zeros = torch.zeros_like(windows)
|
|
550
|
+
x = torch.where(finite, windows, window_zeros)
|
|
551
|
+
# -> (batch, n_windows * n_chans, window_samples)
|
|
552
|
+
x = self.merge_tokens(x)
|
|
553
|
+
|
|
554
|
+
# u_c of every token: a channel keeps its coordinates in all windows
|
|
555
|
+
# (batch, n_chans, 4) -> (batch, 1, n_chans, 4)
|
|
556
|
+
coord_tokens = self.coordinates_over_windows(coord)
|
|
557
|
+
# -> (batch, n_windows, n_chans, 4)
|
|
558
|
+
coord_tokens = coord_tokens.expand(-1, n_windows, -1, -1)
|
|
559
|
+
# -> (batch, n_windows * n_chans, 4)
|
|
560
|
+
coord_tokens = self.merge_coordinates(coord_tokens)
|
|
561
|
+
|
|
562
|
+
# RoPE position of a token: its window index t, shared by all channels
|
|
563
|
+
# (n_windows,) -> (n_windows * n_chans,)
|
|
564
|
+
window_indices = torch.arange(n_windows, device=x.device)
|
|
565
|
+
window_indices = window_indices.repeat_interleave(n_chans)
|
|
566
|
+
# -> (batch, n_windows * n_chans)
|
|
567
|
+
window_indices = window_indices.expand(batch_size, -1)
|
|
568
|
+
|
|
569
|
+
# Token embedding z_{c,t}: signal embedding of x_{c,t} plus the
|
|
570
|
+
# spatio-chromophore embedding of u_c
|
|
571
|
+
# (batch, n_windows * n_chans, window_samples)
|
|
572
|
+
# -> (batch, n_windows * n_chans, embed_dim)
|
|
573
|
+
x = self.embed(x, coord_tokens)
|
|
574
|
+
|
|
575
|
+
# Transformer encoder: joint attention over channels and windows,
|
|
576
|
+
# invalid tokens are never attended
|
|
577
|
+
# (batch, n_windows * n_chans, embed_dim), unchanged
|
|
578
|
+
x = self.encoder(x, window_indices, valid_tokens)
|
|
579
|
+
|
|
580
|
+
# Invalid tokens are zeroed so that they cannot reach the readout
|
|
581
|
+
# (batch, n_windows * n_chans) -> (batch, n_windows * n_chans, 1)
|
|
582
|
+
token_weight = self.token_over_features(valid_tokens)
|
|
583
|
+
token_weight = token_weight.to(x.dtype)
|
|
584
|
+
# (batch, n_windows * n_chans, embed_dim)
|
|
585
|
+
x = x * token_weight
|
|
586
|
+
|
|
587
|
+
# Back to the (window, channel) grid for the readout
|
|
588
|
+
# -> (batch, n_windows, n_chans, embed_dim)
|
|
589
|
+
x = x.unflatten(1, [n_windows, n_chans])
|
|
590
|
+
return x, valid
|
|
591
|
+
|
|
592
|
+
def reset_head(self, n_outputs: int) -> None:
|
|
593
|
+
"""Replace the classification head with a new one of ``n_outputs``."""
|
|
594
|
+
self._set_n_outputs(n_outputs)
|
|
595
|
+
self.final_layer = nn.Linear(self.feature_dim, n_outputs)
|
|
596
|
+
|
|
597
|
+
def load_state_dict(self, state_dict, strict: bool = True, assign: bool = False):
|
|
598
|
+
"""Also takes the official checkpoint (``{"model": ...}``); a missing
|
|
599
|
+
head keeps its init."""
|
|
600
|
+
state_dict = dict(state_dict.get("model", state_dict))
|
|
601
|
+
if not any(k.startswith("final_layer.") for k in state_dict):
|
|
602
|
+
state_dict.update(self.final_layer.state_dict(prefix="final_layer."))
|
|
603
|
+
return super().load_state_dict(state_dict, strict=strict, assign=assign)
|
|
604
|
+
|
|
605
|
+
def forward(
|
|
606
|
+
self,
|
|
607
|
+
x: torch.Tensor,
|
|
608
|
+
return_features: bool = False,
|
|
609
|
+
coordinates: Optional[torch.Tensor] = None,
|
|
610
|
+
ch_mask: Optional[torch.Tensor] = None,
|
|
611
|
+
) -> torch.Tensor | dict[str, torch.Tensor | None]:
|
|
612
|
+
"""Forward pass.
|
|
613
|
+
|
|
614
|
+
Parameters
|
|
615
|
+
----------
|
|
616
|
+
x : torch.Tensor
|
|
617
|
+
Hemoglobin concentrations, ``(batch, n_chans, n_times)``.
|
|
618
|
+
return_features : bool, default=False
|
|
619
|
+
Return the pooled features instead of the logits.
|
|
620
|
+
coordinates : torch.Tensor or None
|
|
621
|
+
:math:`u_c` of the channels of ``x``, as in :meth:`encode_windows`.
|
|
622
|
+
ch_mask : torch.Tensor or None
|
|
623
|
+
``True`` for real channels, ``(batch, n_chans)``
|
|
624
|
+
(:func:`~braindecode.functional.check_ch_mask`). Needs
|
|
625
|
+
``pool="channel_temporal_mean"``; padded channels are left out of
|
|
626
|
+
the attention and the pooling.
|
|
627
|
+
|
|
628
|
+
Returns
|
|
629
|
+
-------
|
|
630
|
+
torch.Tensor or dict
|
|
631
|
+
Logits ``(batch, n_outputs)``, or with ``return_features`` a dict
|
|
632
|
+
with ``features`` ``(batch, feature_dim)`` and ``cls_token``
|
|
633
|
+
(``None``: the model has no class token).
|
|
634
|
+
"""
|
|
635
|
+
# A channel mask only makes sense when the readout averages over
|
|
636
|
+
# channels: the other two keep one feature slot per channel.
|
|
637
|
+
ch_mask = check_ch_mask(ch_mask, x)
|
|
638
|
+
if ch_mask is not None and self.pool != "channel_temporal_mean":
|
|
639
|
+
raise ValueError(
|
|
640
|
+
"ch_mask needs pool='channel_temporal_mean': the other heads "
|
|
641
|
+
"are tied to the channels."
|
|
642
|
+
)
|
|
643
|
+
|
|
644
|
+
# Tokenization, token embedding z_{c,t} and Transformer encoder
|
|
645
|
+
# (batch, n_chans, n_times) -> (batch, n_windows, n_chans, embed_dim)
|
|
646
|
+
# valid: (batch, n_windows, n_chans)
|
|
647
|
+
x, valid = self.encode_windows(x, coordinates, ch_mask)
|
|
648
|
+
|
|
649
|
+
# Readout of the encoded tokens
|
|
650
|
+
if self.pool == "flatten":
|
|
651
|
+
# All tokens are kept and concatenated
|
|
652
|
+
# -> (batch, n_windows * n_chans * embed_dim)
|
|
653
|
+
x = self.flatten_tokens(x)
|
|
654
|
+
else:
|
|
655
|
+
# Mean over the valid windows ("temporal_mean", one vector per
|
|
656
|
+
# channel) or over the valid windows and channels
|
|
657
|
+
# ("channel_temporal_mean", one vector per recording)
|
|
658
|
+
dims: List[int] = [1] if self.pool == "temporal_mean" else [1, 2]
|
|
659
|
+
# (batch, n_windows, n_chans) -> (batch, n_windows, n_chans, 1)
|
|
660
|
+
weight = self.valid_over_features(valid)
|
|
661
|
+
weight = weight.to(x.dtype)
|
|
662
|
+
# Number of valid tokens averaged; at least 1, so a channel with
|
|
663
|
+
# no valid window gives zeros and not NaN
|
|
664
|
+
# -> (batch, n_chans, 1) or (batch, 1)
|
|
665
|
+
count = weight.sum(dim=dims)
|
|
666
|
+
count = count.clamp_min(1.0)
|
|
667
|
+
# Sum of the valid tokens
|
|
668
|
+
# -> (batch, n_chans, embed_dim) or (batch, embed_dim)
|
|
669
|
+
x = x * weight
|
|
670
|
+
x = x.sum(dim=dims)
|
|
671
|
+
x = x / count
|
|
672
|
+
if self.pool == "temporal_mean":
|
|
673
|
+
# The per-channel vectors are concatenated
|
|
674
|
+
# (batch, n_chans, embed_dim) -> (batch, n_chans * embed_dim)
|
|
675
|
+
x = self.flatten_channels(x)
|
|
676
|
+
|
|
677
|
+
if return_features:
|
|
678
|
+
return {"features": x, "cls_token": None}
|
|
679
|
+
|
|
680
|
+
# Classification head
|
|
681
|
+
# (batch, feature_dim) -> (batch, n_outputs)
|
|
682
|
+
x = self.final_layer(x)
|
|
683
|
+
return x
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
class _TokenEmbedding(nn.Module):
|
|
687
|
+
"""Signal embedding of the window plus the spatio-chromophore embedding
|
|
688
|
+
(an MLP of the Fourier features of :math:`u_c`)."""
|
|
689
|
+
|
|
690
|
+
def __init__(
|
|
691
|
+
self,
|
|
692
|
+
window_samples: int,
|
|
693
|
+
embed_dim: int,
|
|
694
|
+
n_coordinates: int,
|
|
695
|
+
n_fourier_bands: int,
|
|
696
|
+
spatial_hidden_dim: int,
|
|
697
|
+
activation: type[nn.Module],
|
|
698
|
+
):
|
|
699
|
+
super().__init__()
|
|
700
|
+
# Parameters
|
|
701
|
+
# phi(u_c) holds a sine and a cosine for every coordinate and band
|
|
702
|
+
n_sin_cos = 2
|
|
703
|
+
fourier_dim = n_coordinates * n_fourier_bands * n_sin_cos
|
|
704
|
+
|
|
705
|
+
# Layers
|
|
706
|
+
# Signal embedding: a linear projection of the raw window x_{c,t}.
|
|
707
|
+
# ``signal.proj`` is the checkpoint's key path.
|
|
708
|
+
self.signal = nn.Sequential(
|
|
709
|
+
OrderedDict(proj=nn.Linear(window_samples, embed_dim))
|
|
710
|
+
)
|
|
711
|
+
|
|
712
|
+
# Fourier frequencies 2^k pi, k = 0, ..., n_fourier_bands - 1: octave
|
|
713
|
+
# bands let the MLP resolve both coarse and fine optode distances.
|
|
714
|
+
freqs = (2.0 ** torch.arange(n_fourier_bands).float()) * torch.pi
|
|
715
|
+
self.register_buffer("freqs", freqs, persistent=False)
|
|
716
|
+
|
|
717
|
+
# Spatio-chromophore embedding: an MLP of the Fourier features
|
|
718
|
+
# phi(u_c), so the position and the chromophore of a channel are an
|
|
719
|
+
# input and not a learned per-channel table. ``spatial.mlp`` is the
|
|
720
|
+
# checkpoint's key path.
|
|
721
|
+
mlp = nn.Sequential(
|
|
722
|
+
nn.Linear(fourier_dim, spatial_hidden_dim),
|
|
723
|
+
activation(),
|
|
724
|
+
nn.Linear(spatial_hidden_dim, embed_dim),
|
|
725
|
+
)
|
|
726
|
+
self.spatial = nn.Sequential(OrderedDict(mlp=mlp))
|
|
727
|
+
|
|
728
|
+
# Shape layers of the Fourier features
|
|
729
|
+
self.coordinates_over_bands = Rearrange(
|
|
730
|
+
"batch tokens coords -> batch tokens coords 1"
|
|
731
|
+
)
|
|
732
|
+
self.merge_bands = Rearrange(
|
|
733
|
+
"batch tokens coords bands -> batch tokens (coords bands)"
|
|
734
|
+
)
|
|
735
|
+
|
|
736
|
+
def forward(self, signal: torch.Tensor, coordinates: torch.Tensor) -> torch.Tensor:
|
|
737
|
+
"""Embed every (channel, window) token.
|
|
738
|
+
|
|
739
|
+
Parameters
|
|
740
|
+
----------
|
|
741
|
+
signal : torch.Tensor
|
|
742
|
+
Windows :math:`x_{c,t}`, ``(batch, n_tokens, window_samples)``.
|
|
743
|
+
coordinates : torch.Tensor
|
|
744
|
+
:math:`u_c` of each token, ``(batch, n_tokens, n_coordinates)``.
|
|
745
|
+
|
|
746
|
+
Returns
|
|
747
|
+
-------
|
|
748
|
+
torch.Tensor
|
|
749
|
+
Tokens :math:`z_{c,t}`, ``(batch, n_tokens, embed_dim)``.
|
|
750
|
+
"""
|
|
751
|
+
# Fourier frequencies 2^k pi on the device and dtype of the input
|
|
752
|
+
# (n_fourier_bands,)
|
|
753
|
+
freqs = self.freqs.to(device=coordinates.device, dtype=coordinates.dtype)
|
|
754
|
+
|
|
755
|
+
# Angles 2^k pi u_{c,j} of every coordinate j and band k
|
|
756
|
+
# (batch, n_tokens, n_coordinates) -> (batch, n_tokens, n_coordinates, 1)
|
|
757
|
+
coordinates = self.coordinates_over_bands(coordinates)
|
|
758
|
+
# -> (batch, n_tokens, n_coordinates, n_fourier_bands)
|
|
759
|
+
angles = coordinates * freqs
|
|
760
|
+
# -> (batch, n_tokens, n_coordinates * n_fourier_bands)
|
|
761
|
+
angles = self.merge_bands(angles)
|
|
762
|
+
|
|
763
|
+
# Signal embedding of the window x_{c,t}
|
|
764
|
+
# (batch, n_tokens, window_samples) -> (batch, n_tokens, embed_dim)
|
|
765
|
+
signal_embedding = self.signal(signal)
|
|
766
|
+
|
|
767
|
+
# Fourier features phi(u_c): all sines, then all cosines
|
|
768
|
+
# -> (batch, n_tokens, 2 * n_coordinates * n_fourier_bands)
|
|
769
|
+
sine = angles.sin()
|
|
770
|
+
cosine = angles.cos()
|
|
771
|
+
fourier = torch.cat([sine, cosine], dim=-1)
|
|
772
|
+
|
|
773
|
+
# Spatio-chromophore embedding: MLP of phi(u_c)
|
|
774
|
+
# -> (batch, n_tokens, embed_dim)
|
|
775
|
+
spatial_embedding = self.spatial(fourier)
|
|
776
|
+
|
|
777
|
+
# Token z_{c,t}: the two embeddings are summed
|
|
778
|
+
# -> (batch, n_tokens, embed_dim)
|
|
779
|
+
x = signal_embedding + spatial_embedding
|
|
780
|
+
return x
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
class _RotarySelfAttention(nn.Module):
|
|
784
|
+
"""The authors' ``MultiHeadAttention``: per-head QK LayerNorm, a rotary
|
|
785
|
+
embedding of the window index and a key padding mask.
|
|
786
|
+
|
|
787
|
+
Private because the attention of :mod:`braindecode.modules` takes neither
|
|
788
|
+
per-token positions nor a mask; ``qkv`` and ``proj`` keep timm's names, as
|
|
789
|
+
in the released ``mtrenirs_10s.pt``.
|
|
790
|
+
"""
|
|
791
|
+
|
|
792
|
+
def __init__(
|
|
793
|
+
self,
|
|
794
|
+
embed_dim: int,
|
|
795
|
+
num_heads: int,
|
|
796
|
+
drop_prob: float,
|
|
797
|
+
rope_base: float,
|
|
798
|
+
qk_norm: bool,
|
|
799
|
+
):
|
|
800
|
+
super().__init__()
|
|
801
|
+
# Parameters
|
|
802
|
+
self.head_dim = embed_dim // num_heads
|
|
803
|
+
self.rope_base = float(rope_base)
|
|
804
|
+
# Query, key and value come out of one fused projection
|
|
805
|
+
n_projections = 3
|
|
806
|
+
|
|
807
|
+
# Layers
|
|
808
|
+
# Fused query/key/value projection of every token
|
|
809
|
+
self.qkv = nn.Linear(embed_dim, n_projections * embed_dim, bias=True)
|
|
810
|
+
# Dropout on the attention weights
|
|
811
|
+
self.attn_drop = nn.Dropout(drop_prob)
|
|
812
|
+
# Output projection that mixes the heads back to the token width
|
|
813
|
+
self.proj = nn.Linear(embed_dim, embed_dim)
|
|
814
|
+
# QK-norm: a LayerNorm on each head's queries and keys bounds the
|
|
815
|
+
# attention logits, which keeps pretraining stable.
|
|
816
|
+
self.q_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity()
|
|
817
|
+
self.k_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity()
|
|
818
|
+
|
|
819
|
+
# Shape layers
|
|
820
|
+
self.split_heads = Rearrange(
|
|
821
|
+
"batch tokens (qkv heads dim) -> qkv batch heads tokens dim",
|
|
822
|
+
qkv=n_projections,
|
|
823
|
+
heads=num_heads,
|
|
824
|
+
)
|
|
825
|
+
self.angles_over_heads = Rearrange("batch tokens dim -> batch 1 tokens dim")
|
|
826
|
+
self.keys_over_queries = Rearrange("batch tokens -> batch 1 1 tokens")
|
|
827
|
+
self.merge_heads = Rearrange(
|
|
828
|
+
"batch heads tokens dim -> batch tokens (heads dim)"
|
|
829
|
+
)
|
|
830
|
+
|
|
831
|
+
def forward(
|
|
832
|
+
self, x: torch.Tensor, positions: torch.Tensor, valid: torch.Tensor
|
|
833
|
+
) -> torch.Tensor:
|
|
834
|
+
"""Self-attention over all (channel, window) tokens.
|
|
835
|
+
|
|
836
|
+
Parameters
|
|
837
|
+
----------
|
|
838
|
+
x : torch.Tensor
|
|
839
|
+
Tokens, ``(batch, n_tokens, embed_dim)``.
|
|
840
|
+
positions : torch.Tensor
|
|
841
|
+
Window index :math:`t` of each token, ``(batch, n_tokens)``.
|
|
842
|
+
valid : torch.Tensor
|
|
843
|
+
``True`` for tokens that can be attended, ``(batch, n_tokens)``.
|
|
844
|
+
|
|
845
|
+
Returns
|
|
846
|
+
-------
|
|
847
|
+
torch.Tensor
|
|
848
|
+
Attended tokens, ``(batch, n_tokens, embed_dim)``.
|
|
849
|
+
"""
|
|
850
|
+
# Fused projection, then one query, key and value per head
|
|
851
|
+
# (batch, n_tokens, embed_dim) -> (batch, n_tokens, 3 * embed_dim)
|
|
852
|
+
qkv = self.qkv(x)
|
|
853
|
+
# -> 3 x (batch, heads, n_tokens, head_dim)
|
|
854
|
+
query, key, value = self.split_heads(qkv).unbind(0)
|
|
855
|
+
|
|
856
|
+
# QK-norm: LayerNorm of the queries and keys of each head
|
|
857
|
+
# (batch, heads, n_tokens, head_dim), unchanged
|
|
858
|
+
query = self.q_norm(query)
|
|
859
|
+
key = self.k_norm(key)
|
|
860
|
+
|
|
861
|
+
# RoPE frequencies base^(-2i / head_dim) of the feature pairs
|
|
862
|
+
# (head_dim // 2,)
|
|
863
|
+
inv_freq = rotary_frequencies(
|
|
864
|
+
self.head_dim, self.rope_base, positions.device, query.dtype
|
|
865
|
+
)
|
|
866
|
+
# RoPE angles t * frequency: the position of a token is its window
|
|
867
|
+
# index t, so channels of one window share a rotation
|
|
868
|
+
# (batch, n_tokens) -> (batch, n_tokens, head_dim)
|
|
869
|
+
positions = positions.to(query.dtype)
|
|
870
|
+
angles = rotary_angles(positions, inv_freq, interleaved=False)
|
|
871
|
+
cosine = angles.cos()
|
|
872
|
+
sine = angles.sin()
|
|
873
|
+
# (batch, n_tokens, head_dim) -> (batch, 1, n_tokens, head_dim)
|
|
874
|
+
cosine = self.angles_over_heads(cosine)
|
|
875
|
+
sine = self.angles_over_heads(sine)
|
|
876
|
+
|
|
877
|
+
# Rotate queries and keys (not values): their dot product then
|
|
878
|
+
# depends only on the difference of the two window indices
|
|
879
|
+
# (batch, heads, n_tokens, head_dim), unchanged
|
|
880
|
+
query = apply_rotary(query, cosine, sine, interleaved=False)
|
|
881
|
+
key = apply_rotary(key, cosine, sine, interleaved=False)
|
|
882
|
+
|
|
883
|
+
# Key padding mask: invalid tokens (NaN window, channel without a
|
|
884
|
+
# location, padded channel) are never attended. A sample with no valid
|
|
885
|
+
# token attends to all of them, so its softmax stays finite.
|
|
886
|
+
# (batch, n_tokens) -> (batch, 1)
|
|
887
|
+
any_valid = valid.any(dim=-1, keepdim=True)
|
|
888
|
+
# (batch, n_tokens)
|
|
889
|
+
attend = valid | ~any_valid
|
|
890
|
+
# (batch, n_tokens) -> (batch, 1, 1, n_tokens)
|
|
891
|
+
attend = self.keys_over_queries(attend)
|
|
892
|
+
# Additive bias: 0 for attended keys, -inf for blocked ones
|
|
893
|
+
# (batch, 1, 1, n_tokens)
|
|
894
|
+
bias = torch.zeros_like(attend, dtype=query.dtype)
|
|
895
|
+
blocked = ~attend
|
|
896
|
+
bias = bias.masked_fill(blocked, float("-inf"))
|
|
897
|
+
|
|
898
|
+
# Scaled dot-product attention, softmax(q k^T / sqrt(head_dim) + bias) v
|
|
899
|
+
# (batch, heads, n_tokens, head_dim)
|
|
900
|
+
dropout_p = self.attn_drop.p if self.training else 0.0
|
|
901
|
+
x = scaled_dot_product_attention(
|
|
902
|
+
query,
|
|
903
|
+
key,
|
|
904
|
+
value,
|
|
905
|
+
attn_mask=bias,
|
|
906
|
+
dropout_p=dropout_p,
|
|
907
|
+
scale=1.0 / math.sqrt(self.head_dim),
|
|
908
|
+
)
|
|
909
|
+
|
|
910
|
+
# Concatenate the heads and project back to the token width
|
|
911
|
+
# (batch, heads, n_tokens, head_dim) -> (batch, n_tokens, embed_dim)
|
|
912
|
+
x = self.merge_heads(x)
|
|
913
|
+
x = self.proj(x)
|
|
914
|
+
return x
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
class _TransformerBlock(nn.Module):
|
|
918
|
+
"""Pre-norm block: QK-norm rotary self-attention, then feed-forward.
|
|
919
|
+
|
|
920
|
+
Private because its attention takes per-token positions and a validity mask
|
|
921
|
+
(:class:`~braindecode.modules.PreNormBlock` calls ``attn(x)`` only) and the
|
|
922
|
+
released ``mtrenirs_10s.pt`` keys follow this layout.
|
|
923
|
+
"""
|
|
924
|
+
|
|
925
|
+
def __init__(
|
|
926
|
+
self,
|
|
927
|
+
embed_dim: int,
|
|
928
|
+
num_heads: int,
|
|
929
|
+
mlp_dim: int,
|
|
930
|
+
drop_prob: float,
|
|
931
|
+
rope_base: float,
|
|
932
|
+
qk_norm: bool,
|
|
933
|
+
activation: type[nn.Module],
|
|
934
|
+
):
|
|
935
|
+
super().__init__()
|
|
936
|
+
# Pre-norm of the attention sub-layer
|
|
937
|
+
self.norm1 = nn.LayerNorm(embed_dim)
|
|
938
|
+
# Joint spatio-temporal self-attention with QK-norm and RoPE
|
|
939
|
+
self.attn = _RotarySelfAttention(
|
|
940
|
+
embed_dim=embed_dim,
|
|
941
|
+
num_heads=num_heads,
|
|
942
|
+
drop_prob=drop_prob,
|
|
943
|
+
rope_base=rope_base,
|
|
944
|
+
qk_norm=qk_norm,
|
|
945
|
+
)
|
|
946
|
+
# Pre-norm of the feed-forward sub-layer
|
|
947
|
+
self.norm2 = nn.LayerNorm(embed_dim)
|
|
948
|
+
# Feed-forward network: embed_dim -> mlp_dim -> embed_dim
|
|
949
|
+
self.mlp = FeedForwardBlock(
|
|
950
|
+
emb_size=embed_dim,
|
|
951
|
+
expansion=1,
|
|
952
|
+
drop_p=drop_prob,
|
|
953
|
+
activation=activation,
|
|
954
|
+
hidden_features=mlp_dim,
|
|
955
|
+
)
|
|
956
|
+
# Dropout on the attention branch before the residual sum
|
|
957
|
+
self.drop = nn.Dropout(drop_prob)
|
|
958
|
+
|
|
959
|
+
def forward(
|
|
960
|
+
self, x: torch.Tensor, positions: torch.Tensor, valid: torch.Tensor
|
|
961
|
+
) -> torch.Tensor:
|
|
962
|
+
"""One pre-norm Transformer block.
|
|
963
|
+
|
|
964
|
+
Parameters
|
|
965
|
+
----------
|
|
966
|
+
x : torch.Tensor
|
|
967
|
+
Tokens, ``(batch, n_tokens, embed_dim)``.
|
|
968
|
+
positions : torch.Tensor
|
|
969
|
+
Window index of each token, ``(batch, n_tokens)``.
|
|
970
|
+
valid : torch.Tensor
|
|
971
|
+
``True`` for tokens that can be attended, ``(batch, n_tokens)``.
|
|
972
|
+
|
|
973
|
+
Returns
|
|
974
|
+
-------
|
|
975
|
+
torch.Tensor
|
|
976
|
+
Tokens, ``(batch, n_tokens, embed_dim)``.
|
|
977
|
+
"""
|
|
978
|
+
# Attention sub-layer: x + Dropout(Attention(LayerNorm(x)))
|
|
979
|
+
# (batch, n_tokens, embed_dim), unchanged
|
|
980
|
+
attended = self.norm1(x)
|
|
981
|
+
attended = self.attn(attended, positions, valid)
|
|
982
|
+
attended = self.drop(attended)
|
|
983
|
+
x = x + attended
|
|
984
|
+
|
|
985
|
+
# Feed-forward sub-layer: x + MLP(LayerNorm(x))
|
|
986
|
+
# (batch, n_tokens, embed_dim), unchanged
|
|
987
|
+
update = self.norm2(x)
|
|
988
|
+
update = self.mlp(update)
|
|
989
|
+
x = x + update
|
|
990
|
+
return x
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
class _Encoder(nn.Module):
|
|
994
|
+
"""The Transformer blocks and a final LayerNorm."""
|
|
995
|
+
|
|
996
|
+
def __init__(self, blocks: list[nn.Module], embed_dim: int):
|
|
997
|
+
super().__init__()
|
|
998
|
+
# The stack of pre-norm Transformer blocks
|
|
999
|
+
self.blocks = nn.ModuleList(blocks)
|
|
1000
|
+
# Final LayerNorm: pre-norm blocks leave the residual stream
|
|
1001
|
+
# unnormalized, so the tokens are normalized once before the readout.
|
|
1002
|
+
self.norm = nn.LayerNorm(embed_dim)
|
|
1003
|
+
|
|
1004
|
+
def forward(
|
|
1005
|
+
self, x: torch.Tensor, positions: torch.Tensor, valid: torch.Tensor
|
|
1006
|
+
) -> torch.Tensor:
|
|
1007
|
+
"""Encode the tokens.
|
|
1008
|
+
|
|
1009
|
+
Parameters
|
|
1010
|
+
----------
|
|
1011
|
+
x : torch.Tensor
|
|
1012
|
+
Tokens :math:`z_{c,t}`, ``(batch, n_tokens, embed_dim)``.
|
|
1013
|
+
positions : torch.Tensor
|
|
1014
|
+
Window index of each token, ``(batch, n_tokens)``.
|
|
1015
|
+
valid : torch.Tensor
|
|
1016
|
+
``True`` for tokens that can be attended, ``(batch, n_tokens)``.
|
|
1017
|
+
|
|
1018
|
+
Returns
|
|
1019
|
+
-------
|
|
1020
|
+
torch.Tensor
|
|
1021
|
+
Encoded tokens, ``(batch, n_tokens, embed_dim)``.
|
|
1022
|
+
"""
|
|
1023
|
+
# Transformer blocks, each attending over all channels and windows
|
|
1024
|
+
# (batch, n_tokens, embed_dim), unchanged
|
|
1025
|
+
for block in self.blocks:
|
|
1026
|
+
x = block(x, positions, valid)
|
|
1027
|
+
|
|
1028
|
+
# Final LayerNorm of the encoded tokens
|
|
1029
|
+
# (batch, n_tokens, embed_dim), unchanged
|
|
1030
|
+
x = self.norm(x)
|
|
1031
|
+
return x
|
|
1032
|
+
|
|
1033
|
+
|
|
1034
|
+
def _coordinates(chs_info, coordinate_center, coordinate_scale) -> np.ndarray:
|
|
1035
|
+
"""``(n_chans, 4)`` :math:`u_c`: ``loc[:3]`` minus ``coordinate_center``,
|
|
1036
|
+
divided by ``coordinate_scale`` (NaN when unknown or all zero), and 0 for
|
|
1037
|
+
HbO, 1 for HbR, as the official ``chromophore_map``; ``(0, 4)`` without
|
|
1038
|
+
``chs_info`` or any location."""
|
|
1039
|
+
if chs_info is None:
|
|
1040
|
+
return np.zeros((0, 4), np.float32)
|
|
1041
|
+
chromophores = fnirs_chromophores_from_chs_info(chs_info)
|
|
1042
|
+
if "unknown" in chromophores:
|
|
1043
|
+
name = chs_info[chromophores.index("unknown")].get("ch_name")
|
|
1044
|
+
raise ValueError(f"MtReNIRS needs HbO/HbR channels, got {name!r}.")
|
|
1045
|
+
loc = extract_channel_locations_from_chs_info(chs_info, fill_missing=True)
|
|
1046
|
+
loc = np.asarray(loc)
|
|
1047
|
+
loc[(loc == 0).all(axis=1)] = np.nan # MNE without a montage: NaN or zeros
|
|
1048
|
+
if not np.isfinite(loc).any(): # forward raises unless coordinates are given
|
|
1049
|
+
return np.zeros((0, 4), np.float32)
|
|
1050
|
+
center = np.asarray(coordinate_center, dtype=np.float32)
|
|
1051
|
+
xyz = (loc - center) / float(coordinate_scale)
|
|
1052
|
+
is_hbr = np.equal(chromophores, "hbr")
|
|
1053
|
+
return np.c_[xyz, is_hbr].astype(np.float32)
|