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
@@ -0,0 +1,785 @@
1
+ # Authors: Bruno Aristimunha <b.aristimunha@gmail.com>
2
+ #
3
+ # License: MIT
4
+ # Adapted from https://github.com/wzhlearning/fNIRS-Transformer (MIT).
5
+ """fNIRS-T and fNIRS-PreT: Transformer Models for fNIRS Classification."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Literal
10
+
11
+ import torch
12
+ from einops.layers.torch import Rearrange, Reduce
13
+ from torch import nn
14
+
15
+ from braindecode.models.base import EEGModuleMixin
16
+ from braindecode.models.util import fnirs_channel_order
17
+ from braindecode.modules import (
18
+ FeedForwardBlock,
19
+ MultiHeadAttention,
20
+ PreNormTransformerBlock,
21
+ )
22
+
23
+
24
+ class FNIRST(EEGModuleMixin, nn.Module, license="mit"):
25
+ r"""fNIRS-T from Wang et al. (2022).
26
+
27
+ :bdg-success:`Convolution` :bdg-info:`Attention/Transformer`
28
+
29
+ .. figure:: https://braindecode.org/dev/_static/model/fnirst.png
30
+ :align: center
31
+ :alt: fNIRS-T and fNIRS-PreT architecture
32
+
33
+ Figure of the authors' repository (``fig/model.png``,
34
+ wzhlearning/fNIRS-Transformer at ``6ebe987f``, MIT): the
35
+ :math:`H \times W \times C` input (channels, samples, HbO/HbR) feeds a
36
+ "Spatial-level" and a "Channel-level" branch, each a "Transformer
37
+ Encoder" with a CLS token. Bottom: fNIRS-T takes filtered,
38
+ baseline-corrected segments; fNIRS-PreT replaces those steps by a
39
+ "Preprocessing Module" (:class:`FNIRSPreT`). The paper (IEEE JBHI
40
+ 2022) is not open access; its caption is not reproduced.
41
+
42
+ From the abstract :footcite:`wang2022fnirst`: "Inspired by the success of
43
+ Transformer based on self-attention mechanism in the fields of natural
44
+ language processing and computer vision, we propose an fNIRS
45
+ classification network based on Transformer, named fNIRS-T. We explore
46
+ the spatial-level and channel-level representation of fNIRS signals to
47
+ improve data utilization and network representation capacity." On the
48
+ three-class finger- and foot-tapping task (30 subjects), "fNIRS-T, CNN,
49
+ and LSTM obtain 75.49%, 72.89%, and 61.94% on test sets".
50
+
51
+ In the authors' code the two levels read the same signals at two
52
+ spatial scales: a convolution turns the time course of each fNIRS
53
+ channel (channel level) or of a group of consecutive channels (spatial
54
+ level) into one token, and a transformer lets these tokens attend to
55
+ each other; time never becomes a token axis. Only the abstract, the
56
+ README, the figure and the code (``model.py``, ``KFold_Train.py``,
57
+ ``LOSO_Train.py``) are public, and the description below comes from
58
+ them.
59
+
60
+ .. rubric:: Architecture Overview
61
+
62
+ In the figure's symbols, :math:`H` = ``n_chans // 2`` fNIRS channels,
63
+ :math:`W` = ``n_times``, :math:`C` = 2 chromophores, :math:`H_S = H -
64
+ k_s + 1` spatial tokens, :math:`H_C = H` channel tokens and :math:`D` =
65
+ ``embed_dim``::
66
+
67
+ input: H HbO rows and H HbR rows (batch, 2 H, W)
68
+ to_chromophore_planes (batch, 2, H, W)
69
+ Spatial level (to_patch_embedding, transformer_patch):
70
+ Conv_S, Rearrange, Linear, LayerNorm (batch, H_S, D)
71
+ prepend CLS, add positions, encoder (batch, H_S + 1, D)
72
+ Channel level (to_channel_embedding, transformer_channel):
73
+ Conv_C, Rearrange, Linear, LayerNorm (batch, H_C, D)
74
+ prepend CLS, add positions, encoder (batch, H_C + 1, D)
75
+ CLS token of each level, Concat (batch, 2 D)
76
+ final_norm, final_layer (batch, n_outputs)
77
+
78
+ .. rubric:: Macro Components
79
+
80
+ - ``to_chromophore_planes`` **Input.** The authors' input is "[B, 2,
81
+ fNIRS channels, sampling points]", where '"2" means two chromophores:
82
+ HbO and HbR' (``model.py``, README). The rows of ``x`` are split into
83
+ these two planes, from the stacked or MNE's interleaved order.
84
+ - ``to_patch_embedding`` **Spatial level ("fNIRS Spatial
85
+ Embedding").** :math:`\mathrm{Conv}_S` maps the two planes to
86
+ :math:`C_S` = ``n_conv_filters`` maps with a :math:`k_s \times k_t`
87
+ kernel and stride :math:`1 \times s_t` (the authors: 8 maps,
88
+ :math:`5 \times 30`, stride :math:`1 \times 4`), so each token covers
89
+ :math:`k_s` consecutive channels in the dataset's order. The
90
+ :math:`C_S \times W_S` responses of a token are flattened, projected
91
+ to :math:`D` and layer-normalized.
92
+ - ``to_channel_embedding`` **Channel level ("fNIRS Channel
93
+ Embedding").** The same with a :math:`1 \times k_t` kernel
94
+ (:math:`\mathrm{Conv}_C`): one token per fNIRS channel.
95
+ - ``cls_token_*``, ``pos_embedding_*``, ``transformer_*`` **Transformer
96
+ Encoder.** Each level prepends a learned class token, adds a learned
97
+ positional embedding (one row per token, the token's only identity),
98
+ applies dropout and runs ``depth`` pre-norm blocks of multi-head
99
+ self-attention and a GELU feed-forward layer of width ``mlp_dim``. The
100
+ queries, keys and values come from bias-free linear maps, and each of
101
+ the ``num_heads`` heads of width :math:`d_h` = ``head_dim`` computes,
102
+ as in the authors' ``Attention``,
103
+
104
+ .. math::
105
+
106
+ \mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left(
107
+ \frac{Q K^{\top}}{\sqrt{d_h}} \right) V .
108
+
109
+ - ``final_norm``, ``final_layer`` **Head.** The class token of each
110
+ level (or, with ``pool="mean"``, the mean of its tokens) is taken, the
111
+ two vectors are concatenated ("Concat"), layer-normalized and
112
+ classified by a linear layer (the authors' ``mlp_head``).
113
+
114
+ .. rubric:: Temporal, Spatial, and Spectral Encoding
115
+
116
+ - *Temporal:* the convolutions slide a :math:`k_t`-sample kernel with
117
+ stride :math:`s_t` along time, and the resulting values become
118
+ features of a token. The README's segments are 140 samples (dataset
119
+ A), 200 (B) and 256 (C). Kernels count samples, so ``sfreq`` is
120
+ unused.
121
+ - *Spatial:* channels or groups of :math:`k_s` consecutive channels,
122
+ identified by their position in the token sequence; no montage or
123
+ optode geometry. The channel order must be the one used in training.
124
+ - *Chromophores:* HbO and HbR are the two input planes, mixed by both
125
+ convolutions from the first layer.
126
+ - *Spectral:* none in the model; fNIRS-T expects band-pass filtered,
127
+ baseline-corrected segments, and :class:`FNIRSPreT` learns that step.
128
+
129
+ .. rubric:: Pretrained Weights
130
+
131
+ None: the authors release code, not weights.
132
+
133
+ .. rubric:: Differences from the reference implementation
134
+
135
+ ``x`` is ``(batch, n_chans, n_times)``, ``n_chans = 2 H``, HbO rows then
136
+ HbR rows, or MNE's interleaved order read from ``chs_info``. The figure
137
+ draws an "MLP Head" per level before "Concat"; the authors' code, which
138
+ this module follows, concatenates first and applies one head, and the
139
+ output is logits. The positional tables have one row per token (the
140
+ authors allocate 101 rows and slice), so an authors' ``state_dict``
141
+ loads after a conversion rather than a ``mapping`` (``to_qkv`` split
142
+ into ``queries``/``keys``/``values``, tables cut, ``mlp_head.{0,1}`` to
143
+ ``final_norm``/``final_layer``); the port then matches the authors'
144
+ model to float32 rounding (max-abs below 1e-6 on their dataset A, B and
145
+ C configurations). The attention always projects its output (the
146
+ authors skip it when ``num_heads=1`` and ``head_dim=embed_dim``).
147
+ ``mask`` is an addition of the port; ``ch_mask`` is refused, as the
148
+ spatial kernel and the positional tables span the whole montage.
149
+
150
+ Parameters
151
+ ----------
152
+ embed_dim : int, default=64
153
+ :math:`D`, the authors' ``dim``, "last dimension of output tensor
154
+ after linear transformation"; 64 for their datasets A and B, 128 for
155
+ C.
156
+ depth : int, default=6
157
+ Authors' ``depth``, "number of Transformer blocks" per level.
158
+ num_heads : int, default=8
159
+ Authors' ``heads``, "number of the multi-head self-attention".
160
+ mlp_dim : int, default=64
161
+ Authors' ``mlp_dim``, "dimension of the MLP layer".
162
+ pool : {"cls", "mean"}, default="cls"
163
+ Read-out of each level (authors' ``pool``): ``"cls"``, its class
164
+ token; ``"mean"``, the mean over its tokens (class token included).
165
+ head_dim : int, default=64
166
+ :math:`d_h`, the authors' ``dim_head``: width of each attention head.
167
+ n_conv_filters : int, default=8
168
+ :math:`C_S = C_C`, feature maps of both convolutions (authors: 8).
169
+ spatial_kernel_size : int, default=5
170
+ :math:`k_s`, height of :math:`\mathrm{Conv}_S` in HbO/HbR pairs
171
+ (authors: 5); at most the number of pairs, ``n_chans // 2``.
172
+ temporal_kernel_size : int, default=30
173
+ :math:`k_t`, temporal kernel of both convolutions, in samples
174
+ (authors: 30); ``n_times`` must be at least this.
175
+ temporal_stride : int, default=4
176
+ :math:`s_t`, temporal stride of both convolutions, in samples
177
+ (authors: 4).
178
+ channel_order : {"stacked", "interleaved"} or None, default=None
179
+ ``[HbO_1..HbO_H, HbR_1..HbR_H]`` or MNE's ``[HbO_1, HbR_1, ...]``;
180
+ ``None`` reads it from ``chs_info``.
181
+ drop_prob : float, default=0.0
182
+ Authors' ``dropout`` in the attention and feed-forward sub-layers.
183
+ embed_drop_prob : float, default=0.0
184
+ Authors' ``emb_dropout``, "dropout for patch embeddings".
185
+ activation : type[nn.Module], default=nn.GELU
186
+ Activation of the feed-forward sub-layers (authors: GELU).
187
+
188
+ Notes
189
+ -----
190
+ The authors' code uses three datasets: A (mental arithmetic vs rest, 8
191
+ subjects, 52 channels, 140 samples), B (Shin et al. 2017, same task, 29
192
+ subjects, 36 channels, 200 samples) and C (Bak et al. 2019, finger and
193
+ foot tapping, 3 classes, 30 subjects, 20 channels, 256 samples). The
194
+ fNIRS-T inputs are band-passed (0.01-0.1 Hz on B and C),
195
+ baseline-corrected and z-scored per window. Training is 5 x 5-fold
196
+ cross-validation over pooled trials or leave-one-subject-out, 120
197
+ epochs, batch 128, AdamW with cosine annealing (``T_max=30``) and label
198
+ smoothing 0.1 in both loops, and the best test-fold accuracy is kept.
199
+ On B and C the loss is "flooded" (``loss = (loss - b).abs() + b``) with
200
+ a level :math:`b` the README decays "at the specified epoch to obtain
201
+ continuous regularization": 0.45, 0.40 and 0.35 from the zero-based
202
+ epochs 0, 30 and 50.
203
+
204
+ Replication on dataset C with the authors' ``KFold_Train.py`` (mean of
205
+ the 25 runs of each seed, averaged over seeds 0-2; macro-F1 at the kept
206
+ epoch):
207
+
208
+ ========== ================= ================ ================
209
+ Model Paper (abstract) Port (acc / F1) Authors' code
210
+ ========== ================= ================ ================
211
+ fNIRS-T 75.49 % 75.03 % / 0.7498 74.73 % / 0.7469
212
+ fNIRS-PreT "competitive" 72.50 % / 0.7244 72.50 % / 0.7245
213
+ ========== ================= ================ ================
214
+
215
+ .. versionadded:: 2.1
216
+
217
+ `License <https://github.com/wzhlearning/fNIRS-Transformer/blob/6ebe987faacc5587e11e8bd0d1177b40ec3ccd8d/LICENSE>`_
218
+
219
+ References
220
+ ----------
221
+ .. footbibliography::
222
+ """
223
+
224
+ def __init__(
225
+ self,
226
+ # Braindecode parameters
227
+ n_outputs: int | None = None,
228
+ n_chans: int | None = None,
229
+ chs_info: list[dict] | None = None,
230
+ n_times: int | None = None,
231
+ input_window_seconds: float | None = None,
232
+ sfreq: float | None = None,
233
+ *,
234
+ # Model-specific parameters
235
+ embed_dim: int = 64,
236
+ depth: int = 6,
237
+ num_heads: int = 8,
238
+ mlp_dim: int = 64,
239
+ pool: Literal["cls", "mean"] = "cls",
240
+ head_dim: int = 64,
241
+ n_conv_filters: int = 8,
242
+ spatial_kernel_size: int = 5,
243
+ temporal_kernel_size: int = 30,
244
+ temporal_stride: int = 4,
245
+ channel_order: Literal["stacked", "interleaved"] | None = None,
246
+ drop_prob: float = 0.0,
247
+ embed_drop_prob: float = 0.0,
248
+ activation: type[nn.Module] = nn.GELU,
249
+ ) -> None:
250
+ super().__init__(
251
+ n_outputs=n_outputs,
252
+ n_chans=n_chans,
253
+ chs_info=chs_info,
254
+ n_times=n_times,
255
+ input_window_seconds=input_window_seconds,
256
+ sfreq=sfreq,
257
+ )
258
+ del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
259
+
260
+ # Parameters
261
+ self.pool = pool
262
+ # Name in the errors of forward, as the other fNIRS models do (a scripted
263
+ # forward cannot read type(self).__name__)
264
+ self._class_name = type(self).__name__
265
+ # H in the authors' figure: fNIRS channels, each an HbO/HbR pair of rows
266
+ n_pairs = self.n_chans // 2
267
+ # W_S = W_C: positions of the temporal kernel along the window; they
268
+ # become features of a token, not tokens
269
+ n_bins = (self.n_times - temporal_kernel_size) // temporal_stride + 1
270
+ # H_S: groups of ``spatial_kernel_size`` consecutive channels
271
+ n_groups = n_pairs - spatial_kernel_size + 1
272
+
273
+ # Checkers
274
+ # The temporal kernel needs at least one position in the window
275
+ if self.n_times < temporal_kernel_size:
276
+ raise ValueError(
277
+ f"n_times ({self.n_times}) must be >= temporal_kernel_size "
278
+ f"({temporal_kernel_size})."
279
+ )
280
+ # The authors' input is [B, 2, channels, samples]: an odd number of
281
+ # rows cannot be split into the HbO and the HbR plane
282
+ if self.n_chans % 2:
283
+ raise ValueError(
284
+ f"{type(self).__name__} needs HbO/HbR pairs: n_chans must be even, "
285
+ f"got {self.n_chans}."
286
+ )
287
+ if pool not in ("cls", "mean"):
288
+ raise ValueError(f"pool must be 'cls' or 'mean', got {pool!r}.")
289
+ # HbO/HbR layout of the rows (the helper refuses a montage that is
290
+ # not paired HbO/HbR)
291
+ order = fnirs_channel_order(self._chs_info, channel_order)
292
+ # Conv_S needs at least one group of channels (the authors' fails too)
293
+ if spatial_kernel_size > n_pairs:
294
+ raise ValueError(
295
+ f"spatial_kernel_size ({spatial_kernel_size}) must be at most the "
296
+ f"number of HbO/HbR pairs ({n_pairs})."
297
+ )
298
+
299
+ # Layers
300
+ # Following the nomenclature of the authors' figure (fig/model.png)
301
+ # Input: the rows are split into the HbO and the HbR plane, the
302
+ # H x W x C input of the figure with the chromophores first
303
+ channel_axes = "(chans chrom)" if order == "interleaved" else "(chrom chans)"
304
+ self.to_chromophore_planes = Rearrange(
305
+ f"batch {channel_axes} time -> batch chrom chans time", chrom=2
306
+ )
307
+
308
+ # fNIRS-T takes filtered, baseline-corrected segments as they are;
309
+ # FNIRSPreT puts its Preprocessing Module here
310
+ self.pre = nn.Identity()
311
+
312
+ # Spatial level
313
+ # fNIRS Spatial Embedding: Conv_S over k_s consecutive channels and
314
+ # k_t samples; the responses of a group are flattened, projected to
315
+ # the embedding size and layer-normalized: one token per group
316
+ self.to_patch_embedding = nn.Sequential(
317
+ nn.Conv2d(
318
+ in_channels=2,
319
+ out_channels=n_conv_filters,
320
+ kernel_size=(spatial_kernel_size, temporal_kernel_size),
321
+ stride=(1, temporal_stride),
322
+ ),
323
+ Rearrange("batch maps tokens bins -> batch tokens (maps bins)"),
324
+ nn.Linear(n_bins * n_conv_filters, embed_dim),
325
+ nn.LayerNorm(embed_dim),
326
+ )
327
+ # Learned class token and positional embedding, one row per token
328
+ # (class token and H_S groups); the row is the token's only identity
329
+ self.cls_token_patch = nn.Parameter(torch.empty(1, 1, embed_dim))
330
+ self.pos_embedding_patch = nn.Parameter(torch.empty(1, n_groups + 1, embed_dim))
331
+ self.dropout_patch = nn.Dropout(embed_drop_prob)
332
+ # Transformer Encoder: ``depth`` pre-norm blocks of bias-free
333
+ # multi-head self-attention and a feed-forward layer of width mlp_dim
334
+ self.transformer_patch = _TransformerEncoder(
335
+ embed_dim=embed_dim,
336
+ depth=depth,
337
+ num_heads=num_heads,
338
+ head_dim=head_dim,
339
+ mlp_dim=mlp_dim,
340
+ drop_prob=drop_prob,
341
+ activation=activation,
342
+ )
343
+
344
+ # Channel level
345
+ # fNIRS Channel Embedding: Conv_C, the same with a 1 x k_t kernel:
346
+ # one token per fNIRS channel
347
+ self.to_channel_embedding = nn.Sequential(
348
+ nn.Conv2d(
349
+ in_channels=2,
350
+ out_channels=n_conv_filters,
351
+ kernel_size=(1, temporal_kernel_size),
352
+ stride=(1, temporal_stride),
353
+ ),
354
+ Rearrange("batch maps tokens bins -> batch tokens (maps bins)"),
355
+ nn.Linear(n_bins * n_conv_filters, embed_dim),
356
+ nn.LayerNorm(embed_dim),
357
+ )
358
+ # Class token and positional embedding (class token and H channels)
359
+ self.cls_token_channel = nn.Parameter(torch.empty(1, 1, embed_dim))
360
+ self.pos_embedding_channel = nn.Parameter(
361
+ torch.empty(1, n_pairs + 1, embed_dim)
362
+ )
363
+ self.dropout_channel = nn.Dropout(embed_drop_prob)
364
+ # Transformer Encoder of the channel level, same layout as above
365
+ self.transformer_channel = _TransformerEncoder(
366
+ embed_dim=embed_dim,
367
+ depth=depth,
368
+ num_heads=num_heads,
369
+ head_dim=head_dim,
370
+ mlp_dim=mlp_dim,
371
+ drop_prob=drop_prob,
372
+ activation=activation,
373
+ )
374
+
375
+ # Head (the authors' mlp_head): the two levels are concatenated
376
+ # ("Concat"), layer-normalized and classified
377
+ # Mean over the tokens of a level, the pool="mean" alternative to its
378
+ # class token
379
+ self.token_mean = Reduce("batch tokens embed_dim -> batch embed_dim", "mean")
380
+ self.final_norm = nn.LayerNorm(embed_dim * 2)
381
+ self.final_layer = nn.Linear(embed_dim * 2, self.n_outputs)
382
+
383
+ self._init_parameters()
384
+
385
+ def _init_parameters(self) -> None:
386
+ # Class tokens and positional tables are drawn from N(0, 1), after the
387
+ # layers, so that reset_parameters() repeats the constructor.
388
+ with torch.no_grad():
389
+ self.cls_token_patch.normal_()
390
+ self.pos_embedding_patch.normal_()
391
+ self.cls_token_channel.normal_()
392
+ self.pos_embedding_channel.normal_()
393
+
394
+ def reset_head(self, n_outputs: int) -> None:
395
+ self._set_n_outputs(n_outputs)
396
+ self.final_layer = nn.Linear(self.final_layer.in_features, n_outputs)
397
+
398
+ def forward(
399
+ self,
400
+ x: torch.Tensor,
401
+ return_features: bool = False,
402
+ ch_mask: torch.Tensor | None = None,
403
+ mask: torch.Tensor | None = None,
404
+ ) -> torch.Tensor | dict[str, torch.Tensor | None]:
405
+ """Forward pass of the fNIRS-T (and fNIRS-PreT) model.
406
+
407
+ Parameters
408
+ ----------
409
+ x : torch.Tensor
410
+ Input tensor with shape ``(batch_size, n_chans, n_times)``.
411
+ return_features : bool, default=False
412
+ If True, return the normalized pooled features and the class
413
+ tokens of the two levels.
414
+ ch_mask : torch.Tensor or None
415
+ Not supported: the spatial kernel and the positional tables span
416
+ every channel.
417
+ mask : torch.Tensor or None
418
+ Boolean tensor with the shape of ``x``; True samples are set to
419
+ zero before the model reads them.
420
+
421
+ Returns
422
+ -------
423
+ torch.Tensor or dict
424
+ Logits with shape ``(batch_size, n_outputs)``, or with
425
+ ``return_features=True`` the dict ``{"features", "cls_token"}``,
426
+ both of shape ``(batch_size, 2 * embed_dim)``.
427
+ """
428
+ # A token is identified only by its row of the positional table, and
429
+ # Conv_S groups neighbouring channels: a subset of them is another
430
+ # layout
431
+ if ch_mask is not None:
432
+ raise ValueError(
433
+ self._class_name + " does not accept ch_mask: the spatial kernel "
434
+ "and the positional tables span every channel."
435
+ )
436
+
437
+ # Below, H = n_chans // 2 fNIRS channels, W = n_times, D = embed_dim,
438
+ # H_S = H - spatial_kernel_size + 1 groups of channels
439
+
440
+ # Hidden samples are set to zero (an addition of the port)
441
+ # (batch, 2 H, W)
442
+ if mask is not None:
443
+ x = x.masked_fill(mask, 0.0)
444
+
445
+ # Input: the rows are split into the HbO and the HbR plane
446
+ # (batch, 2 H, W) -> (batch, 2, H, W)
447
+ x = self.to_chromophore_planes(x)
448
+ # Preprocessing Module of fNIRS-PreT (identity in fNIRS-T, whose
449
+ # segments are already filtered and baseline-corrected)
450
+ # (batch, 2, H, W)
451
+ x = self.pre(x)
452
+ batch_size = x.shape[0]
453
+
454
+ # Spatial level. fNIRS Spatial Embedding: Conv_S, flatten, linear
455
+ # projection, LayerNorm; one token per group of consecutive channels
456
+ # (batch, 2, H, W) -> (batch, H_S, D)
457
+ patch = self.to_patch_embedding(x)
458
+ # Class token of the level, one copy per sample
459
+ # (1, 1, D) -> (batch, 1, D)
460
+ cls_patch = self.cls_token_patch.expand(batch_size, -1, -1)
461
+ # (batch, H_S, D) -> (batch, H_S + 1, D)
462
+ patch = torch.cat((cls_patch, patch), dim=1)
463
+ # Learned positional embedding, which tells the groups apart; shape
464
+ # unchanged
465
+ patch = patch + self.pos_embedding_patch
466
+ patch = self.dropout_patch(patch)
467
+ # Transformer Encoder: the groups attend to each other
468
+ # (batch, H_S + 1, D)
469
+ patch = self.transformer_patch(patch)
470
+
471
+ # Channel level. fNIRS Channel Embedding: Conv_C, flatten, linear
472
+ # projection, LayerNorm; one token per fNIRS channel
473
+ # (batch, 2, H, W) -> (batch, H, D)
474
+ channel = self.to_channel_embedding(x)
475
+ # Class token of the level, one copy per sample
476
+ # (1, 1, D) -> (batch, 1, D)
477
+ cls_channel = self.cls_token_channel.expand(batch_size, -1, -1)
478
+ # (batch, H, D) -> (batch, H + 1, D)
479
+ channel = torch.cat((cls_channel, channel), dim=1)
480
+ # Learned positional embedding, which tells the channels apart; shape
481
+ # unchanged
482
+ channel = channel + self.pos_embedding_channel
483
+ channel = self.dropout_channel(channel)
484
+ # Transformer Encoder: the channels attend to each other
485
+ # (batch, H + 1, D)
486
+ channel = self.transformer_channel(channel)
487
+
488
+ # Class token of each level, the summary of its tokens
489
+ # (batch, D)
490
+ patch_token = patch[:, 0]
491
+ channel_token = channel[:, 0]
492
+ # "Concat" of the two levels
493
+ # 2 x (batch, D) -> (batch, 2 D)
494
+ cls_tokens = torch.cat((patch_token, channel_token), dim=1)
495
+
496
+ if self.pool == "mean":
497
+ # Alternative pooling: the mean of the tokens of each level
498
+ # (batch, tokens, D) -> (batch, D)
499
+ patch = self.token_mean(patch)
500
+ channel = self.token_mean(channel)
501
+ # 2 x (batch, D) -> (batch, 2 D)
502
+ features = torch.cat((patch, channel), dim=1)
503
+ else:
504
+ features = cls_tokens
505
+
506
+ # Head (the authors' mlp_head): LayerNorm of the concatenation
507
+ # (batch, 2 D)
508
+ features = self.final_norm(features)
509
+
510
+ if return_features:
511
+ return {"features": features, "cls_token": cls_tokens}
512
+
513
+ # Linear classifier; the output is logits
514
+ # (batch, 2 D) -> (batch, n_outputs)
515
+ x = self.final_layer(features)
516
+ return x
517
+
518
+
519
+ class FNIRSPreT(FNIRST, license="mit"): # the kwarg is not inherited
520
+ r"""fNIRS-PreT from Wang et al. (2022).
521
+
522
+ :bdg-success:`Convolution` :bdg-info:`Attention/Transformer`
523
+
524
+ .. figure:: https://braindecode.org/dev/_static/model/fnirst.png
525
+ :align: center
526
+ :alt: fNIRS-T and fNIRS-PreT architecture
527
+
528
+ The figure of the authors' repository (``fig/model.png`` of
529
+ wzhlearning/fNIRS-Transformer at ``6ebe987f``, MIT). fNIRS-PreT is the
530
+ right-hand input path: "Modified Beer-Lambert law", "Segmentation",
531
+ then the "Preprocessing Module", then the two branches of fNIRS-T. The
532
+ paper (IEEE JBHI 2022) is not open access; its caption is not
533
+ reproduced.
534
+
535
+ fNIRS-T expects signals that were band-pass filtered and
536
+ baseline-corrected by hand. From the abstract :footcite:`wang2022fnirst`:
537
+ "a preprocessing module, which consists of one-dimensional average
538
+ pooling and layer normalization, is designed to replace filtering and
539
+ baseline correction of data preprocessing. It makes fNIRS-T an
540
+ end-to-end network, called fNIRS-PreT." The abstract adds that
541
+ "fNIRS-PreT using raw data also achieves competitive performance to
542
+ fNIRS-T", without a number.
543
+
544
+ The authors' ``PreBlock`` (``model.py``) is that module: "Preprocessing
545
+ module. It is designed to replace filtering and baseline correction."
546
+ Only the abstract, the README, the figure and the code are public, and
547
+ the description below comes from them.
548
+
549
+ .. rubric:: Architecture Overview
550
+
551
+ This is :class:`~braindecode.models.FNIRST` with the preprocessing module
552
+ (``pre``) first, as the authors' ``fNIRS_PreT`` (``PreBlock``, then
553
+ ``fNIRS_T``). With :math:`H` = ``n_chans // 2`` channels and :math:`W` =
554
+ ``n_times`` samples::
555
+
556
+ input: H HbO rows and H HbR rows (batch, 2 H, W)
557
+ to_chromophore_planes (batch, 2, H, W)
558
+ pre: per plane, average_pooling, norms[i] (batch, 2, H, W)
559
+ fNIRS-T levels, Concat, head (batch, n_outputs)
560
+
561
+ .. rubric:: Macro Components
562
+
563
+ - ``pre.average_pooling`` **Average pooling.** Three moving averages
564
+ along time, ``AvgPool1d`` with kernels :math:`k` = 5, 13 and 7, stride
565
+ 1 and "same" zero padding (the authors' ``pool1``, ``pool2``,
566
+ ``pool3``), shared by HbO and HbR. With :math:`k = 2r + 1`, each is
567
+
568
+ .. math::
569
+
570
+ m_k(x)[t] = \frac{1}{k} \sum_{j=-r}^{r} x[t + j] .
571
+
572
+ - ``pre.norms`` **Layer normalization.** One ``LayerNorm`` over the
573
+ :math:`W` samples per chromophore (the authors' ``ln_0``, ``ln_1``):
574
+ each channel row is centred and scaled over the window, then given a
575
+ learned scale and shift per sample, so the weights are tied to
576
+ ``n_times``.
577
+ - Every other module is that of :class:`~braindecode.models.FNIRST`.
578
+
579
+ .. rubric:: Temporal, Spatial, and Spectral Encoding
580
+
581
+ The module keeps the :math:`W` samples and treats every channel row
582
+ alike; HbO and HbR share the moving averages and have their own
583
+ LayerNorm. It has no explicit frequency decomposition: it stands in for
584
+ the filtering and baseline correction, so the inputs are raw segmented
585
+ concentration changes. The rest is as in
586
+ :class:`~braindecode.models.FNIRST`.
587
+
588
+ .. rubric:: Pretrained Weights
589
+
590
+ None: the authors release code, not weights.
591
+
592
+ .. rubric:: Differences from the reference implementation
593
+
594
+ ``pre.ln_i`` is ``pre.norms.i`` and the authors' ``fNIRS_T.`` prefix is
595
+ removed: an authors' ``fNIRS_PreT`` ``state_dict`` loads after FNIRST's
596
+ conversion with these two renames, and the port and the authors' model
597
+ then agree to float32 rounding (max-abs below 1e-6 on the dataset A, B
598
+ and C configurations). The port indexes each chromophore plane, where
599
+ the authors' ``PreBlock`` calls ``squeeze()``, which also drops the
600
+ batch axis for a batch of one. The input layout, the opt-in ``mask``,
601
+ the logits and the parameters are those of
602
+ :class:`~braindecode.models.FNIRST`.
603
+
604
+ Notes
605
+ -----
606
+ The protocol of the authors' released code is that of
607
+ :class:`~braindecode.models.FNIRST`, on raw data: their README asks to
608
+ disable the filtering and baseline correction of ``B_mat2xls.m`` and
609
+ ``C_mat2xls.m`` by hand for fNIRS-PreT, and ``Load_Dataset_A`` skips the
610
+ dataset A filters for ``model='fNIRS-PreT'``. The flooding levels are
611
+ those of fNIRS-T except on dataset B (0.40, 0.38 and 0.35 from the
612
+ zero-based epochs 0, 30 and 50).
613
+
614
+ The dataset C replication is the fNIRS-PreT row of the table of
615
+ :class:`~braindecode.models.FNIRST`. Both sides received the band-pass
616
+ filtered, baseline-corrected windows of fNIRS-T there, as the released
617
+ ``Load_Dataset_C`` has no raw-data path.
618
+
619
+ .. versionadded:: 2.1
620
+
621
+ `License <https://github.com/wzhlearning/fNIRS-Transformer/blob/6ebe987faacc5587e11e8bd0d1177b40ec3ccd8d/LICENSE>`_
622
+
623
+ References
624
+ ----------
625
+ .. footbibliography::
626
+ """
627
+
628
+ # The signature repeats FNIRST's, so that both models list the same
629
+ # parameters; with docstring inheritance on (docs/conf.py), a subclass
630
+ # sharing FNIRST.__init__ would also be given FNIRST's docstring.
631
+ def __init__(
632
+ self,
633
+ # Braindecode parameters
634
+ n_outputs: int | None = None,
635
+ n_chans: int | None = None,
636
+ chs_info: list[dict] | None = None,
637
+ n_times: int | None = None,
638
+ input_window_seconds: float | None = None,
639
+ sfreq: float | None = None,
640
+ *,
641
+ # Model-specific parameters
642
+ embed_dim: int = 64,
643
+ depth: int = 6,
644
+ num_heads: int = 8,
645
+ mlp_dim: int = 64,
646
+ pool: Literal["cls", "mean"] = "cls",
647
+ head_dim: int = 64,
648
+ n_conv_filters: int = 8,
649
+ spatial_kernel_size: int = 5,
650
+ temporal_kernel_size: int = 30,
651
+ temporal_stride: int = 4,
652
+ channel_order: Literal["stacked", "interleaved"] | None = None,
653
+ drop_prob: float = 0.0,
654
+ embed_drop_prob: float = 0.0,
655
+ activation: type[nn.Module] = nn.GELU,
656
+ ) -> None:
657
+ super().__init__(
658
+ n_outputs=n_outputs,
659
+ n_chans=n_chans,
660
+ chs_info=chs_info,
661
+ n_times=n_times,
662
+ input_window_seconds=input_window_seconds,
663
+ sfreq=sfreq,
664
+ embed_dim=embed_dim,
665
+ depth=depth,
666
+ num_heads=num_heads,
667
+ mlp_dim=mlp_dim,
668
+ pool=pool,
669
+ head_dim=head_dim,
670
+ n_conv_filters=n_conv_filters,
671
+ spatial_kernel_size=spatial_kernel_size,
672
+ temporal_kernel_size=temporal_kernel_size,
673
+ temporal_stride=temporal_stride,
674
+ channel_order=channel_order,
675
+ drop_prob=drop_prob,
676
+ embed_drop_prob=embed_drop_prob,
677
+ activation=activation,
678
+ )
679
+
680
+ # Layers
681
+ # Preprocessing Module: learned in place of the band-pass filter and
682
+ # baseline correction that fNIRS-T expects; it takes the place of the
683
+ # identity between the chromophore planes and the two embeddings
684
+ self.pre = _PreprocessingModule(n_times=self.n_times)
685
+
686
+
687
+ class _TransformerEncoder(nn.Sequential):
688
+ """Transformer Encoder of one level (the authors' ``Transformer``).
689
+
690
+ ``depth`` pre-norm blocks, each a multi-head self-attention with bias-free
691
+ query, key and value maps and a feed-forward layer, both with a residual
692
+ connection. Built only from the shared ``PreNormTransformerBlock``,
693
+ ``MultiHeadAttention`` and ``FeedForwardBlock``; the class groups them
694
+ under the authors' name for the two levels of the model.
695
+
696
+ Parameters
697
+ ----------
698
+ embed_dim : int
699
+ Size of the tokens.
700
+ depth : int
701
+ Number of blocks.
702
+ num_heads : int
703
+ Number of attention heads.
704
+ head_dim : int
705
+ Width of each attention head.
706
+ mlp_dim : int
707
+ Hidden width of the feed-forward layer.
708
+ drop_prob : float
709
+ Dropout probability inside the blocks.
710
+ activation : type[nn.Module]
711
+ Activation of the feed-forward layer.
712
+ """
713
+
714
+ def __init__(
715
+ self,
716
+ embed_dim: int,
717
+ depth: int,
718
+ num_heads: int,
719
+ head_dim: int,
720
+ mlp_dim: int,
721
+ drop_prob: float,
722
+ activation: type[nn.Module],
723
+ ) -> None:
724
+ super().__init__(
725
+ *[
726
+ PreNormTransformerBlock(
727
+ embed_dim,
728
+ # Self-attention: the tokens (channels or groups of
729
+ # channels) attend to each other
730
+ MultiHeadAttention(
731
+ embed_dim, num_heads, head_dim=head_dim, qkv_bias=False
732
+ ),
733
+ # Feed-forward layer of hidden width mlp_dim
734
+ FeedForwardBlock(
735
+ embed_dim, 1, drop_prob, activation, hidden_features=mlp_dim
736
+ ),
737
+ drop_prob,
738
+ )
739
+ for _ in range(depth)
740
+ ]
741
+ )
742
+
743
+
744
+ class _PreprocessingModule(nn.Module):
745
+ """Preprocessing Module of fNIRS-PreT (the authors' ``PreBlock``).
746
+
747
+ Three moving averages in cascade, then a LayerNorm over time for HbO
748
+ (``norms.0``) and one for HbR (``norms.1``).
749
+
750
+ Parameters
751
+ ----------
752
+ n_times : int
753
+ Number of samples of the window, the size of the LayerNorms.
754
+ """
755
+
756
+ def __init__(self, n_times: int) -> None:
757
+ super().__init__()
758
+ # Moving averages of 5, 13 and 7 samples (the authors' values), a
759
+ # low-pass smoothing; the padding keeps the number of samples
760
+ self.average_pooling = nn.Sequential(
761
+ nn.AvgPool1d(kernel_size=5, stride=1, padding=2),
762
+ nn.AvgPool1d(kernel_size=13, stride=1, padding=6),
763
+ nn.AvgPool1d(kernel_size=7, stride=1, padding=3),
764
+ )
765
+ # One normalization over time per chromophore, with its own scale
766
+ # and offset per sample
767
+ self.norms = nn.ModuleList([nn.LayerNorm(n_times) for _ in range(2)])
768
+
769
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
770
+ """Smoothed and normalized planes, ``(batch, 2, n_pairs, n_times)``
771
+ like ``x``."""
772
+ planes = []
773
+ # HbO (plane 0) and HbR (plane 1) are processed separately
774
+ for chromophore, norm in enumerate(self.norms):
775
+ # (batch, 2, n_pairs, n_times) -> (batch, n_pairs, n_times)
776
+ plane = x[:, chromophore]
777
+ # Cascade of moving averages along time; shape unchanged
778
+ plane = self.average_pooling(plane)
779
+ # LayerNorm over the samples of each channel; shape unchanged
780
+ plane = norm(plane)
781
+ planes.append(plane)
782
+ # The two planes are stacked back
783
+ # 2 x (batch, n_pairs, n_times) -> (batch, 2, n_pairs, n_times)
784
+ x = torch.stack(planes, dim=1)
785
+ return x