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
|
@@ -164,6 +164,7 @@ class PBT(EEGModuleMixin, nn.Module):
|
|
|
164
164
|
----------
|
|
165
165
|
d_input : int, optional
|
|
166
166
|
Size (in samples) of each patch (token) extracted along the time axis.
|
|
167
|
+
Each channel must contain at least one complete patch.
|
|
167
168
|
embed_dim : int, optional
|
|
168
169
|
Transformer embedding dimensionality.
|
|
169
170
|
num_layers : int, optional
|
|
@@ -225,6 +226,11 @@ class PBT(EEGModuleMixin, nn.Module):
|
|
|
225
226
|
sfreq=sfreq,
|
|
226
227
|
)
|
|
227
228
|
del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
|
|
229
|
+
if not 0 < d_input <= self.n_times:
|
|
230
|
+
raise ValueError(
|
|
231
|
+
f"PBT requires 0 < d_input <= n_times to form a patch per channel, "
|
|
232
|
+
f"got d_input={d_input} and n_times={self.n_times}."
|
|
233
|
+
)
|
|
228
234
|
# Store hyperparameters
|
|
229
235
|
self.d_input = d_input
|
|
230
236
|
self.embed_dim = embed_dim
|
|
@@ -232,7 +238,7 @@ class PBT(EEGModuleMixin, nn.Module):
|
|
|
232
238
|
self.num_heads = num_heads
|
|
233
239
|
self.drop_prob = drop_prob
|
|
234
240
|
|
|
235
|
-
#
|
|
241
|
+
# Retain the size of the positional table in released checkpoints.
|
|
236
242
|
self.num_embeddings = (self.n_chans * self.n_times) // self.d_input
|
|
237
243
|
|
|
238
244
|
# Classification token (learnable or fixed zero)
|
|
@@ -285,23 +291,21 @@ class PBT(EEGModuleMixin, nn.Module):
|
|
|
285
291
|
self.apply(_init_weights)
|
|
286
292
|
|
|
287
293
|
def forward(self, X: torch.Tensor) -> torch.Tensor:
|
|
288
|
-
"""
|
|
289
|
-
|
|
290
|
-
- split input into windows of size `(num_embeddings - 1) * d_input`
|
|
291
|
-
- for each window: reshape into tokens, map positional indices to embeddings,
|
|
292
|
-
add cls token, run Transformer encoder and collect CLS outputs
|
|
293
|
-
- aggregate CLS outputs across windows (if >1) and pass through `final_layer`
|
|
294
|
+
"""Classify a window from the transformer output of its class token.
|
|
294
295
|
|
|
295
296
|
Parameters
|
|
296
297
|
----------
|
|
297
298
|
X : torch.Tensor
|
|
298
|
-
Input tensor with shape (batch_size, n_chans, n_times)
|
|
299
|
+
Input tensor with shape (batch_size, n_chans, n_times). Each
|
|
300
|
+
channel contributes its complete patches within the configured window.
|
|
299
301
|
|
|
300
302
|
Returns
|
|
301
303
|
-------
|
|
302
304
|
torch.Tensor
|
|
303
305
|
Output logits with shape (batch_size, n_outputs).
|
|
304
306
|
"""
|
|
307
|
+
if X.size(1) != self.n_chans:
|
|
308
|
+
raise ValueError(f"PBT expects {self.n_chans} channels, got {X.size(1)}.")
|
|
305
309
|
X, int_pos = self.patch_signal(X)
|
|
306
310
|
|
|
307
311
|
tokens = self.patching_projection(X)
|
|
@@ -622,7 +626,7 @@ class _Patcher(nn.Module):
|
|
|
622
626
|
def __init__(self, n_chans=2, n_times=1000, d_input=64) -> None:
|
|
623
627
|
super().__init__()
|
|
624
628
|
self.d_input = d_input
|
|
625
|
-
self.num_tokens =
|
|
629
|
+
self.num_tokens = n_chans * (n_times // d_input)
|
|
626
630
|
|
|
627
631
|
def forward(self, X: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
628
632
|
"""Returns patched input together with positional indices
|
|
@@ -635,16 +639,23 @@ class _Patcher(nn.Module):
|
|
|
635
639
|
|
|
636
640
|
Returns
|
|
637
641
|
-------
|
|
638
|
-
x_patched: torch.
|
|
639
|
-
Tensor of shape (B,
|
|
642
|
+
x_patched: torch.Tensor
|
|
643
|
+
Tensor of shape (B, C*(T//d_input), d_input) containing the patches. Each
|
|
644
|
+
patch lies within one channel; trailing samples that do not fill a patch
|
|
645
|
+
are dropped.
|
|
640
646
|
|
|
641
647
|
position: torch.LongTensor
|
|
642
|
-
Tensor of shape (
|
|
648
|
+
Tensor of shape (C*(T//d_input) + 1) containing positional token indices.
|
|
643
649
|
"""
|
|
644
650
|
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
651
|
+
# Old pickles store floor(C*T/D) in num_tokens. Integer division by C
|
|
652
|
+
# gives floor(T/D) for both that count and the current C*floor(T/D).
|
|
653
|
+
n_chans = X.size(1)
|
|
654
|
+
n_patches = self.num_tokens // n_chans
|
|
655
|
+
if n_patches == 0:
|
|
656
|
+
raise ValueError("PBT requires at least one complete patch per channel.")
|
|
657
|
+
x_patched = X[..., : n_patches * self.d_input].reshape(
|
|
658
|
+
X.size(0), n_chans * n_patches, self.d_input
|
|
648
659
|
)
|
|
649
660
|
|
|
650
661
|
position = torch.arange(x_patched.size(1) + 1, device=X.device)
|
braindecode/models/reve.py
CHANGED
|
@@ -697,10 +697,7 @@ class Attention(nn.Module):
|
|
|
697
697
|
q = q.unflatten(-1, (self.heads, -1)).transpose(1, 2)
|
|
698
698
|
k = k.unflatten(-1, (self.heads, -1)).transpose(1, 2)
|
|
699
699
|
v = v.unflatten(-1, (self.heads, -1)).transpose(1, 2)
|
|
700
|
-
|
|
701
|
-
out = scaled_dot_product_attention(
|
|
702
|
-
q, k, v, attn_mask=attn_mask, fused_in_lazy=True
|
|
703
|
-
)
|
|
700
|
+
out = scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
|
|
704
701
|
return self.to_out(out.transpose(1, 2).flatten(2))
|
|
705
702
|
|
|
706
703
|
|
|
@@ -18,7 +18,6 @@ from braindecode.functional import (
|
|
|
18
18
|
scaled_dot_product_attention,
|
|
19
19
|
sinusoidal_positional_encoding,
|
|
20
20
|
)
|
|
21
|
-
from braindecode.functional.attention import _hpu_lazy
|
|
22
21
|
from braindecode.models.base import EEGModuleMixin
|
|
23
22
|
|
|
24
23
|
_DEFAULT_CONV_LAYER_SPEC = ( # downsampling: 128Hz -> 1Hz, receptive field 1.1875s, stride 1s
|
|
@@ -546,7 +545,7 @@ class SignalJEPA(_BaseSignalJEPA):
|
|
|
546
545
|
) -> Union[torch.Tensor, Dict[str, Optional[torch.Tensor]]]:
|
|
547
546
|
local_features = self.feature_encoder(X) # type: ignore
|
|
548
547
|
pos_encoding = self.pos_encoder(local_features) # type: ignore
|
|
549
|
-
local_features
|
|
548
|
+
local_features = local_features + pos_encoding # type: ignore
|
|
550
549
|
contextual_features = self._encode(local_features) # type: ignore
|
|
551
550
|
if return_features:
|
|
552
551
|
out: Dict[str, Optional[torch.Tensor]] = {
|
|
@@ -733,7 +732,7 @@ class SignalJEPA_Contextual(_BaseSignalJEPA):
|
|
|
733
732
|
) -> Union[torch.Tensor, Dict[str, Optional[torch.Tensor]]]:
|
|
734
733
|
local_features = self.feature_encoder(X) # type: ignore
|
|
735
734
|
pos_encoding = self.pos_encoder(local_features) # type: ignore
|
|
736
|
-
local_features
|
|
735
|
+
local_features = local_features + pos_encoding # type: ignore
|
|
737
736
|
contextual_features = self._encode(local_features) # type: ignore
|
|
738
737
|
if return_features:
|
|
739
738
|
out: Dict[str, Optional[torch.Tensor]] = {
|
|
@@ -1430,16 +1429,16 @@ class _ConvFeatureEncoder(nn.Sequential):
|
|
|
1430
1429
|
|
|
1431
1430
|
|
|
1432
1431
|
class _GroupNorm(nn.GroupNorm):
|
|
1433
|
-
"""``nn.GroupNorm``;
|
|
1432
|
+
"""``nn.GroupNorm``; on HPU written out with mean and variance.
|
|
1434
1433
|
|
|
1435
1434
|
In HPU eager mode the backward of torch's group norm compiles new graphs at
|
|
1436
1435
|
every call (about 0.2 s per call on the feature encoder's first block);
|
|
1437
1436
|
the same normalisation from mean/var ops runs from cached kernels.
|
|
1438
|
-
Elsewhere (CPU, CUDA
|
|
1437
|
+
Elsewhere (CPU, CUDA) this is ``F.group_norm``.
|
|
1439
1438
|
"""
|
|
1440
1439
|
|
|
1441
1440
|
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
1442
|
-
if not torch.jit.is_scripting() and x.device.type == "hpu"
|
|
1441
|
+
if not torch.jit.is_scripting() and x.device.type == "hpu":
|
|
1443
1442
|
xg = x.reshape(x.shape[0], self.num_groups, -1)
|
|
1444
1443
|
mean = xg.mean(-1, keepdim=True)
|
|
1445
1444
|
var = xg.var(-1, unbiased=False, keepdim=True)
|
braindecode/models/sleepfm.py
CHANGED
|
@@ -15,7 +15,11 @@ from typing import Dict, List, Optional
|
|
|
15
15
|
import torch
|
|
16
16
|
from torch import nn
|
|
17
17
|
|
|
18
|
-
from braindecode.functional import
|
|
18
|
+
from braindecode.functional import (
|
|
19
|
+
check_ch_mask,
|
|
20
|
+
patch_count,
|
|
21
|
+
sinusoidal_positional_encoding,
|
|
22
|
+
)
|
|
19
23
|
from braindecode.functional.patches import _check_on_non_divisible
|
|
20
24
|
from braindecode.models.base import (
|
|
21
25
|
_RECORD_LOADED_KEYS,
|
|
@@ -86,8 +90,9 @@ class SleepFM(EEGModuleMixin, nn.Module, license="cc-by-nc-4.0"):
|
|
|
86
90
|
The encoder was checked through :class:`SleepFMStager` only (SHHS sleep
|
|
87
91
|
staging, see there); its pretraining was not reproduced.
|
|
88
92
|
|
|
89
|
-
``
|
|
90
|
-
|
|
93
|
+
``ch_mask`` (``(batch, n_chans)``, ``True`` for real channels, as in
|
|
94
|
+
every model and :func:`~braindecode.datasets.pad_channels_collate`)
|
|
95
|
+
keeps the other channels out of every output, and out of the tokenizer's
|
|
91
96
|
batch normalization in training. The official pretraining code normalizes
|
|
92
97
|
zero-padded channels with the real ones; both agree when no channel is
|
|
93
98
|
masked, and always in eval mode.
|
|
@@ -168,6 +173,9 @@ class SleepFM(EEGModuleMixin, nn.Module, license="cc-by-nc-4.0"):
|
|
|
168
173
|
max_seq_length,
|
|
169
174
|
on_non_divisible,
|
|
170
175
|
)
|
|
176
|
+
# Channels of any montage, padded by pad_channels_collate: a recording
|
|
177
|
+
# gets the output it gets alone. SleepFMStager's fixed modality slots
|
|
178
|
+
# keep the release's pooling.
|
|
171
179
|
_add_context_layers(
|
|
172
180
|
self,
|
|
173
181
|
embed_dim,
|
|
@@ -176,6 +184,7 @@ class SleepFM(EEGModuleMixin, nn.Module, license="cc-by-nc-4.0"):
|
|
|
176
184
|
pooling_heads,
|
|
177
185
|
drop_prob,
|
|
178
186
|
max_seq_length,
|
|
187
|
+
pad_invariant=True,
|
|
179
188
|
)
|
|
180
189
|
self.temporal_pooling = _SleepFMAttentionPooling(
|
|
181
190
|
embed_dim, pooling_heads, drop_prob
|
|
@@ -193,6 +202,7 @@ class SleepFM(EEGModuleMixin, nn.Module, license="cc-by-nc-4.0"):
|
|
|
193
202
|
self,
|
|
194
203
|
x: torch.Tensor,
|
|
195
204
|
channel_mask: torch.Tensor | None = None,
|
|
205
|
+
ch_mask: torch.Tensor | None = None,
|
|
196
206
|
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
197
207
|
r"""Return the pooled and the per-patch representations.
|
|
198
208
|
|
|
@@ -212,7 +222,11 @@ class SleepFM(EEGModuleMixin, nn.Module, license="cc-by-nc-4.0"):
|
|
|
212
222
|
x : torch.Tensor
|
|
213
223
|
Input of shape ``(batch, n_chans, n_times)``.
|
|
214
224
|
channel_mask : torch.Tensor | None
|
|
215
|
-
|
|
225
|
+
Deprecated, removed in 2.2: the inverse of ``ch_mask``, ``True`` for
|
|
226
|
+
missing channels. Pass ``ch_mask=~channel_mask``.
|
|
227
|
+
ch_mask : torch.Tensor | None
|
|
228
|
+
Pass by keyword. ``(batch, n_chans)`` mask with ``True`` for real
|
|
229
|
+
channels, see :func:`~braindecode.functional.check_ch_mask`.
|
|
216
230
|
|
|
217
231
|
Returns
|
|
218
232
|
-------
|
|
@@ -221,7 +235,7 @@ class SleepFM(EEGModuleMixin, nn.Module, license="cc-by-nc-4.0"):
|
|
|
221
235
|
contextual_tokens : torch.Tensor
|
|
222
236
|
:math:`h`, shape ``(batch, n_patches, embed_dim)``.
|
|
223
237
|
"""
|
|
224
|
-
mask =
|
|
238
|
+
mask = _missing_channels(_deprecated_channel_mask(ch_mask, channel_mask), x)
|
|
225
239
|
patch_mask: Optional[torch.Tensor] = None
|
|
226
240
|
if mask is None:
|
|
227
241
|
mask = torch.zeros(x.shape[:2], dtype=torch.bool, device=x.device)
|
|
@@ -240,11 +254,16 @@ class SleepFM(EEGModuleMixin, nn.Module, license="cc-by-nc-4.0"):
|
|
|
240
254
|
def forward(
|
|
241
255
|
self,
|
|
242
256
|
x: torch.Tensor,
|
|
257
|
+
return_features: bool | torch.Tensor = False,
|
|
258
|
+
ch_mask: torch.Tensor | None = None,
|
|
243
259
|
channel_mask: torch.Tensor | None = None,
|
|
244
|
-
return_features: bool = False,
|
|
245
260
|
) -> torch.Tensor | dict[str, torch.Tensor | None]:
|
|
246
|
-
"""Return trial logits, or the pooled features
|
|
247
|
-
|
|
261
|
+
"""Return trial logits, or the pooled features; ``ch_mask`` (``True``
|
|
262
|
+
for real channels) and the deprecated ``channel_mask`` are as in
|
|
263
|
+
:meth:`encode`."""
|
|
264
|
+
if isinstance(return_features, torch.Tensor):
|
|
265
|
+
raise TypeError("Pass ch_mask by keyword. True marks real channels.")
|
|
266
|
+
pooled, _ = self.encode(x, channel_mask=channel_mask, ch_mask=ch_mask)
|
|
248
267
|
if return_features:
|
|
249
268
|
out: Dict[str, Optional[torch.Tensor]] = {
|
|
250
269
|
"features": pooled,
|
|
@@ -345,8 +364,8 @@ class SleepFMStager(EEGModuleMixin, nn.Module, license="cc-by-nc-4.0"):
|
|
|
345
364
|
padded patches at the end of shorter recordings. As in the release they
|
|
346
365
|
enter the head as zero embeddings masked out of its Transformer, but the
|
|
347
366
|
LSTM still runs over them, so valid predictions depend on the amount of
|
|
348
|
-
padding (never on its content). ``
|
|
349
|
-
:class:`SleepFM`; a modality without a
|
|
367
|
+
padding (never on its content). ``ch_mask`` (``True`` for real channels)
|
|
368
|
+
works as in :class:`SleepFM`; a modality without a real channel is masked.
|
|
350
369
|
|
|
351
370
|
.. important::
|
|
352
371
|
**Pre-trained Weights Available**
|
|
@@ -550,17 +569,25 @@ class SleepFMStager(EEGModuleMixin, nn.Module, license="cc-by-nc-4.0"):
|
|
|
550
569
|
def forward(
|
|
551
570
|
self,
|
|
552
571
|
x: torch.Tensor,
|
|
553
|
-
|
|
554
|
-
return_features: bool = False,
|
|
572
|
+
return_features: bool | torch.Tensor = False,
|
|
555
573
|
temporal_mask: torch.Tensor | None = None,
|
|
574
|
+
ch_mask: torch.Tensor | None = None,
|
|
575
|
+
channel_mask: torch.Tensor | None = None,
|
|
556
576
|
) -> torch.Tensor | dict[str, torch.Tensor | None]:
|
|
557
|
-
"""Return patch-wise logits, or the per-patch LSTM features.
|
|
577
|
+
"""Return patch-wise logits, or the per-patch LSTM features.
|
|
578
|
+
|
|
579
|
+
``ch_mask`` (``True`` for real channels) and the deprecated
|
|
580
|
+
``channel_mask`` are as in :meth:`SleepFM.encode`; ``temporal_mask`` is
|
|
581
|
+
``True`` for padded patches.
|
|
582
|
+
"""
|
|
583
|
+
if isinstance(return_features, torch.Tensor):
|
|
584
|
+
raise TypeError("Pass ch_mask by keyword. True marks real channels.")
|
|
558
585
|
# The count the tokenizer produces (padded patch included with "pad").
|
|
559
586
|
n_patches = self.patch_embedding.patchify.n_patches(x.shape[-1])
|
|
560
587
|
patch_mask = _check_mask(
|
|
561
588
|
temporal_mask, [x.shape[0], n_patches], x, "temporal_mask"
|
|
562
589
|
)
|
|
563
|
-
mask =
|
|
590
|
+
mask = _missing_channels(_deprecated_channel_mask(ch_mask, channel_mask), x)
|
|
564
591
|
mask_tokens = mask is not None or patch_mask is not None
|
|
565
592
|
if mask is None:
|
|
566
593
|
mask = torch.zeros(x.shape[:2], dtype=torch.bool, device=x.device)
|
|
@@ -712,11 +739,12 @@ class _SleepFMTokenizer(nn.Module):
|
|
|
712
739
|
padded = padding_mask.reshape(-1, 1) # (batch * chans * patch, 1)
|
|
713
740
|
if self.training:
|
|
714
741
|
valid = ~padded[:, 0]
|
|
715
|
-
tokens = x.new_zeros((x.shape[0], self.embed_dim))
|
|
716
742
|
if bool(valid.any()): # BatchNorm of an empty batch is NaN
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
)
|
|
743
|
+
encoded = self.tokenizer(x[valid])
|
|
744
|
+
tokens = encoded.new_zeros((x.shape[0], self.embed_dim))
|
|
745
|
+
tokens = tokens.masked_scatter(~padded, encoded)
|
|
746
|
+
else:
|
|
747
|
+
tokens = x.new_zeros((x.shape[0], self.embed_dim))
|
|
720
748
|
else:
|
|
721
749
|
# Zero the input too, so a non-finite masked value cannot
|
|
722
750
|
# reach the gradients.
|
|
@@ -726,10 +754,16 @@ class _SleepFMTokenizer(nn.Module):
|
|
|
726
754
|
|
|
727
755
|
|
|
728
756
|
class _SleepFMAttentionPooling(nn.Module):
|
|
729
|
-
"""Self-attention, then a masked mean over an unordered set.
|
|
757
|
+
"""Self-attention, then a masked mean over an unordered set.
|
|
758
|
+
|
|
759
|
+
A set of one item skips the attention, as in the release. A set padded to one
|
|
760
|
+
real item runs it, as in the release, unless ``pad_invariant``: then it is
|
|
761
|
+
that item, so the padding does not change a sample's output.
|
|
762
|
+
"""
|
|
730
763
|
|
|
731
|
-
def __init__(self, input_dim, num_heads, drop_prob) -> None:
|
|
764
|
+
def __init__(self, input_dim, num_heads, drop_prob, pad_invariant=False) -> None:
|
|
732
765
|
super().__init__()
|
|
766
|
+
self.pad_invariant = pad_invariant
|
|
733
767
|
self.transformer_layer = nn.TransformerEncoderLayer(
|
|
734
768
|
d_model=input_dim, nhead=num_heads, dropout=drop_prob, batch_first=True
|
|
735
769
|
)
|
|
@@ -755,7 +789,10 @@ class _SleepFMAttentionPooling(nn.Module):
|
|
|
755
789
|
else:
|
|
756
790
|
output = self.transformer_layer(x, src_key_padding_mask=key_padding_mask)
|
|
757
791
|
valid = (~key_padding_mask).unsqueeze(-1).to(output.dtype)
|
|
758
|
-
|
|
792
|
+
n_valid = valid.sum(dim=1)
|
|
793
|
+
output = (output * valid).sum(dim=1) / n_valid
|
|
794
|
+
if self.pad_invariant:
|
|
795
|
+
output = torch.where(n_valid == 1, (x * valid).sum(dim=1), output)
|
|
759
796
|
return output.masked_fill(all_masked, 0)
|
|
760
797
|
|
|
761
798
|
|
|
@@ -803,6 +840,37 @@ class _SleepFMStagingHead(nn.Module):
|
|
|
803
840
|
return features
|
|
804
841
|
|
|
805
842
|
|
|
843
|
+
def _deprecated_channel_mask(
|
|
844
|
+
ch_mask: Optional[torch.Tensor], channel_mask: Optional[torch.Tensor]
|
|
845
|
+
) -> Optional[torch.Tensor]:
|
|
846
|
+
"""``ch_mask`` from the deprecated ``channel_mask``, ``True`` for missing
|
|
847
|
+
channels (braindecode 2.0)."""
|
|
848
|
+
if channel_mask is None:
|
|
849
|
+
return ch_mask
|
|
850
|
+
if ch_mask is not None:
|
|
851
|
+
raise ValueError("Pass ch_mask only: channel_mask is its deprecated inverse.")
|
|
852
|
+
if not torch.jit.is_scripting():
|
|
853
|
+
warnings.warn(
|
|
854
|
+
"channel_mask (True for missing channels) is deprecated and will be "
|
|
855
|
+
"removed in braindecode 2.2; pass ch_mask=~channel_mask (True for "
|
|
856
|
+
"real channels).",
|
|
857
|
+
FutureWarning,
|
|
858
|
+
stacklevel=3,
|
|
859
|
+
)
|
|
860
|
+
return ~channel_mask.to(torch.bool)
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
def _missing_channels(
|
|
864
|
+
ch_mask: Optional[torch.Tensor], x: torch.Tensor
|
|
865
|
+
) -> Optional[torch.Tensor]:
|
|
866
|
+
"""The ``(batch, n_chans)`` mask of missing channels the encoders use, from
|
|
867
|
+
``ch_mask`` (``True`` for real channels)."""
|
|
868
|
+
real = check_ch_mask(ch_mask, x)
|
|
869
|
+
if real is None:
|
|
870
|
+
return None
|
|
871
|
+
return ~real
|
|
872
|
+
|
|
873
|
+
|
|
806
874
|
def _check_mask(
|
|
807
875
|
mask: Optional[torch.Tensor], shape: List[int], x: torch.Tensor, name: str
|
|
808
876
|
) -> Optional[torch.Tensor]:
|
|
@@ -817,7 +885,14 @@ def _check_mask(
|
|
|
817
885
|
|
|
818
886
|
|
|
819
887
|
def _add_context_layers(
|
|
820
|
-
module,
|
|
888
|
+
module,
|
|
889
|
+
embed_dim,
|
|
890
|
+
num_heads,
|
|
891
|
+
num_layers,
|
|
892
|
+
pooling_heads,
|
|
893
|
+
drop_prob,
|
|
894
|
+
n_positions,
|
|
895
|
+
pad_invariant=False,
|
|
821
896
|
):
|
|
822
897
|
"""Add the set pooling, positional table, LayerNorm and pre-norm Transformer.
|
|
823
898
|
|
|
@@ -826,7 +901,7 @@ def _add_context_layers(
|
|
|
826
901
|
released one differs from a CPU recomputation in the last float32 bits.
|
|
827
902
|
"""
|
|
828
903
|
module.spatial_pooling = _SleepFMAttentionPooling(
|
|
829
|
-
embed_dim, pooling_heads, drop_prob
|
|
904
|
+
embed_dim, pooling_heads, drop_prob, pad_invariant
|
|
830
905
|
)
|
|
831
906
|
module.register_buffer(
|
|
832
907
|
"positional_encoding",
|
braindecode/models/summary.csv
CHANGED
|
@@ -91,3 +91,10 @@ Guetschel2026,General,"Prediction, Embedding",200,"chs_info, n_outputs, n_times"
|
|
|
91
91
|
GCNsNet,Motor Imagery,Prediction,160,"n_chans, n_outputs, n_times",359428,"GCNsNet(n_chans=64, n_outputs=4, n_times=640)","Graph Neural Network,Channel",EEG
|
|
92
92
|
NICE,Visual Decoding,"Prediction, Embedding",250,"n_chans, n_outputs, n_times",1956296,"NICE(n_chans=63, n_outputs=200, n_times=250)",Convolution,"EEG, MEG"
|
|
93
93
|
FNIRSNet,General,Prediction,10,"n_chans, n_outputs, n_times",498,"FNIRSNet(n_chans=72, n_outputs=2, n_times=30)","Convolution",fNIRS
|
|
94
|
+
FNIRS4D,General,Prediction,10,"n_chans, n_outputs, n_times",89894,"FNIRS4D(n_chans=72, n_outputs=2, n_times=30)","Convolution,Recurrent",fNIRS
|
|
95
|
+
FNIRST,General,Prediction,10,"n_chans, n_outputs, n_times",1728978,"FNIRST(n_chans=72, n_outputs=2, n_times=200)","Convolution,Attention/Transformer",fNIRS
|
|
96
|
+
FNIRSPreT,General,Prediction,10,"n_chans, n_outputs, n_times",1729778,"FNIRSPreT(n_chans=72, n_outputs=2, n_times=200)","Convolution,Attention/Transformer",fNIRS
|
|
97
|
+
GeoNIRS,General,"Prediction, Embedding",5,"chs_info, n_outputs, n_times",4504904,"GeoNIRS(chs_info=<user>, n_outputs=2, n_times=150, sfreq=5.0)","Attention/Transformer,Channel,Foundation Model",fNIRS
|
|
98
|
+
MtReNIRS,General,"Prediction, Embedding",10,"chs_info, n_outputs, n_times",1231490,"MtReNIRS(chs_info=<user>, n_outputs=2, n_times=100, sfreq=10.0)","Attention/Transformer,Channel,Foundation Model",fNIRS
|
|
99
|
+
JungMAE,General,"Prediction, Embedding",5,"n_chans, n_outputs, n_times",1899074,"JungMAE(n_chans=40, n_outputs=2, n_times=150, sfreq=5.0)","Attention/Transformer,Foundation Model",fNIRS
|
|
100
|
+
FNIRSCNN1D,General,Prediction,5,"n_chans, n_outputs",59714,"FNIRSCNN1D(n_chans=40, n_outputs=2, n_times=60, sfreq=5.0)",Convolution,fNIRS
|
braindecode/models/util.py
CHANGED
|
@@ -20,6 +20,7 @@ from typing import (
|
|
|
20
20
|
Literal,
|
|
21
21
|
Optional,
|
|
22
22
|
Sequence,
|
|
23
|
+
Tuple,
|
|
23
24
|
cast,
|
|
24
25
|
get_args,
|
|
25
26
|
get_origin,
|
|
@@ -364,7 +365,7 @@ _rng = np.random.default_rng(12)
|
|
|
364
365
|
def _fixture_montage_chs() -> tuple[tuple[str, tuple[float, ...]], ...]:
|
|
365
366
|
"""Channels of the montage that supplies the test fixtures' real positions.
|
|
366
367
|
|
|
367
|
-
The montage is ``
|
|
368
|
+
The montage is ``colin27_1005``, named ``standard_1005`` before MNE 1.13
|
|
368
369
|
(see :func:`braindecode.util.resolve_montage_name`; the positions are
|
|
369
370
|
identical). The positions are read back from ``info["chs"][i]["loc"]``
|
|
370
371
|
after :meth:`mne.Info.set_montage`, i.e. in the head frame and in metres,
|
|
@@ -602,6 +603,23 @@ def _dance_signal_params() -> dict[str, Any]:
|
|
|
602
603
|
}
|
|
603
604
|
|
|
604
605
|
|
|
606
|
+
def _fnirs_chs_info(n_pairs: int, interleaved: bool = False) -> list[dict]:
|
|
607
|
+
"""Stacked HbO then HbR channels of ``n_pairs`` source-detector pairs 3 cm
|
|
608
|
+
apart on an 8 cm ring (metres), named as MNE names them (``"S1_D1 hbo"``),
|
|
609
|
+
with the source and detector in ``loc[3:9]`` as MNE stores them;
|
|
610
|
+
``interleaved=True`` gives MNE's ``[HbO_1, HbR_1, ...]`` order."""
|
|
611
|
+
chs = []
|
|
612
|
+
for kind in ("hbo", "hbr"):
|
|
613
|
+
for i in range(n_pairs):
|
|
614
|
+
src = np.array([0.08 * np.cos(i), 0.08 * np.sin(i), 0.05])
|
|
615
|
+
det = src + np.array([0.03, 0.0, 0.0])
|
|
616
|
+
loc = np.concatenate([(src + det) / 2, src, det, np.zeros(3)])
|
|
617
|
+
chs.append({"ch_name": f"S{i + 1}_D{i + 1} {kind}", "loc": loc})
|
|
618
|
+
if interleaved:
|
|
619
|
+
chs = [ch for pair in zip(chs[:n_pairs], chs[n_pairs:]) for ch in pair]
|
|
620
|
+
return chs
|
|
621
|
+
|
|
622
|
+
|
|
605
623
|
# (name, required signal parameters, test parameters). The test parameters are
|
|
606
624
|
# signal parameters the default test signal does not fit, plus, for the
|
|
607
625
|
# largest models, architecture arguments that keep the test instance small
|
|
@@ -929,6 +947,43 @@ models_mandatory_parameters: list[
|
|
|
929
947
|
["n_chans", "n_outputs", "n_times"],
|
|
930
948
|
{"n_chans": 4, "n_times": 60, "sfreq": 5.0},
|
|
931
949
|
),
|
|
950
|
+
(
|
|
951
|
+
"FNIRSCNN1D",
|
|
952
|
+
["n_chans", "n_outputs"],
|
|
953
|
+
{"n_chans": 4, "n_times": 60, "sfreq": 5.0},
|
|
954
|
+
),
|
|
955
|
+
(
|
|
956
|
+
"FNIRS4D",
|
|
957
|
+
["n_chans", "n_outputs", "n_times"],
|
|
958
|
+
lambda: {"chs_info": _fnirs_chs_info(2), "n_times": 60, "sfreq": 5.0},
|
|
959
|
+
),
|
|
960
|
+
(
|
|
961
|
+
"FNIRST",
|
|
962
|
+
["n_chans", "n_outputs", "n_times"],
|
|
963
|
+
# 5 pairs: the authors' spatial kernel spans 5 HbO/HbR pairs
|
|
964
|
+
lambda: {"chs_info": _fnirs_chs_info(5), "n_times": 60, "sfreq": 5.0},
|
|
965
|
+
),
|
|
966
|
+
(
|
|
967
|
+
"FNIRSPreT",
|
|
968
|
+
["n_chans", "n_outputs", "n_times"],
|
|
969
|
+
# 5 pairs: the authors' spatial kernel spans 5 HbO/HbR pairs
|
|
970
|
+
lambda: {"chs_info": _fnirs_chs_info(5), "n_times": 60, "sfreq": 5.0},
|
|
971
|
+
),
|
|
972
|
+
(
|
|
973
|
+
"GeoNIRS",
|
|
974
|
+
["chs_info", "n_outputs", "n_times"],
|
|
975
|
+
lambda: {"chs_info": _fnirs_chs_info(2), "n_times": 150, "sfreq": 5.0},
|
|
976
|
+
),
|
|
977
|
+
(
|
|
978
|
+
"MtReNIRS",
|
|
979
|
+
["chs_info", "n_outputs", "n_times"],
|
|
980
|
+
lambda: {"chs_info": _fnirs_chs_info(2), "n_times": 100, "sfreq": 10.0},
|
|
981
|
+
),
|
|
982
|
+
(
|
|
983
|
+
"JungMAE",
|
|
984
|
+
["n_chans", "n_outputs", "n_times"],
|
|
985
|
+
lambda: {"chs_info": _fnirs_chs_info(2), "n_times": 150, "sfreq": 5.0},
|
|
986
|
+
),
|
|
932
987
|
]
|
|
933
988
|
|
|
934
989
|
################################################################
|
|
@@ -1354,3 +1409,86 @@ def channel_types_from_chs_info(
|
|
|
1354
1409
|
else:
|
|
1355
1410
|
types.append("unknown")
|
|
1356
1411
|
return types
|
|
1412
|
+
|
|
1413
|
+
|
|
1414
|
+
def fnirs_chromophores_from_chs_info(chs_info: Sequence[Dict[str, Any]]) -> list[str]:
|
|
1415
|
+
"""``"hbo"``, ``"hbr"`` or ``"unknown"`` per channel, from MNE's
|
|
1416
|
+
``coil_type`` (``FIFFV_COIL_FNIRS_HBO`` / ``_HBR``), else from the
|
|
1417
|
+
``" hbo"`` / ``" hbr"`` suffix of its name (MNE names them ``"S1_D1 hbo"``)
|
|
1418
|
+
or its ``"kind"``."""
|
|
1419
|
+
coils = {FIFF.FIFFV_COIL_FNIRS_HBO: "hbo", FIFF.FIFFV_COIL_FNIRS_HBR: "hbr"}
|
|
1420
|
+
out = []
|
|
1421
|
+
for ch in chs_info:
|
|
1422
|
+
suffix = str(ch.get("ch_name", "")).lower().rsplit(" ", 1)[-1]
|
|
1423
|
+
kind = str(ch.get("kind", "")).lower()
|
|
1424
|
+
by_name = next((k for k in (suffix, kind) if k in ("hbo", "hbr")), "unknown")
|
|
1425
|
+
out.append(coils.get(int(ch.get("coil_type") or 0), by_name))
|
|
1426
|
+
return out
|
|
1427
|
+
|
|
1428
|
+
|
|
1429
|
+
def fnirs_channel_order(
|
|
1430
|
+
chs_info: Optional[Sequence[Dict[str, Any]]], channel_order: Optional[str] = None
|
|
1431
|
+
) -> str:
|
|
1432
|
+
"""HbO/HbR pair layout of an fNIRS montage: ``"stacked"``
|
|
1433
|
+
(``[HbO_1..HbO_C, HbR_1..HbR_C]``) or ``"interleaved"`` (MNE's
|
|
1434
|
+
``[HbO_1, HbR_1, ...]``).
|
|
1435
|
+
|
|
1436
|
+
Without ``chs_info`` it returns ``channel_order``, or ``"stacked"``. With
|
|
1437
|
+
``chs_info`` every channel must be HbO or HbR, in equal numbers, and the
|
|
1438
|
+
``i``-th HbO and HbR channels must share their name up to the chromophore
|
|
1439
|
+
suffix (``"S1_D1 hbo"`` / ``"S1_D1 hbr"``); the layout is read from it, and
|
|
1440
|
+
an explicit ``channel_order`` must agree.
|
|
1441
|
+
|
|
1442
|
+
Raises ``ValueError`` for an unknown ``channel_order``, a ``chs_info``
|
|
1443
|
+
that is not paired HbO/HbR, or a ``channel_order`` it contradicts.
|
|
1444
|
+
"""
|
|
1445
|
+
if channel_order not in (None, "stacked", "interleaved"):
|
|
1446
|
+
raise ValueError(
|
|
1447
|
+
"channel_order must be 'stacked', 'interleaved' or None, "
|
|
1448
|
+
f"got {channel_order!r}."
|
|
1449
|
+
)
|
|
1450
|
+
if not chs_info:
|
|
1451
|
+
return channel_order or "stacked"
|
|
1452
|
+
chromophores = fnirs_chromophores_from_chs_info(chs_info)
|
|
1453
|
+
names = [str(ch.get("ch_name", "")).rsplit(" ", 1)[0] for ch in chs_info]
|
|
1454
|
+
n = len(chs_info) // 2
|
|
1455
|
+
layouts = {"stacked": (slice(0, n), slice(n, None))}
|
|
1456
|
+
layouts["interleaved"] = (slice(0, None, 2), slice(1, None, 2))
|
|
1457
|
+
found = [
|
|
1458
|
+
order
|
|
1459
|
+
for order, (hbo, hbr) in layouts.items()
|
|
1460
|
+
if chromophores[hbo] == ["hbo"] * n
|
|
1461
|
+
and chromophores[hbr] == ["hbr"] * n
|
|
1462
|
+
and names[hbo] == names[hbr]
|
|
1463
|
+
]
|
|
1464
|
+
if not found:
|
|
1465
|
+
raise ValueError(
|
|
1466
|
+
"chs_info must list paired HbO/HbR channels, stacked or interleaved, "
|
|
1467
|
+
"with matching names (see mne's reorder_channels); got "
|
|
1468
|
+
f"{list(zip(names, chromophores))}."
|
|
1469
|
+
)
|
|
1470
|
+
if channel_order is not None and channel_order not in found:
|
|
1471
|
+
raise ValueError(
|
|
1472
|
+
f"channel_order={channel_order!r} contradicts chs_info, which is "
|
|
1473
|
+
f"{found[0]}."
|
|
1474
|
+
)
|
|
1475
|
+
return channel_order or found[0]
|
|
1476
|
+
|
|
1477
|
+
|
|
1478
|
+
def fnirs_split_hbo_hbr(
|
|
1479
|
+
x: torch.Tensor, channel_order: str
|
|
1480
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
1481
|
+
"""Split fNIRS channels into their HbO and HbR halves.
|
|
1482
|
+
|
|
1483
|
+
The one HbO/HbR split of the fNIRS models: ``x`` is
|
|
1484
|
+
``(batch, n_chans, ...)`` with an even ``n_chans`` in the ``channel_order``
|
|
1485
|
+
given by :func:`fnirs_channel_order`. Returns ``(hbo, hbr)``, each
|
|
1486
|
+
``(batch, n_chans // 2, ...)``, where ``hbo[:, i]`` and ``hbr[:, i]`` are
|
|
1487
|
+
the two chromophores of pair ``i``.
|
|
1488
|
+
"""
|
|
1489
|
+
if channel_order == "interleaved": # [HbO_1, HbR_1, HbO_2, HbR_2, ...]
|
|
1490
|
+
return x[:, 0::2], x[:, 1::2]
|
|
1491
|
+
if channel_order == "stacked": # [HbO_1, ..., HbO_C, HbR_1, ..., HbR_C]
|
|
1492
|
+
n_pairs = x.shape[1] // 2
|
|
1493
|
+
return x[:, :n_pairs], x[:, n_pairs:]
|
|
1494
|
+
raise ValueError("channel_order must be 'stacked' or 'interleaved'.")
|
braindecode/models/zuna.py
CHANGED
|
@@ -16,7 +16,6 @@ from einops.layers.torch import Rearrange
|
|
|
16
16
|
from torch import nn
|
|
17
17
|
|
|
18
18
|
from braindecode.functional import scaled_dot_product_attention
|
|
19
|
-
from braindecode.functional.attention import _hpu_lazy
|
|
20
19
|
from braindecode.models.base import EEGModuleMixin
|
|
21
20
|
from braindecode.models.util import (
|
|
22
21
|
extract_channel_locations_from_chs_info,
|
|
@@ -404,14 +403,9 @@ def _channel_positions(chs_info, n_chans):
|
|
|
404
403
|
names = [str(chs_info[i].get("ch_name", "")) for i in missing]
|
|
405
404
|
unknown = [n for n in names if not n]
|
|
406
405
|
if not unknown:
|
|
407
|
-
montage = (
|
|
408
|
-
"colin27_1005" # standard_1005's name from MNE 1.13
|
|
409
|
-
if "colin27_1005" in mne.channels.get_builtin_montages()
|
|
410
|
-
else "standard_1005"
|
|
411
|
-
)
|
|
412
406
|
info = mne.create_info(names, 256.0, "eeg")
|
|
413
407
|
info.set_montage(
|
|
414
|
-
|
|
408
|
+
"colin27_1005", match_case=False, match_alias=True, on_missing="ignore"
|
|
415
409
|
)
|
|
416
410
|
filled = np.array([ch["loc"][:3] for ch in info["chs"]], dtype=locs.dtype)
|
|
417
411
|
ok = np.isfinite(filled).all(1) & filled.any(1)
|
|
@@ -471,9 +465,7 @@ class _RotaryPositionEmbedding(nn.Module):
|
|
|
471
465
|
rotary_sine: torch.Tensor,
|
|
472
466
|
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
473
467
|
if not torch.jit.is_scripting() and query.device.type == "hpu":
|
|
474
|
-
|
|
475
|
-
if fused is not None:
|
|
476
|
-
return fused
|
|
468
|
+
return _hpu_fused_rotary(query, key, rotary_cosine, rotary_sine)
|
|
477
469
|
rotary_cosine = rotary_cosine.unsqueeze(0).unsqueeze(2)
|
|
478
470
|
rotary_sine = rotary_sine.unsqueeze(0).unsqueeze(2)
|
|
479
471
|
|
|
@@ -548,21 +540,16 @@ def _hpu_fused_rotary(
|
|
|
548
540
|
key: torch.Tensor,
|
|
549
541
|
rotary_cosine: torch.Tensor,
|
|
550
542
|
rotary_sine: torch.Tensor,
|
|
551
|
-
) ->
|
|
552
|
-
"""``_RotaryPositionEmbedding``
|
|
553
|
-
|
|
554
|
-
Gaudi's fused pairwise RoPE kernel.
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
tokens per batch in eager mode); the kernel does it in one pass, also inside
|
|
561
|
-
a compiled region. Same float32 arithmetic, so the outputs are identical;
|
|
562
|
-
the gradient is rounded to the input dtype once instead of once per term.
|
|
543
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
544
|
+
"""``_RotaryPositionEmbedding`` on HPU, eager and compiled.
|
|
545
|
+
|
|
546
|
+
Gaudi's fused pairwise RoPE kernel. The formula runs as about ten
|
|
547
|
+
element-wise ops on float32 copies of the queries and keys (a quarter of a
|
|
548
|
+
ZUNA block's train-step time at 107,520 tokens per batch in eager mode);
|
|
549
|
+
the kernel does it in one pass, also inside a compiled region. Same float32
|
|
550
|
+
arithmetic, so the outputs are identical; the gradient is rounded to the
|
|
551
|
+
input dtype once instead of once per term.
|
|
563
552
|
"""
|
|
564
|
-
if not torch.compiler.is_compiling() and _hpu_lazy():
|
|
565
|
-
return None
|
|
566
553
|
work = torch.promote_types(query.dtype, torch.float32)
|
|
567
554
|
cosine = rotary_cosine.unsqueeze(0).unsqueeze(2)
|
|
568
555
|
# The kernel applies the pair sign itself: pass sin(angle), which is
|