braindecode.models.MEGGPT#

class braindecode.models.MEGGPT(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, *, n_tokens=66, n_codes=128, rnn_hidden_size=128, temperature=0.1, embed_dim=256, num_heads=4, feedforward_dim=1024, n_patches=(100, 25, 20, 10, 8), patch_lens=(1, 4, 4, 8, 8), n_last_steps=16, patch_band=(8, None, None, None, None), activation=<class 'torch.nn.modules.activation.GELU'>, drop_prob=0.2, embedding_init_bound=0.05, on_non_divisible='pad')[source]#

MEG-GPT from Huang et al. (2026) [huang2026meggpt].

Foundation Model Attention/Transformer Recurrent

MEG-GPT architecture

MEG-GPT predicting the next token from token, channel, position and optional extra embeddings through a Transformer decoder, reproduced from [huang2026meggpt] (CC BY 4.0).#

Added in version 2.1.

Architecture Overview

With B the batch, C = n_chans, D = embed_dim and S the number of segments (n_times, padded or cropped to a multiple of the segment length, divided by it):

  1. The EphysTokenizer encoder [ephystokenizer] turns each channel into a stream of discrete tokens, one per sample: a GRU runs over the channel, a linear layer and a layer norm give one logit per codebook entry, and the argmax is remapped to a token id through the released vocabulary. x (B, C, T) -> token ids (B, C, S * 100).

  2. The token stream is cut into segments of n_patches[0] * patch_lens[0] tokens (100, i.e. 0.4 s at 250 Hz). Token, time and channel embeddings are summed. -> (B * S, 100, C, D).

  3. A stack of causal time-attention layers runs on every channel. In layer i the keys and values are pooled into n_patches[i] patches of patch_lens[i] steps and the output keeps the last steps only, so the sequence shrinks to n_last_steps outputs per segment. -> (B * S, n_last_steps, C, D), merged to (B, S * n_last_steps, C, D).

  4. The outputs are averaged over time and segments into (batch, n_chans, embed_dim) features (Section 2.4 of the paper), flattened and classified by a linear layer. -> (B, C, D) -> (B, C * D) -> (B, n_outputs).

Macro Components

MEGGPT.tokenizer

Operations: per-channel GRU, linear layer, layer norm, argmax and vocabulary lookup.

Role: discretise each sample of each channel. The argmax has no gradient, so the tokenizer is frozen (its parameters do not require gradients).

MEGGPT.layers

Operations: pre-norm causal attention over time with patched keys and values (a linear layer mixes the heads and steps of a patch), a banded mask in layers with a patch_band, and a feed-forward block.

Role: model the temporal dependencies of each brain region.

MEGGPT.final_layer

Operations: flatten and linear projection.

Role: map the time-averaged features to class logits.

Temporal, Spatial, and Spectral Encoding

  • Temporal: the tokenizer GRU encodes the whole window in one pass (the reference uses 200-sample windows, with the same tokens up to 200 samples); the GPT attends causally within independent segments of n_patches[0] * patch_lens[0] tokens.

  • Spatial: each parcel is tokenized and attended alone, with a learned channel embedding; only the flattened final_layer mixes parcels.

  • Spectral: implicit in the tokenizer GRU; there is no explicit transform.

Additional Mechanisms

  • Input: the 52 parcels of the Glasser 52 parcellation in the released order, since the channel embedding is indexed by position, sign-flip aligned (Section 2.5.3), at 250 Hz and z-scored over the recording (tokenize_session(standardize=True) in the reference); the model neither normalises nor checks sfreq. With on_non_divisible="pad", the feature mean skips the kept steps after the end of the input.

  • Channel mask: with return_features=True, ch_mask (the mask of pad_channels_collate(), real channels first) gives each recording the features of its real parcels run alone, and zeros for padded channels. The flattened head is tied to n_chans, so without return_features it raises a ValueError.

  • Token mask: token_mask (True=hide) zeroes selected clean token embeddings before the causal decoder, without changing the frozen tokenizer or the attention masks; it is neither the released pretraining method nor a bidirectional masked-sample reconstruction objective. encode_tokens() returns next-token targets for a downstream vocabulary head; the encoder installs none.

  • Session embedding: the released model adds one for its 621 Cam-CAN sessions; the paper discards it downstream (Section 2.5.4), so the class has none, the converted weights drop it, and the forward equals the released model called without session labels.

  • Not ported: only the released configuration, time attention with patching. The reference’s optional channel and cross attention, unpatched keys, rotary or sinusoidal positions and batch/group norms are not implemented.

Pretrained Weights

The released Cam-CAN MEG-GPT and EphysTokenizer weights, converted to this class’s keys without the next-token head and the tokenizer’s signal decoder, are at braindecode/meggpt-pretrained (revision 5c49e27c); the head is randomly initialized:

from braindecode.models import MEGGPT
model = MEGGPT.from_pretrained("braindecode/meggpt-pretrained", n_outputs=4)

They expect the input described above: source-space MEG at 250 Hz, the 52 parcels in the released order, sign-flip aligned and z-scored over the recording (Section 2.5.3). On the same token ids, the decoder outputs and the features equal those of the authors’ model called without session labels (#1555).

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

  • n_chans (int) – Number of EEG channels.

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

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

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

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

  • n_tokens (int) – Size of the GPT vocabulary (65 used codebook entries plus id 0 for the unused ones in the released vocabulary).

  • n_codes (int) – Codebook size of the tokenizer.

  • rnn_hidden_size (int) – Hidden size of the tokenizer GRU.

  • temperature (float) – Divisor of the tokenizer’s normalised logits before the argmax (the released EphysTokenizer value). It leaves the argmax unchanged except for float near-ties, so keep it to reproduce the released tokens.

  • embed_dim (int) – Embedding and model dimension.

  • num_heads (int) – Number of attention heads.

  • feedforward_dim (int) – Hidden width of the feed-forward blocks.

  • n_patches (Sequence[int]) – Number of key/value patches in each layer.

  • patch_lens (Sequence[int]) – Steps per key/value patch in each layer. Layer i reads n_patches[i] * patch_lens[i] steps and outputs as many steps as the next layer reads; n_patches[0] * patch_lens[0] is the segment length.

  • n_last_steps (int) – Number of steps the last layer outputs per segment.

  • patch_band (Sequence[Optional[int]]) – Half-width, in patches, of the banded attention of each layer; None for no band.

  • activation (type[Module]) – Activation of the feed-forward blocks.

  • drop_prob (float) – Dropout after the embeddings, the attention and the feed-forward blocks.

  • embedding_init_bound (float) – Bound b of the uniform initialisation U(-b, b) of the token embedding, as in the reference initializer.

  • on_non_divisible (str) – How a window that is not a multiple of the segment length is handled: right zero-padded, cropped, or rejected.

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.

Methods

encode_tokens(token_ids, token_mask=None, ch_mask=None, lengths=None)[source]#

Encode cached token ids and return their shifted next-token targets.

Parameters:
  • token_ids (Tensor) – Clean int64 ids (batch, n_chans, n_times), e.g. from model.tokenizer(x).

  • token_mask (Optional[Tensor]) – Boolean, same shape, True hides that token’s embedding.

  • ch_mask (Optional[Tensor]) – Boolean (batch, n_chans), True for real channels (real parcels first).

  • lengths (Optional[Tensor]) – Int64 (batch,) valid time counts, default n_times; ids past them are zeroed before the embedding.

Returns:

features and tokens as in forward, and token_ids, the ids as encoded (invalid ones zeroed, padded or cropped). output_indices are the positions of the ids that tokens output, the last n_last_steps of each segment. next_token_targets are the ids at output_indices + 1, target_valid marks those on real channels and before lengths, and prediction_mask also requires the target token to be hidden by token_mask, if given. The three are (batch, n_chans, n_segments * n_last_steps); invalid targets are zero.

Return type:

Dict[str, Tensor]

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

ch_mask: optional (batch, n_chans) mask of real channels, see check_ch_mask(). Needs return_features=True; the features and tokens of padded channels are zero. token_mask is a boolean (batch, n_chans, n_times) mask (True=hide): selected clean token embeddings are replaced by zeros before positions and causal context, not before tokenization. See encode_tokens() for next-token targets and loss selection.

Parameters:
  • x (Tensor) – The description is missing.

  • return_features (bool) – The description is missing.

  • ch_mask (Optional[Tensor]) – The description is missing.

  • token_mask (Optional[Tensor]) – The description is missing.

Return type:

Union[Tensor, Dict[str, Optional[Tensor]]]

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.