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 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.encoderandMEGXL.quantizerOperations. Each channel is divided by its RMS, a causal SEANet encoder downsamples it by
prod(ratios), andn_qresidual codebooks pick their entry by cosine similarity. Role. Frozen BioCodec tokenizer (no gradients, no codebook updates).MEGXL.rvq_projectorOperations. The
n_qcodebook vectors of a token are concatenated and projected tolatent_dim.MEGXL.position_projector,MEGXL.orientation_projector,MEGXL.sensor_type_layerOperations. 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.blocksOperations. Half of the features attend over time (RoPE), the other half over the channels, then a feed-forward layer (BrainOmni’s block).
MEGXL.final_layerOperations. Linear layer on the time-averaged, flattened
n_chans * latent_dimfeatures. 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_infoas in the authors’ preprocessing:loc[:3]centred and divided bysqrt(3 * mean(|r|^2)), the coil x-axis of planar gradiometers or the coil normal of other coils as orientation. MEG coils whose name containsMAGare 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 aValueError. MEG-XL is pretrained on MEG only.The RoPE table holds
n_rope_positions= 625 positions, those of the 150 s pretraining window (torch.polarvalues in the converted weights); a longer window rebuilds it fromcos/sin, one ulp away fromtorch.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()andencode_codes()accept a temporal code-corruptionmaskand caller-ownedmask_valuebefore 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 atbraindecode/megxl-pretrained(revision0446ce5d); 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.
- 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 tomne.Infofor 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 savedrotatetables; 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.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_hubpackage 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.scriptreturns features only on models whoseforwarddeclaresreturn_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)ofx.xis(batch, n_chans, n_times), with the same length for every sample and the fullchs_infomontage: 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 indexn_times // prod(ratios), which a loss on complete hops leaves out.maskandmask_valuehide code content, seeencode_codes(); neighbouring codes still carry that content in their receptive fields.
- 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
codesas targets. There is no padding mask: batch recordings of equal length.- Parameters:
codes (
Tensor) – Integer codes(batch, n_chans, n_tokens, n_q)fromtokenize().mask (
Optional[Tensor]) – Boolean(batch, n_chans, n_tokens): True replaces the projected code content of that token bymask_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 withmask; 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:
- forward(x, return_features=False)[source]#
Classify
xor return the pooled features.There is no
ch_mask: the head flattens then_chans * latent_dimfeatures and the sensor geometry is the fixedchs_infomontage, so every sample needs alln_chanschannels.