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,1545 @@
1
+ # Authors: Bruno Aristimunha <b.aristimunha@gmail.com>
2
+ #
3
+ # Adapted from https://github.com/GeoNIRS/GeoNIRS (81f8995; paper arXiv:2610.17845).
4
+
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ from typing import Literal, Optional
9
+
10
+ import numpy as np
11
+ import torch
12
+ from einops.layers.torch import Rearrange
13
+ from torch import nn
14
+
15
+ from braindecode.functional import (
16
+ check_ch_mask,
17
+ pad_or_crop_to_patches,
18
+ patch_count,
19
+ scaled_dot_product_attention,
20
+ )
21
+ from braindecode.functional.patches import _check_on_non_divisible
22
+ from braindecode.models.base import EEGModuleMixin
23
+ from braindecode.models.util import fnirs_channel_order, fnirs_split_hbo_hbr
24
+
25
+
26
+ class GeoNIRS(EEGModuleMixin, nn.Module):
27
+ r"""GeoNIRS from Li et al. (2026).
28
+
29
+ :bdg-info:`Attention/Transformer` :bdg-dark-line:`Channel` :bdg-danger:`Foundation Model`
30
+
31
+ GeoNIRS is an fNIRS foundation model pretrained on unlabelled recordings
32
+ with different probe layouts :footcite:`li2026geonirs`. Two things make
33
+ such pretraining hard (§1): "channel semantics vary across probe layouts:
34
+ the same channel index may correspond to different cortical locations",
35
+ and "Slowly varying hemodynamic signals make within-signal masked
36
+ reconstruction susceptible to temporal interpolation."
37
+
38
+ GeoNIRS answers the first with geometry: it "uses the physical locations
39
+ of source-detector pairs as a shared spatial reference across
40
+ heterogeneous probe layouts" and "compresses variable-size channel sets
41
+ into a fixed-size latent representation". It answers the second by
42
+ rebuilding one chromophore from the other ("bidirectional HbO/HbR
43
+ cross-reconstruction with contiguous temporal masking"). This class is
44
+ the pretrained encoder of Figure 1 of the paper (`arXiv:2610.17845
45
+ <https://arxiv.org/abs/2610.17845>`_) with the paper's linear head; the
46
+ pretraining decoders are not part of it.
47
+
48
+ .. rubric:: Architecture Overview
49
+
50
+ For :math:`C` HbO/HbR pairs at 5 Hz, cut into :math:`P` patches of
51
+ :math:`S` samples::
52
+
53
+ x (batch, 2C, n_times)
54
+ - temporal encoders, one per chromophore -> 2 x (batch, C, P, D)
55
+ - geometry encoder -> (batch, C, D)
56
+ - channel compressor, M latent queries -> 2 x (batch, M, P, D)
57
+ - chromophore projections, D -> F -> (batch, 2, M, P, F)
58
+ - read-out: pool="flatten" -> (batch, 2 * M * P * F)
59
+ pool="mean_std" -> (batch, 4 * M * F)
60
+ - head_dropout, final_layer -> (batch, n_outputs)
61
+
62
+ GeoNIRS-Base on a 12 s window (``n_times=60``) gives tokens of shape
63
+ ``(batch, 2, 16, 6, 64)``, read out as 12288 or 4096 features.
64
+
65
+ .. rubric:: Macro Components
66
+
67
+ - ``GeoNIRS.hbo_encoder``, ``GeoNIRS.hbr_encoder`` **Temporal encoders**
68
+ (§2.2)
69
+
70
+ "Every patch is projected into a :math:`D`-dimensional token and
71
+ augmented with a learnable temporal positional embedding. Separate HbO
72
+ and HbR temporal encoders then model the token sequence within each
73
+ physical channel". Inside: a linear projection, LayerNorm, an embedding
74
+ of the patch index and a pre-norm Transformer over the patches of one
75
+ channel. All channels share the weights, so "the model does not require
76
+ a fixed :math:`C_d`".
77
+
78
+ - ``GeoNIRS.geometry_encoder`` **Geometry encoder** (Appendix B.2)
79
+
80
+ "Each physical channel :math:`c` is represented by a six-dimensional
81
+ geometry vector" of its source :math:`s_c` and detector :math:`d_c`:
82
+
83
+ .. math::
84
+
85
+ g_c = [\mathrm{mid}_c, \Delta_c], \qquad
86
+ \mathrm{mid}_c = \frac{s_c + d_c}{2}, \qquad \Delta_c = d_c - s_c.
87
+
88
+ The midpoint gives "the spatial location of the channel" and
89
+ :math:`\Delta_c` "the source-detector separation and orientation".
90
+ Coordinates are centred and divided by "a fixed reference scale of
91
+ 25.46 mm"; an MLP and one Transformer layer turn them into :math:`G`.
92
+
93
+ - ``GeoNIRS.channel_compressor`` **Geometry-aware channel compressor**
94
+ (§2.3)
95
+
96
+ "To transform variable-size physical channel sets into fixed-length
97
+ representations, we introduce :math:`M` learnable latent queries",
98
+ :math:`L`. For each patch :math:`p` they attend over the channels, with
99
+ keys made of the two chromophores fused and the geometry:
100
+
101
+ .. math::
102
+
103
+ \bar{H}_p = \tfrac{1}{2}\left(H^O_{:,p} + H^R_{:,p}\right), \quad
104
+ Q = W_Q\,\mathrm{LN}(L), \quad
105
+ K_p = W_K\,\mathrm{LN}\left(\bar{H}_p + G\right), \quad
106
+ A_p = \mathrm{softmax}\left(\frac{Q K_p^\top}{\sqrt{d_h}}\right),
107
+ \quad Z^s_p = A_p\,W_V\,\mathrm{LN}\left(H^s_{:,p}\right),
108
+ \quad s \in \{O, R\}.
109
+
110
+ "HbO and HbR share the same attention weights but retain separate value
111
+ representations", and "Invalid channels are masked before the softmax
112
+ operation." An output projection and a feed-forward block follow.
113
+
114
+ - ``GeoNIRS.hbo_projection``, ``GeoNIRS.hbr_projection``
115
+ **Chromophore projections** (§2.4)
116
+
117
+ "a chromophore-specific residual projection that maps the feature
118
+ dimension from :math:`D` to :math:`F` without mixing latent channels or
119
+ temporal patches": three residual blocks, of widths [192, 128, 96, 64]
120
+ for GeoNIRS-Base (Table 6).
121
+
122
+ - ``GeoNIRS.final_layer`` **Head** (§2.5, Appendix B.5.2)
123
+
124
+ The tokens of the two chromophores are "flattened, standardized using
125
+ training-set statistics, followed by dropout (:math:`p = 0.1`) and a
126
+ single linear classification layer". ``pool="flatten"`` is that head
127
+ without the standardization; ``pool="mean_std"`` reads out the mean and
128
+ standard deviation of :math:`[Z^O \,\|\, Z^R]` over the valid patches.
129
+
130
+ .. rubric:: Temporal, Spatial, and Spectral Encoding
131
+
132
+ - **Temporal.** A patch is :math:`S = 10` samples, 2 s at 5 Hz, and the
133
+ positional embedding has 15 rows, the 30 s pretraining window. The
134
+ compressor keeps the patch axis: :math:`M` tokens per 2 s patch.
135
+ - **Spatial.** A channel has no index embedding. It is known only through
136
+ its geometry :math:`g_c`, in the keys of the compressor, so any number
137
+ of channels in any layout maps to the same :math:`M` latent channels.
138
+ Zeroing or shuffling the geometry at inference lowers the task-averaged
139
+ balanced accuracy by 2.34 and 3.24 points (Table 3).
140
+ - **Chromophores.** The rows are HbO and HbR concentration changes (no
141
+ HbT), each with its own temporal encoder and projection. The encoder
142
+ has no frequency decomposition.
143
+ - **Validity masks.** "Samples and channels rejected during preprocessing
144
+ quality control, together with patches containing insufficient valid
145
+ samples, are excluded using validity masks" (§2.2). Here a non-finite
146
+ sample is missing, a patch needs ``minimum_patch_valid_fraction`` of
147
+ its samples, and ``ch_mask`` marks padded pairs.
148
+
149
+ .. rubric:: Pretrained Weights
150
+
151
+ The authors release both backbones in the ``checkpoint/`` folder (Git
152
+ LFS) of `GeoNIRS/GeoNIRS@81f8995
153
+ <https://github.com/GeoNIRS/GeoNIRS/tree/81f8995e5c3aa6b70e55812b194fc04e4e7ea5b7/checkpoint>`_,
154
+ ``geonirs_base.pt`` and ``geonirs_large.pt``. Both use :math:`M = 16` and
155
+ :math:`S = 10` (Table 6); the defaults build GeoNIRS-Base.
156
+
157
+ ============================== ==================== =====================
158
+ Component GeoNIRS-Base GeoNIRS-Large
159
+ ============================== ==================== =====================
160
+ Pretraining corpus 8 datasets, 383.30 h 22 datasets, 827.04 h
161
+ ``embed_dim`` (:math:`D`) 192 384
162
+ ``depth`` / ``num_heads`` 4 / 8 6 / 12
163
+ ``feature_dim`` (:math:`F`) 64 128
164
+ Parameters, without the head 4,443,462 24,394,310
165
+ ============================== ==================== =====================
166
+
167
+ :meth:`load_state_dict` takes the file as released: it drops the
168
+ pretraining decoders and keeps the head's initialisation. The weights
169
+ expect 5 Hz signals standardized per recording and at most 150 samples.
170
+
171
+ .. code-block:: python
172
+
173
+ import torch
174
+ from braindecode.models import GeoNIRS
175
+
176
+ payload = torch.load("geonirs_base.pt", map_location="cpu", weights_only=True)
177
+ model = GeoNIRS(chs_info=raw.info["chs"], n_outputs=2, n_times=60, sfreq=5.0)
178
+ model.load_state_dict(payload)
179
+
180
+ .. rubric:: Differences from the reference implementation
181
+
182
+ - **Input.** One ``(batch, 2C, n_times)`` tensor, stacked or interleaved
183
+ (the MNE layout), instead of a batch of ``hbo``, ``hbr``, validity
184
+ masks and ``geometry``. A NaN marks a sample the reference zero-fills
185
+ and flags.
186
+ - **Geometry.** Read from ``chs_info`` (``loc[3:9]``), centred and scaled
187
+ as the reference's ``scripts/build_fair_input.py``; a pair without
188
+ positions gets a zero geometry. ``forward(geometry=...)`` replaces it.
189
+ - **Head.** The training-set standardization is left to the caller.
190
+ ``pool="mean_std"`` gives the features of the reference's
191
+ ``mean_std_linear`` head.
192
+ - **Added:** ``on_non_divisible="pad"`` / ``"crop"`` and ``ch_mask``.
193
+ **Left out:** the decoders, the temporal masking and LoRA.
194
+
195
+ .. versionadded:: 2.1
196
+
197
+ Parameters
198
+ ----------
199
+ patch_size : int, default=10
200
+ Samples per patch, :math:`S` in the paper: 2 s at 5 Hz.
201
+ max_patches : int, default=15
202
+ Rows of the temporal positional embedding, the 15 patches of a 30 s
203
+ pretraining window; raised to the patch count of ``n_times``.
204
+ on_non_divisible : {"error", "pad", "crop"}, default="error"
205
+ ``n_times`` not a multiple of ``patch_size``: refuse (as the
206
+ reference); pad with missing samples, to which the validity rule
207
+ applies; or crop.
208
+ embed_dim : int, default=192
209
+ Token width, :math:`D` in the paper ("Embedding width", Table 6).
210
+ num_heads : int, default=8
211
+ Heads of the temporal Transformers (Table 6).
212
+ depth : int, default=4
213
+ Layers of each temporal Transformer (Table 6).
214
+ mlp_ratio : float, default=4.0
215
+ Feed-forward width of the temporal Transformers, over ``embed_dim``.
216
+ geometry_hidden_dim : int or None, default=None
217
+ Hidden width of the geometry MLP; ``None`` is ``embed_dim`` (Table 6).
218
+ geometry_heads : int or None, default=None
219
+ Heads of the geometry Transformer layer; ``None`` is ``num_heads``.
220
+ n_latent_channels : int, default=16
221
+ Learnable latent queries, :math:`M` in the paper.
222
+ compressor_heads : int or None, default=None
223
+ Heads of the compressor's attention; ``None`` is ``num_heads``.
224
+ feature_dim : int, default=64
225
+ Token width after the projection, :math:`F` in the paper (Table 6).
226
+ use_channel_geometry : bool, default=True
227
+ Add the geometry :math:`G` to the keys of the compressor. ``False``
228
+ builds no geometry encoder: the "w/o Geometry" variant of Table 4.
229
+ pool : {"flatten", "mean_std"}, default="flatten"
230
+ Read-out of the ``(batch, 2, M, P, F)`` tokens: all of them flattened
231
+ (the head of the paper), or their mean and standard deviation over
232
+ the valid patches.
233
+ channel_order : {"stacked", "interleaved"} or None, default=None
234
+ ``[HbO_1..HbO_C, HbR_1..HbR_C]`` or ``[HbO_1, HbR_1, ...]``; ``None``
235
+ reads it from ``chs_info`` (stacked without it).
236
+ drop_prob : float, default=0.1
237
+ Dropout in the backbone, 0.1 in both checkpoints.
238
+ head_drop_prob : float, default=0.1
239
+ Dropout before ``final_layer``, :math:`p = 0.1` in Appendix B.5.2.
240
+ minimum_patch_valid_fraction : float, default=0.8
241
+ Share of measured samples a patch needs to be valid: "at least 80% of
242
+ its time points" (Appendix B.1.2).
243
+ activation : type[nn.Module], default=nn.GELU
244
+ Activation of the backbone; GELU in the reference.
245
+
246
+ Notes
247
+ -----
248
+ **Protocol.** For pretraining (Appendix B.1), raw intensity is converted
249
+ to HbO and HbR concentration changes with the modified Beer-Lambert law,
250
+ resampled to 5 Hz and standardized per recording, HbO and HbR separately,
251
+ then cut into 30 s windows; B.1.1 lists no band-pass filter. Downstream
252
+ (§3.1, Appendix B.5-B.6), eight held-out binary tasks in windows of 12 s
253
+ or 10 s are scored by subject-level five-fold cross-validation with seeds
254
+ 810 and 811. With linear probing, LoRA and full fine-tuning GeoNIRS
255
+ reaches 63.06, 63.42 and 63.54 task-averaged balanced accuracy (Table 1).
256
+
257
+ **Replication.** Linear probe of the frozen GeoNIRS-Base on DS42 (action
258
+ mode, ds005935) and DS19 (pain intensity, ds005777), with the paper's
259
+ folds and seeds. "Authors' pipeline" is their repository at 81f8995 run
260
+ end to end; "Port" is this class with a re-implementation of their probe.
261
+
262
+ =============== ======== ====== ================= ======
263
+ Task Metric Paper Authors' pipeline Port
264
+ =============== ======== ====== ================= ======
265
+ DS42 macro-F1 0.7018 0.7000 0.7039
266
+ DS42 AUROC 0.7840 0.7840 0.7840
267
+ DS19 macro-F1 0.5598 0.5599 0.5304
268
+ DS19 AUROC 0.5683 0.5687 0.5549
269
+ =============== ======== ====== ================= ======
270
+
271
+ Both pipelines build the same windows (1628 and 1190), on which this
272
+ class gives the authors' encoder features (max-abs difference 0.0, Base
273
+ and Large, eval mode).
274
+
275
+ References
276
+ ----------
277
+ .. footbibliography::
278
+ """
279
+
280
+ def __init__(
281
+ self,
282
+ # Braindecode parameters
283
+ n_outputs: int | None = None,
284
+ n_chans: int | None = None,
285
+ chs_info: list[dict] | None = None,
286
+ n_times: int | None = None,
287
+ input_window_seconds: float | None = None,
288
+ sfreq: float | None = None,
289
+ *,
290
+ # Model-specific parameters
291
+ patch_size: int = 10,
292
+ max_patches: int = 15,
293
+ on_non_divisible: Literal["error", "pad", "crop"] = "error",
294
+ embed_dim: int = 192,
295
+ num_heads: int = 8,
296
+ depth: int = 4,
297
+ mlp_ratio: float = 4.0,
298
+ geometry_hidden_dim: int | None = None,
299
+ geometry_heads: int | None = None,
300
+ n_latent_channels: int = 16,
301
+ compressor_heads: int | None = None,
302
+ feature_dim: int = 64,
303
+ use_channel_geometry: bool = True,
304
+ pool: Literal["flatten", "mean_std"] = "flatten",
305
+ channel_order: Literal["stacked", "interleaved"] | None = None,
306
+ drop_prob: float = 0.1,
307
+ head_drop_prob: float = 0.1,
308
+ minimum_patch_valid_fraction: float = 0.8,
309
+ activation: type[nn.Module] = nn.GELU,
310
+ ) -> None:
311
+ super().__init__(
312
+ n_outputs=n_outputs,
313
+ n_chans=n_chans,
314
+ chs_info=chs_info,
315
+ n_times=n_times,
316
+ input_window_seconds=input_window_seconds,
317
+ sfreq=sfreq,
318
+ )
319
+ del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
320
+
321
+ # Parameters
322
+ self.patch_size = patch_size
323
+ self.on_non_divisible = on_non_divisible
324
+ self.embed_dim = embed_dim
325
+ self.n_latent_channels = n_latent_channels
326
+ self.feature_dim = feature_dim
327
+ self.pool = pool
328
+ # ``None`` takes the value of the temporal encoders, as in both
329
+ # checkpoints
330
+ self.geometry_hidden_dim = geometry_hidden_dim or embed_dim
331
+ self.geometry_heads = geometry_heads or num_heads
332
+ self.compressor_heads = compressor_heads or num_heads
333
+ # Measured samples a patch needs to be valid ("at least 80% of its
334
+ # time points", Appendix B.1.2): 8 of 10 with the defaults
335
+ self.min_valid_samples = math.ceil(
336
+ patch_size * float(minimum_patch_valid_fraction)
337
+ )
338
+
339
+ # Checkers
340
+ # The rows are HbO/HbR pairs of the same source-detector channels
341
+ if self.n_chans % 2:
342
+ raise ValueError("GeoNIRS needs HbO/HbR pairs: n_chans must be even.")
343
+ if pool not in ("flatten", "mean_std"):
344
+ raise ValueError(f"pool must be 'flatten' or 'mean_std', got {pool!r}.")
345
+ # Every attention splits the embed_dim features evenly over its heads
346
+ heads = {"num_heads": num_heads, "compressor_heads": self.compressor_heads}
347
+ if use_channel_geometry:
348
+ heads["geometry_heads"] = self.geometry_heads
349
+ for name, n_heads in heads.items():
350
+ if embed_dim % n_heads:
351
+ raise ValueError(
352
+ f"embed_dim ({embed_dim}) must be divisible by {name} "
353
+ f"({n_heads}): a head takes embed_dim / {name} features."
354
+ )
355
+ # A fraction above 1 would drop every patch and give all-zero tokens
356
+ if not 0.0 <= minimum_patch_valid_fraction <= 1.0:
357
+ raise ValueError(
358
+ "minimum_patch_valid_fraction must be in [0, 1], got "
359
+ f"{minimum_patch_valid_fraction}."
360
+ )
361
+ # Where the HbO and HbR rows are (stacked or interleaved); raises when
362
+ # chs_info does not list HbO/HbR pairs
363
+ self.channel_order = fnirs_channel_order(self._chs_info, channel_order)
364
+ _check_on_non_divisible(on_non_divisible)
365
+ # P, the patches of one window; raises for a window the patches do not
366
+ # tile when on_non_divisible="error"
367
+ self.n_patches = patch_count(self.n_times, patch_size, on_non_divisible)
368
+
369
+ # Layers
370
+ # Following paper nomenclature
371
+
372
+ # Temporal encoders (§2.2): "Separate HbO and HbR temporal encoders
373
+ # then model the token sequence within each physical channel", giving
374
+ # H^O and H^R. The positional embedding needs a row per patch of the
375
+ # window, so it grows past ``max_patches`` for a longer window.
376
+ self.hbo_encoder = _TemporalEncoder(
377
+ patch_size=self.patch_size,
378
+ max_patches=max(max_patches, self.n_patches),
379
+ embed_dim=self.embed_dim,
380
+ num_heads=num_heads,
381
+ depth=depth,
382
+ mlp_ratio=mlp_ratio,
383
+ drop_prob=drop_prob,
384
+ activation=activation,
385
+ )
386
+ self.hbr_encoder = _TemporalEncoder(
387
+ patch_size=self.patch_size,
388
+ max_patches=max(max_patches, self.n_patches),
389
+ embed_dim=self.embed_dim,
390
+ num_heads=num_heads,
391
+ depth=depth,
392
+ mlp_ratio=mlp_ratio,
393
+ drop_prob=drop_prob,
394
+ activation=activation,
395
+ )
396
+
397
+ # Geometry encoder (Appendix B.2): the source-detector geometry g_c of
398
+ # each channel becomes G, "a shared spatial reference across
399
+ # heterogeneous probe layouts". The "w/o Geometry" variant (Table 4)
400
+ # has none.
401
+ self.geometry_encoder = None
402
+ if use_channel_geometry:
403
+ self.geometry_encoder = _GeometryEncoder(
404
+ embed_dim=self.embed_dim,
405
+ hidden_dim=self.geometry_hidden_dim,
406
+ num_heads=self.geometry_heads,
407
+ drop_prob=drop_prob,
408
+ activation=activation,
409
+ )
410
+
411
+ # Geometry-aware channel compressor (§2.3): M latent queries map the
412
+ # C channels of a recording to M latent channels
413
+ self.channel_compressor = _ChannelCompressorAttention(
414
+ embed_dim=self.embed_dim,
415
+ n_latent_channels=self.n_latent_channels,
416
+ num_heads=self.compressor_heads,
417
+ drop_prob=drop_prob,
418
+ activation=activation,
419
+ )
420
+
421
+ # Chromophore projections Pi_O and Pi_R (§2.4): D -> F, giving Z^O
422
+ # and Z^R
423
+ self.hbo_projection = _ChromophoreProjection(
424
+ embed_dim=self.embed_dim,
425
+ feature_dim=self.feature_dim,
426
+ drop_prob=drop_prob,
427
+ activation=activation,
428
+ )
429
+ self.hbr_projection = _ChromophoreProjection(
430
+ embed_dim=self.embed_dim,
431
+ feature_dim=self.feature_dim,
432
+ drop_prob=drop_prob,
433
+ activation=activation,
434
+ )
435
+
436
+ # Geometry g_c of the pairs of chs_info (Eqs. 4-5), used when forward
437
+ # gets no ``geometry``. Derived from chs_info, so not saved with the
438
+ # weights.
439
+ self.register_buffer(
440
+ "default_geometry",
441
+ torch.from_numpy(_optode_geometry(self._chs_info, self.channel_order)),
442
+ persistent=False,
443
+ )
444
+
445
+ # Validity masks: the time axis of the sample mask is cut in patches,
446
+ # and the masks get the axes they are broadcast over
447
+ self.split_patches = Rearrange(
448
+ "batch pairs (patches samples) -> batch pairs patches samples",
449
+ samples=self.patch_size,
450
+ )
451
+ self.pair_over_time = Rearrange("batch pairs -> batch pairs 1")
452
+ self.patch_over_latents = Rearrange("batch patches -> batch 1 patches")
453
+ self.patch_over_features = Rearrange("batch patches -> batch 1 patches 1")
454
+
455
+ # Read-out of the (batch, 2, M, P, F) tokens. "flatten": every token,
456
+ # the head of the paper (Appendix B.5.2). "mean_std": mean and
457
+ # standard deviation over the valid patches.
458
+ self.flatten_foundation = Rearrange(
459
+ "batch chrom latents patches dim -> batch (chrom latents patches dim)"
460
+ )
461
+ self.mean_std = _ValidMeanStd()
462
+ if self.pool == "flatten":
463
+ n_features = 2 * n_latent_channels * self.n_patches * feature_dim
464
+ else:
465
+ n_features = 4 * n_latent_channels * feature_dim
466
+
467
+ # Head (Appendix B.5.2): "dropout (p = 0.1) and a single linear
468
+ # classification layer"
469
+ self.head_dropout = nn.Dropout(head_drop_prob)
470
+ self.final_layer = nn.Linear(n_features, self.n_outputs)
471
+
472
+ def forward(
473
+ self,
474
+ x: torch.Tensor,
475
+ return_features: bool = False,
476
+ geometry: Optional[torch.Tensor] = None,
477
+ ch_mask: Optional[torch.Tensor] = None,
478
+ ) -> torch.Tensor | dict[str, torch.Tensor | None]:
479
+ """Forward pass.
480
+
481
+ Parameters
482
+ ----------
483
+ x : torch.Tensor
484
+ HbO/HbR signals of shape ``(batch, n_chans, n_times)``. A NaN
485
+ marks a missing sample.
486
+ return_features : bool, default=False
487
+ Return the features the head reads instead of the outputs.
488
+ geometry : torch.Tensor, optional
489
+ Geometry vector of each pair, ``(n_pairs, 6)`` or ``(batch,
490
+ n_pairs, 6)``; see :meth:`encode`.
491
+ ch_mask : torch.Tensor, optional
492
+ ``(batch, n_chans)`` mask of the real channels of a padded batch;
493
+ see :meth:`encode`.
494
+
495
+ Returns
496
+ -------
497
+ torch.Tensor or dict
498
+ Outputs of shape ``(batch, n_outputs)``. With
499
+ ``return_features=True``, ``{"features": Tensor, "cls_token":
500
+ None}`` with the ``(batch, n_features)`` input of ``final_layer``.
501
+ """
502
+ # Backbone of the paper (§2.2-2.4): temporal encoders, geometry
503
+ # encoder, channel compressor and chromophore projections
504
+ # (batch, n_chans, n_times) -> (batch, 2, M, P, F): Z^O and Z^R
505
+ encoded = self.encode(x, geometry=geometry, ch_mask=ch_mask)
506
+ x = encoded["foundation"]
507
+
508
+ if self.pool == "flatten":
509
+ # Read-out of the paper: the representation "is flattened"
510
+ # (Appendix B.5.2)
511
+ # (batch, 2, M, P, F) -> (batch, 2 * M * P * F)
512
+ x = self.flatten_foundation(x)
513
+ else:
514
+ # Mean and standard deviation of [Z^O | Z^R] over the valid
515
+ # patches of each latent channel
516
+ # (batch, 2, M, P, F) -> (batch, 4 * M * F)
517
+ x = self.mean_std(x, encoded["valid"])
518
+
519
+ # Head (Appendix B.5.2): "dropout (p = 0.1) and a single linear
520
+ # classification layer"
521
+ x = self.head_dropout(x)
522
+ if return_features:
523
+ return {"features": x, "cls_token": None}
524
+
525
+ # (batch, n_features) -> (batch, n_outputs)
526
+ x = self.final_layer(x)
527
+ return x
528
+
529
+ def encode(
530
+ self,
531
+ x: torch.Tensor,
532
+ geometry: Optional[torch.Tensor] = None,
533
+ ch_mask: Optional[torch.Tensor] = None,
534
+ ) -> dict[str, torch.Tensor]:
535
+ """Encode a window into the latent tokens of the two chromophores.
536
+
537
+ The backbone of the paper: temporal encoders, geometry encoder,
538
+ channel compressor and chromophore projections.
539
+
540
+ Parameters
541
+ ----------
542
+ x : torch.Tensor
543
+ HbO/HbR signals of shape ``(batch, n_chans, n_times)``. A NaN
544
+ marks a missing sample.
545
+ geometry : torch.Tensor, optional
546
+ Geometry vector :math:`g_c` of each pair, ``(n_pairs, 6)`` or
547
+ ``(batch, n_pairs, 6)``. ``None`` takes the one of ``chs_info``.
548
+ Not read with ``use_channel_geometry=False``.
549
+ ch_mask : torch.Tensor, optional
550
+ ``(batch, n_chans)`` mask of the real channels of a padded batch;
551
+ it must pad whole HbO/HbR pairs.
552
+
553
+ Returns
554
+ -------
555
+ dict of torch.Tensor
556
+ ``"foundation"``: :math:`Z^O` and :math:`Z^R`, ``(batch, 2,
557
+ n_latent_channels, n_patches, feature_dim)``. ``"valid"``:
558
+ boolean ``(batch, n_latent_channels, n_patches)``, ``False`` for
559
+ the patches that have no valid channel (their tokens are zero).
560
+ """
561
+ # Padded channels of the batch, as pairs: both chromophores of a
562
+ # padded pair must be flagged
563
+ # (batch, n_chans) -> (batch, n_pairs)
564
+ pair_mask: Optional[torch.Tensor] = None
565
+ ch_mask = check_ch_mask(ch_mask, x)
566
+ if ch_mask is not None:
567
+ hbo_mask, hbr_mask = fnirs_split_hbo_hbr(ch_mask, self.channel_order)
568
+ if not torch.equal(hbo_mask, hbr_mask):
569
+ raise ValueError("ch_mask needs whole HbO/HbR pairs.")
570
+ pair_mask = hbo_mask
571
+
572
+ # The window is cut into P patches of S samples (§2.2)
573
+ # (batch, n_chans, n_times) -> (batch, n_chans, P * S)
574
+ n_times = x.shape[-1]
575
+ x = pad_or_crop_to_patches(x, self.patch_size, self.on_non_divisible)
576
+
577
+ # Paired chromophore signals X^O and X^R of the C source-detector pairs
578
+ # (batch, n_chans, P * S) -> 2 x (batch, n_pairs, P * S)
579
+ hbo, hbr = fnirs_split_hbo_hbr(x, self.channel_order)
580
+ batch_size, n_pairs, _ = hbo.shape
581
+
582
+ # Validity masks (§2.2). A sample is measured when both chromophores
583
+ # are finite; a pair is valid when it has a measured sample and is
584
+ # not padding.
585
+ hbo_finite = torch.isfinite(hbo)
586
+ hbr_finite = torch.isfinite(hbr)
587
+ # (batch, n_pairs, P * S)
588
+ finite = hbo_finite & hbr_finite
589
+ # The samples added by on_non_divisible="pad" are not measured
590
+ finite[:, :, n_times:] = False
591
+ # (batch, n_pairs)
592
+ channel_valid = finite.any(dim=-1)
593
+ if pair_mask is not None:
594
+ channel_valid = pair_mask & channel_valid
595
+ # (batch, n_pairs) -> (batch, n_pairs, 1)
596
+ channel_valid_over_time = self.pair_over_time(channel_valid)
597
+ # (batch, n_pairs, P * S)
598
+ sample_valid = finite & channel_valid_over_time
599
+
600
+ # Missing samples are set to zero, as the reference does
601
+ zeros = torch.zeros_like(hbo)
602
+ hbo = torch.where(sample_valid, hbo, zeros)
603
+ hbr = torch.where(sample_valid, hbr, zeros)
604
+
605
+ # A patch is valid when enough of its samples are measured ("at least
606
+ # 80% of its time points", Appendix B.1.2)
607
+ # (batch, n_pairs, P * S) -> (batch, n_pairs, P, S) -> (batch, n_pairs, P)
608
+ patch_valid = self.split_patches(sample_valid)
609
+ patch_valid = patch_valid.sum(dim=-1)
610
+ patch_valid = patch_valid >= self.min_valid_samples
611
+ patch_valid = patch_valid & channel_valid_over_time
612
+
613
+ # Geometry encoder (Appendix B.2): g_c of each pair -> G
614
+ geometry_embedding: Optional[torch.Tensor] = None
615
+ if self.geometry_encoder is not None:
616
+ if geometry is None:
617
+ # the geometry of chs_info, shared by the whole batch
618
+ pair_geometry = self.default_geometry
619
+ if pair_geometry.numel() == 0:
620
+ raise ValueError(
621
+ "GeoNIRS needs the channel geometry: chs_info with "
622
+ "source/detector locations (loc[3:9]) or the geometry "
623
+ "argument."
624
+ )
625
+ if pair_geometry.shape[0] != n_pairs:
626
+ raise ValueError(
627
+ "x and chs_info have different channel counts: pass the "
628
+ "geometry of the HbO/HbR pairs of x."
629
+ )
630
+ else:
631
+ # one g_c (6 numbers, as default_geometry) per pair of x, for
632
+ # the whole batch or for each window
633
+ pair_geometry = geometry
634
+ pair_shape = [n_pairs, self.default_geometry.shape[-1]]
635
+ if list(pair_geometry.shape[-2:]) != pair_shape:
636
+ raise ValueError(
637
+ "geometry and x have different channel counts, or "
638
+ "geometry is not 6-D: pass (n_pairs, 6) or (batch, "
639
+ "n_pairs, 6), one row per HbO/HbR pair of x."
640
+ )
641
+ pair_geometry = pair_geometry.to(device=x.device, dtype=hbo.dtype)
642
+ # (n_pairs, 6) or (batch, n_pairs, 6) -> (batch, n_pairs, 6)
643
+ pair_geometry = pair_geometry.expand(batch_size, -1, -1)
644
+ # (batch, n_pairs, 6) -> (batch, n_pairs, D): G
645
+ geometry_embedding = self.geometry_encoder(pair_geometry, channel_valid)
646
+
647
+ # Temporal encoders (§2.2), one per chromophore: the patches of each
648
+ # channel become the tokens H^O and H^R
649
+ # (batch, n_pairs, P * S) -> (batch, n_pairs, P, D)
650
+ hbo = self.hbo_encoder(hbo, patch_valid)
651
+ hbr = self.hbr_encoder(hbr, patch_valid)
652
+
653
+ # Geometry-aware channel compressor (§2.3): the C channels of each
654
+ # patch are compressed into M latent channels, with one attention map
655
+ # for both chromophores
656
+ # (batch, n_pairs, P, D) -> (batch, M, P, D)
657
+ hbo, hbr = self.channel_compressor(hbo, hbr, geometry_embedding, patch_valid)
658
+
659
+ # A patch is kept when at least one pair is valid in it
660
+ # (batch, n_pairs, P) -> (batch, P)
661
+ time_valid = patch_valid.any(dim=1)
662
+ # (batch, P) -> (batch, 1, P, 1)
663
+ valid_scale = self.patch_over_features(time_valid)
664
+ valid_scale = valid_scale.to(hbo.dtype)
665
+
666
+ # Chromophore projections Pi_O and Pi_R (§2.4): Z^O and Z^R, zero at
667
+ # the patches that are not kept
668
+ # (batch, M, P, D) -> (batch, M, P, F)
669
+ hbo = self.hbo_projection(hbo)
670
+ hbo = hbo * valid_scale
671
+ hbr = self.hbr_projection(hbr)
672
+ hbr = hbr * valid_scale
673
+
674
+ # The two chromophores side by side: the "base representation" of
675
+ # Table 6
676
+ # 2 x (batch, M, P, F) -> (batch, 2, M, P, F)
677
+ foundation = torch.stack([hbo, hbr], dim=1)
678
+
679
+ # Validity of the tokens, the same for every latent channel
680
+ # (batch, P) -> (batch, 1, P) -> (batch, M, P)
681
+ valid = self.patch_over_latents(time_valid)
682
+ valid = valid.expand(-1, self.n_latent_channels, -1)
683
+ return {"foundation": foundation, "valid": valid}
684
+
685
+ def reset_head(self, n_outputs: int) -> None:
686
+ """Replace ``final_layer`` by a new one with ``n_outputs`` outputs.
687
+
688
+ Parameters
689
+ ----------
690
+ n_outputs : int
691
+ New number of outputs.
692
+ """
693
+ self._set_n_outputs(n_outputs)
694
+ # The read-out does not change, so the head keeps its input width
695
+ n_features = self.final_layer.in_features
696
+ self.final_layer = nn.Linear(n_features, self.n_outputs)
697
+
698
+ def load_state_dict(self, state_dict, strict: bool = True, assign: bool = False):
699
+ """Load a state dict, or a checkpoint as the authors release it.
700
+
701
+ Parameters
702
+ ----------
703
+ state_dict : dict
704
+ A state dict of this class, or the released file's payload
705
+ (``{"model": ..., "config": ...}``).
706
+ strict : bool, default=True
707
+ As in :meth:`torch.nn.Module.load_state_dict`.
708
+ assign : bool, default=False
709
+ As in :meth:`torch.nn.Module.load_state_dict`.
710
+
711
+ Returns
712
+ -------
713
+ NamedTuple
714
+ The missing and unexpected keys.
715
+ """
716
+ # The released files keep the weights under "model"
717
+ state_dict = state_dict.get("model", state_dict)
718
+ # The reconstruction decoders are pretraining-only (§2.5: "the
719
+ # reconstruction decoders are discarded")
720
+ decoders = ("hbo_to_hbr_decoder.", "hbr_to_hbo_decoder.")
721
+ cleaned = {k: v for k, v in state_dict.items() if not k.startswith(decoders)}
722
+ # A backbone checkpoint has no head: the head keeps its initialisation
723
+ if not any(k.startswith("final_layer.") for k in cleaned):
724
+ head = self.final_layer.state_dict(prefix="final_layer.")
725
+ cleaned.update(head)
726
+ return super().load_state_dict(cleaned, strict=strict, assign=assign)
727
+
728
+
729
+ class _TemporalEncoder(nn.Module):
730
+ """Temporal encoder of one chromophore (paper §2.2).
731
+
732
+ "Every patch is projected into a D-dimensional token and augmented with a
733
+ learnable temporal positional embedding", then a Transformer models "the
734
+ token sequence within each physical channel". The authors'
735
+ ``TemporalStreamEncoder``; HbO and HbR each have their own.
736
+
737
+ Parameters
738
+ ----------
739
+ patch_size : int
740
+ Samples per patch, :math:`S`.
741
+ max_patches : int
742
+ Rows of the temporal positional embedding.
743
+ embed_dim : int
744
+ Token width, :math:`D`.
745
+ num_heads : int
746
+ Heads of the Transformer.
747
+ depth : int
748
+ Layers of the Transformer.
749
+ mlp_ratio : float
750
+ Feed-forward width of the Transformer, over ``embed_dim``.
751
+ drop_prob : float
752
+ Dropout of the Transformer.
753
+ activation : type[nn.Module], default=nn.GELU
754
+ Activation of the Transformer.
755
+ init_std : float, default=0.02
756
+ Standard deviation of the initial positional embedding (the
757
+ reference's ``time_embedding_init_std``).
758
+ """
759
+
760
+ def __init__(
761
+ self,
762
+ patch_size: int,
763
+ max_patches: int,
764
+ embed_dim: int,
765
+ num_heads: int,
766
+ depth: int,
767
+ mlp_ratio: float,
768
+ drop_prob: float,
769
+ activation: type[nn.Module] = nn.GELU,
770
+ init_std: float = 0.02,
771
+ ):
772
+ super().__init__()
773
+ self.init_std = init_std
774
+
775
+ # Non-overlapping patches: the time axis becomes (patches, samples)
776
+ self.split_patches = Rearrange(
777
+ "batch pairs (patches samples) -> batch pairs patches samples",
778
+ samples=patch_size,
779
+ )
780
+ # Patch projection: the S samples of a patch become one D-wide token
781
+ self.patch_projection = nn.Linear(patch_size, embed_dim)
782
+ self.patch_norm = nn.LayerNorm(embed_dim)
783
+ # Learnable temporal positional embedding: one row per patch index
784
+ self.time_embedding = nn.Embedding(max_patches, embed_dim)
785
+ # Temporal Transformer (pre-norm, final LayerNorm). It attends over
786
+ # the patches of ONE channel, so its weights serve any channel count.
787
+ self.temporal_transformer = nn.TransformerEncoder(
788
+ nn.TransformerEncoderLayer(
789
+ d_model=embed_dim,
790
+ nhead=num_heads,
791
+ dim_feedforward=round(embed_dim * mlp_ratio),
792
+ dropout=drop_prob,
793
+ activation=activation(),
794
+ batch_first=True,
795
+ norm_first=True,
796
+ ),
797
+ num_layers=depth,
798
+ norm=nn.LayerNorm(embed_dim),
799
+ enable_nested_tensor=False,
800
+ )
801
+ self.output_norm = nn.LayerNorm(embed_dim)
802
+
803
+ # The validity mask gets a feature axis to multiply the tokens
804
+ self.patch_over_features = Rearrange(
805
+ "batch pairs patches -> batch pairs patches 1"
806
+ )
807
+ # Every channel becomes its own sequence of patches for the Transformer
808
+ self.merge_pairs = Rearrange(
809
+ "batch pairs patches dim -> (batch pairs) patches dim"
810
+ )
811
+ self.merge_pair_mask = Rearrange("batch pairs patches -> (batch pairs) patches")
812
+
813
+ self.reset_parameters()
814
+
815
+ def reset_parameters(self) -> None:
816
+ nn.init.normal_(self.time_embedding.weight, std=self.init_std)
817
+
818
+ def forward(self, x: torch.Tensor, patch_valid: torch.Tensor) -> torch.Tensor:
819
+ """Encode the patches of each channel.
820
+
821
+ Parameters
822
+ ----------
823
+ x : torch.Tensor
824
+ One chromophore, missing samples set to zero, of shape
825
+ ``(batch, n_pairs, n_patches * patch_size)``.
826
+ patch_valid : torch.Tensor
827
+ Boolean ``(batch, n_pairs, n_patches)``, ``True`` for the patches
828
+ that hold enough measured samples.
829
+
830
+ Returns
831
+ -------
832
+ torch.Tensor
833
+ :math:`H^s` of the paper, ``(batch, n_pairs, n_patches,
834
+ embed_dim)``, zero at the invalid patches.
835
+ """
836
+ # Cut each channel into P non-overlapping patches of S samples
837
+ # (batch, n_pairs, P * S) -> (batch, n_pairs, P, S)
838
+ x = self.split_patches(x)
839
+ n_patches = x.shape[2]
840
+
841
+ # Patch projection and LayerNorm: one D-dimensional token per patch
842
+ # (batch, n_pairs, P, S) -> (batch, n_pairs, P, D)
843
+ x = self.patch_projection(x)
844
+ x = self.patch_norm(x)
845
+
846
+ # Learnable temporal positional embedding of the patch index 0..P-1
847
+ # (P, D), broadcast over batch and pairs
848
+ time_position = self.time_embedding.weight[:n_patches]
849
+ x = x + time_position
850
+
851
+ # Validity mask: an invalid patch carries no token
852
+ # (batch, n_pairs, P) -> (batch, n_pairs, P, 1)
853
+ weight = self.patch_over_features(patch_valid)
854
+ weight = weight.to(x.dtype)
855
+ x = x * weight
856
+ token_shape = x.shape
857
+
858
+ # Which patches each channel may attend to. The reference skips a
859
+ # channel with no valid patch; here such a channel attends to all its
860
+ # patches (an all-padded row would give NaN) and is zeroed below.
861
+ # (batch, n_pairs, P) -> (batch * n_pairs, P)
862
+ rows_valid = self.merge_pair_mask(patch_valid)
863
+ row_active = rows_valid.any(dim=1, keepdim=True)
864
+ attend = rows_valid | ~row_active
865
+ padding = ~attend
866
+
867
+ # Temporal Transformer over the patch sequence of each channel
868
+ # (batch, n_pairs, P, D) -> (batch * n_pairs, P, D)
869
+ x = self.merge_pairs(x)
870
+ x = self.temporal_transformer(x, src_key_padding_mask=padding)
871
+ # (batch * n_pairs, P, D) -> (batch, n_pairs, P, D)
872
+ x = x.reshape(token_shape)
873
+
874
+ # Output LayerNorm, with the invalid patches zero before and after it
875
+ # (batch, n_pairs, P, D): H^s
876
+ x = x * weight
877
+ x = self.output_norm(x)
878
+ x = x * weight
879
+ return x
880
+
881
+
882
+ class _GeometryEncoder(nn.Module):
883
+ """Geometry encoder (paper Appendix B.2, Table 6).
884
+
885
+ Turns the six-dimensional geometry vector :math:`g_c` of each channel
886
+ (midpoint and source-to-detector offset) into its embedding :math:`G`,
887
+ with an MLP and a Transformer over the channels. The authors'
888
+ ``SourceDetectorGeometryEncoder``.
889
+
890
+ Parameters
891
+ ----------
892
+ embed_dim : int
893
+ Width of the geometry embedding, :math:`D`.
894
+ hidden_dim : int
895
+ Hidden width of the MLP.
896
+ num_heads : int
897
+ Heads of the Transformer.
898
+ drop_prob : float
899
+ Dropout of the Transformer.
900
+ activation : type[nn.Module], default=nn.GELU
901
+ Activation of the MLP and of the Transformer.
902
+ geometry_dim : int, default=6
903
+ Size of :math:`g_c`: three midpoint and three offset coordinates
904
+ (Eq. 4).
905
+ depth : int, default=1
906
+ Layers of the Transformer ("1 layer", Table 6).
907
+ mlp_ratio : float, default=2.0
908
+ Feed-forward width of the Transformer, over ``embed_dim`` (the
909
+ reference's ``embedding_dim * 2``).
910
+ """
911
+
912
+ def __init__(
913
+ self,
914
+ embed_dim: int,
915
+ hidden_dim: int,
916
+ num_heads: int,
917
+ drop_prob: float,
918
+ activation: type[nn.Module] = nn.GELU,
919
+ geometry_dim: int = 6,
920
+ depth: int = 1,
921
+ mlp_ratio: float = 2.0,
922
+ ):
923
+ super().__init__()
924
+
925
+ # Geometry MLP: g_c (6 numbers) -> one D-wide token per channel
926
+ self.geometry_projection = nn.Sequential(
927
+ nn.Linear(geometry_dim, hidden_dim),
928
+ activation(),
929
+ nn.Linear(hidden_dim, embed_dim),
930
+ nn.LayerNorm(embed_dim),
931
+ )
932
+ # Spatial Transformer (pre-norm, final LayerNorm): each channel sees
933
+ # where the other channels of the montage are
934
+ self.spatial_transformer = nn.TransformerEncoder(
935
+ nn.TransformerEncoderLayer(
936
+ d_model=embed_dim,
937
+ nhead=num_heads,
938
+ dim_feedforward=round(embed_dim * mlp_ratio),
939
+ dropout=drop_prob,
940
+ activation=activation(),
941
+ batch_first=True,
942
+ norm_first=True,
943
+ ),
944
+ num_layers=depth,
945
+ norm=nn.LayerNorm(embed_dim),
946
+ enable_nested_tensor=False,
947
+ )
948
+
949
+ # The channel mask gets a feature axis to multiply the tokens
950
+ self.pair_over_features = Rearrange("batch pairs -> batch pairs 1")
951
+
952
+ def forward(self, geometry: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:
953
+ """Embed the geometry of each channel.
954
+
955
+ Parameters
956
+ ----------
957
+ geometry : torch.Tensor
958
+ :math:`g_c` of each pair, ``(batch, n_pairs, 6)``.
959
+ valid : torch.Tensor
960
+ Boolean ``(batch, n_pairs)``, ``True`` for the pairs that hold
961
+ data.
962
+
963
+ Returns
964
+ -------
965
+ torch.Tensor
966
+ :math:`G` of the paper, ``(batch, n_pairs, embed_dim)``, zero for
967
+ the invalid pairs.
968
+ """
969
+ # A pair without data has no geometry: its g_c is set to zero
970
+ # (batch, n_pairs) -> (batch, n_pairs, 1)
971
+ valid_over_features = self.pair_over_features(valid)
972
+ zeros = torch.zeros_like(geometry)
973
+ # (batch, n_pairs, 6)
974
+ x = torch.where(valid_over_features, geometry, zeros)
975
+
976
+ # Geometry MLP: g_c -> one token per channel
977
+ # (batch, n_pairs, 6) -> (batch, n_pairs, D)
978
+ x = self.geometry_projection(x)
979
+ weight = valid_over_features.to(x.dtype)
980
+ x = x * weight
981
+
982
+ # Which channels may be attended to. As in the temporal encoder, a
983
+ # recording with no valid pair attends to all and is zeroed below.
984
+ any_valid = valid.any(dim=1, keepdim=True)
985
+ attend = valid | ~any_valid
986
+ padding = ~attend
987
+
988
+ # Spatial Transformer over the channels of the montage
989
+ # (batch, n_pairs, D): G
990
+ x = self.spatial_transformer(x, src_key_padding_mask=padding)
991
+ x = x * weight
992
+ return x
993
+
994
+
995
+ class _ChannelCompressorAttention(nn.Module):
996
+ """Geometry-aware channel compressor (paper §2.3).
997
+
998
+ "To transform variable-size physical channel sets into fixed-length
999
+ representations", ``n_latent_channels`` learnable latent queries attend
1000
+ over the channels of each patch. The keys are the fused HbO/HbR tokens
1001
+ plus the geometry; "HbO and HbR share the same attention weights but
1002
+ retain separate value representations". The authors'
1003
+ ``BrainOmniChannelCompressor``.
1004
+
1005
+ Private because one softmax over the fused HbO/HbR keys weighs both
1006
+ chromophores' values (one dropout mask), and the released checkpoints
1007
+ name its projections ``q_proj``/``k_proj``/``v_proj``/``out_proj``.
1008
+
1009
+ Parameters
1010
+ ----------
1011
+ embed_dim : int
1012
+ Token width, :math:`D`.
1013
+ n_latent_channels : int
1014
+ Learnable latent queries, :math:`M`.
1015
+ num_heads : int
1016
+ Attention heads, each of width :math:`d_h` = ``embed_dim / num_heads``.
1017
+ drop_prob : float
1018
+ Dropout on the attention weights and in the feed-forward block.
1019
+ activation : type[nn.Module], default=nn.GELU
1020
+ Activation of the feed-forward block.
1021
+ mlp_ratio : float, default=2.0
1022
+ Width of the feed-forward block, over ``embed_dim`` (the reference's
1023
+ ``embedding_dim * 2``).
1024
+ init_std : float, default=0.02
1025
+ Standard deviation of the initial latent queries (the reference's
1026
+ ``randn * 0.02``).
1027
+ """
1028
+
1029
+ def __init__(
1030
+ self,
1031
+ embed_dim: int,
1032
+ n_latent_channels: int,
1033
+ num_heads: int,
1034
+ drop_prob: float,
1035
+ activation: type[nn.Module] = nn.GELU,
1036
+ mlp_ratio: float = 2.0,
1037
+ init_std: float = 0.02,
1038
+ ):
1039
+ super().__init__()
1040
+ self.head_dim = embed_dim // num_heads
1041
+ self.init_std = init_std
1042
+
1043
+ # Latent queries L: the M channels of the compressed montage, shared
1044
+ # by every recording whatever its probe layout
1045
+ self.latent_queries = nn.Parameter(torch.empty(n_latent_channels, embed_dim))
1046
+
1047
+ # LayerNorms of the queries (L), the keys (fused tokens + geometry)
1048
+ # and the values (tokens of one chromophore)
1049
+ self.q_norm = nn.LayerNorm(embed_dim)
1050
+ self.k_norm = nn.LayerNorm(embed_dim)
1051
+ self.v_norm = nn.LayerNorm(embed_dim)
1052
+ # W_Q, W_K, W_V of §2.3; W_V is shared by HbO and HbR
1053
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
1054
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
1055
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
1056
+ # "an output projection and a feed-forward block" (§2.3)
1057
+ self.out_proj = nn.Linear(embed_dim, embed_dim)
1058
+ # Dropout on the attention weights A_p
1059
+ self.attn_dropout = nn.Dropout(drop_prob)
1060
+ self.out_norm = nn.LayerNorm(embed_dim)
1061
+ self.ffn = nn.Sequential(
1062
+ nn.LayerNorm(embed_dim),
1063
+ nn.Linear(embed_dim, round(embed_dim * mlp_ratio)),
1064
+ activation(),
1065
+ nn.Dropout(drop_prob),
1066
+ nn.Linear(round(embed_dim * mlp_ratio), embed_dim),
1067
+ )
1068
+
1069
+ # The attention runs over the channels of ONE patch: patches join
1070
+ # the batch axis, for the tokens and for their validity
1071
+ self.patches_first = Rearrange(
1072
+ "batch pairs patches dim -> (batch patches) pairs dim"
1073
+ )
1074
+ self.patches_first_mask = Rearrange(
1075
+ "batch pairs patches -> (batch patches) pairs"
1076
+ )
1077
+ # The geometry is the same for every patch of a window
1078
+ self.geometry_over_patches = Rearrange("batch pairs dim -> batch 1 pairs dim")
1079
+ self.merge_patches = Rearrange(
1080
+ "batch patches pairs dim -> (batch patches) pairs dim"
1081
+ )
1082
+ # The latent queries are the same for every window and patch
1083
+ self.latents_over_batch = Rearrange("latents dim -> 1 latents dim")
1084
+ # Multi-head layout of queries, keys and values
1085
+ self.split_heads = Rearrange(
1086
+ "batch tokens (heads dim) -> batch heads tokens dim", heads=num_heads
1087
+ )
1088
+ # The channel validity masks the keys, for every head and query
1089
+ self.keys_over_queries = Rearrange("batch pairs -> batch 1 1 pairs")
1090
+ # Heads are merged back and the two chromophores, attended together
1091
+ # as [V^O | V^R], are separated again
1092
+ self.merge_heads = Rearrange(
1093
+ "batch heads latents (chrom dim) -> chrom batch latents (heads dim)",
1094
+ chrom=2,
1095
+ )
1096
+ self.active_over_features = Rearrange("batch one -> batch one 1")
1097
+ # Output layout: latent channels before patches
1098
+ self.latents_first = Rearrange(
1099
+ "batch patches latents dim -> batch latents patches dim"
1100
+ )
1101
+
1102
+ self.reset_parameters()
1103
+
1104
+ def reset_parameters(self) -> None:
1105
+ nn.init.normal_(self.latent_queries, 0.0, self.init_std)
1106
+
1107
+ def forward(
1108
+ self,
1109
+ hbo: torch.Tensor,
1110
+ hbr: torch.Tensor,
1111
+ geometry: Optional[torch.Tensor],
1112
+ patch_valid: torch.Tensor,
1113
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1114
+ """Compress the channels of each patch into the latent channels.
1115
+
1116
+ Parameters
1117
+ ----------
1118
+ hbo, hbr : torch.Tensor
1119
+ :math:`H^O` and :math:`H^R` of the temporal encoders, each
1120
+ ``(batch, n_pairs, n_patches, embed_dim)``.
1121
+ geometry : torch.Tensor or None
1122
+ :math:`G` of the geometry encoder, ``(batch, n_pairs,
1123
+ embed_dim)``; ``None`` leaves it out of the keys.
1124
+ patch_valid : torch.Tensor
1125
+ Boolean ``(batch, n_pairs, n_patches)``.
1126
+
1127
+ Returns
1128
+ -------
1129
+ tuple of torch.Tensor
1130
+ The compressed HbO and HbR tokens, each ``(batch,
1131
+ n_latent_channels, n_patches, embed_dim)``, zero at the patches
1132
+ with no valid channel.
1133
+ """
1134
+ batch_size, _, n_patches, _ = hbo.shape
1135
+
1136
+ # One attention problem per patch p: its C channels are the tokens
1137
+ # (batch, n_pairs, P, D) -> (batch * P, n_pairs, D): H^O_{:,p}, H^R_{:,p}
1138
+ hbo = self.patches_first(hbo)
1139
+ hbr = self.patches_first(hbr)
1140
+ # (batch, n_pairs, P) -> (batch * P, n_pairs)
1141
+ valid = self.patches_first_mask(patch_valid)
1142
+
1143
+ # Normalised latent queries LN(L), one copy per patch
1144
+ # (M, D) -> (1, M, D) -> (batch * P, M, D)
1145
+ latents = self.q_norm(self.latent_queries)
1146
+ latents = self.latents_over_batch(latents)
1147
+ latents = latents.expand(valid.shape[0], -1, -1)
1148
+
1149
+ # Fused chromophores: \bar{H}_p = (H^O_{:,p} + H^R_{:,p}) / 2
1150
+ # (batch * P, n_pairs, D)
1151
+ fused = hbo + hbr
1152
+ fused = 0.5 * fused
1153
+ if geometry is not None:
1154
+ # Geometry-aware keys: \bar{H}_p + G, with G repeated over patches
1155
+ # (batch, n_pairs, D) -> (batch, 1, n_pairs, D) -> (batch * P, n_pairs, D)
1156
+ patch_geometry = self.geometry_over_patches(geometry)
1157
+ patch_geometry = patch_geometry.expand(-1, n_patches, -1, -1)
1158
+ patch_geometry = self.merge_patches(patch_geometry)
1159
+ fused = fused + patch_geometry
1160
+
1161
+ # Queries: Q = W_Q LN(L)
1162
+ # (batch * P, M, D) -> (batch * P, heads, M, d_h)
1163
+ query = self.q_proj(latents)
1164
+ query = self.split_heads(query)
1165
+
1166
+ # Keys: K_p = W_K LN(\bar{H}_p + G)
1167
+ # (batch * P, n_pairs, D) -> (batch * P, heads, n_pairs, d_h)
1168
+ key = self.k_norm(fused)
1169
+ key = self.k_proj(key)
1170
+ key = self.split_heads(key)
1171
+
1172
+ # Values, one set per chromophore: V^s_p = W_V LN(H^s_{:,p})
1173
+ # (batch * P, n_pairs, D) -> (batch * P, heads, n_pairs, d_h)
1174
+ value_hbo = self.v_norm(hbo)
1175
+ value_hbo = self.v_proj(value_hbo)
1176
+ value_hbo = self.split_heads(value_hbo)
1177
+ value_hbr = self.v_norm(hbr)
1178
+ value_hbr = self.v_proj(value_hbr)
1179
+ value_hbr = self.split_heads(value_hbr)
1180
+ # "HbO and HbR share the same attention weights": attending once to
1181
+ # [V^O | V^R] applies one A_p (and one dropout mask) to both
1182
+ # (batch * P, heads, n_pairs, 2 * d_h)
1183
+ value = torch.cat([value_hbo, value_hbr], dim=-1)
1184
+
1185
+ # "Invalid channels are masked before the softmax". A patch with no
1186
+ # valid channel attends to all of them (an all-masked row would give
1187
+ # NaN) and is zeroed in the output block; the reference skips it.
1188
+ # (batch * P, 1)
1189
+ active = valid.any(dim=1, keepdim=True)
1190
+ attend = valid | ~active
1191
+ # (batch * P, n_pairs) -> (batch * P, 1, 1, n_pairs)
1192
+ attend = self.keys_over_queries(attend)
1193
+
1194
+ # Z^s_p = A_p V^s_p, with A_p = softmax(Q K_p^T / sqrt(d_h))
1195
+ # (batch * P, heads, M, 2 * d_h)
1196
+ dropout_p = self.attn_dropout.p if self.training else 0.0
1197
+ x = scaled_dot_product_attention(
1198
+ query,
1199
+ key,
1200
+ value,
1201
+ attn_mask=attend,
1202
+ dropout_p=dropout_p,
1203
+ scale=self.head_dim**-0.5,
1204
+ exact=True,
1205
+ )
1206
+ # Merge the heads and separate the chromophores
1207
+ # (batch * P, heads, M, 2 * d_h) -> (2, batch * P, M, D): Z^O_p, Z^R_p
1208
+ x = self.merge_heads(x)
1209
+
1210
+ # (batch * P, 1) -> (batch * P, 1, 1)
1211
+ active_weight = self.active_over_features(active)
1212
+ active_weight = active_weight.to(x.dtype)
1213
+
1214
+ # Output projection and feed-forward block, chromophore by chromophore
1215
+ # (batch * P, M, D)
1216
+ hbo = self._output_block(x[0], latents, active_weight)
1217
+ hbr = self._output_block(x[1], latents, active_weight)
1218
+
1219
+ # Patches leave the batch axis; latent channels come before patches
1220
+ # (batch * P, M, D) -> (batch, P, M, D) -> (batch, M, P, D)
1221
+ hbo = hbo.unflatten(0, [batch_size, n_patches])
1222
+ hbo = self.latents_first(hbo)
1223
+ hbo = hbo.contiguous()
1224
+ hbr = hbr.unflatten(0, [batch_size, n_patches])
1225
+ hbr = self.latents_first(hbr)
1226
+ hbr = hbr.contiguous()
1227
+ return hbo, hbr
1228
+
1229
+ def _output_block(
1230
+ self, x: torch.Tensor, latents: torch.Tensor, active_weight: torch.Tensor
1231
+ ) -> torch.Tensor:
1232
+ """The "output projection and a feed-forward block" of §2.3, for the
1233
+ attended values of one chromophore.
1234
+
1235
+ Called once per chromophore: running both in one call would draw one
1236
+ dropout mask for the two instead of one each.
1237
+
1238
+ Parameters
1239
+ ----------
1240
+ x : torch.Tensor
1241
+ :math:`Z^s_p`, ``(batch * n_patches, n_latent_channels,
1242
+ embed_dim)``.
1243
+ latents : torch.Tensor
1244
+ The normalised latent queries, same shape.
1245
+ active_weight : torch.Tensor
1246
+ ``(batch * n_patches, 1, 1)``, 1 for the patches that have a
1247
+ valid channel and 0 for the others.
1248
+
1249
+ Returns
1250
+ -------
1251
+ torch.Tensor
1252
+ Same shape as ``x``.
1253
+ """
1254
+ # Output projection W_O, residual on the latent queries, LayerNorm
1255
+ # (batch * P, M, D)
1256
+ x = self.out_proj(x)
1257
+ x = latents + x
1258
+ x = self.out_norm(x)
1259
+
1260
+ # Feed-forward block with its residual connection
1261
+ update = self.ffn(x)
1262
+ x = x + update
1263
+
1264
+ # A patch with no valid channel has no tokens
1265
+ x = x * active_weight
1266
+ return x
1267
+
1268
+
1269
+ class _ChromophoreProjection(nn.Module):
1270
+ r"""Chromophore-specific residual projection :math:`\Pi_s` (paper §2.4).
1271
+
1272
+ "a chromophore-specific residual projection that maps the feature
1273
+ dimension from D to F without mixing latent channels or temporal
1274
+ patches". The authors' ``FeatureProjection`` / ``ScaledFeatureProjection``;
1275
+ HbO and HbR each have their own.
1276
+
1277
+ Parameters
1278
+ ----------
1279
+ embed_dim : int
1280
+ Input width, :math:`D`.
1281
+ feature_dim : int
1282
+ Output width, :math:`F`.
1283
+ drop_prob : float
1284
+ Dropout inside each residual block.
1285
+ activation : type[nn.Module], default=nn.GELU
1286
+ Activation inside each residual block.
1287
+ """
1288
+
1289
+ def __init__(
1290
+ self,
1291
+ embed_dim: int,
1292
+ feature_dim: int,
1293
+ drop_prob: float,
1294
+ activation: type[nn.Module] = nn.GELU,
1295
+ ):
1296
+ super().__init__()
1297
+ # "Projection dimensions" of Table 6: [192, 128, 96, 64] for
1298
+ # GeoNIRS-Base and [384, 192, 96, 128] for GeoNIRS-Large. The
1299
+ # reference writes the first by hand and [D, D / 2, D / 4, F] for
1300
+ # every other size; we follow it.
1301
+ widths = [embed_dim, embed_dim // 2, embed_dim // 4, feature_dim]
1302
+ if embed_dim == 192 and feature_dim == 64:
1303
+ widths = [192, 128, 96, 64]
1304
+
1305
+ # One residual block per change of width; ``blocks`` is the name the
1306
+ # released checkpoints use
1307
+ self.blocks = nn.ModuleList(
1308
+ [
1309
+ _ResidualProjectionBlock(
1310
+ input_dim=input_dim,
1311
+ output_dim=output_dim,
1312
+ drop_prob=drop_prob,
1313
+ activation=activation,
1314
+ )
1315
+ for input_dim, output_dim in zip(widths[:-1], widths[1:])
1316
+ ]
1317
+ )
1318
+
1319
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1320
+ """Project the latent tokens of one chromophore.
1321
+
1322
+ Parameters
1323
+ ----------
1324
+ x : torch.Tensor
1325
+ Compressed tokens, ``(batch, n_latent_channels, n_patches,
1326
+ embed_dim)``.
1327
+
1328
+ Returns
1329
+ -------
1330
+ torch.Tensor
1331
+ :math:`Z^s` of the paper, ``(batch, n_latent_channels, n_patches,
1332
+ feature_dim)``.
1333
+ """
1334
+ # Each block acts on the last axis only, so latent channels and
1335
+ # patches are never mixed. The width shrinks block by block, e.g.
1336
+ # 192 -> 128 -> 96 -> 64 for GeoNIRS-Base
1337
+ # (batch, M, P, D) -> (batch, M, P, F)
1338
+ for block in self.blocks:
1339
+ x = block(x)
1340
+ return x
1341
+
1342
+
1343
+ class _ResidualProjectionBlock(nn.Module):
1344
+ """One stage of the chromophore projection: a linear skip plus a scaled
1345
+ two-layer update (the authors' ``ResidualProjectionBlock``).
1346
+
1347
+ Private because no shared block has a learned residual scale on a
1348
+ width-changing skip projection.
1349
+
1350
+ Parameters
1351
+ ----------
1352
+ input_dim : int
1353
+ Input width.
1354
+ output_dim : int
1355
+ Output width.
1356
+ drop_prob : float
1357
+ Dropout between the two layers of the update.
1358
+ activation : type[nn.Module], default=nn.GELU
1359
+ Activation between the two layers of the update.
1360
+ init_scale : float, default=0.1
1361
+ Initial value of the learnable ``residual_scale`` (0.1 in the
1362
+ reference): the block starts close to its linear skip.
1363
+ """
1364
+
1365
+ def __init__(
1366
+ self,
1367
+ input_dim: int,
1368
+ output_dim: int,
1369
+ drop_prob: float,
1370
+ activation: type[nn.Module] = nn.GELU,
1371
+ init_scale: float = 0.1,
1372
+ ):
1373
+ super().__init__()
1374
+ self.init_scale = init_scale
1375
+
1376
+ # Skip path: a linear map, since the width changes
1377
+ self.skip = nn.Linear(input_dim, output_dim)
1378
+ # Update path: LayerNorm and a two-layer perceptron
1379
+ self.main = nn.Sequential(
1380
+ nn.LayerNorm(input_dim),
1381
+ nn.Linear(input_dim, output_dim),
1382
+ activation(),
1383
+ nn.Dropout(drop_prob),
1384
+ nn.Linear(output_dim, output_dim),
1385
+ )
1386
+ # Learnable weight of the update path
1387
+ self.residual_scale = nn.Parameter(torch.empty(()))
1388
+
1389
+ self.reset_parameters()
1390
+
1391
+ def reset_parameters(self) -> None:
1392
+ nn.init.constant_(self.residual_scale, self.init_scale)
1393
+
1394
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1395
+ """``(..., input_dim)`` -> ``(..., output_dim)``."""
1396
+ # Linear skip: (..., input_dim) -> (..., output_dim)
1397
+ skip = self.skip(x)
1398
+ # Scaled update: residual_scale * MLP(LayerNorm(x))
1399
+ update = self.main(x)
1400
+ update = self.residual_scale * update
1401
+ # (..., output_dim)
1402
+ x = skip + update
1403
+ return x
1404
+
1405
+
1406
+ class _ValidMeanStd(nn.Module):
1407
+ r"""Read-out ``pool="mean_std"``: mean and standard deviation of
1408
+ :math:`Z^{\mathrm{joint}} = [Z^O \,\|\, Z^R]` (paper §2.5) over the valid
1409
+ patches of each latent channel.
1410
+
1411
+ The features of the reference's ``mean_std_linear`` head
1412
+ (``valid_temporal_mean_std``): the window length no longer sets the
1413
+ feature count.
1414
+ """
1415
+
1416
+ def __init__(self):
1417
+ super().__init__()
1418
+ # Z^joint: the two chromophores concatenated along the feature axis
1419
+ self.join_chromophores = Rearrange(
1420
+ "batch chrom latents patches dim -> batch latents patches (chrom dim)"
1421
+ )
1422
+ # The validity gets a feature axis to weigh the tokens
1423
+ self.valid_over_features = Rearrange(
1424
+ "batch latents patches -> batch latents patches 1"
1425
+ )
1426
+ # The mean gets its patch axis back to be subtracted from the tokens
1427
+ self.mean_over_patches = Rearrange("batch latents dim -> batch latents 1 dim")
1428
+ # One feature vector per window: [mean | std] of each latent channel
1429
+ self.flatten_statistics = Rearrange(
1430
+ "stat batch latents dim -> batch (latents stat dim)"
1431
+ )
1432
+
1433
+ def forward(self, x: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:
1434
+ """Pool the tokens over the valid patches.
1435
+
1436
+ Parameters
1437
+ ----------
1438
+ x : torch.Tensor
1439
+ :math:`Z^O` and :math:`Z^R`, ``(batch, 2, n_latent_channels,
1440
+ n_patches, feature_dim)``.
1441
+ valid : torch.Tensor
1442
+ Boolean ``(batch, n_latent_channels, n_patches)``.
1443
+
1444
+ Returns
1445
+ -------
1446
+ torch.Tensor
1447
+ ``(batch, 4 * n_latent_channels * feature_dim)``.
1448
+ """
1449
+ # Z^joint = [Z^O | Z^R]
1450
+ # (batch, 2, M, P, F) -> (batch, M, P, 2 * F)
1451
+ x = self.join_chromophores(x)
1452
+
1453
+ # Number of valid patches of each latent channel (at least 1, so a
1454
+ # window with no valid patch gives zeros and not NaN)
1455
+ # (batch, M, P) -> (batch, M, P, 1) -> (batch, M, 1)
1456
+ weight = self.valid_over_features(valid)
1457
+ weight = weight.to(x.dtype)
1458
+ count = weight.sum(dim=2)
1459
+ count = count.clamp_min(1.0)
1460
+
1461
+ # Mean over the valid patches
1462
+ # (batch, M, P, 2 * F) -> (batch, M, 2 * F)
1463
+ mean = x * weight
1464
+ mean = mean.sum(dim=2)
1465
+ mean = mean / count
1466
+
1467
+ # Standard deviation over the valid patches (population formula, as
1468
+ # the reference): sqrt(sum((z - mean)^2) / count)
1469
+ # (batch, M, 2 * F) -> (batch, M, 1, 2 * F)
1470
+ centre = self.mean_over_patches(mean)
1471
+ std = x - centre
1472
+ std = std * weight
1473
+ std = std.square()
1474
+ # (batch, M, P, 2 * F) -> (batch, M, 2 * F)
1475
+ std = std.sum(dim=2)
1476
+ std = std / count
1477
+ std = std.clamp_min(0.0)
1478
+ std = std.sqrt()
1479
+
1480
+ # [mean | std] of each latent channel, flattened
1481
+ # 2 x (batch, M, 2 * F) -> (2, batch, M, 2 * F) -> (batch, 4 * M * F)
1482
+ x = torch.stack([mean, std])
1483
+ x = self.flatten_statistics(x)
1484
+ return x
1485
+
1486
+
1487
+ def _optode_geometry(
1488
+ chs_info, channel_order: str, scale: float = 25.460582556839242 / 1000.0
1489
+ ) -> np.ndarray:
1490
+ """Geometry vector :math:`g_c` of each HbO/HbR pair of ``chs_info``
1491
+ (paper Appendix B.2, Eqs. 4-5), as the reference builds it for a
1492
+ downstream dataset (``scripts/build_fair_input.py``).
1493
+
1494
+ Parameters
1495
+ ----------
1496
+ chs_info : list of dict or None
1497
+ MNE channel information; ``loc[3:9]`` holds the source and the
1498
+ detector of an fNIRS channel, in metres.
1499
+ channel_order : {"stacked", "interleaved"}
1500
+ Where the HbO and HbR rows are.
1501
+ scale : float
1502
+ The "fixed reference scale of 25.46 mm" of the paper, in metres
1503
+ (the reference's ``GEOMETRY_SCALE_M``).
1504
+
1505
+ Returns
1506
+ -------
1507
+ np.ndarray
1508
+ ``(n_pairs, 6)`` float32, ``[midpoint, detector - source]`` of each
1509
+ pair, centred and divided by ``scale``; a pair without positions is
1510
+ zero. ``(0, 6)`` when no pair has positions.
1511
+ """
1512
+ empty = np.zeros((0, 6), dtype=np.float32)
1513
+ if chs_info is None:
1514
+ return empty
1515
+
1516
+ # The two chromophores of a pair share their optodes: read the HbO rows
1517
+ channel_index = torch.arange(len(chs_info))[None]
1518
+ hbo_index, _ = fnirs_split_hbo_hbr(channel_index, channel_order)
1519
+
1520
+ # Source s_c and detector d_c of each pair, from loc[3:9]
1521
+ # (n_pairs, 6); a missing or short loc stays zero
1522
+ optodes = np.zeros((hbo_index.shape[1], 6))
1523
+ for row, i in zip(optodes, hbo_index[0].tolist()):
1524
+ loc = chs_info[i].get("loc")
1525
+ loc = np.ravel(loc if loc is not None else [])[3:9]
1526
+ row[: loc.size] = loc
1527
+ # A pair has positions when they are finite and not all zero
1528
+ present = np.isfinite(optodes).all(axis=1) & (optodes != 0).any(axis=1)
1529
+ if not present.any():
1530
+ return empty
1531
+
1532
+ # "Geometry coordinates are additionally centered to remove global
1533
+ # translation differences": the centre is the mean of the optodes that
1534
+ # have a position
1535
+ present_optodes = np.concatenate([optodes[present, :3], optodes[present, 3:]])
1536
+ center = present_optodes.mean(axis=0)
1537
+ # Dimensionless coordinates: centred, then divided by the reference scale
1538
+ source = (optodes[:, :3] - center) / scale
1539
+ detector = (optodes[:, 3:] - center) / scale
1540
+
1541
+ # g_c = [mid_c, Delta_c], mid_c = (s_c + d_c) / 2, Delta_c = d_c - s_c
1542
+ geometry = np.concatenate([0.5 * (source + detector), detector - source], axis=1)
1543
+ # A pair without positions has a zero geometry, as in the reference
1544
+ geometry[~present] = 0.0
1545
+ return geometry.astype(np.float32)