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
|
@@ -306,7 +306,7 @@ class Guetschel2026(EEGModuleMixin, nn.Module, license="mit"):
|
|
|
306
306
|
|
|
307
307
|
from braindecode.models import Guetschel2026
|
|
308
308
|
|
|
309
|
-
raw.set_montage("
|
|
309
|
+
raw.set_montage("colin27_1020") # channel positions, in metres
|
|
310
310
|
model = Guetschel2026.from_pretrained(
|
|
311
311
|
Guetschel2026.hub_repo_id("mae", "9cm", 2),
|
|
312
312
|
chs_info=raw.info["chs"],
|
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
# Authors: Bruno Aristimunha <b.aristimunha@gmail.com> (braindecode adaptation)
|
|
2
|
+
#
|
|
3
|
+
# Adapted from the masked autoencoder module of the GeoNIRS authors,
|
|
4
|
+
# https://github.com/GeoNIRS/GeoNIRS (``model/`` at commit 81f8995), their
|
|
5
|
+
# implementation of Jung, Lee and An (2025), doi:10.1109/BCI65088.2025.10931275.
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
from typing import Literal, Optional
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
from einops.layers.torch import Rearrange, Reduce
|
|
13
|
+
from torch import nn
|
|
14
|
+
|
|
15
|
+
from braindecode.functional import (
|
|
16
|
+
pad_or_crop_to_patches,
|
|
17
|
+
patch_count,
|
|
18
|
+
sinusoidal_positional_encoding,
|
|
19
|
+
)
|
|
20
|
+
from braindecode.functional.patches import _check_on_non_divisible
|
|
21
|
+
from braindecode.models.base import EEGModuleMixin
|
|
22
|
+
from braindecode.models.util import fnirs_channel_order, fnirs_split_hbo_hbr
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class JungMAE(EEGModuleMixin, nn.Module):
|
|
26
|
+
r"""JungMAE from Jung et al. (2025), as implemented by the GeoNIRS authors.
|
|
27
|
+
|
|
28
|
+
:bdg-info:`Attention/Transformer` :bdg-danger:`Foundation Model`
|
|
29
|
+
|
|
30
|
+
.. versionadded:: 2.1
|
|
31
|
+
|
|
32
|
+
Labelled fNIRS data are slow and costly to collect, and supervised
|
|
33
|
+
decoders need a lot of them. Jung, Lee and An :footcite:`jung2025mae`
|
|
34
|
+
"propose a novel foundation model for fNIRS data based on a
|
|
35
|
+
self-supervised masked autoencoder framework", pretrained on unlabelled
|
|
36
|
+
recordings. They report that it matches supervised training "while
|
|
37
|
+
requiring only one-third of the labeled training data", and that "a larger
|
|
38
|
+
masking size aligns with the low-frequency nature of fNIRS signals". Their
|
|
39
|
+
paper (IEEE BCI 2025) is not open access and came without code, so what is
|
|
40
|
+
said about it here comes from its abstract.
|
|
41
|
+
|
|
42
|
+
This class ports the implementation and the ``jung_mae.pt`` weights of the
|
|
43
|
+
GeoNIRS authors (``GeoNIRS/GeoNIRS`` at commit ``81f8995``), who use the
|
|
44
|
+
model as a baseline and call it Jung-MAE (Tables 1, 14 and 15 of
|
|
45
|
+
:footcite:`li2026geonirs`). Their paper describes it as "a paper-guided
|
|
46
|
+
implementation of the multi-dataset fNIRS pretraining framework of Jung et
|
|
47
|
+
al. (2025)" which, to "accommodate heterogeneous channel counts", "uses
|
|
48
|
+
channel-independent encoding with shared parameters" (Section 3.1). The
|
|
49
|
+
details below are read from the GeoNIRS code.
|
|
50
|
+
|
|
51
|
+
.. rubric:: Architectural Overview
|
|
52
|
+
|
|
53
|
+
Every HbO/HbR pair (one source-detector channel) is a sequence of its own.
|
|
54
|
+
Its window is cut into 2 s patches, each patch becomes one token that
|
|
55
|
+
holds both chromophores, and a small Transformer encodes the tokens of
|
|
56
|
+
that pair. The same weights serve every pair, which is how one checkpoint
|
|
57
|
+
handles montages of any size. The classifier then flattens the tokens of
|
|
58
|
+
all the pairs. With :math:`B` the batch size, :math:`C` = ``n_chans // 2``
|
|
59
|
+
pairs, :math:`Q` = ``patch_size``, :math:`P` patches and :math:`D` =
|
|
60
|
+
``embed_dim``, the model has the following sequence of steps::
|
|
61
|
+
|
|
62
|
+
x (B, 2C, n_times): HbO and HbR rows, NaN = missing sample
|
|
63
|
+
1. HbO/HbR split, invalid samples to zero -> (B, C, P*Q) each
|
|
64
|
+
2. to_patches: [HbO_t, HbR_t, ...] -> (B*C, P, 2Q)
|
|
65
|
+
3. patch_embed + sinusoidal position -> (B*C, P, D)
|
|
66
|
+
4. encoder, invalid patches not attended -> (B, C, P, D) encode()
|
|
67
|
+
5. flatten_layer, head_dropout -> (B, C*P*D)
|
|
68
|
+
6. final_layer -> (B, n_outputs)
|
|
69
|
+
|
|
70
|
+
.. rubric:: Macro Components
|
|
71
|
+
|
|
72
|
+
- ``JungMAE.patch_embed`` **Patch tokenization**
|
|
73
|
+
|
|
74
|
+
A patch interleaves the :math:`Q` HbO samples :math:`o` and HbR samples
|
|
75
|
+
:math:`r` of pair :math:`c`. One :class:`~torch.nn.Linear` maps it to a
|
|
76
|
+
:math:`D`-wide token, and the fixed sinusoidal encoding of the patch
|
|
77
|
+
index :math:`p` is added:
|
|
78
|
+
|
|
79
|
+
.. math::
|
|
80
|
+
|
|
81
|
+
\mathbf{z}_{c,p} = \mathbf{W}\,[o_{c,pQ},\, r_{c,pQ},\, \dots,\,
|
|
82
|
+
o_{c,pQ+Q-1},\, r_{c,pQ+Q-1}] + \mathbf{b} + \mathrm{PE}(p).
|
|
83
|
+
|
|
84
|
+
- **Patch validity** (``minimum_patch_valid_fraction``)
|
|
85
|
+
|
|
86
|
+
A sample is valid when both chromophores are finite and it is not in
|
|
87
|
+
``mask``. Invalid samples are set to zero, and a patch counts only when
|
|
88
|
+
at least :math:`\lceil 0.8\,Q \rceil` of its samples are valid. The
|
|
89
|
+
GeoNIRS paper applies the same 80 % rule to its own model (Appendix
|
|
90
|
+
B.1.2).
|
|
91
|
+
|
|
92
|
+
- ``JungMAE.encoder`` **Transformer encoder**
|
|
93
|
+
|
|
94
|
+
Four pre-norm :class:`~torch.nn.TransformerEncoderLayer` blocks (8
|
|
95
|
+
heads, feed-forward width 768, GELU) and a final
|
|
96
|
+
:class:`~torch.nn.LayerNorm`, over the :math:`P` tokens of one pair.
|
|
97
|
+
Invalid patches are not attended and their output is zero, so a pair
|
|
98
|
+
without any valid patch gives zero features.
|
|
99
|
+
|
|
100
|
+
- ``JungMAE.final_layer`` **Classification head**
|
|
101
|
+
|
|
102
|
+
Flatten, :class:`~torch.nn.Dropout` and one :class:`~torch.nn.Linear`,
|
|
103
|
+
the ``flatten_linear`` head of the GeoNIRS benchmark. It is not
|
|
104
|
+
pretrained, and its input size fixes ``n_chans`` and ``n_times``.
|
|
105
|
+
|
|
106
|
+
.. rubric:: Temporal, Spatial, and Chromophore Encoding
|
|
107
|
+
|
|
108
|
+
- **Temporal.** Non-overlapping 2 s patches (10 samples at 5 Hz) with a
|
|
109
|
+
fixed sinusoidal position. The GeoNIRS paper pretrains on 30 s windows
|
|
110
|
+
(15 patches) and keeps each downstream task's 10 s or 12 s window
|
|
111
|
+
(Appendix B.1.2).
|
|
112
|
+
- **Spatial.** None. Pairs never attend to each other and the model sees
|
|
113
|
+
no optode position. A pair is identified only by where its features sit
|
|
114
|
+
in the head input, so the pairs must keep the order used in training.
|
|
115
|
+
- **Chromophores.** HbO and HbR share each token, sample by sample; HbT
|
|
116
|
+
is not used. The rows must be the HbO and the HbR rows of the same
|
|
117
|
+
pairs (see ``channel_order``).
|
|
118
|
+
|
|
119
|
+
.. rubric:: Pretraining
|
|
120
|
+
|
|
121
|
+
In the reference, each pair keeps half of its valid patches visible,
|
|
122
|
+
drawn at random, and hides the others. The encoder reads the visible
|
|
123
|
+
tokens only. A lighter decoder (two layers of width 96, with a learned
|
|
124
|
+
mask token) predicts every patch, and the loss is the mean squared error
|
|
125
|
+
over the valid samples of the hidden patches. The decoder is stored in
|
|
126
|
+
``jung_mae.pt`` and is not part of this class.
|
|
127
|
+
|
|
128
|
+
.. rubric:: Known Limitations
|
|
129
|
+
|
|
130
|
+
- The model "does not model physical channel geometry" (GeoNIRS paper,
|
|
131
|
+
Section 3.1): different channel counts "are supported without modeling
|
|
132
|
+
physical channel coordinates or cross-layout correspondence" (Table 13).
|
|
133
|
+
- It is "a paper-guided implementation rather than an exact reproduction
|
|
134
|
+
of the original method" (GeoNIRS paper, Appendix G).
|
|
135
|
+
|
|
136
|
+
.. rubric:: Pretrained Weights
|
|
137
|
+
|
|
138
|
+
``checkpoint/jung_mae.pt`` of ``GeoNIRS/GeoNIRS`` at ``81f8995`` was
|
|
139
|
+
trained by the GeoNIRS authors and is not on Hugging Face. It
|
|
140
|
+
holds the encoder (1,783,872 parameters), the decoder (244,436) and the
|
|
141
|
+
model configuration, which equals the defaults of this class.
|
|
142
|
+
|
|
143
|
+
.. important::
|
|
144
|
+
:meth:`load_state_dict` takes the file as released. It drops the
|
|
145
|
+
decoder and keeps the new ``final_layer``:
|
|
146
|
+
|
|
147
|
+
.. code-block:: python
|
|
148
|
+
|
|
149
|
+
import torch
|
|
150
|
+
from braindecode.models import JungMAE
|
|
151
|
+
|
|
152
|
+
payload = torch.load("jung_mae.pt", map_location="cpu", weights_only=True)
|
|
153
|
+
model = JungMAE(n_chans=40, n_outputs=2, n_times=60, sfreq=5.0)
|
|
154
|
+
model.load_state_dict(payload)
|
|
155
|
+
|
|
156
|
+
The weights expect the inputs of the GeoNIRS paper (Appendix B.1): HbO and
|
|
157
|
+
HbR in µmol/L resampled to 5 Hz, each chromophore z-scored per recording
|
|
158
|
+
over all its valid channels and time points.
|
|
159
|
+
|
|
160
|
+
.. rubric:: Differences from the Reference Implementation
|
|
161
|
+
|
|
162
|
+
- **Input.** One tensor ``(batch, n_chans, n_times)``, with the HbO rows
|
|
163
|
+
then the HbR rows, or MNE's interleaved order read from ``chs_info``.
|
|
164
|
+
The reference takes ``hbo`` and ``hbr`` tensors with validity masks.
|
|
165
|
+
Here NaN marks a missing sample (an all-NaN row is a missing channel),
|
|
166
|
+
and the opt-in ``mask`` marks more.
|
|
167
|
+
- **Parity.** The reference packs the valid tokens of each pair; this
|
|
168
|
+
class masks the invalid ones as attention keys. With ``jung_mae.pt``
|
|
169
|
+
the features equal those of the authors' module (max-abs 0.0) in eval
|
|
170
|
+
mode under :func:`torch.no_grad`. With gradients on they differ by
|
|
171
|
+
about 2e-6 at most (float32 rounding), and in training mode the
|
|
172
|
+
dropout draws differ.
|
|
173
|
+
- **Head.** The benchmark head standardizes the flattened features with
|
|
174
|
+
training-set statistics before its Dropout; this head does not, so
|
|
175
|
+
standardize the eval-mode ``return_features`` yourself to reproduce
|
|
176
|
+
the benchmark. ``final_layer`` starts Xavier-uniform with a zero bias,
|
|
177
|
+
as the other Linear layers of the reference.
|
|
178
|
+
- **Additions.** ``on_non_divisible="pad"`` or ``"crop"`` (the reference
|
|
179
|
+
refuses a partial patch) and ``mask``. ``ch_mask`` is refused, because
|
|
180
|
+
``final_layer`` spans every pair.
|
|
181
|
+
|
|
182
|
+
Parameters
|
|
183
|
+
----------
|
|
184
|
+
patch_size : int, default=10
|
|
185
|
+
Samples per patch (``patch_samples`` in the reference), 2 s at 5 Hz.
|
|
186
|
+
embed_dim : int, default=192
|
|
187
|
+
Width of the tokens (``encoder_dim`` in the reference).
|
|
188
|
+
depth : int, default=4
|
|
189
|
+
Number of Transformer layers (``encoder_layers`` in the reference).
|
|
190
|
+
num_heads : int, default=8
|
|
191
|
+
Attention heads per layer (``encoder_heads`` in the reference).
|
|
192
|
+
mlp_ratio : float, default=4.0
|
|
193
|
+
Feed-forward width over ``embed_dim``.
|
|
194
|
+
drop_prob : float, default=0.1
|
|
195
|
+
Dropout of the encoder layers (``dropout`` in the reference).
|
|
196
|
+
head_drop_prob : float, default=0.1
|
|
197
|
+
Dropout before ``final_layer`` (``head_dropout`` in the benchmark).
|
|
198
|
+
minimum_patch_valid_fraction : float, default=0.8
|
|
199
|
+
Fraction of valid samples a patch needs, in (0, 1].
|
|
200
|
+
activation : type[nn.Module], default=nn.GELU
|
|
201
|
+
Activation of the feed-forward layers.
|
|
202
|
+
channel_order : {"stacked", "interleaved"} or None, default=None
|
|
203
|
+
``[HbO_1..HbO_C, HbR_1..HbR_C]`` or MNE's ``[HbO_1, HbR_1, ...]``.
|
|
204
|
+
``None`` reads it from ``chs_info`` (``"stacked"`` without it).
|
|
205
|
+
``n_chans`` must be even.
|
|
206
|
+
on_non_divisible : {"error", "pad", "crop"}, default="error"
|
|
207
|
+
What to do when ``n_times`` is not a multiple of ``patch_size``:
|
|
208
|
+
raise, as the reference does; pad with missing samples, to which the
|
|
209
|
+
validity rule applies; or crop.
|
|
210
|
+
|
|
211
|
+
Notes
|
|
212
|
+
-----
|
|
213
|
+
The GeoNIRS benchmark (Section 3.1 and Appendices B.5-B.6 of
|
|
214
|
+
:footcite:`li2026geonirs`) evaluates eight held-out binary tasks with
|
|
215
|
+
subject-level five-fold cross-validation and the seeds 810 and 811. Every
|
|
216
|
+
method gets the same windows and folds and the same training: 30 epochs,
|
|
217
|
+
AdamW, class-weighted cross-entropy and model selection by validation
|
|
218
|
+
balanced accuracy. Jung-MAE-LP trains the head only, with a learning rate
|
|
219
|
+
of 1e-4.
|
|
220
|
+
|
|
221
|
+
This class with ``jung_mae.pt`` and the benchmark's linear-probe loop
|
|
222
|
+
reproduces Jung-MAE-LP (mean over the five test folds and the two seeds):
|
|
223
|
+
|
|
224
|
+
===================== ======== ================= ==============
|
|
225
|
+
Task Metric GeoNIRS paper (%) This class (%)
|
|
226
|
+
===================== ======== ================= ==============
|
|
227
|
+
DS42 (action mode) macro-F1 68.36 68.35
|
|
228
|
+
DS42 (action mode) AUROC 76.78 76.80
|
|
229
|
+
DS19 (pain intensity) macro-F1 54.23 54.95
|
|
230
|
+
DS19 (pain intensity) AUROC 58.39 58.63
|
|
231
|
+
===================== ======== ================= ==============
|
|
232
|
+
|
|
233
|
+
References
|
|
234
|
+
----------
|
|
235
|
+
.. footbibliography::
|
|
236
|
+
"""
|
|
237
|
+
|
|
238
|
+
def __init__(
|
|
239
|
+
self,
|
|
240
|
+
# Braindecode parameters
|
|
241
|
+
n_outputs: int | None = None,
|
|
242
|
+
n_chans: int | None = None,
|
|
243
|
+
chs_info=None,
|
|
244
|
+
n_times: int | None = None,
|
|
245
|
+
input_window_seconds: float | None = None,
|
|
246
|
+
sfreq: float | None = None,
|
|
247
|
+
*,
|
|
248
|
+
# Model-specific parameters
|
|
249
|
+
patch_size: int = 10,
|
|
250
|
+
embed_dim: int = 192,
|
|
251
|
+
depth: int = 4,
|
|
252
|
+
num_heads: int = 8,
|
|
253
|
+
mlp_ratio: float = 4.0,
|
|
254
|
+
drop_prob: float = 0.1,
|
|
255
|
+
head_drop_prob: float = 0.1,
|
|
256
|
+
minimum_patch_valid_fraction: float = 0.8,
|
|
257
|
+
activation: type[nn.Module] = nn.GELU,
|
|
258
|
+
channel_order: Literal["stacked", "interleaved"] | None = None,
|
|
259
|
+
on_non_divisible: Literal["error", "pad", "crop"] = "error",
|
|
260
|
+
) -> None:
|
|
261
|
+
super().__init__(
|
|
262
|
+
n_outputs=n_outputs,
|
|
263
|
+
n_chans=n_chans,
|
|
264
|
+
chs_info=chs_info,
|
|
265
|
+
n_times=n_times,
|
|
266
|
+
input_window_seconds=input_window_seconds,
|
|
267
|
+
sfreq=sfreq,
|
|
268
|
+
)
|
|
269
|
+
del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
|
|
270
|
+
|
|
271
|
+
# Checkers
|
|
272
|
+
# Layout of the HbO and HbR rows, read from chs_info when it is given
|
|
273
|
+
self.channel_order = fnirs_channel_order(self._chs_info, channel_order)
|
|
274
|
+
# A token holds the two chromophores of one source-detector pair
|
|
275
|
+
if self.n_chans % 2 != 0:
|
|
276
|
+
raise ValueError(
|
|
277
|
+
"JungMAE needs HbO/HbR pairs, because a token holds both "
|
|
278
|
+
f"chromophores of a pair: n_chans must be even, got {self.n_chans}."
|
|
279
|
+
)
|
|
280
|
+
_check_on_non_divisible(on_non_divisible)
|
|
281
|
+
# A patch holds patch_size samples of each chromophore
|
|
282
|
+
if patch_size < 1:
|
|
283
|
+
raise ValueError(
|
|
284
|
+
f"patch_size must be positive, got {patch_size}: "
|
|
285
|
+
"a patch needs at least one sample."
|
|
286
|
+
)
|
|
287
|
+
# At zero a patch without data would be encoded; above one, none would
|
|
288
|
+
if not 0 < minimum_patch_valid_fraction <= 1:
|
|
289
|
+
raise ValueError(
|
|
290
|
+
"minimum_patch_valid_fraction must be in (0, 1], "
|
|
291
|
+
f"got {minimum_patch_valid_fraction}: it is the share of valid "
|
|
292
|
+
"samples a patch needs to be encoded."
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
# Parameters
|
|
296
|
+
# Q in the docstring: samples of each chromophore in one patch
|
|
297
|
+
self.patch_size = patch_size
|
|
298
|
+
# What to do with a window that is not a whole number of patches
|
|
299
|
+
self.on_non_divisible = on_non_divisible
|
|
300
|
+
# C pairs and P patches: with the token width, the input size of the head
|
|
301
|
+
n_pairs = self.n_chans // 2
|
|
302
|
+
n_patches = patch_count(self.n_times, patch_size, on_non_divisible)
|
|
303
|
+
# Validity rule of the reference: a patch is encoded when at least
|
|
304
|
+
# ceil(minimum_patch_valid_fraction * Q) of its samples are valid
|
|
305
|
+
self.min_valid_samples = math.ceil(patch_size * minimum_patch_valid_fraction)
|
|
306
|
+
|
|
307
|
+
# Layers
|
|
308
|
+
# Following the nomenclature of the reference implementation
|
|
309
|
+
|
|
310
|
+
# Patch tokenization. The window of one pair is cut into P patches, and
|
|
311
|
+
# the Q HbO and Q HbR samples of a patch are interleaved,
|
|
312
|
+
# [HbO_t, HbR_t, HbO_t+1, HbR_t+1, ...]: both chromophores share a token
|
|
313
|
+
self.to_patches = Rearrange(
|
|
314
|
+
"batch pairs (patches samples) chromophores"
|
|
315
|
+
" -> (batch pairs) patches (samples chromophores)",
|
|
316
|
+
samples=patch_size,
|
|
317
|
+
)
|
|
318
|
+
# Patch embedding: the linear projection of a patch to a token of width
|
|
319
|
+
# D (W and b in the docstring equation)
|
|
320
|
+
self.patch_embed = nn.Linear(
|
|
321
|
+
in_features=2 * patch_size,
|
|
322
|
+
out_features=embed_dim,
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
# Patch validity. Number of valid samples in each patch, which encode
|
|
326
|
+
# compares with min_valid_samples
|
|
327
|
+
self.count_valid_samples = Reduce(
|
|
328
|
+
"batch pairs (patches samples) -> batch pairs patches",
|
|
329
|
+
reduction="sum",
|
|
330
|
+
samples=patch_size,
|
|
331
|
+
)
|
|
332
|
+
# The encoder reads each pair as a sequence of its own, so the patch
|
|
333
|
+
# validity is laid out like the tokens: one row per pair
|
|
334
|
+
self.merge_pairs = Rearrange("batch pairs patches -> (batch pairs) patches")
|
|
335
|
+
# Trailing axis, to zero every feature of the token of an invalid patch
|
|
336
|
+
self.to_token_mask = Rearrange("rows patches -> rows patches 1")
|
|
337
|
+
|
|
338
|
+
# Transformer encoder: pre-norm layers and a final LayerNorm, over the
|
|
339
|
+
# P tokens of one pair. All the pairs go through the same weights (the
|
|
340
|
+
# "channel-independent encoding with shared parameters" of the GeoNIRS
|
|
341
|
+
# paper), so one checkpoint serves any number of channels
|
|
342
|
+
self.encoder = nn.TransformerEncoder(
|
|
343
|
+
nn.TransformerEncoderLayer(
|
|
344
|
+
d_model=embed_dim,
|
|
345
|
+
nhead=num_heads,
|
|
346
|
+
dim_feedforward=int(embed_dim * mlp_ratio),
|
|
347
|
+
dropout=drop_prob,
|
|
348
|
+
activation=activation(),
|
|
349
|
+
batch_first=True,
|
|
350
|
+
norm_first=True,
|
|
351
|
+
),
|
|
352
|
+
num_layers=depth,
|
|
353
|
+
norm=nn.LayerNorm(embed_dim),
|
|
354
|
+
enable_nested_tensor=False,
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
# Classification head, the flatten_linear head of the GeoNIRS benchmark.
|
|
358
|
+
# It is not pretrained: the checkpoint holds the encoder and the decoder
|
|
359
|
+
|
|
360
|
+
# The tokens of all the pairs and patches, in one vector per window
|
|
361
|
+
self.flatten_layer = Rearrange("batch ... -> batch (...)")
|
|
362
|
+
# Dropout on that vector, before the classifier
|
|
363
|
+
self.head_dropout = nn.Dropout(head_drop_prob)
|
|
364
|
+
# Linear classifier over C * P * D features
|
|
365
|
+
self.final_layer = nn.Linear(
|
|
366
|
+
in_features=n_pairs * n_patches * embed_dim,
|
|
367
|
+
out_features=self.n_outputs,
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
# Initialization of the reference
|
|
371
|
+
self._init_parameters()
|
|
372
|
+
|
|
373
|
+
def _init_parameters(self) -> None:
|
|
374
|
+
"""Xavier-uniform weights and zero biases, as the reference."""
|
|
375
|
+
for module in self.modules():
|
|
376
|
+
# Patch embedding, feed-forward layers and classifier
|
|
377
|
+
if isinstance(module, nn.Linear):
|
|
378
|
+
nn.init.xavier_uniform_(module.weight)
|
|
379
|
+
nn.init.zeros_(module.bias)
|
|
380
|
+
# Query, key and value projections. nn.TransformerEncoder copies
|
|
381
|
+
# one layer, so without this draw every layer would start equal
|
|
382
|
+
elif isinstance(module, nn.MultiheadAttention):
|
|
383
|
+
nn.init.xavier_uniform_(module.in_proj_weight)
|
|
384
|
+
nn.init.zeros_(module.in_proj_bias)
|
|
385
|
+
|
|
386
|
+
def forward(
|
|
387
|
+
self,
|
|
388
|
+
x: torch.Tensor,
|
|
389
|
+
return_features: bool = False,
|
|
390
|
+
ch_mask: Optional[torch.Tensor] = None,
|
|
391
|
+
mask: Optional[torch.Tensor] = None,
|
|
392
|
+
) -> torch.Tensor | dict[str, torch.Tensor | None]:
|
|
393
|
+
"""Forward pass of the JungMAE model.
|
|
394
|
+
|
|
395
|
+
Parameters
|
|
396
|
+
----------
|
|
397
|
+
x : torch.Tensor
|
|
398
|
+
Input tensor with shape (batch_size, n_chans, n_times). NaN marks
|
|
399
|
+
a missing sample.
|
|
400
|
+
return_features : bool, default=False
|
|
401
|
+
If True, return the input of ``final_layer`` instead of the
|
|
402
|
+
logits.
|
|
403
|
+
ch_mask : None
|
|
404
|
+
Not supported, because ``final_layer`` spans every pair. Mark a
|
|
405
|
+
missing channel with NaN instead.
|
|
406
|
+
mask : torch.Tensor of bool, optional
|
|
407
|
+
Same shape as ``x``. True samples count as missing.
|
|
408
|
+
|
|
409
|
+
Returns
|
|
410
|
+
-------
|
|
411
|
+
torch.Tensor or dict
|
|
412
|
+
Output tensor with shape (batch_size, n_outputs), or
|
|
413
|
+
``{"features": (batch_size, n_pairs * n_patches * embed_dim),
|
|
414
|
+
"cls_token": None}`` with ``return_features=True``.
|
|
415
|
+
"""
|
|
416
|
+
# Shapes use the symbols of the class docstring: C pairs, P patches of
|
|
417
|
+
# Q samples, tokens of width D.
|
|
418
|
+
|
|
419
|
+
# The classifier spans every pair, so a padded channel cannot be left
|
|
420
|
+
# out of it: a missing channel is given as NaN instead
|
|
421
|
+
if ch_mask is not None:
|
|
422
|
+
raise ValueError("JungMAE does not accept ch_mask; use NaN channels.")
|
|
423
|
+
|
|
424
|
+
# Encoder: one token per patch of each HbO/HbR pair, zero where the
|
|
425
|
+
# patch is invalid ("foundation" in the reference)
|
|
426
|
+
# (batch, 2C, n_times) -> (batch, C, P, D)
|
|
427
|
+
encoded = self.encode(x, mask)
|
|
428
|
+
x = encoded["foundation"]
|
|
429
|
+
|
|
430
|
+
# Input of the flatten_linear head of the benchmark: every token of
|
|
431
|
+
# the window in one vector, pair after pair
|
|
432
|
+
# (batch, C, P, D) -> (batch, C * P * D)
|
|
433
|
+
x = self.flatten_layer(x)
|
|
434
|
+
|
|
435
|
+
# Dropout on the features, before the classifier
|
|
436
|
+
# (batch, C * P * D), unchanged
|
|
437
|
+
x = self.head_dropout(x)
|
|
438
|
+
if return_features:
|
|
439
|
+
return {"features": x, "cls_token": None}
|
|
440
|
+
|
|
441
|
+
# Linear classifier: the logits of the window
|
|
442
|
+
# (batch, C * P * D) -> (batch, n_outputs)
|
|
443
|
+
x = self.final_layer(x)
|
|
444
|
+
return x
|
|
445
|
+
|
|
446
|
+
def encode(
|
|
447
|
+
self, x: torch.Tensor, mask: Optional[torch.Tensor] = None
|
|
448
|
+
) -> dict[str, torch.Tensor]:
|
|
449
|
+
"""Encode the patches of every HbO/HbR pair.
|
|
450
|
+
|
|
451
|
+
Parameters
|
|
452
|
+
----------
|
|
453
|
+
x : torch.Tensor
|
|
454
|
+
Input tensor with shape (batch_size, n_chans, n_times). NaN marks
|
|
455
|
+
a missing sample.
|
|
456
|
+
mask : torch.Tensor of bool, optional
|
|
457
|
+
Same shape as ``x``. True samples count as missing.
|
|
458
|
+
|
|
459
|
+
Returns
|
|
460
|
+
-------
|
|
461
|
+
dict of torch.Tensor
|
|
462
|
+
``"foundation"``, the tokens with shape (batch_size, n_pairs,
|
|
463
|
+
n_patches, embed_dim), zero at the invalid patches, and
|
|
464
|
+
``"valid"``, the boolean patch validity with shape (batch_size,
|
|
465
|
+
n_pairs, n_patches). These are the names of the reference.
|
|
466
|
+
"""
|
|
467
|
+
# Shapes use the symbols of the class docstring: C pairs, P patches of
|
|
468
|
+
# Q samples, tokens of width D.
|
|
469
|
+
|
|
470
|
+
# Samples hidden by ``mask`` are missing data, like NaN
|
|
471
|
+
# (batch, 2C, n_times), unchanged
|
|
472
|
+
if mask is not None:
|
|
473
|
+
x = x.masked_fill(mask, float("nan"))
|
|
474
|
+
n_times = x.shape[-1]
|
|
475
|
+
|
|
476
|
+
# The window is cut into whole patches of Q samples: a partial last
|
|
477
|
+
# patch is refused, padded or cropped (on_non_divisible)
|
|
478
|
+
# (batch, 2C, n_times) -> (batch, 2C, P * Q)
|
|
479
|
+
x = pad_or_crop_to_patches(x, self.patch_size, self.on_non_divisible)
|
|
480
|
+
|
|
481
|
+
# The two chromophores of each source-detector pair
|
|
482
|
+
# (batch, 2C, P * Q) -> HbO (batch, C, P * Q) and HbR (batch, C, P * Q)
|
|
483
|
+
hbo, hbr = fnirs_split_hbo_hbr(x, self.channel_order)
|
|
484
|
+
batch_size, n_pairs, _ = hbo.shape
|
|
485
|
+
|
|
486
|
+
# Sample validity: a sample counts when both chromophores are finite.
|
|
487
|
+
# The samples added by the padding do not count
|
|
488
|
+
# -> (batch, C, P * Q), bool
|
|
489
|
+
hbo_valid = torch.isfinite(hbo)
|
|
490
|
+
hbr_valid = torch.isfinite(hbr)
|
|
491
|
+
valid_samples = hbo_valid & hbr_valid
|
|
492
|
+
valid_samples[:, :, n_times:] = False
|
|
493
|
+
|
|
494
|
+
# Patch validity: a patch is encoded when at least
|
|
495
|
+
# ceil(minimum_patch_valid_fraction * Q) of its samples are valid
|
|
496
|
+
# (batch, C, P * Q) -> (batch, C, P), bool
|
|
497
|
+
n_valid_samples = self.count_valid_samples(valid_samples)
|
|
498
|
+
valid_patches = n_valid_samples >= self.min_valid_samples
|
|
499
|
+
|
|
500
|
+
# The same validity with one row per pair, as the encoder reads the
|
|
501
|
+
# tokens, and its complement
|
|
502
|
+
# (batch, C, P) -> (batch * C, P), bool
|
|
503
|
+
valid_tokens = self.merge_pairs(valid_patches)
|
|
504
|
+
invalid_tokens = ~valid_tokens
|
|
505
|
+
|
|
506
|
+
# Invalid samples are set to zero before the projection, as in the
|
|
507
|
+
# reference
|
|
508
|
+
# (batch, C, P * Q) each, unchanged
|
|
509
|
+
hbo = torch.where(valid_samples, hbo, 0.0)
|
|
510
|
+
hbr = torch.where(valid_samples, hbr, 0.0)
|
|
511
|
+
|
|
512
|
+
# Patch tokenization: HbO and HbR are paired sample by sample ...
|
|
513
|
+
# -> (batch, C, P * Q, 2)
|
|
514
|
+
x = torch.stack((hbo, hbr), dim=-1)
|
|
515
|
+
# ... and cut into patches [HbO_t, HbR_t, HbO_t+1, HbR_t+1, ...], with
|
|
516
|
+
# each pair as a sequence of its own
|
|
517
|
+
# (batch, C, P * Q, 2) -> (batch * C, P, 2 * Q)
|
|
518
|
+
x = self.to_patches(x)
|
|
519
|
+
|
|
520
|
+
# Patch embedding: linear projection of each patch to a token,
|
|
521
|
+
# z = W patch + b
|
|
522
|
+
# (batch * C, P, 2 * Q) -> (batch * C, P, D)
|
|
523
|
+
x = self.patch_embed(x)
|
|
524
|
+
|
|
525
|
+
# Fixed sinusoidal encoding PE(p) of the patch index p, added to the
|
|
526
|
+
# tokens. It is computed in float32 at least and then cast, which is
|
|
527
|
+
# what the reference does in half precision
|
|
528
|
+
# (P, D), broadcast over the batch * C sequences
|
|
529
|
+
_, n_patches, embed_dim = x.shape
|
|
530
|
+
positions_dtype = torch.promote_types(x.dtype, torch.float32)
|
|
531
|
+
positions = sinusoidal_positional_encoding(
|
|
532
|
+
n_patches, embed_dim, device=x.device, dtype=positions_dtype
|
|
533
|
+
)
|
|
534
|
+
positions = positions.to(x.dtype)
|
|
535
|
+
x = x + positions
|
|
536
|
+
|
|
537
|
+
# Invalid patches are hidden from the attention as keys. A pair without
|
|
538
|
+
# any valid patch keeps all its keys, because a softmax over no key is
|
|
539
|
+
# NaN; its tokens are zeroed below
|
|
540
|
+
# (batch * C, P), bool
|
|
541
|
+
has_valid_token = valid_tokens.any(dim=-1, keepdim=True)
|
|
542
|
+
key_padding_mask = invalid_tokens & has_valid_token
|
|
543
|
+
|
|
544
|
+
# Transformer encoder over the P tokens of each pair, with the same
|
|
545
|
+
# weights for every pair
|
|
546
|
+
# (batch * C, P, D), unchanged
|
|
547
|
+
x = self.encoder(x, src_key_padding_mask=key_padding_mask)
|
|
548
|
+
|
|
549
|
+
# The token of an invalid patch is zero, so a pair without data gives
|
|
550
|
+
# zero features
|
|
551
|
+
# (batch * C, P, D), unchanged
|
|
552
|
+
invalid_tokens = self.to_token_mask(invalid_tokens)
|
|
553
|
+
x = x.masked_fill(invalid_tokens, 0.0)
|
|
554
|
+
|
|
555
|
+
# The pairs back on their own axis
|
|
556
|
+
# (batch * C, P, D) -> (batch, C, P, D)
|
|
557
|
+
x = x.unflatten(0, [batch_size, n_pairs])
|
|
558
|
+
return {"foundation": x, "valid": valid_patches}
|
|
559
|
+
|
|
560
|
+
def reset_head(self, n_outputs: int) -> None:
|
|
561
|
+
self._set_n_outputs(n_outputs)
|
|
562
|
+
# A new classifier over the same C * P * D features
|
|
563
|
+
self.final_layer = nn.Linear(self.final_layer.in_features, n_outputs)
|
|
564
|
+
# Drawn as the constructor draws it (_init_parameters)
|
|
565
|
+
nn.init.xavier_uniform_(self.final_layer.weight)
|
|
566
|
+
nn.init.zeros_(self.final_layer.bias)
|
|
567
|
+
|
|
568
|
+
def load_state_dict(self, state_dict, strict: bool = True, assign: bool = False):
|
|
569
|
+
"""Load a state dict, or the ``jung_mae.pt`` payload as released.
|
|
570
|
+
|
|
571
|
+
The payload keeps the weights under ``"model"`` and has the
|
|
572
|
+
pretraining decoder, which is dropped. A state dict without
|
|
573
|
+
``final_layer`` keeps the head of this model.
|
|
574
|
+
"""
|
|
575
|
+
# The released file is a payload with the weights under "model"
|
|
576
|
+
state_dict = state_dict.get("model", state_dict)
|
|
577
|
+
# The pretraining decoder (its input projection, mask token, layers and
|
|
578
|
+
# prediction layer) is not part of this class
|
|
579
|
+
decoder_keys = ("decoder_embed.", "mask_token", "decoder.", "prediction.")
|
|
580
|
+
state_dict = {
|
|
581
|
+
key: value
|
|
582
|
+
for key, value in state_dict.items()
|
|
583
|
+
if not key.startswith(decoder_keys)
|
|
584
|
+
}
|
|
585
|
+
# The checkpoint has no classifier: the one of this model is kept, so
|
|
586
|
+
# that a strict load of the encoder passes
|
|
587
|
+
head = {}
|
|
588
|
+
if not any(key.startswith("final_layer.") for key in state_dict):
|
|
589
|
+
head = self.final_layer.state_dict(prefix="final_layer.")
|
|
590
|
+
state_dict.update(head)
|
|
591
|
+
result = super().load_state_dict(state_dict, strict=strict, assign=assign)
|
|
592
|
+
provenance = self.__dict__.get("_pretrained_provenance")
|
|
593
|
+
if provenance is not None:
|
|
594
|
+
# The head was supplied by this model, not by the checkpoint
|
|
595
|
+
provenance["loaded"].difference_update(head)
|
|
596
|
+
return result
|