braindecode.models.FNIRS4D#

class braindecode.models.FNIRS4D(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, *, n_layers=4, d_state=64, dt_min=0.001, dt_max=0.1, a_real_init=0.5, avg_size=10, drop_prob=0.5, prenorm=False, compute_hbt=True, channel_order=None, mean_branch='multiscale', activation=<class 'torch.nn.modules.activation.GELU'>, branch_activation=<class 'torch.nn.modules.activation.ELU'>)[source]#

fNIRS4D from Wang et al. (2026).

Convolution Recurrent

Added in version 2.1.

fNIRS4D architecture

fig/fig2.png of wzhlearning/fNIRS4D (eb13e5e, Apache-2.0), resized.#

fNIRS4D [1] builds fNIRS domain knowledge into a lightweight network of diagonal state space layers (S4D, [2]): activation patterns give its mixed hemoglobin input, hemodynamic responses its knowledge embedding (KE) and feature engineering its selectable mean hemoglobin branch, and knowledge aggregation (KA) runs S4D blocks over them. The repository’s fig/fig1.png ties each kind of knowledge to a block, and the layers follow the authors’ fNIRS4D.py. In the authors’ training loops (UFFT and WG, same splits, seeds 0-2) the port matches the authors’ accuracy, every paired difference with a 95 % interval including zero (#1582); in the GeoNIRS loop it gives 67.89 and 49.86 macro-F1 on DS42 and DS19, against 68.98 and 50.79 in GeoNIRS Table 14 [3] and 69.03 and 50.60 for the GeoNIRS copy of fNIRS4D in the same loop.

Architecture Overview

With \(H\) = n_chans rows (d_model in the authors’ S4D), \(T\) = n_times samples, \(N\) = n_layers and the figure’s names:

input: HbO and HbR rows                      (batch, H, T)
Mixed Hemoglobin [HbO, HbT], to_fnirs_tensor (batch, 1, H, T)
Selectable branch (mean_hemoglobin_branch):
  MHB or MAMHB                               (batch, H)
Knowledge Embedding (knowledge_embedding):
  Conv_1 (1 x T), IN, Conv_1x1, Rearrange    (batch, H, H)
Knowledge Aggregation:
  N x (S4D, dropout, residual, LN)           (batch, H, H)
  AP_4: mean over the sequence               (batch, H)
concatenate with the branch, final_layer FC  (batch, n_outputs)

Macro Components

  • compute_hbt Mixed Hemoglobin. The rows become HbO and total hemoglobin, \(\mathrm{HbT} = \mathrm{HbO} + \mathrm{HbR}\), as in the authors’ dataloader.py; the pairs come from channel_order or chs_info.

  • knowledge_embedding (fNIRS_knowledge_embedding in the reference) Knowledge Embedding (KE). \(H\) filters of \(1 \times T\), so each reads the whole window of one row (the kernel shape of FNIRSNet’s DHRConv), instance normalization and a \(1 \times 1\) convolution. Each row becomes a sequence of \(H\) filter responses, which the S4D layers read.

  • s4d_layers, norms Knowledge Aggregation (KA). \(N\) blocks of S4D, dropout, a residual sum and a LayerNorm over the rows (post-norm, or before the layer with prenorm=True), then the mean over the sequence (\(\mathrm{AP}_4\)). An S4D layer runs one diagonal state space model per row: the continuous system (Gu et al., Eq. (1)) is discretized with the zero-order hold (Section 3.1),

    \[x'(t) = A x(t) + B u(t), \quad y(t) = C x(t), \qquad \bar{A} = e^{\Delta A}, \quad \bar{B} = (\Delta A)^{-1} (e^{\Delta A} - I) \, \Delta B,\]

    and applied as a convolution with a Vandermonde kernel (Eqs. (6)-(7)):

    \[y = u * \bar{K}, \qquad \bar{K}_\ell = \sum_{n} C_n \bar{A}_n^{\ell} \bar{B}_n .\]

    \(A\) is diagonal and complex, initialized with S4D-Lin, \(A_n = -a + i \pi n\) with \(a\) = a_real_init (1/2 in Eq. (9)); the step \(\Delta\) is learned per row from a log-uniform start in [dt_min, dt_max]. \(B = 1\) as in the authors’ S4DKernel, the sum keeps d_state // 2 entries and the kernel is twice its real part (conjugate pairs, Listing 1 of Gu et al.). The layer adds a skip term \(D u\), then GELU, dropout and a \(1 \times 1\) convolution with a GLU.

  • mean_hemoglobin_branch MHB and MAMHB. The intra-subject mean hemoglobin branch (mean_branch="time_mean") is the mean of each row over time (\(\mathrm{AP}_1\)). The inter-subject multi-scale aggregated one ("multiscale") averages all rows into one signal (\(\mathrm{AP}_2\), avg_1) and reads it, and its avg_size-sample moving average (\(\mathrm{AP}_3\), avg_2), with full-window convolutions of \(H/2\) filters, BN and ELU (conv_1/bn_1, conv_2/bn_2); the two halves are concatenated.

  • final_layer FC. One linear layer on the \(H\) KA features and the \(H\) branch features.

Temporal, Spatial, and Spectral Encoding

  • Temporal. One 3 s window of \(T\) samples (40 at 13.3 Hz, 30 at 10 Hz, in the authors’ scripts). KE reads all samples of a row at once, so the S4D layers run along the KE filters, not along time. Kernels count samples, so there is no sampling-rate argument.

  • Spatial. No montage or optode geometry. Each row is one S4D channel, LayerNorm normalizes across rows and MAMHB averages them, so the rows keep the order of training.

  • Spectral. None in the model; the signals are filtered beforehand. The authors band-pass (UFFT [4], MA [5], as for FNIRSNet) or low-pass at 0.2 Hz (WG [6]), cut 3 s windows with a 1 s step, form HbT per window and z-score with the training-set statistics.

  • Chromophores. HbO and HbT; compute_hbt=False takes the rows as given.

Additional Mechanisms

  • Hemoglobin input. HbT is formed inside the model, as in the authors’ dataloader.py; the authors sum before their z-score, so to reproduce it pass their [HbO, HbT] arrays with compute_hbt=False. There is no ch_mask.

  • S4D kernel. Applied as a causal convolution in real arithmetic instead of the authors’ complex FFT, equal up to float32 rounding and free of complex tensors, so torch.jit.script and torch.export run on it; nn.Dropout1d replaces the authors’ DropoutNd.

  • Pretrained weights. None: the authors release code, not weights.

License

Parameters:
  • n_outputs (int | None) – Number of outputs of the model. This is the number of classes in the case of classification.

  • n_chans (int | None) – Number of EEG channels.

  • chs_info (list[dict] | None) – Information about each individual EEG channel. This should be filled with info["chs"]. Refer to mne.Info for more details.

  • n_times (int | None) – Number of time samples of the input window.

  • input_window_seconds (float | None) – Length of the input window in seconds.

  • sfreq (float | None) – Sampling frequency of the EEG recordings.

  • n_layers (int) – Number of S4D blocks, \(N\); the authors use 4, and 1 for WG subject-independent.

  • d_state (int) – State size of each S4D kernel, even: it keeps d_state // 2 conjugate pairs.

  • dt_min (float) – Lower end of the log-uniform initial range of the S4D step \(\Delta\), positive.

  • dt_max (float) – Upper end of that range, at least dt_min.

  • a_real_init (float) – Initial decay rate of every state, \(-\mathrm{Re}(A_n)\), positive; 0.5 is S4D-Lin (Eq. (9)).

  • avg_size (int) – Width of the \(\mathrm{AP}_3\) moving average of the "multiscale" branch (avg_size_2 in the reference), at most n_times.

  • drop_prob (float) – Dropout in and after each S4D layer (dropout in the reference).

  • prenorm (bool) – LayerNorm before each S4D layer instead of after the residual; the authors’ default is post-norm.

  • compute_hbt (bool) – Replace HbR by HbT = HbO + HbR (even n_chans).

  • channel_order (Optional[Literal['stacked', 'interleaved']]) – [HbO..., HbR...] (the authors’) or [HbO_1, HbR_1, ...] (MNE); None reads chs_info, else assumes "stacked". Ignored when compute_hbt=False.

  • mean_branch (Literal['multiscale', 'time_mean']) – The selectable branch (mode in the reference): MAMHB, inter-subject ("LOSO-CV", needs an even n_chans), or MHB, intra-subject ("KFold-CV").

  • activation (type[Module]) – Activation inside each S4D layer.

  • branch_activation (type[Module]) – Activation of the "multiscale" branch.

Raises:

ValueError – If some input signal-related parameters are not specified: and can not be inferred.

Notes

If some input signal-related parameters are not specified, there will be an attempt to infer them from the other parameters.

References

Hugging Face Hub integration

When the optional huggingface_hub package is installed, all models automatically gain the ability to be pushed to and loaded from the Hugging Face Hub. Install with:

pip install braindecode[hub]

Pushing a model to the Hub:

from braindecode.models import FNIRS4D

# Train your model
model = FNIRS4D(n_chans=22, n_outputs=4, n_times=1000)
# ... training code ...

# Push to the Hub; ``datasets`` and ``base_model`` go to the card
model.push_to_hub(
    repo_id="username/my-fnirs4d-model",
    commit_message="Initial model upload",
    model_card_kwargs={"datasets": ["BNCI2014_001"]},
)

Loading a model from the Hub:

from braindecode.models import FNIRS4D

# Load pretrained model
model = FNIRS4D.from_pretrained("username/my-fnirs4d-model")
# Data the weights were trained on, from the Hub model card
print(model.card_data.datasets if model.card_data else None)

# Load with a different number of outputs (head is rebuilt automatically)
model = FNIRS4D.from_pretrained("username/my-fnirs4d-model", n_outputs=4)

Extracting features and replacing the head:

import torch

x = torch.randn(1, model.n_chans, model.n_times)
# Extract encoder features and a mean-pooled 2-D embedding
out = model(x, return_features=True)
embedding = out["embedding"]  # (batch, dim)
features = out["features"]

# Replace the classification head
model.reset_head(n_outputs=10)

Note that torch.jit.script returns features only on models whose forward declares return_features.

Saving and restoring full configuration:

import json

config = model.get_config()            # all __init__ params
with open("config.json", "w") as f:
    json.dump(config, f)

model2 = FNIRS4D.from_config(config)    # reconstruct (no weights)

All model parameters (both EEG-specific and model-specific such as dropout rates, activation functions, number of filters) are automatically saved to the Hub and restored when loading.

See Loading and Adapting Pretrained Foundation Models for a complete tutorial.

Methods

forward(x, return_features=False)[source]#

Forward pass of the fNIRS4D model.

Parameters:
  • x (Tensor) – Input tensor with shape (batch_size, n_chans, n_times): HbO and HbR rows, or the rows as given with compute_hbt=False.

  • return_features (bool) – If True, return the features that feed the FC layer.

Returns:

Logits with shape (batch_size, n_outputs), or with return_features=True the dict {"features", "cls_token"}, features of shape (batch_size, 2 * n_chans) and cls_token None.

Return type:

Tensor | dict[str, Tensor | None]

reset_head(n_outputs)[source]#

Replace the classification head for a new number of outputs.

This is called automatically by from_pretrained() when the user passes an n_outputs that differs from the saved config, and attaches a head to a model built with n_outputs=None. The default replaces the last linear or convolutional layer of final_layer by a new one with n_outputs outputs, and raises NotImplementedError when that layer is constrained, when final_layer holds more than one such layer, or when it does not end with one. Override in subclasses that need a model-specific head structure. Implementations keep changed constructor arguments in sync with self._update_init_kwargs, so that a saved model can be loaded back. Implementations requiring positive outputs can also use self._set_n_outputs to validate and record the new value.

Parameters:

n_outputs (int) – New number of output classes.

Return type:

None

Examples

>>> from braindecode.models import BENDR
>>> model = BENDR(n_chans=22, n_times=1000, n_outputs=4)
>>> model.reset_head(10)
>>> model.n_outputs
10

Added in version 1.4.