Skip to content

Add MEG-XL (long-context MEG brain-to-text foundation model) - #1554

Merged
bruAristimunha merged 40 commits into
braindecode:masterfrom
bruAristimunha:feat/meg-megxl
Nov 10, 2026
Merged

bruAristimunha merged 40 commits into
braindecode:masterfrom
bruAristimunha:feat/meg-megxl

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #1553: this branch contains its SEANet + BBL commits; review the MEG-XL commits only. The diff shrinks once #1553 merges.

Adds braindecode.models.MEGXL, MEG-XL: Data-Efficient Brain-to-Text via Long-Context Pre-Training (Jayalath & Parker Jones, ICML 2026, arXiv:2602.02494). Code: neural-processing-lab/MEG-XL @ 97da0417, License (MIT). Weights: pnpl/MEG-XL (MIT card). Tokenizer: BioCodec (MIT).

Related: #1392.

Model

  • Frozen BioCodec tokenizer. Per-channel RMS scaling, then modules.SEANetEncoder(causal=True, n_residual_layers=2, compress=1, true_skip=True), then 6 RVQ codebooks picked by cosine similarity. The codebooks live in modules.ResidualVectorQuantizer; the 6-line encode is in the model because BioCodec uses cosine similarity, not Euclidean distance. This gives ceil(n_times / 12) tokens.
  • Embeddings. The code embeddings are projected to 512. Gaussian Fourier features of sensor position and orientation are added, plus a GRAD/MAG embedding. The geometry comes from chs_info through BrainOmni's geometry helper.
  • Backbone. 8 criss-cross blocks, reusing BrainOmni's _SpatialTemporalBlock. One refactor commit lets its RoPE take a cache length; the default 240 keeps BrainOmni bit-identical, and MEG-XL uses 625 (the 150 s window).
  • Head. Mean over time, flatten, then Linear. return_features and reset_head are supported.

Not ported (training only): temporal block masking, mask_token, the code-prediction head, the BioCodec decoder.

Parity

Original code vs port, released meg-xl-med-v2.ckpt (step 113000), CPU float32, eval:

geometry codes features max-abs 119 gradients max-abs
Neuromag 306 ch, B=1, 20 s equal 0.0 0.0
Neuromag 306 ch, B=2, 20 s equal 0.0 0.0
KIT 157 ch, B=1, 20 s equal 0.0 0.0
Neuromag 306 ch, 150 s (625 tokens) equal 0.0 (forward only)
from_pretrained on the local converted export equal 0.0 0.0
  • Eval dropout. The original keeps attention dropout (p=0.1) on in eval mode: two of its eval forwards differ by up to 7.4. For parity that dropout is zeroed, and the port is deterministic in eval, as BrainOmni is.
  • Geometry precision. The authors normalise sensor positions in float64 and the port in float32. Positions differ by 1.8e-7 and features by 2.6e-5 (relative 7.5e-7). The shared helper is unchanged so BrainOmni keeps its bits.
  • Batched geometry. An earlier revision projected static geometry once and broadcast it. Five gradients then differed at B=2 (up to 1.3e-3). A controlled intervention showed this construction was the cause, and the port now uses the original's batched geometry. A shared regression test covers it.

Tests (CPU, -k "not compiled"):

Replication

In progress (NeuralBench harness, NEMAR data, both the port and the authors' code; every pipeline gets an independent code review before results are posted): word decoding with the released checkpoint on a public paper dataset, using the authors' protocol. Results will be added here.

Open decisions

  • Converted weights: braindecode/megxl-pretrained @ 5b5dcbcc (from pnpl/MEG-XL meg-xl-med-v2.ckpt, MIT). MEGXL.from_pretrained("braindecode/megxl-pretrained", chs_info=..., n_outputs=...) matches the authors' code to 0.0 (codes, features, 119 gradients) after a fresh download. No head is shipped (its shape depends on the montage).
  • Head: pooled Linear(n_chans * 512, n_outputs). The authors' T5-embedding word MLP is task-specific and not the default.
  • EEG channels are accepted (GRAD embedding, zero orientation), as in BrainOmni, but MEG-XL was pretrained on MEG only.

Replication (braindecode maintainers)

Protocol. Paper cell: MEG-XL (arXiv:2602.02494 v2) Fig. 4, MEG-MASC, 150 s
context, linear probe on frozen features, balanced top-10 accuracy with a 50-word retrieval set (chance 0.20):
0.2197 ± 0.0096 (bar half-width; SD or SEM not stated; 5 pre-training seeds). Data: MEG-MASC from NEMAR nm000229
v1.0.1, read through NeuralBench inputs. For every arm, the authors' probe script
(evaluate_criss_cross_word_classification_linear_probe.py, MEG-XL @97da0417, released checkpoint
meg-xl-med-v2.ckpt) runs unchanged on cached frozen-encoder features. The features come from three encoders: the
authors' module with attention dropout zeroed, braindecode MEGXL (ab7e7e1) with the authors' batch sensor geometry,
and MEGXL built from each recording's chs_info. Splits, vocabulary, T5 targets, probe init, seed 42 and batch
order are identical across arms. Settings: train_pct 0.07 (Fig. 4 caption); early stopping on validation balanced
top-10 @250 (patience 10, min_delta 0.001); 882 test segments from 27 subjects; one probe seed per arm. The rules
were fixed before the first training metric existed: a 5 % relative band around the paper value for the authors'
code, and 1 % relative between port and authors' code.

MEG-XL replication on MEG-MASC

arm value value − 0.20 vs paper (rel.) kept epoch / epochs run
Paper (Fig. 4, MEG-MASC 150 s) 0.2197 ± 0.0096 +0.0197
Authors' code, attention dropout zeroed orig_det_0.07 0.2130 +0.0130 −3.1 % (REPLICATED, 5 % band) 1 / 11
braindecode MEGXL, authors' batch sensor geometry port_det_0.07 0.2321 +0.0321 +5.6 % 5 / 15
braindecode MEGXL, each recording's own chs_info port_own_0.07 0.2249 +0.0249 +2.3 % 5 / 15
Secondary, not in any verdict: authors' code as released (attention dropout on in eval; replay of 12 stored dropout draws) orig_stoch_0.07 0.2263 +0.0263 +3.0 % 6 / 16
Secondary control, 25 % train data (config default): authors' code orig_det_0.25 0.2330 +0.0330 +6.0 % 2 / 12
Secondary control, 25 % train data: braindecode MEGXL port_det_0.25 0.2449 +0.0449 +11.4 % 3 / 13

"Kept epoch" is the epoch whose checkpoint early stopping kept and that is scored on test; "epochs run" is the epoch
at which training stopped. The authors' value 0.2130 is its epoch-1 checkpoint.

Pre-registered verdict lines (verbatim):

PAPER_VERDICT: REPLICATED | decided by orig_det_0.07 X=0.2130 (value-0.20 +0.0130), paper 0.2197 (value-0.20 +0.0197 +- 0.0096), rel -0.0305, band [0.2087, 0.2307]; port Y=0.2321 (value-0.20 +0.0321); port_own W=0.2249 (value-0.20 +0.0249)
PORT_DET_VS_AUTHORS: DIFFERS | port_det_0.07=0.2321 (value-0.20 +0.0321) vs orig_det_0.07=0.2130 (value-0.20 +0.0130); diff +0.019086 (rel +0.08959, tol 0.01 relative; +1.4653 of orig_det's above-chance margin); feature parity rel max 1.17e-06 median 0 over 3332 det segments
PORT_OWN_VS_AUTHORS: DIFFERS | port_own_0.07=0.2249 (value-0.20 +0.0249) vs orig_det_0.07=0.2130 (value-0.20 +0.0130); diff +0.011850 (rel +0.05563, tol 0.01 relative; +0.9098 of orig_det's above-chance margin); feature parity rel max 2.94e-06 median 6.99e-07 over 3332 det segments

Localisation of the two DIFFERS lines (post-hoc reviewer diagnostic, not pre-registered; it changes no verdict):

  • At epoch 1, all three 0.07 trainings give the same retrieval metrics, on validation and on test (test 0.2130 in each arm).
  • Each saved probe gives the same test value on the authors' features and on either port's: 0.213025 (authors' probe),
    0.232111 (port_det probe) and 0.224875 (port_own probe), each on all three feature sets.
  • The difference is which checkpoint early stopping kept: epoch 1 for the authors' arm, epoch 5 for both port arms
    (panel c). The criterion is validation balanced top-10 @250, chance 0.04.
  • At matched epochs (1-11), port_det minus authors' code on test has mean −0.0003 (SD 0.0076, 11 epochs).
  • Determinism repeat of the authors' arm (same command, seed 42, same cached features, new output folder, 2 h
    window, expectation written before submission): epochs 1-7 reproduce all 77 values the original run printed
    (losses, validation/test retrieval metrics, best-checkpoint saves). The kept checkpoint's tensors are bitwise
    equal to the original's (epoch 1). The run stopped at the window, so the epoch-11 stop and the after-load test
    value were not repeated. Within these epochs, two runs of the same arm do not drift apart. The drift between
    arms from epoch 2 on therefore goes with the only input that differs between arms: the features (max relative
    difference 1.17e-6 / 2.94e-6).

Conclusions.

  • Paper: "The authors' released code (MEG-XL @97da0417, attention dropout zeroed, released checkpoint), run on NEMAR
    nm000229 through NeuralBench inputs at train_pct 0.07, reaches 0.2130 balanced top-10 accuracy (50-word retrieval,
    chance 0.20) vs the paper's 0.2197 ± 0.0096: −3.1 % relative, inside the pre-registered 5 % band (REPLICATED). One
    probe seed. The reported value is the epoch-1 checkpoint."
  • Port vs authors' code, features: "The braindecode MEGXL port produces the same frozen-encoder features as the
    authors' module with attention dropout zeroed: max relative difference per segment 1.17e-6 (authors' sensor
    geometry), 2.94e-6 (each recording's own chs_info), over 3332 segments." Scope: deterministic forward only (see the
    last deviation below).
  • Port vs authors' code, downstream probe: "On the downstream probe the pre-registered 1 % rule gives DIFFERS: port
    0.2321 / 0.2249 vs authors 0.2130. The trainings are identical at epoch 1 and differ in the checkpoint kept by early
    stopping (epoch 5 vs 1). Each saved probe gives the same value on the port's and the authors' features."
  • Secondary rows are labelled controls. They are not averaged with the primary rows and do not replace them.
Per-subject paired differences (27 subjects), shown next to same-code comparators

All subjects in a comparison are scored by the same two probes, so these are not independent replicates. The
same-code comparators (no port involved) give similar counts.

comparison mean SD subjects higher / lower
port_det_0.07 − orig_det_0.07 +0.0216 0.0237 22 / 5
port_own_0.07 − orig_det_0.07 +0.0128 0.0216 19 / 8
same code: orig_stoch_0.07 − orig_det_0.07 +0.0147 0.0221 20 / 7
same code: orig_det_0.25 − orig_det_0.07 +0.0194 0.0230 22 / 5

Deviations.

  • train_pct 0.07 (Fig. 4 caption) instead of the config's 0.25; the 0.25 arms are pre-registered controls.
  • Inputs from the NeuralBench extractor on NEMAR nm000229 v1.0.1 (max relative difference vs the authors'
    preprocessing 4.7e-8); CPU; backbone features cached once per arm; one probe seed per arm vs the paper's 5
    pre-training seeds, so the table has no run-to-run error bar for our arms.
  • Checkpoint: the released meg-xl-med-v2.ckpt is at step 113000; the paper's Fig. 4 points come from 35000-step
    context-scaling runs. Whether the release is one of those models is unknown.
  • The released module keeps attention dropout_p = 0.1 on in eval mode. The primary arms zero it, so the feature
    parity above covers the deterministic forward only; orig_stoch_0.07 (secondary) approximates the as-released
    behaviour with 12 stored dropout draws.

Evidence (figure as PNG/SVG/PDF and plotted values): replication-evidence/megxl-20261109 @ f639638b on the maintainer fork.

Move BrainOmni's private EnCodec SEANet (conv, transposed conv, LSTM, residual block, encoder, decoder) to braindecode/modules/seanet.py, with in_channels/out_channels, n_residual_layers, dilation_base, compress, true_skip and causal options whose defaults keep BrainOmni unchanged (seeded state_dict, outputs, loss and gradients bit-identical to 05b764d).
Move BrainOmni's private EnCodec SEANet (conv, transposed conv, LSTM, residual block, encoder, decoder) to braindecode/modules/seanet.py, with in_channels/out_channels, n_residual_layers, dilation_base, compress, true_skip and causal options whose defaults keep BrainOmni unchanged (seeded state_dict, outputs, loss and gradients bit-identical to 05b764d).
Port of neural-processing-lab/the-brains-bitter-lesson @3965a2be (MIT): dataset-conditional projector, shared SEANetEncoder, subject embedding with the mean-subject fallback, linear head. The released CamCAN checkpoint loads after a key conversion (only final_layer missing) and matches the original Backbone bit for bit (features, logits, all gradients; CPU float32, eval).
_SpatialTemporalBlock, _MultiHeadAttentionRoPE and _RotaryPositionalEmbedding take the number of cached RoPE positions (default 240, unchanged). BrainOmni and BrainTokenizer state dicts, eval outputs, train loss and gradients are bit-identical to the parent commit (megxl lane evidence/char_brainomni.log).
MEG-XL (Jayalath and Parker Jones, ICML 2026): frozen BioCodec tokenizer (causal SEANet encoder + 6 cosine-similarity RVQ codebooks) and an 8-layer criss-cross transformer with Gaussian Fourier sensor embeddings, reusing BrainOmni's spatial-temporal block, braindecode.modules.SEANetEncoder and ResidualVectorQuantizer. The released meg-xl-med-v2.ckpt matches the authors' code bit for bit on CPU (20 s and 150 s windows, 306 Neuromag channels).
Resolutions:
- braindecode/models/__init__.py: master's lazy-import scheme (braindecode#1510); BBL
  re-added as one `from .bbl import BBL` line in the TYPE_CHECKING block
  (__all__ and the lazy map are derived from it).
- docs/whats_new.rst: rebuilt from master's file; the SEANet refactor and BBL
  entries moved to the current 2.1.0 section.
- docs/api.rst: master's file; BBL added to the models list and the SEANet
  section placed after master's new Quantization section.
- NOTICE.txt (auto-merged): master's file plus the bbl.py and seanet.py lines
  and the SEANet sentence.
Brings origin/master e031f8f and the BBL port (98043af). The SEANet
patch is the same on both sides (581bb9b = 2fe3ba0).

Resolutions:
- braindecode/models/__init__.py: master's lazy TYPE_CHECKING import
  block (braindecode#1510) with BBL, plus `from .megxl import MEGXL`.
- NOTICE.txt: BBL's rewrapped MIT paragraph and file list, plus
  `braindecode/models/megxl.py`.
- docs/api.rst: master + BBL (Quantization section, BBL entry), MEGXL entry.
- docs/whats_new.rst: master's 2.1.0 section with the BBL, MEG-XL and
  SEANet entries.
- test/unit_tests/models/test_models.py: keep both the BBL and the MEG-XL test.
- versionadded 2.1 (master's dev line).
- test_return_features: MEGXL in _MODELS (return_features dict, default
  forward and reset_head on 22 EEG channels, one block).
- Docstring: sensor normalisation is a division by sqrt(3 mean |r|^2);
  EEG channels get the gradiometer embedding with zero orientation and
  their own normalisation, other kinds raise; ceil(n_times / 12) tokens;
  the weights point to the braindecode/meg-xl-med-v2 Hub mirror.
- tokenize: say why the shared RVQ forward is not used (cosine vs
  Euclidean code choice).
- Drop the .contiguous() of the two non-persistent geometry buffers.
- BrainOmni RoPE docstring: name MEG-XL's 625 positions, rewrap.
A wider runtime input was cropped by F.pad's negative amount when it exceeded n_sensors; padding by n_sensors - n_chans makes it fail in the projector instead.
Brings fix 086ce56 (BBL pads from the configured n_chans). No conflicts; MEG-XL code untouched.
Brings 388ac6c (BBL docstring: checkpoint preprocessing). No conflicts; MEG-XL code untouched.
Brings 840b6c3 (BBL Hub weights docs). docs/whats_new.rst: took feat/meg-bbl's BBL entry, kept the MEGXL entry.
@codecov

codecov Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.11321% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.60%. Comparing base (1aea042) to head (f75d7f3).
⚠️ Report is 4 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1554      +/-   ##
==========================================
+ Coverage   91.54%   91.60%   +0.06%     
==========================================
  Files         172      175       +3     
  Lines       22623    22809     +186     
==========================================
+ Hits        20711    20895     +184     
- Misses       1912     1914       +2     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Brings 3df3488 (BBL COMPAT entry). test_pretrained_compat.py: kept both the MEGXL and the BBL COMPAT entries and NO_STRATEGY members.
Brings in the ch_mask series (braindecode#1545 braindecode#1548 braindecode#1540 braindecode#1549 braindecode#1542 braindecode#1543 braindecode#1544 braindecode#1550), braindecode#1557 and braindecode#1559 (master dba9d42). No conflicts; NOTICE.txt and docs/whats_new.rst carry only this PR's additions over master.
Padded channels are zeroed, the empty sensor slots of the reference collator, and the input is padded from its own channel count (never cropped), so each recording of a padded batch gives its output alone. Shape comments in BBL.forward and the SEANet blocks (comments only there).
forward(x, return_features=False, ch_mask=None) raises a ValueError naming ch_mask when one is given: the head flattens n_chans * latent_dim features and the sensor geometry is the chs_info montage, so a recording cannot run on fewer channels (option (b) of the ch_mask contract, braindecode#1548). Every tensor line of tokenize/encode/forward/_fourier_features carries its shape; no other code change.
Merge pushed BBL ee94750 (codefix 2026-11-09). Resolve whats_new by keeping BBL's ch_mask entry and MEGXL's ch_mask refusal entry. Shared SEANet changes are shape comments only, owned by the BBL lane.
Share clean code embedding through encode_codes; replace selected projected content before metadata/context with a caller-owned vector. Preserve default parameters, keys, initialization and forward dictionary. Equal-valid-length full-montage windows only; distinguish encoded corruption from padding and raw-wave masking. Test code perturbation isolation, no-mask parity, gradients and token-hop boundaries.
Brings in 29c230e (braindecode#1558, checkpoint provenance in from_pretrained and the
notebook model card).

Resolution: docs/whats_new.rst rebuilt from master's file (with its restored
RST section underlines) plus this PR's two Enhancements bullets (BBL and the
shared SEANet modules), unchanged.
Merge origin/master 0f1cce2 (braindecode#1551 CORTEG).

Resolved: test/unit_tests/models/test_pretrained_compat.py NO_STRATEGY
keeps master's CORTEG and this branch's BBL (one entry per line).
NOTICE.txt, docs/whats_new.rst, docs/api.rst, summary.csv and
models/__init__.py merged automatically; the diff against master is
exactly this branch's additions.
@bruAristimunha
bruAristimunha marked this pull request as ready for review November 10, 2026 06:19
Copilot AI balanced review requested due to automatic review settings November 10, 2026 06:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@bruAristimunha
bruAristimunha merged commit 3f9e360 into braindecode:master Nov 10, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants