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
braindecode/models/base.py
CHANGED
|
@@ -466,7 +466,12 @@ class EEGModuleMixin(_BaseHubMixin, metaclass=_BraindecodeDocstringMeta):
|
|
|
466
466
|
"Modifying chs_info argument using the _deserialize_chs_info() method"
|
|
467
467
|
)
|
|
468
468
|
|
|
469
|
-
if
|
|
469
|
+
if ( # under a channel_strategy the input montage changes per call
|
|
470
|
+
channel_strategy == "native"
|
|
471
|
+
and n_chans is not None
|
|
472
|
+
and chs_info is not None
|
|
473
|
+
and len(chs_info) != n_chans
|
|
474
|
+
):
|
|
470
475
|
raise ValueError(f"{n_chans=} different from {chs_info=} length")
|
|
471
476
|
if (
|
|
472
477
|
n_times is not None
|
|
@@ -531,23 +536,43 @@ class EEGModuleMixin(_BaseHubMixin, metaclass=_BraindecodeDocstringMeta):
|
|
|
531
536
|
def _channel_forward(self, *args, chs_info=None, ch_names=None, **kwargs):
|
|
532
537
|
"""``forward`` under a channel strategy: map ``x`` (recorded with
|
|
533
538
|
``chs_info``, default the model's) onto the target, then run the backbone."""
|
|
539
|
+
# pad_channels_collate / set_return_ch_pos: pos and ch_mask describe the
|
|
540
|
+
# input montage of each sample; the backbone gets the full target one.
|
|
541
|
+
# pos describes the input channels, never the backbone's mapped ones
|
|
542
|
+
ch_mask, pos = kwargs.pop("ch_mask", None), kwargs.pop("pos", None)
|
|
534
543
|
bound = inspect.signature(type(self).forward).bind_partial(
|
|
535
544
|
self, *args, **kwargs
|
|
536
545
|
)
|
|
537
546
|
if bound.arguments.get("ch_mask") is not None:
|
|
538
|
-
# The channel layer mixes every input channel into each target one,
|
|
539
|
-
# so padding would leak into the real channels.
|
|
540
547
|
raise ValueError(
|
|
541
|
-
"ch_mask
|
|
542
|
-
"
|
|
548
|
+
"Pass ch_mask by keyword under a channel_strategy: the channel layer "
|
|
549
|
+
"uses it to map each sample, the backbone never sees it."
|
|
550
|
+
)
|
|
551
|
+
if chs_info is None and pos is not None and ch_mask is not None: # no names
|
|
552
|
+
mask = (
|
|
553
|
+
torch.ones(pos.shape[:2], dtype=torch.bool)
|
|
554
|
+
if ch_mask is None
|
|
555
|
+
else ch_mask
|
|
556
|
+
)
|
|
557
|
+
chs_info = [
|
|
558
|
+
[
|
|
559
|
+
{"ch_name": f"E{i}", "kind": "eeg", "loc": np.r_[p, np.zeros(9)]}
|
|
560
|
+
for i, p in enumerate(pb[mb.cpu().numpy()])
|
|
561
|
+
]
|
|
562
|
+
for pb, mb in zip(pos.detach().cpu().double().numpy(), mask)
|
|
563
|
+
]
|
|
564
|
+
elif ch_mask is not None and not (chs_info and isinstance(chs_info[0], list)):
|
|
565
|
+
raise ValueError(
|
|
566
|
+
"ch_mask under a channel_strategy needs the montage of each sample: "
|
|
567
|
+
"pos (set_return_ch_pos(True)) or chs_info as a list of montages."
|
|
543
568
|
)
|
|
544
569
|
if chs_info is None and ch_names is not None: # LaBraM: names of x's channels
|
|
545
570
|
chs_info = [{"ch_name": n} for n in ch_names]
|
|
546
571
|
if args:
|
|
547
|
-
args = (self.channel_layer(args[0], chs_info)[0], *args[1:])
|
|
572
|
+
args = (self.channel_layer(args[0], chs_info, ch_mask)[0], *args[1:])
|
|
548
573
|
else: # x by keyword: the backbone's first input (x, X, eeg...)
|
|
549
574
|
x = list(inspect.signature(type(self).forward).parameters)[1]
|
|
550
|
-
kwargs[x] = self.channel_layer(kwargs[x], chs_info)[0]
|
|
575
|
+
kwargs[x] = self.channel_layer(kwargs[x], chs_info, ch_mask)[0]
|
|
551
576
|
return type(self).forward(self, *args, **kwargs)
|
|
552
577
|
|
|
553
578
|
@property
|
|
@@ -891,14 +916,19 @@ class EEGModuleMixin(_BaseHubMixin, metaclass=_BraindecodeDocstringMeta):
|
|
|
891
916
|
|
|
892
917
|
def load_state_dict(self, state_dict, *args, **kwargs):
|
|
893
918
|
mapping = self.mapping if self.mapping else {}
|
|
919
|
+
own = super().state_dict()
|
|
894
920
|
new_state_dict = OrderedDict()
|
|
895
921
|
for k, v in state_dict.items():
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
922
|
+
k = mapping.get(k, k)
|
|
923
|
+
# Checkpoints saved before a weight was parametrized (max-norm
|
|
924
|
+
# constraints) store it as ``weight``; the module now keeps it
|
|
925
|
+
# as ``parametrizations.weight.original``.
|
|
926
|
+
module, _, name = k.rpartition(".")
|
|
927
|
+
parametrized = f"{module}.parametrizations.weight.original".lstrip(".")
|
|
928
|
+
if name == "weight" and k not in own and parametrized in own:
|
|
929
|
+
k = parametrized
|
|
930
|
+
new_state_dict[k] = v
|
|
900
931
|
# A backbone checkpoint has no weights for a trainable channel layer.
|
|
901
|
-
own = super().state_dict()
|
|
902
932
|
# Load hooks may expand tensors with locally initialized values. Only
|
|
903
933
|
# attribute whole tensors whose checkpoint shape already matches.
|
|
904
934
|
from_checkpoint = {
|
|
@@ -1105,7 +1135,7 @@ class EEGModuleMixin(_BaseHubMixin, metaclass=_BraindecodeDocstringMeta):
|
|
|
1105
1135
|
f"Trained on (model card): {', '.join(data['datasets']) or 'not listed'}\n"
|
|
1106
1136
|
f"Loaded from the listed checkpoint(s): {data['loaded']:,} of {data['total']:,} "
|
|
1107
1137
|
f"{scope} ({data['percent']:.1f}% of materialised parameters){new}\n"
|
|
1108
|
-
"Cite Braindecode (Zenodo): https://doi.org/10.5281/zenodo.
|
|
1138
|
+
"Cite Braindecode (Zenodo): https://doi.org/10.5281/zenodo.8214376"
|
|
1109
1139
|
)
|
|
1110
1140
|
|
|
1111
1141
|
def _repr_html_(self) -> str:
|
|
@@ -1182,6 +1212,13 @@ class EEGModuleMixin(_BaseHubMixin, metaclass=_BraindecodeDocstringMeta):
|
|
|
1182
1212
|
|
|
1183
1213
|
config = build_model_config(self)
|
|
1184
1214
|
config["braindecode_version"] = __version__
|
|
1215
|
+
if callable(getattr(getattr(self, "channel_layer", None), "strategy", None)):
|
|
1216
|
+
warnings.warn(
|
|
1217
|
+
"The function channel_strategy is not saved: pass it again to "
|
|
1218
|
+
"from_pretrained(..., channel_strategy=...).",
|
|
1219
|
+
UserWarning,
|
|
1220
|
+
stacklevel=2,
|
|
1221
|
+
)
|
|
1185
1222
|
|
|
1186
1223
|
# Save to config.json
|
|
1187
1224
|
config_path = save_directory / "config.json"
|
braindecode/models/biot.py
CHANGED
|
@@ -534,6 +534,12 @@ class _BIOTEncoder(nn.Module):
|
|
|
534
534
|
# channel's (batch, freq, ts) block is contiguous
|
|
535
535
|
spec = self.stft(x.transpose(0, 1).reshape(n_chans * batch_size, 1, n_times))
|
|
536
536
|
spec = spec.unflatten(0, [n_chans, batch_size])
|
|
537
|
+
# Every channel token in one lookup of a 1-D index, then one row per
|
|
538
|
+
# channel. A 0-d index per channel would also trip Intel Gaudi, whose
|
|
539
|
+
# embedding backward sends a 0-d index's gradient to row 0.
|
|
540
|
+
channel_tokens = self.channel_tokens(
|
|
541
|
+
self.index[n_channel_offset : n_channel_offset + n_chans]
|
|
542
|
+
)
|
|
537
543
|
emb_seq = []
|
|
538
544
|
token_masks = []
|
|
539
545
|
for i in range(n_chans):
|
|
@@ -545,10 +551,9 @@ class _BIOTEncoder(nn.Module):
|
|
|
545
551
|
batch_size, ts, _ = channel_spec_emb.shape
|
|
546
552
|
# (batch_size, ts, emb)
|
|
547
553
|
# Step by step the following lines do the following operations:
|
|
548
|
-
# -
|
|
549
|
-
#
|
|
550
|
-
#
|
|
551
|
-
# which channel's embedding is retrieved.
|
|
554
|
+
# - channel_tokens[i]:
|
|
555
|
+
# The token of channel i + n_channel_offset, where
|
|
556
|
+
# n_channel_offset adjusts which channel's embedding is used.
|
|
552
557
|
# - .unsqueeze(0).unsqueeze(0):
|
|
553
558
|
# Adds two singleton dimensions to the embedding tensor.
|
|
554
559
|
# [emb_size] to [1, 1, emb_size] .
|
|
@@ -556,10 +561,7 @@ class _BIOTEncoder(nn.Module):
|
|
|
556
561
|
# Replicates the embedding tensor to match the batch size and
|
|
557
562
|
# time steps (ts),
|
|
558
563
|
channel_token_emb = (
|
|
559
|
-
|
|
560
|
-
.unsqueeze(0)
|
|
561
|
-
.unsqueeze(0)
|
|
562
|
-
.repeat(batch_size, ts, 1)
|
|
564
|
+
channel_tokens[i].unsqueeze(0).unsqueeze(0).repeat(batch_size, ts, 1)
|
|
563
565
|
)
|
|
564
566
|
# (batch_size, ts, emb)
|
|
565
567
|
# The positional embedding is explaining with more
|
|
@@ -17,7 +17,6 @@ import torchaudio as ta
|
|
|
17
17
|
from torch import nn
|
|
18
18
|
from torch.nn import functional as F
|
|
19
19
|
|
|
20
|
-
from braindecode.functional.attention import _hpu_lazy
|
|
21
20
|
from braindecode.models.base import EEGModuleMixin
|
|
22
21
|
from braindecode.models.util import has_valid_locations, positions_from_chs_info
|
|
23
22
|
from braindecode.modules import ChannelMerger
|
|
@@ -713,7 +712,7 @@ class _ConvSequence(nn.Module):
|
|
|
713
712
|
nn.Conv1d(
|
|
714
713
|
chout, 2 * chout, 1 + 2 * glu_context, padding=glu_context
|
|
715
714
|
),
|
|
716
|
-
|
|
715
|
+
nn.GLU(dim=1),
|
|
717
716
|
)
|
|
718
717
|
)
|
|
719
718
|
else:
|
|
@@ -728,17 +727,6 @@ class _ConvSequence(nn.Module):
|
|
|
728
727
|
return x
|
|
729
728
|
|
|
730
729
|
|
|
731
|
-
class _GLU(nn.GLU):
|
|
732
|
-
"""``nn.GLU`` that Intel Gaudi's lazy mode can compile."""
|
|
733
|
-
|
|
734
|
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
735
|
-
if not torch.jit.is_scripting() and x.device.type == "hpu" and _hpu_lazy():
|
|
736
|
-
# Its graph compiler fails on ``aten.glu`` after a convolution.
|
|
737
|
-
a, b = x.chunk(2, dim=self.dim)
|
|
738
|
-
return a * torch.sigmoid(b)
|
|
739
|
-
return F.glu(x, self.dim)
|
|
740
|
-
|
|
741
|
-
|
|
742
730
|
def _pad_multiple(x: torch.Tensor, base: int) -> torch.Tensor:
|
|
743
731
|
"""Pad tensor to be a multiple of base."""
|
|
744
732
|
length = x.shape[-1]
|
braindecode/models/codebrain.py
CHANGED
|
@@ -15,7 +15,6 @@ from torch import nn
|
|
|
15
15
|
from torch.nn.utils.parametrizations import weight_norm
|
|
16
16
|
|
|
17
17
|
from braindecode.functional import _real_dft, spectral_input
|
|
18
|
-
from braindecode.functional.attention import _hpu_lazy
|
|
19
18
|
from braindecode.functional.functions import _next_fast_len
|
|
20
19
|
from braindecode.models.base import EEGModuleMixin
|
|
21
20
|
|
|
@@ -442,6 +441,9 @@ class _GConv(nn.Module):
|
|
|
442
441
|
self.register_buffer(
|
|
443
442
|
"kernel_norm_initialized", torch.tensor(0, dtype=torch.bool)
|
|
444
443
|
)
|
|
444
|
+
# The buffer as a Python bool: torch.compile guards on it once instead
|
|
445
|
+
# of breaking the graph to read a tensor on every forward.
|
|
446
|
+
self._kernel_norm_ready = False
|
|
445
447
|
|
|
446
448
|
# ========== Learnable parameters ==========
|
|
447
449
|
self.skip_weight = nn.Parameter(torch.randn(channels, self.d_model))
|
|
@@ -475,6 +477,10 @@ class _GConv(nn.Module):
|
|
|
475
477
|
)
|
|
476
478
|
self.output_linear = nn.Linear(self.d_model * self.channels, self.d_model)
|
|
477
479
|
|
|
480
|
+
def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs):
|
|
481
|
+
super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)
|
|
482
|
+
self._kernel_norm_ready = bool(self.kernel_norm_initialized)
|
|
483
|
+
|
|
478
484
|
def forward(
|
|
479
485
|
self, x: torch.Tensor, return_kernel: bool = False
|
|
480
486
|
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
|
@@ -505,11 +511,12 @@ class _GConv(nn.Module):
|
|
|
505
511
|
# Lazy-init kernel normalisation on first forward pass
|
|
506
512
|
# In place, so a first forward under torch.inference_mode() does not
|
|
507
513
|
# leave inference tensors in the buffers for a later training step.
|
|
508
|
-
if not self.
|
|
514
|
+
if not self._kernel_norm_ready:
|
|
509
515
|
self.kernel_norm.copy_(
|
|
510
516
|
torch.linalg.vector_norm(kernel, 2, dim=-1, keepdim=True).detach()
|
|
511
517
|
)
|
|
512
518
|
self.kernel_norm_initialized.fill_(True)
|
|
519
|
+
self._kernel_norm_ready = True
|
|
513
520
|
|
|
514
521
|
# Pad or truncate kernel to match seq_len
|
|
515
522
|
if kernel.size(-1) > seq_len:
|
|
@@ -896,20 +903,10 @@ class _ResidualGroup(nn.Module):
|
|
|
896
903
|
def forward(self, input_data: torch.Tensor) -> torch.Tensor:
|
|
897
904
|
noise = input_data
|
|
898
905
|
h = noise
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
skip_list = []
|
|
904
|
-
for block in self.residual_blocks:
|
|
905
|
-
h, skip_n = block((h, noise))
|
|
906
|
-
skip_list.append(skip_n)
|
|
907
|
-
skip = torch.stack(skip_list, dim=0).sum(dim=0)
|
|
908
|
-
else:
|
|
909
|
-
skip = torch.zeros((), dtype=h.dtype, device=h.device)
|
|
910
|
-
for block in self.residual_blocks:
|
|
911
|
-
h, skip_n = block((h, noise))
|
|
912
|
-
skip = skip_n + skip
|
|
906
|
+
skip = torch.zeros((), dtype=h.dtype, device=h.device)
|
|
907
|
+
for block in self.residual_blocks:
|
|
908
|
+
h, skip_n = block((h, noise))
|
|
909
|
+
skip = skip_n + skip
|
|
913
910
|
|
|
914
911
|
return skip * math.sqrt(1.0 / self.num_res_layers)
|
|
915
912
|
|
|
@@ -995,9 +992,7 @@ class _PatchEmbedding(nn.Module):
|
|
|
995
992
|
self.d_model = self.emb_dim
|
|
996
993
|
|
|
997
994
|
# ========== Learnable parameters ==========
|
|
998
|
-
self.mask_encoding = nn.Parameter(
|
|
999
|
-
torch.zeros(self.emb_dim), requires_grad=False
|
|
1000
|
-
)
|
|
995
|
+
self.mask_encoding = nn.Parameter(torch.zeros(patch_size), requires_grad=False)
|
|
1001
996
|
|
|
1002
997
|
# ========== Layers ==========
|
|
1003
998
|
# Temporal projection: 3-layer Conv2d stack
|
braindecode/models/eegpt.py
CHANGED
|
@@ -449,7 +449,7 @@ class EEGPT(EEGModuleMixin, nn.Module):
|
|
|
449
449
|
|
|
450
450
|
# These channels correspond to a subset of the standard 10-20 system.
|
|
451
451
|
# The order matches the pre-trained weights and corresponds to
|
|
452
|
-
# mne.channels.make_standard_montage("
|
|
452
|
+
# mne.channels.make_standard_montage("colin27_1020") (filtered).
|
|
453
453
|
_ALLOWED_CHANNELS = {
|
|
454
454
|
"FP1",
|
|
455
455
|
"FPZ",
|
braindecode/models/eegtcnet.py
CHANGED
|
@@ -56,11 +56,18 @@ class EEGTCNet(EEGModuleMixin, nn.Module):
|
|
|
56
56
|
tcn_batch_norm : bool, optional
|
|
57
57
|
If ``True`` (default), insert a :class:`~torch.nn.BatchNorm1d` after each
|
|
58
58
|
TCN convolution and use a bias in the residual ``1x1`` downsample, matching
|
|
59
|
-
the original Keras source. Set to ``False`` to
|
|
60
|
-
braindecode
|
|
61
|
-
|
|
59
|
+
the original Keras source. Set to ``False`` to get the TCN block of
|
|
60
|
+
braindecode before 1.6.1, for example to load checkpoints trained with it.
|
|
61
|
+
To also get the outputs of that version, set ``temporal_activation=True``.
|
|
62
|
+
Default is ``True``.
|
|
62
63
|
|
|
63
64
|
.. versionadded:: 1.6.1
|
|
65
|
+
temporal_activation : bool, optional
|
|
66
|
+
If ``True``, apply ``activation`` between the temporal batch norm and the
|
|
67
|
+
depthwise convolution, as braindecode did before 2.1. The authors' code
|
|
68
|
+
has no activation there. Default is ``False``.
|
|
69
|
+
|
|
70
|
+
.. versionadded:: 2.1
|
|
64
71
|
|
|
65
72
|
References
|
|
66
73
|
----------
|
|
@@ -92,6 +99,7 @@ class EEGTCNet(EEGModuleMixin, nn.Module):
|
|
|
92
99
|
drop_prob_eeg: float | None = None,
|
|
93
100
|
drop_prob_tcn: float | None = None,
|
|
94
101
|
tcn_batch_norm: bool = True,
|
|
102
|
+
temporal_activation: bool = False,
|
|
95
103
|
):
|
|
96
104
|
super().__init__(
|
|
97
105
|
n_outputs=n_outputs,
|
|
@@ -110,6 +118,7 @@ class EEGTCNet(EEGModuleMixin, nn.Module):
|
|
|
110
118
|
self.drop_prob_eeg = drop_prob if drop_prob_eeg is None else drop_prob_eeg
|
|
111
119
|
self.drop_prob_tcn = drop_prob if drop_prob_tcn is None else drop_prob_tcn
|
|
112
120
|
self.tcn_batch_norm = tcn_batch_norm
|
|
121
|
+
self.temporal_activation = temporal_activation
|
|
113
122
|
self.depth_multiplier = depth_multiplier
|
|
114
123
|
self.filter_1 = filter_1
|
|
115
124
|
self.kern_length = kern_length
|
|
@@ -130,6 +139,7 @@ class EEGTCNet(EEGModuleMixin, nn.Module):
|
|
|
130
139
|
depth_multiplier=self.depth_multiplier,
|
|
131
140
|
drop_prob=self.drop_prob_eeg,
|
|
132
141
|
activation=self.activation,
|
|
142
|
+
temporal_activation=self.temporal_activation,
|
|
133
143
|
)
|
|
134
144
|
self.arrange_dim_eegnet = Rearrange(
|
|
135
145
|
"batch filter2 rtimes 1 -> batch rtimes filter2"
|
|
@@ -153,6 +163,18 @@ class EEGTCNet(EEGModuleMixin, nn.Module):
|
|
|
153
163
|
max_norm_val=self.max_norm_const,
|
|
154
164
|
)
|
|
155
165
|
|
|
166
|
+
@classmethod
|
|
167
|
+
def _fill_legacy_defaults(cls, kwargs):
|
|
168
|
+
"""Rebuild configs saved before a key existed as they were.
|
|
169
|
+
|
|
170
|
+
Saved configs hold every init argument, so a missing key means an
|
|
171
|
+
older save: ``temporal_activation`` (added in 2.1) defaults to
|
|
172
|
+
``True`` and ``tcn_batch_norm`` (added in 1.6.1) to ``False``.
|
|
173
|
+
"""
|
|
174
|
+
super()._fill_legacy_defaults(kwargs)
|
|
175
|
+
kwargs.setdefault("temporal_activation", True)
|
|
176
|
+
kwargs.setdefault("tcn_batch_norm", False)
|
|
177
|
+
|
|
156
178
|
@_disable_batch_norm_training_if_batch_size_one
|
|
157
179
|
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
158
180
|
"""
|
|
@@ -205,6 +227,8 @@ class _EEGNetTC(nn.Module):
|
|
|
205
227
|
Dropout rate.
|
|
206
228
|
activation : nn.Module
|
|
207
229
|
Activation function.
|
|
230
|
+
temporal_activation : bool
|
|
231
|
+
If ``True``, apply ``activation`` after the temporal batch norm.
|
|
208
232
|
"""
|
|
209
233
|
|
|
210
234
|
def __init__(
|
|
@@ -215,10 +239,12 @@ class _EEGNetTC(nn.Module):
|
|
|
215
239
|
depth_multiplier: int = 2,
|
|
216
240
|
drop_prob: float = 0.5,
|
|
217
241
|
activation: type[nn.Module] = nn.ELU,
|
|
242
|
+
temporal_activation: bool = False,
|
|
218
243
|
):
|
|
219
244
|
super().__init__()
|
|
220
245
|
self.activation = activation()
|
|
221
246
|
self.drop_prob = drop_prob
|
|
247
|
+
self.temporal_activation = temporal_activation
|
|
222
248
|
self.n_chans = n_chans
|
|
223
249
|
self.filter_1 = filter_1
|
|
224
250
|
self.filter_2 = self.filter_1 * depth_multiplier
|
|
@@ -268,7 +294,8 @@ class _EEGNetTC(nn.Module):
|
|
|
268
294
|
# x shape: (batch_size, 1, n_times, n_chans)
|
|
269
295
|
x = self.conv1(x)
|
|
270
296
|
x = self.bn1(x)
|
|
271
|
-
|
|
297
|
+
if self.temporal_activation:
|
|
298
|
+
x = self.activation(x)
|
|
272
299
|
|
|
273
300
|
x = self.depthwise_conv(x)
|
|
274
301
|
x = self.bn2(x)
|
braindecode/models/emg2qwerty.py
CHANGED
|
@@ -750,10 +750,16 @@ class _RotationInvariantMLP(nn.Module):
|
|
|
750
750
|
self.offsets = tuple(offsets) if len(offsets) > 0 else (0,)
|
|
751
751
|
|
|
752
752
|
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
|
|
753
|
-
# Gaudi eager mode rolls a non-contiguous tensor wrongly.
|
|
753
|
+
# Gaudi eager mode rolls a non-contiguous tensor wrongly. Offset 0 is the
|
|
754
|
+
# input itself: no copy, and no roll by 0 in the backward (of a slice of
|
|
755
|
+
# the stack's gradient, which Gaudi also rolls wrongly).
|
|
754
756
|
inputs = inputs.contiguous()
|
|
755
757
|
rolled = torch.stack(
|
|
756
|
-
[
|
|
758
|
+
[
|
|
759
|
+
inputs.roll(offset, dims=2) if offset else inputs
|
|
760
|
+
for offset in self.offsets
|
|
761
|
+
],
|
|
762
|
+
dim=2,
|
|
757
763
|
)
|
|
758
764
|
per_roll_features = self.mlp(rolled.flatten(start_dim=3))
|
|
759
765
|
if self.pooling == "max":
|