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.
Files changed (49) 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 +4 -14
  8. braindecode/functional/channels.py +282 -0
  9. braindecode/models/__init__.py +6 -0
  10. braindecode/models/attn_sleep.py +40 -6
  11. braindecode/models/base.py +50 -13
  12. braindecode/models/biot.py +10 -8
  13. braindecode/models/brainmodule.py +1 -13
  14. braindecode/models/codebrain.py +14 -19
  15. braindecode/models/eegpt.py +1 -1
  16. braindecode/models/eegtcnet.py +31 -4
  17. braindecode/models/emg2qwerty.py +8 -2
  18. braindecode/models/fnirs4d.py +761 -0
  19. braindecode/models/fnirs_cnn1d.py +339 -0
  20. braindecode/models/fnirs_t.py +785 -0
  21. braindecode/models/fnirsnet.py +268 -86
  22. braindecode/models/geonirs.py +1545 -0
  23. braindecode/models/guetschel2026.py +1 -1
  24. braindecode/models/jung_mae.py +596 -0
  25. braindecode/models/luna.py +43 -33
  26. braindecode/models/mapa.py +4 -5
  27. braindecode/models/model.html.jinja +24 -9
  28. braindecode/models/msvtnet.py +1 -2
  29. braindecode/models/mtrenirs.py +1053 -0
  30. braindecode/models/patchedtransformer.py +26 -15
  31. braindecode/models/reve.py +1 -4
  32. braindecode/models/signal_jepa.py +5 -6
  33. braindecode/models/sleepfm.py +98 -23
  34. braindecode/models/summary.csv +7 -0
  35. braindecode/models/util.py +139 -1
  36. braindecode/models/zuna.py +11 -24
  37. braindecode/modules/attention.py +9 -8
  38. braindecode/modules/channels.py +170 -30
  39. braindecode/modules/layers.py +2 -8
  40. braindecode/preprocessing/preprocess.py +4 -0
  41. braindecode/preprocessing/windowers.py +14 -6
  42. braindecode/util.py +21 -28
  43. braindecode/version.py +1 -1
  44. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/METADATA +25 -9
  45. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/RECORD +49 -42
  46. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/NOTICE.txt +6 -0
  47. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/WHEEL +0 -0
  48. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/LICENSE.txt +0 -0
  49. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,339 @@
1
+ # Authors: Bruno Aristimunha <b.aristimunha@gmail.com> (braindecode adaptation)
2
+ #
3
+ # Adapted from the 1D-CNN baseline of the GeoNIRS authors,
4
+ # https://github.com/GeoNIRS/GeoNIRS (``model/cnn1d.py`` at commit 81f8995,
5
+ # where the class is named ``DirectEventCNN1DClassifier``).
6
+ from __future__ import annotations
7
+
8
+ import torch
9
+ from einops.layers.torch import Rearrange
10
+ from torch import nn
11
+
12
+ from braindecode.models.base import EEGModuleMixin
13
+
14
+
15
+ class FNIRSCNN1D(EEGModuleMixin, nn.Module):
16
+ r"""FNIRSCNN1D, the 1D-CNN of Trakoolwilaiwan et al. (2018), as in GeoNIRS.
17
+
18
+ :bdg-success:`Convolution`
19
+
20
+ .. versionadded:: 2.1
21
+
22
+ Trakoolwilaiwan et al. :footcite:`trakoolwilaiwan2018cnn` proposed
23
+ convolutional neural networks for fNIRS brain-computer interfaces, to
24
+ classify rest, right- and left-hand motor execution from HbO/HbR signals.
25
+ The GeoNIRS benchmark :footcite:`li2026geonirs` uses a "1D-CNN
26
+ (Trakoolwilaiwan et al., 2018)" as its first supervised neural baseline
27
+ (Section 3.1; the "1D-CNN" rows of Tables 1, 14 and 15, and 88.4 K
28
+ parameters in Table 10). This class ports that baseline: the
29
+ ``DirectEventCNN1DClassifier`` of the GeoNIRS repository (commit
30
+ ``81f8995``) as its benchmark builds it, one classifier per event window.
31
+ The two GroupNorm and GELU stages are the GeoNIRS authors' (the networks
32
+ of Trakoolwilaiwan et al. use one or three convolutions of kernel 3 with
33
+ max pooling and dropout), and the architecture is documented from their
34
+ code.
35
+
36
+ The model is small and direct. Two temporal convolutions read the window,
37
+ the second of them at half the sampling rate; the result is averaged over
38
+ time and classified. Nothing in it knows about channels, chromophores or
39
+ optode geometry: the first convolution mixes every row. With :math:`B`
40
+ the batch size, :math:`C` = ``n_chans``, :math:`T` = ``n_times`` and
41
+ :math:`F_1`, :math:`F_2` the two filter counts, the steps are::
42
+
43
+ x (B, C, T): HbO rows then HbR rows; NaN or inf = missing sample
44
+ 1. temporal_conv1: Conv1d, GroupNorm, GELU, MaxPool1d -> (B, F_1, T // 2)
45
+ 2. temporal_conv2: Conv1d, GroupNorm, GELU -> (B, F_2, T // 2)
46
+ 3. time_pool, flatten_layer, head_dropout -> (B, F_2)
47
+ 4. final_layer -> (B, n_outputs)
48
+
49
+ .. rubric:: Macro Components
50
+
51
+ - ``FNIRSCNN1D.temporal_conv1`` **First temporal convolution**
52
+
53
+ :class:`~torch.nn.Conv1d` (64 filters, kernel 7, ``padding="same"``),
54
+ :class:`~torch.nn.GroupNorm` (8 groups), GELU and
55
+ :class:`~torch.nn.MaxPool1d` (kernel 2), which halves the time axis.
56
+ The kernel spans 7 samples, 1.4 s at the 5 Hz of the GeoNIRS inputs.
57
+
58
+ - ``FNIRSCNN1D.temporal_conv2`` **Second temporal convolution**
59
+
60
+ :class:`~torch.nn.Conv1d` (128 filters, kernel 5, ``padding="same"``),
61
+ :class:`~torch.nn.GroupNorm` (8 groups) and GELU, at half rate, so its
62
+ 5 samples span 2 s of the input.
63
+
64
+ - ``FNIRSCNN1D.final_layer`` **Classification head**
65
+
66
+ The feature maps are averaged over time
67
+ (:class:`~torch.nn.AdaptiveAvgPool1d`), then
68
+ :class:`~torch.nn.Dropout` (0.5) and one :class:`~torch.nn.Linear`.
69
+ The average is what lets the model take a window of any length.
70
+
71
+ .. rubric:: Temporal, Spatial, and Chromophore Encoding
72
+
73
+ - **Temporal.** Two short kernels and one halving of the rate. The final
74
+ average throws the position of a response away, so the model reads the
75
+ window as a bag of short patterns.
76
+ - **Spatial.** None. The first convolution mixes every row, and no
77
+ optode position is read.
78
+ - **Chromophores.** HbO and HbR are ordinary rows. Their order must be
79
+ the one used in training: the GeoNIRS benchmark stacks the HbO rows
80
+ before the HbR rows, ``HbO_1, ..., HbO_C, HbR_1, ..., HbR_C``.
81
+ ``chs_info`` is not read.
82
+
83
+ .. rubric:: Pretrained Weights
84
+
85
+ None. The baseline is trained from scratch on each task.
86
+
87
+ .. rubric:: Differences from the Reference Implementation
88
+
89
+ - **Input.** One tensor ``(batch, n_chans, n_times)``. The reference
90
+ takes a batch dictionary with ``hbo``, ``hbr`` and a validity mask,
91
+ replaces the invalid samples by zero and stacks the HbO rows before
92
+ the HbR rows. Here a non-finite value (NaN or inf) marks a missing
93
+ sample and is read as zero. The reference's mask covers both
94
+ chromophores of a pair, so a sample missing in one of them should be
95
+ NaN in both.
96
+ - **Parity.** With the same seed, this class and the authors' module
97
+ draw the same weights and give the same logits (max-abs 0.0), in eval
98
+ mode and in train mode. ``mapping`` renames their ``encoder.`` and
99
+ ``linear.`` keys, so their state dict loads with ``strict=True``.
100
+ - **Event pairs.** The reference can also aggregate the events of a pair
101
+ before its head (``event_pair_mode``). The benchmark builds it with
102
+ that mode off, and this class has only that mode.
103
+ - **Additions.** The kernel lengths, the pooling length, the number of
104
+ normalization groups and ``activation`` are arguments, fixed in the
105
+ reference. ``ch_mask`` is refused, because the first convolution spans
106
+ every row.
107
+
108
+ Parameters
109
+ ----------
110
+ n_filters_conv1 : int, default=64
111
+ Filters of the first temporal convolution (``conv_dim`` in the
112
+ reference).
113
+ n_filters_conv2 : int, default=128
114
+ Filters of the second temporal convolution, and the feature size
115
+ (``embedding_dim`` in the reference).
116
+ kernel_size_conv1 : int, default=7
117
+ Kernel length of the first temporal convolution, in samples; an odd
118
+ length keeps the reference's symmetric padding.
119
+ kernel_size_conv2 : int, default=5
120
+ Kernel length of the second temporal convolution, in samples; an odd
121
+ length keeps the reference's symmetric padding.
122
+ pool_size : int, default=2
123
+ Length and stride of the max pooling after the first convolution.
124
+ n_norm_groups : int, default=8
125
+ Groups of both :class:`~torch.nn.GroupNorm` layers. It must divide
126
+ both filter counts.
127
+ drop_prob : float, default=0.5
128
+ Dropout probability before ``final_layer`` (``dropout`` in the
129
+ reference).
130
+ activation : type[nn.Module], default=nn.GELU
131
+ Activation after each :class:`~torch.nn.GroupNorm`.
132
+
133
+ Notes
134
+ -----
135
+ In the GeoNIRS benchmark (Section 3.1 and Appendices B.1 and B.5-B.6 of
136
+ :footcite:`li2026geonirs`), "baseline models receive the same frozen
137
+ downstream inputs as GeoNIRS" and "follow the unified protocol in Table
138
+ 8": HbO and HbR in µmol/L resampled to 5 Hz and z-scored per recording;
139
+ eight held-out binary tasks with subject-level five-fold cross-validation
140
+ and the seeds 810 and 811; 30 epochs, batch 16, AdamW (weight decay
141
+ 0.05; learning rate 1e-4, from the repository's ``downstream.yaml``),
142
+ class-weighted cross-entropy, and model selection by validation balanced
143
+ accuracy.
144
+
145
+ Replication through the authors' training loop with this class in place
146
+ of theirs (mean over the five test folds and the two seeds; the authors'
147
+ module gives the same value in each of the 20 cells, max-abs 0.0; half
148
+ the range across the two seeds is at most 0.29 points):
149
+
150
+ ===================== ======== ================= ==============
151
+ Task Metric GeoNIRS paper (%) This class (%)
152
+ ===================== ======== ================= ==============
153
+ DS42 (action mode) macro-F1 55.53 55.85
154
+ DS42 (action mode) AUROC 59.67 59.32
155
+ DS19 (pain intensity) macro-F1 50.05 50.22
156
+ DS19 (pain intensity) AUROC 50.76 49.73
157
+ ===================== ======== ================= ==============
158
+
159
+ References
160
+ ----------
161
+ .. footbibliography::
162
+ """
163
+
164
+ def __init__(
165
+ self,
166
+ # Braindecode parameters
167
+ n_outputs: int | None = None,
168
+ n_chans: int | None = None,
169
+ chs_info: list[dict] | None = None,
170
+ n_times: int | None = None,
171
+ input_window_seconds: float | None = None,
172
+ sfreq: float | None = None,
173
+ *,
174
+ # Model-specific parameters
175
+ n_filters_conv1: int = 64,
176
+ n_filters_conv2: int = 128,
177
+ kernel_size_conv1: int = 7,
178
+ kernel_size_conv2: int = 5,
179
+ pool_size: int = 2,
180
+ n_norm_groups: int = 8,
181
+ drop_prob: float = 0.5,
182
+ activation: type[nn.Module] = nn.GELU,
183
+ ) -> None:
184
+ super().__init__(
185
+ n_outputs=n_outputs,
186
+ n_chans=n_chans,
187
+ chs_info=chs_info,
188
+ n_times=n_times,
189
+ input_window_seconds=input_window_seconds,
190
+ sfreq=sfreq,
191
+ )
192
+ del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
193
+
194
+ # Layers
195
+ # Following the nomenclature of the reference implementation
196
+
197
+ # First temporal convolution. This is where the channels are mixed:
198
+ # every filter reads all the HbO and HbR rows at once
199
+ self.temporal_conv1 = nn.Sequential(
200
+ # F1 filters over all the rows and kernel_size_conv1 samples
201
+ # (1.4 s at the 5 Hz of the benchmark)
202
+ nn.Conv1d(
203
+ in_channels=self.n_chans,
204
+ out_channels=n_filters_conv1,
205
+ kernel_size=kernel_size_conv1,
206
+ padding="same",
207
+ ),
208
+ # Normalizes groups of filters within each window, so it needs no
209
+ # batch statistics
210
+ nn.GroupNorm(n_norm_groups, n_filters_conv1),
211
+ activation(),
212
+ # Keeps the strongest response of every pool_size samples, which
213
+ # halves the sampling rate. A last incomplete group is dropped, as
214
+ # in the reference (no ceil_mode)
215
+ nn.MaxPool1d(kernel_size=pool_size),
216
+ )
217
+
218
+ # Second temporal convolution, on the pooled feature maps
219
+ self.temporal_conv2 = nn.Sequential(
220
+ # F2 filters over kernel_size_conv2 pooled samples, twice as long
221
+ # in time as on the input (2 s at 5 Hz)
222
+ nn.Conv1d(
223
+ in_channels=n_filters_conv1,
224
+ out_channels=n_filters_conv2,
225
+ kernel_size=kernel_size_conv2,
226
+ padding="same",
227
+ ),
228
+ nn.GroupNorm(n_norm_groups, n_filters_conv2),
229
+ activation(),
230
+ )
231
+
232
+ # Global average pooling: one value per filter, for a window of any
233
+ # length. The position of a response in the window is not kept
234
+ self.time_pool = nn.AdaptiveAvgPool1d(output_size=1)
235
+ # Drops the time axis, which the pooling leaves with one sample
236
+ self.flatten_layer = Rearrange("batch filters 1 -> batch filters")
237
+
238
+ # Classification head: dropout on the F2 features, then the linear
239
+ # classifier that gives the logits
240
+ self.head_dropout = nn.Dropout(drop_prob)
241
+ self.final_layer = nn.Linear(
242
+ in_features=n_filters_conv2,
243
+ out_features=self.n_outputs,
244
+ )
245
+
246
+ # Names of the reference, so that its state dict loads strictly. It
247
+ # keeps both convolution stages in one "encoder" Sequential, where the
248
+ # layers with parameters sit at positions 0, 1, 4 and 5, and names its
249
+ # classifier "linear"
250
+ self.mapping = {
251
+ "encoder.0.weight": "temporal_conv1.0.weight",
252
+ "encoder.0.bias": "temporal_conv1.0.bias",
253
+ "encoder.1.weight": "temporal_conv1.1.weight",
254
+ "encoder.1.bias": "temporal_conv1.1.bias",
255
+ "encoder.4.weight": "temporal_conv2.0.weight",
256
+ "encoder.4.bias": "temporal_conv2.0.bias",
257
+ "encoder.5.weight": "temporal_conv2.1.weight",
258
+ "encoder.5.bias": "temporal_conv2.1.bias",
259
+ "linear.weight": "final_layer.weight",
260
+ "linear.bias": "final_layer.bias",
261
+ }
262
+
263
+ def forward(
264
+ self,
265
+ x: torch.Tensor,
266
+ return_features: bool = False,
267
+ ch_mask: torch.Tensor | None = None,
268
+ ) -> torch.Tensor | dict[str, torch.Tensor | None]:
269
+ """Forward pass of the FNIRSCNN1D model.
270
+
271
+ Parameters
272
+ ----------
273
+ x : torch.Tensor
274
+ Input tensor with shape (batch_size, n_chans, n_times). A
275
+ non-finite value (NaN or inf) marks a missing sample and is read
276
+ as zero.
277
+ return_features : bool, default=False
278
+ If True, return the input of ``final_layer`` instead of the
279
+ logits.
280
+ ch_mask : None
281
+ Not supported, because the first convolution spans every row.
282
+
283
+ Returns
284
+ -------
285
+ torch.Tensor or dict
286
+ Output tensor with shape (batch_size, n_outputs), or
287
+ ``{"features": (batch_size, n_filters_conv2),
288
+ "cls_token": None}`` with ``return_features=True``.
289
+ """
290
+ # Shapes use the symbols of the class docstring: C rows, T samples,
291
+ # F1 and F2 filters.
292
+
293
+ # The first convolution reads every row at once, so a padded channel
294
+ # cannot be left out of it
295
+ if ch_mask is not None:
296
+ raise ValueError(
297
+ "FNIRSCNN1D does not accept ch_mask: "
298
+ "its first convolution spans every row."
299
+ )
300
+
301
+ # Missing samples (NaN or inf) are read as zero, as the reference does
302
+ # with its validity mask
303
+ # (batch, C, T), unchanged
304
+ x = x.nan_to_num(nan=0.0, posinf=0.0, neginf=0.0)
305
+
306
+ # First temporal convolution: F1 filters over all the rows, GroupNorm
307
+ # and GELU, then max pooling
308
+ # (batch, C, T) -> (batch, F1, T // pool_size)
309
+ x = self.temporal_conv1(x)
310
+
311
+ # Second temporal convolution: F2 filters on the pooled maps, GroupNorm
312
+ # and GELU
313
+ # (batch, F1, T // pool_size) -> (batch, F2, T // pool_size)
314
+ x = self.temporal_conv2(x)
315
+
316
+ # Global average pooling: the mean of each feature map over time
317
+ # (batch, F2, T // pool_size) -> (batch, F2, 1)
318
+ x = self.time_pool(x)
319
+
320
+ # The features of the window, one value per filter
321
+ # (batch, F2, 1) -> (batch, F2)
322
+ x = self.flatten_layer(x)
323
+
324
+ # Dropout on the features, before the classifier
325
+ # (batch, F2), unchanged
326
+ x = self.head_dropout(x)
327
+ if return_features:
328
+ return {"features": x, "cls_token": None}
329
+
330
+ # Linear classifier: the logits of the window
331
+ # (batch, F2) -> (batch, n_outputs)
332
+ x = self.final_layer(x)
333
+ return x
334
+
335
+ def reset_head(self, n_outputs: int) -> None:
336
+ self._set_n_outputs(n_outputs)
337
+ # A new classifier over the same F2 features, with PyTorch's default
338
+ # initialization, as in the constructor
339
+ self.final_layer = nn.Linear(self.final_layer.in_features, n_outputs)