braindecode.models.FNIRST#

class braindecode.models.FNIRST(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, *, embed_dim=64, depth=6, num_heads=8, mlp_dim=64, pool='cls', head_dim=64, n_conv_filters=8, spatial_kernel_size=5, temporal_kernel_size=30, temporal_stride=4, channel_order=None, drop_prob=0.0, embed_drop_prob=0.0, activation=<class 'torch.nn.modules.activation.GELU'>)[source]#

fNIRS-T from Wang et al. (2022).

Convolution Attention/Transformer

Added in version 2.1.

fNIRS-T and fNIRS-PreT architecture

Figure of the authors’ repository (fig/model.png, wzhlearning/fNIRS-Transformer at 6ebe987f, MIT).#

fNIRS-T [1] classifies fNIRS windows with a Transformer over two levels of tokens. A convolution turns the time course of each fNIRS channel (channel level) or of a group of consecutive channels (spatial level) into one token, and a Transformer lets these tokens attend to each other; time never becomes a token axis. FNIRSPreT adds a learned preprocessing module in front. The description follows the authors’ code (model.py, KFold_Train.py, LOSO_Train.py), as the paper is not open access.

Architecture Overview

In the figure’s symbols, \(H\) = n_chans // 2 fNIRS channels, \(W\) = n_times, \(C\) = 2 chromophores, \(H_S = H - k_s + 1\) spatial tokens, \(H_C = H\) channel tokens and \(D\) = embed_dim:

input: H HbO rows and H HbR rows             (batch, 2 H, W)
to_chromophore_planes                        (batch, 2, H, W)
Spatial level (to_patch_embedding, transformer_patch):
  Conv_S, Rearrange, Linear, LayerNorm       (batch, H_S, D)
  prepend CLS, add positions, encoder        (batch, H_S + 1, D)
Channel level (to_channel_embedding, transformer_channel):
  Conv_C, Rearrange, Linear, LayerNorm       (batch, H_C, D)
  prepend CLS, add positions, encoder        (batch, H_C + 1, D)
CLS token of each level, Concat              (batch, 2 D)
final_norm, final_layer                      (batch, n_outputs)

Macro Components

  • to_chromophore_planes Input. The rows of x are split into the HbO and the HbR plane, from the stacked or MNE’s interleaved order.

  • to_patch_embedding Spatial level (“fNIRS Spatial Embedding”). \(\mathrm{Conv}_S\) maps the two planes to \(C_S\) = n_conv_filters maps with a \(k_s \times k_t\) kernel and stride \(1 \times s_t\), so each token covers \(k_s\) consecutive channels in the dataset’s order. The \(C_S \times W_S\) responses of a token are flattened, projected to \(D\) and layer-normalized.

  • to_channel_embedding Channel level (“fNIRS Channel Embedding”). The same with a \(1 \times k_t\) kernel (\(\mathrm{Conv}_C\)): one token per fNIRS channel.

  • cls_token_*, pos_embedding_*, transformer_* Transformer Encoder. Each level prepends a learned class token, adds a learned positional embedding (one row per token, the token’s only identity), applies dropout and runs depth pre-norm blocks of multi-head self-attention, with bias-free query, key and value maps, and a feed-forward layer of width mlp_dim. Each of the num_heads heads of width \(d_h\) = head_dim computes, as in the authors’ Attention,

    \[\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left( \frac{Q K^{\top}}{\sqrt{d_h}} \right) V .\]
  • final_norm, final_layer Head. The class token of each level (or, with pool="mean", the mean of its tokens) is taken, and the two vectors are concatenated, layer-normalized and classified by a linear layer (the authors’ mlp_head). The figure draws a head per level before the concatenation; the authors’ code, followed here, concatenates first.

Temporal, Spatial, and Spectral Encoding

  • Temporal. The convolutions slide a \(k_t\)-sample kernel with stride \(s_t\) along time, and the resulting values become the features of a token. The README’s segments are 140 samples (dataset A), 200 (B) and 256 (C). Kernels count samples, so sfreq is unused. The authors’ datasets are A (mental arithmetic vs rest, 8 subjects, 52 channels), B (Shin et al. 2017, same task, 29 subjects, 36 channels) and C (Bak et al. 2019, finger and foot tapping, 3 classes, 30 subjects, 20 channels).

  • Spatial. Channels, or groups of \(k_s\) consecutive channels, identified by their position in the token sequence: no montage or optode geometry, so the channels keep the order of training.

  • Spectral. None in the model: fNIRS-T expects segments band-passed (third-order Butterworth, 0.01-0.1 Hz, filtfilt, on datasets B and C), baseline-corrected and z-scored per window; FNIRSPreT learns that step.

  • Chromophores. HbO and HbR are the two input planes, mixed by both convolutions from the first layer.

Additional Mechanisms

  • Reference. For the same weights the port matches the authors’ model to float32 rounding (max-abs below 1e-6 on their dataset A, B and C configurations). The positional tables have one row per token (the authors allocate 101 rows and slice). The attention always projects its output (the authors skip it when num_heads=1 and head_dim=embed_dim). On dataset C with the authors’ KFold_Train.py (seeds 0-2) the port gives 75.03 % accuracy against 74.73 % for the authors’ code and 75.49 % in the paper; for FNIRSPreT both give 72.50 % (#1584).

  • Read-out. pool picks the class token or the mean of the tokens; the output is logits. There is no ch_mask: the spatial kernel and the positional tables span the whole montage.

  • 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.

  • embed_dim (int) – \(D\), the width of the tokens (dim in the reference; 64 for its datasets A and B, 128 for C).

  • depth (int) – Transformer blocks per level.

  • num_heads (int) – Attention heads (heads in the reference).

  • mlp_dim (int) – Hidden width of the feed-forward layers.

  • pool (Literal['cls', 'mean']) – Read-out of each level: its class token, or the mean over its tokens (class token included).

  • head_dim (int) – \(d_h\), the width of each attention head (dim_head in the reference).

  • n_conv_filters (int) – \(C_S = C_C\), feature maps of both convolutions (authors: 8).

  • spatial_kernel_size (int) – \(k_s\), height of \(\mathrm{Conv}_S\) in HbO/HbR pairs (authors: 5), at most n_chans // 2.

  • temporal_kernel_size (int) – \(k_t\), temporal kernel of both convolutions, in samples (authors: 30), at most n_times.

  • temporal_stride (int) – \(s_t\), temporal stride of both convolutions, in samples (authors: 4).

  • channel_order (Optional[Literal['stacked', 'interleaved']]) – [HbO_1..HbO_H, HbR_1..HbR_H] or MNE’s [HbO_1, HbR_1, ...]; None reads it from chs_info.

  • drop_prob (float) – Dropout in the attention and feed-forward sub-layers (dropout in the reference).

  • embed_drop_prob (float) – Dropout of the token embeddings (emb_dropout in the reference).

  • activation (type[Module]) – Activation of the feed-forward sub-layers (authors: GELU).

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 FNIRST

# Train your model
model = FNIRST(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-fnirst-model",
    commit_message="Initial model upload",
    model_card_kwargs={"datasets": ["BNCI2014_001"]},
)

Loading a model from the Hub:

from braindecode.models import FNIRST

# Load pretrained model
model = FNIRST.from_pretrained("username/my-fnirst-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 = FNIRST.from_pretrained("username/my-fnirst-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 = FNIRST.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 fNIRS-T (and fNIRS-PreT) model.

Parameters:
  • x (Tensor) – Input tensor with shape (batch_size, n_chans, n_times).

  • return_features (bool) – If True, return the normalized pooled features and the class tokens of the two levels.

Returns:

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

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.