Repository navigation
Add MEG-XL (long-context MEG brain-to-text foundation model) - #1554
Merged
bruAristimunha merged 40 commits intoNov 10, 2026
Merged
Conversation
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 Report❌ Patch coverage is 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:
|
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
marked this pull request as ready for review
November 10, 2026 06:19
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
modules.SEANetEncoder(causal=True, n_residual_layers=2, compress=1, true_skip=True), then 6 RVQ codebooks picked by cosine similarity. The codebooks live inmodules.ResidualVectorQuantizer; the 6-line encode is in the model because BioCodec uses cosine similarity, not Euclidean distance. This givesceil(n_times / 12)tokens.chs_infothrough BrainOmni's geometry helper._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).Linear.return_featuresandreset_headare 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:from_pretrainedon the local converted exportTests (CPU,
-k "not compiled"):test_models/test_return_features/test_integration: 1844 passed.test_brainomni/test_private_blocks/test_modules: 517 passed.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
braindecode/megxl-pretrained@5b5dcbcc(frompnpl/MEG-XLmeg-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).Linear(n_chans * 512, n_outputs). The authors' T5-embedding word MLP is task-specific and not the default.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 checkpointmeg-xl-med-v2.ckpt) runs unchanged on cached frozen-encoder features. The features come from three encoders: theauthors' module with attention dropout zeroed, braindecode
MEGXL(ab7e7e1) with the authors' batch sensor geometry,and
MEGXLbuilt from each recording'schs_info. Splits, vocabulary, T5 targets, probe init, seed 42 and batchorder 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.
orig_det_0.07MEGXL, authors' batch sensor geometryport_det_0.07MEGXL, each recording's ownchs_infoport_own_0.07orig_stoch_0.07orig_det_0.25MEGXLport_det_0.25"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):
Localisation of the two DIFFERS lines (post-hoc reviewer diagnostic, not pre-registered; it changes no verdict):
0.232111 (
port_detprobe) and 0.224875 (port_ownprobe), each on all three feature sets.(panel c). The criterion is validation balanced top-10 @250, chance 0.04.
port_detminus authors' code on test has mean −0.0003 (SD 0.0076, 11 epochs).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.
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."
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).
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."
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.
port_det_0.07−orig_det_0.07port_own_0.07−orig_det_0.07orig_stoch_0.07−orig_det_0.07orig_det_0.25−orig_det_0.07Deviations.
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.
meg-xl-med-v2.ckptis at step 113000; the paper's Fig. 4 points come from 35000-stepcontext-scaling runs. Whether the release is one of those models is unknown.
dropout_p = 0.1on in eval mode. The primary arms zero it, so the featureparity above covers the deterministic forward only;
orig_stoch_0.07(secondary) approximates the as-releasedbehaviour with 12 stored dropout draws.
Evidence (figure as PNG/SVG/PDF and plotted values):
replication-evidence/megxl-20261109@f639638bon the maintainer fork.