braindecode.models.MEGXL#

class braindecode.models.MEGXL(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, *, latent_dim=512, num_layers=8, num_heads=8, drop_prob=0.1, n_rope_positions=625, fourier_pos_dim=250, position_scale=1.8, orientation_scale=1.0, tokenizer_dim=128, n_filters=32, ratios=(3, 2, 2), kernel_size=3, last_kernel_size=3, n_residual_layers=2, n_q=6, codebook_size=256, codebook_dim=16, min_rms=1e-08)[source]#

MEG-XL from Jayalath and Parker Jones (2026) [megxl].

Foundation Model Attention/Transformer

MEG-XL architecture

MEG-XL pretraining: per-channel BioCodec tokenization, input embedding construction and temporal block masking, reproduced from [megxl] (CC BY 4.0).#

Architecture Overview

A frozen BioCodec tokenizer turns every channel into discrete codes; a criss-cross transformer contextualizes them over time and sensors:

(batch, n_chans, n_times) -> BioCodec (SEANet + RVQ codes) -> codebook
embeddings -> projection + sensor embeddings -> criss-cross blocks ->
mean over time -> (batch, n_chans * latent_dim) -> (batch, n_outputs)

Macro Components

MEGXL.encoder and MEGXL.quantizer

Operations. Each channel is divided by its RMS, a causal SEANet encoder downsamples it by prod(ratios), and n_q residual codebooks pick their entry by cosine similarity. Role. Frozen BioCodec tokenizer (no gradients, no codebook updates).

MEGXL.rvq_projector

Operations. The n_q codebook vectors of a token are concatenated and projected to latent_dim.

MEGXL.position_projector, MEGXL.orientation_projector, MEGXL.sensor_type_layer

Operations. Gaussian random Fourier features of the sensor position and orientation, each projected to latent_dim, plus a gradiometer/magnetometer embedding, added to every token of the channel. Role. Montage-agnostic channel identity.

MEGXL.blocks

Operations. Half of the features attend over time (RoPE), the other half over the channels, then a feed-forward layer (BrainOmni’s block).

MEGXL.final_layer

Operations. Linear layer on the time-averaged, flattened n_chans * latent_dim features. Role. Classification head (not pretrained).

Temporal, Spatial, and Spectral Encoding

  • Temporal: ceil(n_times / 12) tokens of 240 ms at 50 Hz (the SEANet pads the end, as BioCodec does); RoPE attention spans the whole window (150 s in pretraining).

  • Spatial: attention over the channels, keyed by sensor geometry.

  • Spectral: learned implicitly by the tokenizer’s convolutions.

Additional Mechanisms

  • Sensor geometry comes from chs_info as in the authors’ preprocessing: loc[:3] centred and divided by sqrt(3 * mean(|r|^2)), the coil x-axis of planar gradiometers or the coil normal of other coils as orientation. MEG coils whose name contains MAG are magnetometers, the other MEG coils gradiometers. EEG channels also get the gradiometer embedding, with zero orientation and positions normalised apart from the MEG ones; other channel kinds raise a ValueError. MEG-XL is pretrained on MEG only.

  • The RoPE table holds n_rope_positions = 625 positions, those of the 150 s pretraining window (torch.polar values in the converted weights); a longer window rebuilds it from cos/sin, one ulp away from torch.polar.

  • The released attention keeps its dropout (0.1) active in eval mode; here dropout is off in eval mode, so the eval forward is deterministic.

  • encode() and encode_codes() accept a temporal code-corruption mask and caller-owned mask_value before metadata and context. They return actual temporal hidden states for native masked RVQ-code prediction. The mask sampler, learned mask vector and prediction head belong to the caller, not the default encoder checkpoint. Channel padding (ch_mask) is separate and remains unsupported.

Important

Weights converted from the released meg-xl-med-v2.ckpt (pnpl/MEG-XL, step 113000, with its frozen BioCodec tokenizer) are on the Hugging Face Hub at braindecode/megxl-pretrained (revision 0446ce5d); the head is not pretrained:

from braindecode.models import MEGXL
model = MEGXL.from_pretrained("braindecode/megxl-pretrained", chs_info=raw.info["chs"], n_outputs=2)

Input is expected at 50 Hz, preprocessed as in the authors’ code (0.1-40 Hz band-pass, baseline correction and robust scaling per 3 s chunk, clipped to [-5, 5]).

Added in version 2.1.

License

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.

  • latent_dim (int) – Transformer dimension.

  • num_layers (int) – Number of criss-cross blocks.

  • num_heads (int) – Attention heads (even: half temporal, half spatial).

  • drop_prob (float) – Dropout of the attention and feed-forward layers.

  • n_rope_positions (int) – Positions cached by the rotary embedding of the temporal attention: 625 for the 150 s pretraining window (150 s x 50 Hz / 12 samples per token). It sets the shape of the saved rotate tables; a longer window rebuilds them.

  • fourier_pos_dim (int) – Size of the Fourier features of the sensor position and orientation.

  • position_scale (float) – Standard deviation of the position Fourier frequencies.

  • orientation_scale (float) – Standard deviation of the orientation Fourier frequencies.

  • tokenizer_dim (int) – SEANet output dimension.

  • n_filters (int) – Base number of SEANet filters.

  • ratios (tuple[int, ...]) – SEANet downsampling ratios.

  • kernel_size (int) – Kernel size of the first SEANet convolution. Frozen with the release: the pretrained tokenizer expects 3.

  • last_kernel_size (int) – Kernel size of the last SEANet convolution. Frozen with the release: 3.

  • n_residual_layers (int) – Residual blocks before each SEANet downsampling. Frozen with the release: 2.

  • n_q (int) – Number of residual codebooks.

  • codebook_size (int) – Entries per codebook.

  • codebook_dim (int) – Codebook dimension.

  • min_rms (float) – Floor of the per-channel RMS that the tokenizer divides by (1e-8), so that a flat channel is not divided by zero.

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

[megxl] (1,2)

Jayalath, D., Parker Jones, O. (2026). MEG-XL: Data-Efficient Brain-to-Text via Long-Context Pre-Training. ICML 2026. https://arxiv.org/abs/2602.02494

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 MEGXL

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

Loading a model from the Hub:

from braindecode.models import MEGXL

# Load pretrained model
model = MEGXL.from_pretrained("username/my-megxl-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 = MEGXL.from_pretrained("username/my-megxl-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 = MEGXL.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

encode(x, mask=None, mask_value=None)[source]#

Contextual tokens (batch, n_chans, n_tokens, latent_dim) of x.

x is (batch, n_chans, n_times), with the same length for every sample and the full chs_info montage: padding a shorter recording would change its RMS scale, convolutions and LSTM state. n_tokens = ceil(n_times / prod(ratios)): a partial final hop adds a boundary token, at index n_times // prod(ratios), which a loss on complete hops leaves out. mask and mask_value hide code content, see encode_codes(); neighbouring codes still carry that content in their receptive fields.

Parameters:
Return type:

Tensor

encode_codes(codes, mask=None, mask_value=None)[source]#

Contextual tokens (batch, n_chans, n_tokens, latent_dim) of BioCodec codes.

Tokenizing once lets a self-supervised loss reuse the clean codes as targets. There is no padding mask: batch recordings of equal length.

Parameters:
  • codes (Tensor) – Integer codes (batch, n_chans, n_tokens, n_q) from tokenize().

  • mask (Optional[Tensor]) – Boolean (batch, n_chans, n_tokens): True replaces the projected code content of that token by mask_value, before the sensor metadata is added and before attention. Masked tokens still take part in attention.

  • mask_value (Optional[Tensor]) – Replacement vector (latent_dim,), required with mask; the caller owns it, and any prediction head.

Returns:

The tokens (batch, n_chans, n_tokens, latent_dim). No parameter is added to the model.

Return type:

Tensor

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

Classify x or return the pooled features.

There is no ch_mask: the head flattens the n_chans * latent_dim features and the sensor geometry is the fixed chs_info montage, so every sample needs all n_chans channels.

Parameters:
  • x (Tensor) – Input of shape (batch, n_chans, n_times).

  • return_features (bool) – If True, return {"features": (batch, n_chans * latent_dim), "cls_token": None} instead of the logits.

Return type:

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

reset_head(n_outputs)[source]#

Replace the classification head for n_outputs classes.

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.

tokenize(x)[source]#

BioCodec codes (batch, n_chans, n_tokens, n_q) of x.

Parameters:

x (Tensor) – The description is missing.

Return type:

Tensor