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,761 @@
1
+ # Authors: Bruno Aristimunha <b.aristimunha@gmail.com>
2
+ #
3
+ # License: Apache-2.0
4
+ # Adapted from https://github.com/wzhlearning/fNIRS4D (Apache-2.0); S4D kernel after
5
+ # https://github.com/state-spaces/s4 (Apache-2.0).
6
+ """fNIRS4D: Domain Knowledge Fused State Space Model for fNIRS-Based BCIs."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from typing import Literal
12
+
13
+ import torch
14
+ import torch.nn.functional as F
15
+ from einops.layers.torch import Rearrange
16
+ from torch import nn
17
+
18
+ from braindecode.models.base import EEGModuleMixin
19
+ from braindecode.models.util import (
20
+ _disable_batch_norm_training_if_batch_size_one,
21
+ fnirs_channel_order,
22
+ fnirs_split_hbo_hbr,
23
+ )
24
+
25
+
26
+ class FNIRS4D(EEGModuleMixin, nn.Module, license="apache-2.0"):
27
+ r"""fNIRS4D from Wang et al. (2026).
28
+
29
+ :bdg-success:`Convolution` :bdg-secondary:`Recurrent`
30
+
31
+ .. figure:: https://braindecode.org/dev/_static/model/fnirs4d.png
32
+ :align: center
33
+ :alt: fNIRS4D architecture
34
+
35
+ ``fig/fig2.png`` of wzhlearning/fNIRS4D (``eb13e5e``, Apache-2.0),
36
+ resized: preprocessing, "fNIRS4D for Signal Classification" with its
37
+ "Selectable Branches" MAMHB (inter-subject) and MHB (intra-subject),
38
+ and the three task paradigms. The paper (IEEE TIM 2026) is not open
39
+ access; its caption is not reproduced.
40
+
41
+ From the abstract :footcite:`wang2026fnirs4d`: "many studies focus
42
+ solely on deep neural networks (DNNs) but neglect the importance of
43
+ fNIRS domain knowledge. We refine domain knowledge into neuroscientific
44
+ knowledge and expert prior. This article aims to integrate domain
45
+ knowledge into DNNs, including activation patterns, hemodynamic
46
+ responses, and feature engineering."
47
+
48
+ The backbone is a state space model: "Diagonally structured state space
49
+ sequence model (S4D), simple and efficient diagonal versions of SSMs,
50
+ are introduced to the fNIRS domain. We incorporate domain knowledge into
51
+ an S4D-based lightweight fNIRS classification model named fNIRS4D." The
52
+ S4D layer is that of Gu et al. :footcite:`gu2022s4d`. The repository's
53
+ ``fig/fig1.png`` ties each kind of knowledge to a block: activation
54
+ patterns to the "Mixed Hemoglobin" input, hemodynamic responses to
55
+ Knowledge Embedding (KE), feature engineering to the selectable mean
56
+ hemoglobin branches, with Knowledge Aggregation (KA) over all of them.
57
+ Only the abstract, README, figures and code are public, and the text
58
+ below comes from them.
59
+
60
+ .. rubric:: Architecture Overview
61
+
62
+ With :math:`H` = ``n_chans`` rows (``d_model`` in the authors' S4D),
63
+ :math:`T` = ``n_times`` samples, :math:`N` = ``n_layers`` and the
64
+ figure's names::
65
+
66
+ input: HbO and HbR rows (batch, H, T)
67
+ Mixed Hemoglobin [HbO, HbT], to_fnirs_tensor (batch, 1, H, T)
68
+ Selectable branch (mean_hemoglobin_branch):
69
+ MHB or MAMHB (batch, H)
70
+ Knowledge Embedding (fNIRS_knowledge_embedding):
71
+ Conv_1 (1 x T), IN, Conv_1x1, Rearrange (batch, H, H)
72
+ Knowledge Aggregation:
73
+ N x (S4D, dropout, residual, LN) (batch, H, H)
74
+ AP_4: mean over the sequence (batch, H)
75
+ concatenate with the branch, final_layer FC (batch, n_outputs)
76
+
77
+ .. rubric:: Macro Components
78
+
79
+ - ``compute_hbt`` **Mixed Hemoglobin.** The rows become HbO and total
80
+ hemoglobin, :math:`\mathrm{HbT} = \mathrm{HbO} + \mathrm{HbR}`, as in
81
+ the authors' ``dataloader.py``; HbO/HbR pairs come from
82
+ ``channel_order`` or ``chs_info``.
83
+ - ``fNIRS_knowledge_embedding`` **Knowledge Embedding (KE).** A
84
+ convolution with :math:`H` filters of :math:`1 \times T`, so each
85
+ filter reads the whole window of one row (the kernel shape of
86
+ :class:`~braindecode.models.FNIRSNet`'s DHRConv), instance
87
+ normalization and a :math:`1 \times 1` convolution. The result is
88
+ rearranged so that each row becomes a sequence of :math:`H` filter
89
+ responses, the sequence the S4D layers read.
90
+ - ``s4d_layers``, ``norms`` **Knowledge Aggregation (KA).** :math:`N`
91
+ S4D blocks, each S4D, dropout, a residual sum and a LayerNorm over the
92
+ rows (post-norm, or before the layer with ``prenorm=True``), then the
93
+ mean over the sequence (:math:`\mathrm{AP}_4`). Each S4D layer runs one
94
+ diagonal state space model per row. Gu et al. start from the
95
+ continuous system (their Eq. (1)), discretize it with the zero-order
96
+ hold (Section 3.1),
97
+
98
+ .. math::
99
+
100
+ x'(t) = A x(t) + B u(t), \quad y(t) = C x(t), \qquad
101
+ \bar{A} = e^{\Delta A}, \quad
102
+ \bar{B} = (\Delta A)^{-1} (e^{\Delta A} - I) \, \Delta B,
103
+
104
+ and apply it as a convolution with a Vandermonde kernel
105
+ (Eqs. (6)-(7)):
106
+
107
+ .. math::
108
+
109
+ y = u * \bar{K}, \qquad
110
+ \bar{K}_\ell = \sum_{n} C_n \bar{A}_n^{\ell} \bar{B}_n .
111
+
112
+ :math:`A` is diagonal and complex, initialized with S4D-Lin,
113
+ :math:`A_n = -\tfrac{1}{2} + i \pi n` (Eq. (9)); the step
114
+ :math:`\Delta` is learned per row from a log-uniform start in
115
+ [0.001, 0.1]. As in the authors' ``S4DKernel``, :math:`B = 1`, the sum
116
+ keeps ``d_state // 2`` entries and the kernel is twice its real part
117
+ ("same as adding conjugate pairs", Listing 1 of Gu et al.). The layer
118
+ adds a skip term :math:`D u`, then GELU, dropout, and a
119
+ :math:`1 \times 1` convolution with a GLU.
120
+ - ``mean_hemoglobin_branch`` **MHB and MAMHB.** The intra-subject Mean
121
+ Hemoglobin Branch (``mean_branch="time_mean"``) is the mean of each
122
+ row over time (:math:`\mathrm{AP}_1`). The inter-subject Multi-scale
123
+ Aggregated Mean Hemoglobin Branch (``"multiscale"``) averages all rows
124
+ into one signal (:math:`\mathrm{AP}_2`, ``avg_1``) and reads it twice,
125
+ directly and after an ``avg_size``-sample moving average
126
+ (:math:`\mathrm{AP}_3`, ``avg_2``), each time with a full-window
127
+ convolution of :math:`H/2` filters, BN and ELU (``conv_1``/``bn_1``,
128
+ ``conv_2``/``bn_2``); the two halves are concatenated.
129
+ - ``final_layer`` **FC.** One linear layer on the :math:`H` KA features
130
+ and the :math:`H` branch features.
131
+
132
+ .. rubric:: Temporal, Spatial, and Spectral Encoding
133
+
134
+ - *Temporal:* one 3 s window (40 samples on UFFT, 30 on MA and WG in
135
+ the authors' scripts). KE reads all samples of a row at once, so the
136
+ S4D layers run along the KE filters, not along time; the branches
137
+ summarize time by means and full-window convolutions. Kernels count
138
+ samples, so there is no sampling-rate argument.
139
+ - *Spatial:* no montage or optode geometry. Each row is one S4D channel,
140
+ LayerNorm normalizes across rows and MAMHB averages them; the row
141
+ order must be the one used in training.
142
+ - *Chromophores:* HbO and HbT; ``compute_hbt=False`` takes the rows as
143
+ given.
144
+ - *Spectral:* none in the model; the authors band-pass (UFFT, MA) or
145
+ low-pass (WG) the signals first.
146
+
147
+ .. rubric:: Pretrained Weights
148
+
149
+ None: the authors release code, not weights.
150
+
151
+ .. rubric:: Differences from the reference implementation
152
+
153
+ ``x`` is ``(batch, n_chans, n_times)``; ``to_fnirs_tensor`` adds the
154
+ authors' singleton axis, and HbT is formed inside the model (the authors
155
+ sum before their z-score; to reproduce it, pass their [HbO, HbT] arrays
156
+ with ``compute_hbt=False``). The S4D kernel is applied as a causal
157
+ convolution in real arithmetic instead of a complex FFT, equal up to
158
+ float32 rounding and free of complex tensors, so ``torch.jit.script``
159
+ and ``torch.export`` run on it; ``nn.Dropout1d`` replaces the authors'
160
+ ``DropoutNd``, and their unused ``_optim`` weight-decay hints are not
161
+ set. Names are the authors'; ``mapping`` renames ``fc.0.*``, so their
162
+ ``state_dict`` loads with ``strict=True``. ``mean_branch`` is their
163
+ ``mode``, and ``avg_size``, ``d_state`` and the activations expose
164
+ values their code fixes. A training batch of one sample runs the BN
165
+ layers on their running statistics, and ``ch_mask`` raises a
166
+ ``ValueError``.
167
+
168
+ Parameters
169
+ ----------
170
+ n_layers : int, default=4
171
+ Number of S4D blocks, the figure's :math:`N`; the authors use 4,
172
+ and 1 for WG subject-independent.
173
+ d_state : int, default=64
174
+ State size of each S4D kernel (the authors' ``d_state``), even: the
175
+ kernel keeps ``d_state // 2`` conjugate pairs.
176
+ avg_size : int, default=10
177
+ Width of the :math:`\mathrm{AP}_3` moving average of the
178
+ ``"multiscale"`` branch (the authors' ``avg_size_2``), at most
179
+ ``n_times``.
180
+ drop_prob : float, default=0.5
181
+ Dropout in and after each S4D layer (the authors' ``dropout``).
182
+ prenorm : bool, default=False
183
+ LayerNorm before each S4D layer instead of after the residual (the
184
+ authors' default is post-norm).
185
+ compute_hbt : bool, default=True
186
+ Replace HbR by HbT = HbO + HbR (even ``n_chans``).
187
+ channel_order : {"stacked", "interleaved"} or None, default=None
188
+ ``[HbO..., HbR...]`` (the authors') or ``[HbO_1, HbR_1, ...]`` (MNE);
189
+ ``None`` reads ``chs_info``, else assumes ``"stacked"``. Ignored when
190
+ ``compute_hbt=False``.
191
+ mean_branch : {"multiscale", "time_mean"}, default="multiscale"
192
+ The selectable branch (the authors' ``mode``): MAMHB for
193
+ ``"LOSO-CV"`` (needs an even ``n_chans``) or MHB for ``"KFold-CV"``.
194
+ activation : type[nn.Module], default=nn.GELU
195
+ Activation inside each S4D layer.
196
+ branch_activation : type[nn.Module], default=nn.ELU
197
+ Activation of the ``"multiscale"`` branch.
198
+
199
+ Notes
200
+ -----
201
+ The authors' code trains on UFFT :footcite:`bak2019ufft` (``n_chans`` =
202
+ ``n_times`` = 40), MA :footcite:`shin2017openaccess` and WG
203
+ :footcite:`shin2018simultaneous` (72 rows, 30 samples), with their BBCI
204
+ preprocessing, 3 s windows with a 1 s step, HbT per window and a z-score
205
+ from the training set. Subject-specific runs (MHB) use 5-fold CV over
206
+ trial blocks, 120 epochs, AdamW (lr 0.001 on UFFT, 0.0005 on MA and WG)
207
+ decayed by 0.2 at epochs 20, 40 and 60; subject-independent runs (MAMHB)
208
+ leave one subject out, batch 512, cosine lr over 30 epochs. Last-epoch
209
+ test accuracy.
210
+
211
+ In the authors' training loops, on the same UFFT and WG arrays, splits
212
+ and seeds (0-2), the port matches the authors' code: accuracy in %,
213
+ paired difference in points with its 95 % interval, all including zero.
214
+
215
+ ========== ========= ============= ====================
216
+ Cell This port Authors' code Paired diff [95% CI]
217
+ ========== ========= ============= ====================
218
+ UFFT KFold 71.98 72.00 -0.01 [-0.49, +0.46]
219
+ UFFT LOSO 65.81 65.85 -0.04 [-0.32, +0.24]
220
+ WG KFold 61.54 61.33 +0.21 [-0.50, +0.91]
221
+ WG LOSO 61.92 62.00 -0.07 [-0.54, +0.39]
222
+ ========== ========= ============= ====================
223
+
224
+ In the GeoNIRS benchmark :footcite:`li2026geonirs` (macro-F1 in %, 12 s
225
+ windows, subject-level 5-fold CV, seeds 810 and 811, ``"multiscale"``),
226
+ the port gives 67.89 on DS42 action mode and 49.86 on DS19 pain
227
+ intensity, against 68.98 and 50.79 in GeoNIRS Table 14 and 69.03 and
228
+ 50.60 for the GeoNIRS copy of fNIRS4D in the same loop.
229
+
230
+ .. versionadded:: 2.1
231
+
232
+ `License <https://github.com/wzhlearning/fNIRS4D/blob/eb13e5e5b47043ad408d8a50b3ec9fe079926c12/LICENSE>`_
233
+
234
+ References
235
+ ----------
236
+ .. footbibliography::
237
+ """
238
+
239
+ def __init__(
240
+ self,
241
+ # Braindecode parameters
242
+ n_outputs: int | None = None,
243
+ n_chans: int | None = None,
244
+ chs_info: list[dict] | None = None,
245
+ n_times: int | None = None,
246
+ input_window_seconds: float | None = None,
247
+ sfreq: float | None = None,
248
+ *,
249
+ # Model-specific parameters
250
+ n_layers: int = 4,
251
+ d_state: int = 64,
252
+ avg_size: int = 10,
253
+ drop_prob: float = 0.5,
254
+ prenorm: bool = False,
255
+ compute_hbt: bool = True,
256
+ channel_order: Literal["stacked", "interleaved"] | None = None,
257
+ mean_branch: Literal["multiscale", "time_mean"] = "multiscale",
258
+ activation: type[nn.Module] = nn.GELU,
259
+ branch_activation: type[nn.Module] = nn.ELU,
260
+ ) -> None:
261
+ super().__init__(
262
+ n_outputs=n_outputs,
263
+ n_chans=n_chans,
264
+ chs_info=chs_info,
265
+ n_times=n_times,
266
+ input_window_seconds=input_window_seconds,
267
+ sfreq=sfreq,
268
+ )
269
+ del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
270
+
271
+ # The authors' head is ``fc = Sequential(Linear)``: their state_dict
272
+ # loads as is
273
+ self.mapping = {f"fc.0.{k}": f"final_layer.{k}" for k in ("weight", "bias")}
274
+
275
+ # Parameters
276
+ self.prenorm = prenorm
277
+ self.compute_hbt = compute_hbt
278
+
279
+ # Checkers
280
+ # HbT = HbO + HbR is a sum over pairs: an odd number of rows has an
281
+ # unpaired chromophore
282
+ if compute_hbt and self.n_chans % 2:
283
+ raise ValueError(
284
+ f"compute_hbt needs HbO/HbR pairs, got n_chans={self.n_chans}."
285
+ )
286
+ # Knowledge Embedding gives a (H, 1) map per filter, and the instance
287
+ # normalization cannot normalize a single value
288
+ if self.n_chans < 2:
289
+ raise ValueError(f"FNIRS4D needs n_chans >= 2, got n_chans={self.n_chans}.")
290
+ if mean_branch not in ("multiscale", "time_mean"):
291
+ raise ValueError(
292
+ f"mean_branch must be 'multiscale' or 'time_mean', got {mean_branch!r}."
293
+ )
294
+ if mean_branch == "multiscale":
295
+ # MAMHB has H / 2 filters per scale, so that its two scales give
296
+ # the H features the FC layer expects
297
+ if self.n_chans % 2:
298
+ raise ValueError(
299
+ "mean_branch='multiscale' needs an even n_chans, "
300
+ f"got {self.n_chans}."
301
+ )
302
+ # The moving average (AP_3) needs at least one full window
303
+ if avg_size > self.n_times:
304
+ raise ValueError(
305
+ f"avg_size must be at most n_times={self.n_times}, got {avg_size}."
306
+ )
307
+ # HbO/HbR layout of the rows, read from chs_info when HbT is formed
308
+ # here (the helper refuses a montage that is not paired HbO/HbR)
309
+ pairs_info = self._chs_info if compute_hbt else None
310
+ self.channel_order = fnirs_channel_order(pairs_info, channel_order)
311
+
312
+ # Layers
313
+ # Following the nomenclature of the authors' figure (fig/fig2.png)
314
+ # The authors' input has a singleton axis: (batch, 1, H, T)
315
+ self.to_fnirs_tensor = Rearrange("batch chans time -> batch 1 chans time")
316
+
317
+ # Selectable branch (feature engineering as expert prior)
318
+ self.mean_hemoglobin_branch: nn.Module
319
+ if mean_branch == "multiscale":
320
+ # Multi-scale Aggregated Mean Hemoglobin Branch (MAMHB), the
321
+ # inter-subject (LOSO-CV) branch
322
+ self.mean_hemoglobin_branch = _MultiscaleMeanHemoglobinBranch(
323
+ n_chans=self.n_chans,
324
+ n_times=self.n_times,
325
+ avg_size=avg_size,
326
+ activation=branch_activation,
327
+ )
328
+ else:
329
+ # Mean Hemoglobin Branch (MHB), the intra-subject (KFold-CV)
330
+ # branch: AP_1, the mean of each row over the window
331
+ self.mean_hemoglobin_branch = nn.Sequential(
332
+ nn.AvgPool2d(kernel_size=(1, self.n_times), stride=1),
333
+ Rearrange("batch 1 chans 1 -> batch chans"),
334
+ )
335
+ # Knowledge Embedding (KE): hemodynamic responses as domain knowledge
336
+ self.fNIRS_knowledge_embedding = nn.Sequential(
337
+ # Conv_1: H filters of 1 x T, each reads the whole response of
338
+ # one row (the kernel shape of fNIRSNet's DHRConv)
339
+ nn.Conv2d(
340
+ in_channels=1,
341
+ out_channels=self.n_chans,
342
+ kernel_size=(1, self.n_times),
343
+ ),
344
+ # IN: each filter map is normalized over the rows
345
+ nn.InstanceNorm2d(self.n_chans),
346
+ # Conv_1x1: mixes the H filters
347
+ nn.Conv2d(
348
+ in_channels=self.n_chans,
349
+ out_channels=self.n_chans,
350
+ kernel_size=1,
351
+ ),
352
+ # Each row becomes one S4D channel (d_model = H) and the H filter
353
+ # responses its sequence
354
+ Rearrange("batch filters chans 1 -> batch chans filters"),
355
+ )
356
+
357
+ # Knowledge Aggregation (KA): N blocks of S4D and LayerNorm
358
+ self.s4d_layers = nn.ModuleList()
359
+ self.norms = nn.ModuleList()
360
+ for _ in range(n_layers):
361
+ self.s4d_layers.append(
362
+ _S4DLayer(
363
+ d_model=self.n_chans,
364
+ d_state=d_state,
365
+ drop_prob=drop_prob,
366
+ activation=activation,
367
+ )
368
+ )
369
+ # LN over the rows (the S4D channels)
370
+ self.norms.append(nn.LayerNorm(self.n_chans))
371
+ # Dropout of whole S4D channels before the residual sum
372
+ self.dropout = nn.Dropout1d(drop_prob)
373
+ # LayerNorm and the sequence mean (AP_4) read the row axis last
374
+ self.channels_last = Rearrange("batch chans filters -> batch filters chans")
375
+ self.channels_first = Rearrange("batch filters chans -> batch chans filters")
376
+
377
+ # Final fully connected layer, on the H features of KA and the H
378
+ # features of the mean hemoglobin branch
379
+ self.final_layer = nn.Linear(
380
+ in_features=2 * self.n_chans,
381
+ out_features=self.n_outputs,
382
+ )
383
+
384
+ def reset_head(self, n_outputs: int) -> None:
385
+ self._set_n_outputs(n_outputs)
386
+ self.final_layer = nn.Linear(self.final_layer.in_features, n_outputs)
387
+
388
+ @_disable_batch_norm_training_if_batch_size_one
389
+ def forward(
390
+ self,
391
+ x: torch.Tensor,
392
+ return_features: bool = False,
393
+ ch_mask: torch.Tensor | None = None,
394
+ ) -> torch.Tensor | dict[str, torch.Tensor | None]:
395
+ """Forward pass of the fNIRS4D model.
396
+
397
+ Parameters
398
+ ----------
399
+ x : torch.Tensor
400
+ Input tensor with shape ``(batch_size, n_chans, n_times)``: HbO
401
+ and HbR rows, or the rows as given with ``compute_hbt=False``.
402
+ return_features : bool, default=False
403
+ If True, return the features that feed the FC layer.
404
+ ch_mask : torch.Tensor or None
405
+ Not supported: every layer is sized by ``n_chans``.
406
+
407
+ Returns
408
+ -------
409
+ torch.Tensor or dict
410
+ Logits with shape ``(batch_size, n_outputs)``, or with
411
+ ``return_features=True`` the dict ``{"features", "cls_token"}``,
412
+ ``features`` of shape ``(batch_size, 2 * n_chans)`` and
413
+ ``cls_token`` None.
414
+ """
415
+ # The rows are the S4D channels and the LayerNorm axis: a subset of
416
+ # them is another model
417
+ if ch_mask is not None:
418
+ raise ValueError("FNIRS4D does not accept ch_mask: layers span n_chans.")
419
+
420
+ # Below, H = n_chans and T = n_times
421
+
422
+ # Mixed Hemoglobin (activation patterns as domain knowledge): the
423
+ # rows become HbO and total hemoglobin, HbT = HbO + HbR
424
+ if self.compute_hbt:
425
+ # (batch, H, T) -> 2 x (batch, H / 2, T)
426
+ hbo, hbr = fnirs_split_hbo_hbr(x, self.channel_order)
427
+ # (batch, H / 2, T)
428
+ hbt = hbo + hbr
429
+ # [HbO, HbT]: (batch, H, T)
430
+ x = torch.cat((hbo, hbt), dim=1)
431
+
432
+ # Singleton axis of the authors' input
433
+ # (batch, H, T) -> (batch, 1, H, T)
434
+ x = self.to_fnirs_tensor(x)
435
+
436
+ # Selectable branch, on the input: mean hemoglobin features (MHB:
437
+ # time mean of each row; MAMHB: two scales of the row average)
438
+ # (batch, 1, H, T) -> (batch, H)
439
+ mean_features = self.mean_hemoglobin_branch(x)
440
+
441
+ # Knowledge Embedding (KE): Conv_1 over the whole window of each
442
+ # row, IN, Conv_1x1; each row is then a sequence of H filter responses
443
+ # (batch, 1, H, T) -> (batch, H, H) = (batch, rows, filters)
444
+ x = self.fNIRS_knowledge_embedding(x)
445
+
446
+ # Knowledge Aggregation (KA): N x (S4D, dropout, residual, LN)
447
+ for layer, norm in zip(self.s4d_layers, self.norms):
448
+ # (batch, H, H)
449
+ layer_input = x
450
+ # Pre-norm variant: LN over the rows before the S4D layer
451
+ if self.prenorm:
452
+ # (batch, rows, filters) -> (batch, filters, rows)
453
+ layer_input = self.channels_last(layer_input)
454
+ layer_input = norm(layer_input)
455
+ # (batch, filters, rows) -> (batch, rows, filters)
456
+ layer_input = self.channels_first(layer_input)
457
+ # S4D: one diagonal state space model per row, run along its
458
+ # sequence of filter responses; shape unchanged
459
+ layer_output = layer(layer_input)
460
+ # Whole S4D channels are dropped; shape unchanged
461
+ layer_output = self.dropout(layer_output)
462
+ # Residual sum; shape unchanged
463
+ x = x + layer_output
464
+ # Post-norm (the authors' default): LN over the rows after the sum
465
+ if not self.prenorm:
466
+ # (batch, rows, filters) -> (batch, filters, rows)
467
+ x = self.channels_last(x)
468
+ x = norm(x)
469
+ # (batch, filters, rows) -> (batch, rows, filters)
470
+ x = self.channels_first(x)
471
+
472
+ # (batch, rows, filters) -> (batch, filters, rows)
473
+ x = self.channels_last(x)
474
+ # AP_4: mean over the sequence. Tensor.mean and not a Reduce layer,
475
+ # which permutes first and changes the float32 rounding of the
476
+ # gradients
477
+ # (batch, H, H) -> (batch, H)
478
+ x = x.mean(dim=1)
479
+
480
+ # KA features and mean hemoglobin features side by side
481
+ # 2 x (batch, H) -> (batch, 2 H)
482
+ features = torch.cat((x, mean_features), 1)
483
+
484
+ if return_features:
485
+ return {"features": features, "cls_token": None}
486
+
487
+ # FC layer
488
+ # (batch, 2 H) -> (batch, n_outputs)
489
+ x = self.final_layer(features)
490
+ return x
491
+
492
+
493
+ class _MultiscaleMeanHemoglobinBranch(nn.Module):
494
+ """Multi-scale Aggregated Mean Hemoglobin Branch (MAMHB).
495
+
496
+ The authors' inter-subject (LOSO-CV) branch: the average of all rows
497
+ (AP_2) and its moving average (AP_3), each read by a full-window temporal
498
+ convolution, batch normalization and ``activation``.
499
+
500
+ Parameters
501
+ ----------
502
+ n_chans : int
503
+ Number of rows of the input; each scale has ``n_chans // 2`` filters.
504
+ n_times : int
505
+ Number of samples of the window.
506
+ avg_size : int
507
+ Length of the moving average, in samples.
508
+ activation : type[nn.Module]
509
+ Activation after each batch normalization.
510
+ """
511
+
512
+ def __init__(
513
+ self,
514
+ n_chans: int,
515
+ n_times: int,
516
+ avg_size: int,
517
+ activation: type[nn.Module],
518
+ ) -> None:
519
+ super().__init__()
520
+ # Parameters
521
+ # H / 2 filters per scale, as the authors': the two scales together
522
+ # give as many features as KA
523
+ n_filters = n_chans // 2
524
+ # Samples left after the moving average, T' = T - avg_size + 1
525
+ n_times_avg = n_times - avg_size + 1
526
+
527
+ # Layers
528
+ # AP_2: average over all rows, one mean hemoglobin signal
529
+ self.avg_1 = nn.AvgPool2d(kernel_size=(n_chans, 1), stride=1)
530
+ # AP_3: moving average over time, the second (smoother) scale
531
+ self.avg_2 = nn.AvgPool2d(kernel_size=(1, avg_size), stride=1)
532
+ # First scale: full-window convolution of the mean signal
533
+ self.conv_1 = nn.Conv2d(
534
+ in_channels=1, out_channels=n_filters, kernel_size=(1, n_times)
535
+ )
536
+ self.bn_1 = nn.BatchNorm2d(n_filters)
537
+ # Second scale: full-window convolution of the smoothed signal
538
+ self.conv_2 = nn.Conv2d(
539
+ in_channels=1, out_channels=n_filters, kernel_size=(1, n_times_avg)
540
+ )
541
+ self.bn_2 = nn.BatchNorm2d(n_filters)
542
+ self.activation = activation()
543
+ self.flatten = Rearrange("batch filters 1 1 -> batch filters")
544
+
545
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
546
+ """Mean hemoglobin features ``(batch, n_chans)`` of ``x``
547
+ ``(batch, 1, n_chans, n_times)``."""
548
+ # Below, H = n_chans, T = n_times and T' = T - avg_size + 1
549
+
550
+ # AP_2: the rows are averaged into one mean hemoglobin signal
551
+ # (batch, 1, H, T) -> (batch, 1, 1, T)
552
+ mean = self.avg_1(x)
553
+ # AP_3: its moving average, the second scale
554
+ # (batch, 1, 1, T) -> (batch, 1, 1, T')
555
+ short = self.avg_2(mean)
556
+
557
+ # First scale: H / 2 filters read the whole mean signal
558
+ # (batch, 1, 1, T) -> (batch, H / 2, 1, 1)
559
+ full = self.conv_1(mean)
560
+ # Batch normalization and activation (ELU by default); shape unchanged
561
+ full = self.bn_1(full)
562
+ full = self.activation(full)
563
+
564
+ # Second scale: H / 2 filters read the whole smoothed signal
565
+ # (batch, 1, 1, T') -> (batch, H / 2, 1, 1)
566
+ short = self.conv_2(short)
567
+ # Batch normalization and activation (ELU by default); shape unchanged
568
+ short = self.bn_2(short)
569
+ short = self.activation(short)
570
+
571
+ # Multi-scale aggregation: the two scales are concatenated
572
+ # 2 x (batch, H / 2, 1, 1) -> (batch, H, 1, 1)
573
+ features = torch.cat((full, short), dim=1)
574
+ # (batch, H, 1, 1) -> (batch, H)
575
+ features = self.flatten(features)
576
+ return features
577
+
578
+
579
+ class _S4DKernel(nn.Module):
580
+ """Convolution kernel of a diagonal state space model (S4D-Lin).
581
+
582
+ ``K_l = 2 Re(C (exp(dt A) - 1) / A exp(dt A l))`` for ``l = 0..length-1``,
583
+ the Vandermonde kernel of Gu et al. (2022), Eqs. (6)-(7), with ``B = 1``
584
+ and the zero-order hold. It is computed in real arithmetic, with
585
+ ``A = -exp(log_A_real) + i A_imag`` and ``dt = exp(log_dt)``.
586
+
587
+ Parameters
588
+ ----------
589
+ d_model : int
590
+ Number of independent state space models (one per S4D channel).
591
+ d_state : int
592
+ State size; ``d_state // 2`` complex entries are kept, the kernel
593
+ being twice the real part (conjugate pairs).
594
+ """
595
+
596
+ def __init__(self, d_model: int, d_state: int) -> None:
597
+ super().__init__()
598
+ # Output matrix C, complex: real and imaginary parts on the last axis
599
+ self.C = nn.Parameter(torch.empty(d_model, d_state // 2, 2))
600
+ # Step of the discretization, one per channel, learned in log scale
601
+ self.log_dt = nn.Parameter(torch.empty(d_model))
602
+ # Diagonal state matrix A: the real part is kept negative (stable)
603
+ # through -exp(log_A_real)
604
+ self.log_A_real = nn.Parameter(torch.empty(d_model, d_state // 2))
605
+ self.A_imag = nn.Parameter(torch.empty(d_model, d_state // 2))
606
+ self.reset_parameters()
607
+
608
+ def reset_parameters(self) -> None:
609
+ # C ~ complex N(0, 1): each part has variance 1 / 2
610
+ nn.init.normal_(self.C, 0.0, math.sqrt(0.5))
611
+ # dt log-uniform in [0.001, 0.1], as in the reference S4D
612
+ nn.init.uniform_(self.log_dt, math.log(0.001), math.log(0.1))
613
+ # S4D-Lin (Gu et al., Eq. (9)): A_n = -1 / 2 + i pi n
614
+ nn.init.constant_(self.log_A_real, math.log(0.5))
615
+ with torch.no_grad():
616
+ self.A_imag.copy_(
617
+ math.pi * torch.arange(self.A_imag.shape[1]).to(self.A_imag)
618
+ )
619
+
620
+ def forward(self, length: int) -> torch.Tensor:
621
+ """Kernel ``(d_model, length)`` for a sequence of ``length`` steps."""
622
+ # Every tensor below is (d_model, d_state // 2) unless noted. The
623
+ # complex numbers are carried as real and imaginary parts, A = a + i b
624
+
625
+ # Step of the discretization (Delta in Gu et al.)
626
+ # (d_model,) -> (d_model, 1), broadcasts over the state
627
+ dt = torch.exp(self.log_dt)
628
+ dt = dt.unsqueeze(-1)
629
+ # Diagonal of A, with a negative real part
630
+ a = -torch.exp(self.log_A_real)
631
+ b = self.A_imag
632
+ # dt A, the exponent of the zero-order hold
633
+ dt_a = a * dt
634
+ dt_b = b * dt
635
+
636
+ # Zero-order hold, numerator of B_bar: exp(dt A) - 1 = e_real + i e_imag.
637
+ # expm1 and 1 - cos = 2 sin^2 keep the precision for small dt
638
+ exp_dt_a = torch.exp(dt_a)
639
+ cos_dt_b = torch.cos(dt_b)
640
+ sin_dt_b = torch.sin(dt_b)
641
+ half_sin = torch.sin(0.5 * dt_b)
642
+ e_real = torch.expm1(dt_a) * cos_dt_b - 2.0 * half_sin * half_sin
643
+ e_imag = exp_dt_a * sin_dt_b
644
+
645
+ # B_bar = (exp(dt A) - 1) / A with B = 1: a complex division, written
646
+ # as a product with the conjugate of A over |A|^2 (> 0, since a < 0)
647
+ modulus = a * a + b * b
648
+ w_real = (e_real * a + e_imag * b) / modulus
649
+ w_imag = (e_imag * a - e_real * b) / modulus
650
+ # C B_bar, the coefficient of each state in the kernel (complex product)
651
+ c_real, c_imag = self.C.unbind(-1)
652
+ ct_real = c_real * w_real - c_imag * w_imag
653
+ ct_imag = c_real * w_imag + c_imag * w_real
654
+
655
+ # Vandermonde basis A_bar^l = exp(dt A l), l = 0..length - 1
656
+ # (d_model, d_state // 2, length)
657
+ steps = torch.arange(length, device=dt.device, dtype=dt.dtype)
658
+ dt_a_steps = dt_a.unsqueeze(-1) * steps
659
+ decay = torch.exp(dt_a_steps)
660
+ angles = dt_b.unsqueeze(-1) * steps
661
+ basis_real = decay * torch.cos(angles)
662
+ basis_imag = decay * torch.sin(angles)
663
+
664
+ # K_l = sum_n C_n B_bar_n A_bar_n^l: real part of the complex product,
665
+ # summed over the states
666
+ # (d_model, d_state // 2, length) -> (d_model, length)
667
+ kernel = torch.einsum("hn,hnl->hl", ct_real, basis_real)
668
+ kernel = kernel - torch.einsum("hn,hnl->hl", ct_imag, basis_imag)
669
+ # Twice the real part: "same as adding conjugate pairs"
670
+ kernel = 2.0 * kernel
671
+ return kernel
672
+
673
+
674
+ class _S4DLayer(nn.Module):
675
+ """S4D layer of Gu et al. (2022), as in the authors' ``S4D``.
676
+
677
+ One diagonal state space model per channel, applied as a causal depthwise
678
+ convolution with the :class:`_S4DKernel`, plus the skip term ``D u``,
679
+ then ``activation``, dropout and a 1 x 1 convolution with a GLU.
680
+
681
+ Parameters
682
+ ----------
683
+ d_model : int
684
+ Number of S4D channels.
685
+ d_state : int
686
+ State size of each state space model.
687
+ drop_prob : float
688
+ Dropout probability, over whole channels.
689
+ activation : type[nn.Module]
690
+ Activation after the state space model.
691
+ """
692
+
693
+ def __init__(
694
+ self,
695
+ d_model: int,
696
+ d_state: int,
697
+ drop_prob: float,
698
+ activation: type[nn.Module],
699
+ ) -> None:
700
+ super().__init__()
701
+ # Skip term D of the state space model, y = C x + D u, one per channel
702
+ self.D = nn.Parameter(torch.empty(d_model))
703
+ # Impulse response of the state space model, as a convolution kernel
704
+ self.kernel = _S4DKernel(d_model=d_model, d_state=d_state)
705
+ self.activation = activation()
706
+ self.dropout = nn.Dropout1d(drop_prob)
707
+ # Output linear layer: a position-wise map to 2 d_model channels,
708
+ # halved again by the gate of the GLU
709
+ self.output_linear = nn.Sequential(
710
+ nn.Conv1d(in_channels=d_model, out_channels=2 * d_model, kernel_size=1),
711
+ nn.GLU(dim=-2),
712
+ )
713
+ # Weight layout of a depthwise conv1d: (out_channels, 1, length)
714
+ self.to_conv_weight = Rearrange("d_model length -> d_model 1 length")
715
+ # Draws D, then the kernel a second time (its __init__ drew it once):
716
+ # the seeded weights of the replications in FNIRS4D's docstring follow
717
+ # this order
718
+ self.reset_parameters()
719
+
720
+ def reset_parameters(self) -> None:
721
+ nn.init.normal_(self.D)
722
+ self.kernel.reset_parameters()
723
+
724
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
725
+ """Output ``(batch, d_model, length)`` of ``x`` of the same shape."""
726
+ # x is the input u of the state space models: (batch, d_model, length)
727
+ length = x.shape[-1]
728
+
729
+ # Kernel K of each channel's state space model, as long as the sequence
730
+ # (d_model, length)
731
+ kernel = self.kernel(length)
732
+ # conv1d computes a correlation: the kernel is reversed so that the
733
+ # result is the convolution y = u * K
734
+ kernel = kernel.flip(-1)
735
+ # (d_model, length) -> (d_model, 1, length)
736
+ kernel = self.to_conv_weight(kernel)
737
+
738
+ # Causal: step l sees only the inputs up to l, so the sequence is
739
+ # padded on the left
740
+ # (batch, d_model, length) -> (batch, d_model, 2 * length - 1)
741
+ padded = F.pad(x, (length - 1, 0))
742
+ # y = u * K, one kernel per channel (depthwise)
743
+ # (batch, d_model, 2 * length - 1) -> (batch, d_model, length)
744
+ y = F.conv1d(padded, kernel, groups=x.shape[1])
745
+
746
+ # Skip term D u of the state space model
747
+ # (d_model,) -> (d_model, 1), broadcasts over the sequence
748
+ skip = self.D.unsqueeze(-1)
749
+ # (batch, d_model, length)
750
+ skip = x * skip
751
+ y = y + skip
752
+
753
+ # Activation (GELU by default) and dropout of whole channels; shape
754
+ # unchanged
755
+ y = self.activation(y)
756
+ y = self.dropout(y)
757
+
758
+ # Output linear layer with its GLU gate
759
+ # (batch, d_model, length) -> (batch, d_model, length)
760
+ y = self.output_linear(y)
761
+ return y