braindecode 2.1.0.dev181999048__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.
Files changed (53) hide show
  1. braindecode/augmentation/functional.py +1 -1
  2. braindecode/augmentation/transforms.py +1 -1
  3. braindecode/datasets/base.py +17 -12
  4. braindecode/datasets/bids/hub.py +13 -1
  5. braindecode/datautil/serialization.py +7 -0
  6. braindecode/functional/__init__.py +10 -0
  7. braindecode/functional/attention.py +12 -54
  8. braindecode/functional/channel_mask.py +18 -10
  9. braindecode/functional/channels.py +282 -0
  10. braindecode/models/__init__.py +7 -0
  11. braindecode/models/attn_sleep.py +40 -6
  12. braindecode/models/base.py +50 -13
  13. braindecode/models/biot.py +10 -8
  14. braindecode/models/brainmodule.py +1 -13
  15. braindecode/models/cbramod.py +9 -5
  16. braindecode/models/codebrain.py +14 -19
  17. braindecode/models/csbrain.py +12 -9
  18. braindecode/models/eegpt.py +1 -1
  19. braindecode/models/eegtcnet.py +31 -4
  20. braindecode/models/emg2qwerty.py +8 -2
  21. braindecode/models/fnirs4d.py +761 -0
  22. braindecode/models/fnirs_cnn1d.py +339 -0
  23. braindecode/models/fnirs_t.py +785 -0
  24. braindecode/models/fnirsnet.py +374 -0
  25. braindecode/models/geonirs.py +1545 -0
  26. braindecode/models/guetschel2026.py +1 -1
  27. braindecode/models/jung_mae.py +596 -0
  28. braindecode/models/labram.py +4 -18
  29. braindecode/models/luna.py +43 -33
  30. braindecode/models/mapa.py +4 -5
  31. braindecode/models/model.html.jinja +24 -9
  32. braindecode/models/msvtnet.py +1 -2
  33. braindecode/models/mtrenirs.py +1053 -0
  34. braindecode/models/patchedtransformer.py +26 -15
  35. braindecode/models/reve.py +1 -4
  36. braindecode/models/signal_jepa.py +5 -6
  37. braindecode/models/sleepfm.py +98 -23
  38. braindecode/models/summary.csv +8 -0
  39. braindecode/models/util.py +144 -1
  40. braindecode/models/zuna.py +11 -24
  41. braindecode/modules/attention.py +9 -9
  42. braindecode/modules/channels.py +170 -30
  43. braindecode/modules/layers.py +2 -8
  44. braindecode/preprocessing/preprocess.py +4 -0
  45. braindecode/preprocessing/windowers.py +14 -6
  46. braindecode/util.py +21 -28
  47. braindecode/version.py +1 -1
  48. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/METADATA +25 -9
  49. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/RECORD +53 -45
  50. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/NOTICE.txt +16 -0
  51. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/WHEEL +0 -0
  52. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/LICENSE.txt +0 -0
  53. {braindecode-2.1.0.dev181999048.dist-info → braindecode-2.1.0.dev182154342.dist-info}/top_level.txt +0 -0
@@ -95,6 +95,12 @@ class AttnSleep(EEGModuleMixin, nn.Module):
95
95
  Activation function class to apply in the multi-resolution CNN layer.
96
96
  Should be a PyTorch activation module class like ``nn.ReLU`` or
97
97
  ``nn.GELU``. Default is ``nn.GELU``.
98
+ attn_query_norm : bool
99
+ If ``True``, apply the layer norm of the attention block to the query
100
+ before the attention, as braindecode 1.0 to 2.0 did. If ``False``
101
+ (default), attend with the raw query, as the authors' code does.
102
+
103
+ .. versionadded:: 2.1
98
104
 
99
105
  References
100
106
  ----------
@@ -124,6 +130,7 @@ class AttnSleep(EEGModuleMixin, nn.Module):
124
130
  chs_info=None,
125
131
  n_chans=None,
126
132
  n_times=None,
133
+ attn_query_norm=False,
127
134
  ):
128
135
  if (
129
136
  sum(value is not None for value in (n_times, sfreq, input_window_seconds))
@@ -190,7 +197,12 @@ class AttnSleep(EEGModuleMixin, nn.Module):
190
197
  ff = _PositionwiseFeedForward(d_model, d_ff, drop_prob, activation=activation)
191
198
  tce = _TCE(
192
199
  _EncoderLayer(
193
- d_model, deepcopy(attn), deepcopy(ff), after_reduced_cnn_size, drop_prob
200
+ d_model,
201
+ deepcopy(attn),
202
+ deepcopy(ff),
203
+ after_reduced_cnn_size,
204
+ drop_prob,
205
+ attn_query_norm,
194
206
  ),
195
207
  n_tce,
196
208
  )
@@ -205,6 +217,11 @@ class AttnSleep(EEGModuleMixin, nn.Module):
205
217
  if not return_feats:
206
218
  self.final_layer = nn.Linear(self.len_last_layer, self.n_outputs)
207
219
 
220
+ @classmethod
221
+ def _fill_legacy_defaults(cls, kwargs):
222
+ super()._fill_legacy_defaults(kwargs)
223
+ kwargs.setdefault("attn_query_norm", True)
224
+
208
225
  @staticmethod
209
226
  def _feature_length(mrcnn, n_times):
210
227
  training_states = [(module, module.training) for module in mrcnn.modules()]
@@ -473,11 +490,18 @@ class _MultiHeadedAttention(nn.Module):
473
490
  class _ResidualLayerNormAttn(nn.Module):
474
491
  r"""A residual connection followed by a layer norm."""
475
492
 
476
- def __init__(self, size, dropout, fn_attn):
493
+ def __init__(self, size, dropout, fn_attn, norm_query):
477
494
  super().__init__()
478
495
  self.norm = nn.LayerNorm(size, eps=1e-6)
479
496
  self.dropout = nn.Dropout(dropout)
480
497
  self.fn_attn = fn_attn
498
+ self.norm_query = norm_query
499
+
500
+ def __setstate__(self, state):
501
+ # Full models pickled before the raw-query option normalized the
502
+ # query. Set the flag on the instance so TorchScript also sees it.
503
+ state.setdefault("norm_query", True)
504
+ super().__setstate__(state)
481
505
 
482
506
  def forward(
483
507
  self,
@@ -486,9 +510,10 @@ class _ResidualLayerNormAttn(nn.Module):
486
510
  value: torch.Tensor,
487
511
  ) -> torch.Tensor:
488
512
  """Apply residual connection to any sublayer with the same size."""
489
- x_norm = self.norm(x)
490
-
491
- out = self.fn_attn(x_norm, key, value)
513
+ # The reference attends with the raw query. ``norm_query`` keeps the
514
+ # braindecode 1.0 to 2.0 behaviour.
515
+ query = self.norm(x) if self.norm_query else x
516
+ out = self.fn_attn(query, key, value)
492
517
 
493
518
  return x + self.dropout(out)
494
519
 
@@ -537,7 +562,15 @@ class _EncoderLayer(nn.Module):
537
562
  Each of these sublayers have residual and layer norm, implemented by _ResidualLayerNorm.
538
563
  """
539
564
 
540
- def __init__(self, size, self_attn, feed_forward, after_reduced_cnn_size, dropout):
565
+ def __init__(
566
+ self,
567
+ size,
568
+ self_attn,
569
+ feed_forward,
570
+ after_reduced_cnn_size,
571
+ dropout,
572
+ attn_query_norm,
573
+ ):
541
574
  super().__init__()
542
575
  self.size = size
543
576
  self.self_attn = self_attn
@@ -547,6 +580,7 @@ class _EncoderLayer(nn.Module):
547
580
  size=size,
548
581
  dropout=dropout,
549
582
  fn_attn=self_attn,
583
+ norm_query=attn_query_norm,
550
584
  )
551
585
  self.residual_ff = _ResidualLayerNormFF(
552
586
  size=size,
@@ -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 n_chans is not None and chs_info is not None and len(chs_info) != n_chans:
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 needs channel_strategy='native': the channel layer maps "
542
- "all input channels, padded ones included, onto the target montage."
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
- if k in mapping:
897
- new_state_dict[mapping[k]] = v
898
- else:
899
- new_state_dict[k] = v
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.17699192"
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"
@@ -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
- # - self.channel_tokens(self.index[i + n_channel_offset]):
549
- # Fetches the embedding for a channel specified by i + n_channel_offset,
550
- # where i is the current index and n_channel_offset adjusts
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
- self.channel_tokens(self.index[i + n_channel_offset])
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
- _GLU(dim=1),
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]
@@ -143,7 +143,9 @@ class CBraMod(EEGModuleMixin, nn.Module):
143
143
  activation : type[nn.Module], default=nn.GELU
144
144
  Activation function used in Transformer feedforward layers.
145
145
  emb_dim : int, default=200
146
- Output embedding dimension.
146
+ Output dimension of ``proj_out``, the pretraining reconstruction layer.
147
+ It is kept so the released weights load, but it is not applied: features
148
+ and head use the encoder output, of size ``d_model``.
147
149
  drop_prob : float, default=0.1
148
150
  Dropout probability.
149
151
  return_encoder_output : bool, default=False
@@ -227,7 +229,7 @@ class CBraMod(EEGModuleMixin, nn.Module):
227
229
  self.encoder = _TransformerEncoder(encoder_layer, num_layers=n_layer)
228
230
  self.proj_out = nn.Sequential(nn.Linear(d_model, emb_dim))
229
231
 
230
- self._emb_dim = emb_dim
232
+ self._d_model = d_model
231
233
  self._patch_size = patch_size
232
234
  self._encoder_output = return_encoder_output
233
235
  self._init_parameters()
@@ -236,7 +238,7 @@ class CBraMod(EEGModuleMixin, nn.Module):
236
238
  self.final_layer = nn.Identity()
237
239
  elif self._knows_geometry():
238
240
  n_patch = self._n_patch()
239
- flat_dim = self.n_chans * n_patch * emb_dim
241
+ flat_dim = self.n_chans * n_patch * d_model
240
242
  self.final_layer = nn.Sequential(
241
243
  nn.Flatten(), nn.Linear(flat_dim, self.n_outputs)
242
244
  )
@@ -253,7 +255,7 @@ class CBraMod(EEGModuleMixin, nn.Module):
253
255
  self._encoder_output = False
254
256
  if self._knows_geometry():
255
257
  n_patch = self._n_patch()
256
- flat_dim = self.n_chans * n_patch * self._emb_dim
258
+ flat_dim = self.n_chans * n_patch * self._d_model
257
259
  self.final_layer = nn.Sequential(
258
260
  nn.Flatten(), nn.Linear(flat_dim, n_outputs)
259
261
  )
@@ -312,7 +314,9 @@ class CBraMod(EEGModuleMixin, nn.Module):
312
314
  x = self.rearrange(x)
313
315
  patch_emb = self.patch_embedding(x, mask, ch_mask)
314
316
  feats = self.encoder(patch_emb, src_key_padding_mask=key_padding_mask)
315
- out = self.proj_out(feats)
317
+ # proj_out is the pretraining reconstruction layer: the original
318
+ # fine-tuning models replace it by nn.Identity(), so it is not run.
319
+ out = feats
316
320
  if ch_mask is not None:
317
321
  out = out.masked_fill(~ch_mask[:, :, None, None], 0.0)
318
322
  if return_features:
@@ -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.kernel_norm_initialized:
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
- if not torch.jit.is_scripting() and h.device.type == "hpu" and _hpu_lazy():
900
- # Gaudi's lazy-mode graph compiler fails on the backward of the
901
- # sequential skip sum (one skip_conv dedw node lands in two
902
- # pipeline bundles); one n-ary stack-sum reduction compiles.
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
@@ -224,8 +224,10 @@ class CSBrain(EEGModuleMixin, nn.Module):
224
224
  activation : type[nn.Module], default=nn.GELU
225
225
  Activation function used in the encoder feedforward blocks.
226
226
  emb_dim : int, default=200
227
- Output dimension of the final projection applied to the encoder
228
- output.
227
+ Output dimension of ``proj_out``, the pretraining reconstruction layer.
228
+ It is kept so the released weights load, but it is not applied:
229
+ features use the encoder output, of size ``d_model`` (the patch size).
230
+ It still sets the hidden widths of the task head.
229
231
  temporal_kernel_sizes : tuple[int, ...], default=(1, 3, 5)
230
232
  Kernel sizes of the cross-scale temporal embedding convolutions.
231
233
  drop_prob : float, default=0.1
@@ -235,9 +237,8 @@ class CSBrain(EEGModuleMixin, nn.Module):
235
237
  Dropout probability of the task head. ``None`` uses ``drop_prob``.
236
238
  The reference fine-tuning models keep the backbone at 0.1 and set
237
239
  only the head dropout (``--dropout 0.3`` for BCIC IV-2a), and they
238
- replace ``proj_out`` by ``nn.Identity()`` after loading the
239
- pretrained weights: ``drop_prob=0.1, head_drop_prob=0.3``, then
240
- ``model.proj_out = nn.Identity()``.
240
+ skip ``proj_out`` (it is replaced by ``nn.Identity()`` there, and not
241
+ applied here): ``drop_prob=0.1, head_drop_prob=0.3``.
241
242
  brain_regions : sequence of int | None, default=None
242
243
  Explicit region id per input channel (0 frontal, 1 parietal, 2
243
244
  temporal, 3 occipital, 4 central), taking precedence over the
@@ -258,7 +259,7 @@ class CSBrain(EEGModuleMixin, nn.Module):
258
259
  (e.g. 800 for 4 s and 2000 for 10 s windows at 200 Hz). Some
259
260
  reference heads differ, e.g. SEED-V (1 s windows) uses 800; pass it
260
261
  here to load those checkpoints. The first head layer has
261
- ``n_chans * n_patch * emb_dim * head_hidden_dim`` weights, which grows
262
+ ``n_chans * n_patch * d_model * head_hidden_dim`` weights, which grows
262
263
  quadratically with the window length by default (about 2.3e9 for 64
263
264
  channels and 30 s), so set a smaller width for long windows.
264
265
  return_encoder_output : bool, default=False
@@ -446,7 +447,7 @@ class CSBrain(EEGModuleMixin, nn.Module):
446
447
 
447
448
  def _make_task_head(self) -> nn.Sequential:
448
449
  # Three-layer MLP head of the reference fine-tuning models: flatten
449
- # (chans, patches, emb_dim) -> n_patch * emb_dim -> emb_dim -> n_outputs.
450
+ # (chans, patches, d_model) -> n_patch * emb_dim -> emb_dim -> n_outputs.
450
451
  # n_chans / n_times may come from chs_info / input_window_seconds.
451
452
  # Without them the layers are lazy and the hidden width falls back to
452
453
  # 4 * emb_dim, the reference value for 4 s windows.
@@ -466,7 +467,7 @@ class CSBrain(EEGModuleMixin, nn.Module):
466
467
  hidden = self._head_hidden_dim or n_patch * self._emb_dim
467
468
  return nn.Sequential(
468
469
  nn.Flatten(),
469
- nn.Linear(n_chans * n_patch * self._emb_dim, hidden),
470
+ nn.Linear(n_chans * n_patch * self._d_model, hidden),
470
471
  nn.ELU(),
471
472
  nn.Dropout(self._head_drop_prob),
472
473
  nn.Linear(hidden, self._emb_dim),
@@ -508,7 +509,9 @@ class CSBrain(EEGModuleMixin, nn.Module):
508
509
  emb = self.temporal_embed(emb) + emb
509
510
  emb = self.region_embed(emb) + emb
510
511
  emb = layer(emb)
511
- out = self.proj_out(emb)
512
+ # proj_out is the pretraining reconstruction layer: the reference
513
+ # fine-tuning models replace it by nn.Identity(), so it is not run.
514
+ out = emb
512
515
  if return_features:
513
516
  features: Dict[str, Optional[Tensor]] = {"features": out, "cls_token": None}
514
517
  return features
@@ -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("standard_1020") (filtered).
452
+ # mne.channels.make_standard_montage("colin27_1020") (filtered).
453
453
  _ALLOWED_CHANNELS = {
454
454
  "FP1",
455
455
  "FPZ",
@@ -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 recover the previous
60
- braindecode architecture (e.g. to load checkpoints trained before this
61
- change). Default is ``True``.
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
- x = self.activation(x)
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)
@@ -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
- [inputs.roll(offset, dims=2) for offset in self.offsets], dim=2
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":