Skip to content

Add MEG-GPT (source-space MEG foundation model) - #1555

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

bruAristimunha merged 18 commits into
braindecode:masterfrom
bruAristimunha:feat/meg-meggpt

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Adds braindecode.models.MEGGPT, a source-space MEG foundation model from OHBA: MEG-GPT: A transformer-based foundation model for magnetoencephalography data (Huang, Cho, Gohil, Parker Jones & Woolrich, Imaging Neuroscience 2026, doi:10.1162/imag.a.1301, arXiv:2510.18080). Code: OHBA-analysis/MEG-GPT @ 78ff9439, License (MIT). Tokenizer encoder: OHBA-analysis/EphysTokenizer @ 44cac87c, License (MIT).

Related: #1392.

Model

  1. Tokenizer (frozen, inside the model). A GRU runs over each parcel. Then a linear layer, a layer norm and an argmax, and the released vocabulary gives one of 66 token ids per sample.
  2. Segmenting. The token stream is cut into 100-token segments (0.4 s at 250 Hz) through functional.pad_or_crop_to_patches (on_non_divisible). Token, time and channel embeddings are summed.
  3. Decoder. Five causal time-attention layers per channel, with patched keys/values and the released band mask. The output shrinks 100 → 100 → 80 → 80 → 64 → 16 steps. Reuses modules.FeedForwardBlock.
  4. Features and head. Features are the decoder output averaged over time and segments, (batch, n_chans, 256) (paper §2.4). final_layer is flatten + linear. return_features and reset_head are supported.

Input: (batch, 52, n_times), the 52 Glasser parcels at 250 Hz, each z-scored over the recording and sign-flip aligned as in the paper. The model does not normalise its input.

Design decisions.

  • The Cam-CAN session embedding is dropped, as the paper does for downstream use (§2.5.4).
  • Only the released configuration is ported: time attention with patching. Channel/cross attention (MEG-GPT-2) is off in the released config and is not ported.
  • The port runs the tokenizer GRU over the whole window. The reference tokenize_session restarts it every 200 samples, so over 1000 samples 99.3 % of the tokens agree.

Parity

Original code vs port, released Cam-CAN weights, CPU float32, eval. load_state_dict reports only the new head missing.

check result
token ids, 200 samples vs tokenize_session identical
token ids, 1000 samples vs the released encoder over the window identical
attention masks, 5 layers identical
decoder hidden states, features, next-token logits (released head) max-abs 0.0
features over 10 segments (1000 samples) max-abs 0.0
gradients, one backward, 99 tensors max-abs 0.0
from_pretrained on the local converted export same, all 0.0

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

  • test_models/test_return_features/test_integration/test_private_blocks: 1826 passed.
  • pre-commit clean.

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): a downstream result from the paper with the released checkpoint, on public data where the paper's data allow it. Results will be added here.

Open decisions

  • Converted weights: braindecode/meggpt-pretrained @ 5c49e27c (from the MIT OHBA-analysis/MEG-GPT repository's released Cam-CAN checkpoint). MEGGPT.from_pretrained("braindecode/meggpt-pretrained") matches the authors' code to 0.0 (hidden states, features, 99 gradients) after a fresh download; the classification head is untrained (seed 0).
  • on_non_divisible="pad" is the library default. For this causal model "crop" may be the better default, because a padded last segment counts fully in the feature mean (documented).
  • Optional session embedding (n_sessions, BrainModule's subject_index pattern) to reproduce the pre-training forward: not added.

Replication (braindecode maintainers)

We evaluated the frozen released PyTorch checkpoint through braindecode MEGGPT (2f253bc1) and the released original code (78ff9439) on identical NeuralBench windows from Wakeman–Henson, NEMAR on000117 v1.0.0. We rebuilt 52-parcel, sign-aligned source time courses using 1–45 Hz data for both LCMV covariance and application. A training-only scaler and multinomial logistic regression (max_iter=1000, random_state=42; PCA retaining 60% variance for the PCA baseline) used runs 1–5; test sets were run 6 of the 15 available training subjects and all six runs of the paper's held-out subject 19 (BIDS sub-16). We also ran the authors' TensorFlow paper model/scripts on those parcel files, plus a diagnostic openfmri ds117 control using the paper's full 18+1 split. Values below are mean accuracy ± SEM over test sessions, independently recomputed from per-session results; recipe available on request.

Input / features Test set (sessions) Paper Fig. 8 Authors' paper-model code Port / NeuralBench
NEMAR · baseline within (15) 0.54 0.5927 ± 0.0143 0.5910 ± 0.0149
NEMAR · baseline new (6) 0.41 0.4822 ± 0.0178 0.4852 ± 0.0173
NEMAR · baseline+PCA within (15) 0.56 0.6152 ± 0.0140 0.6152 ± 0.0140
NEMAR · baseline+PCA new (6) 0.45 0.5122 ± 0.0173 0.5122 ± 0.0173
NEMAR · zero-shot within (15) 0.59 0.6266 ± 0.0073 0.6021 ± 0.0097
NEMAR · zero-shot new (6) 0.49 0.4980 ± 0.0146 0.5152 ± 0.0099
C3 openfmri · baseline within (18) 0.54 0.5398 ± 0.0211 not run
C3 openfmri · baseline new (6) 0.41 0.4506 ± 0.0357 not run
C3 openfmri · baseline+PCA within (18) 0.56 0.5691 ± 0.0196 not run
C3 openfmri · baseline+PCA new (6) 0.45 0.4542 ± 0.0325 not run
C3 openfmri · zero-shot within (18) 0.59 0.5924 ± 0.0150 not run
C3 openfmri · zero-shot new (6) 0.49 0.4856 ± 0.0252 not run

Port vs original: all 21 primary per-session accuracies are identical (maximum absolute difference 0) for released PyTorch code with the same window-tokenisation convention. Paper comparison: all six primary NEMAR cells escalate under the joint two-column 5%-relative criterion. The diagnostic C3 authors-code results put five of six cells within that band; baseline new-subject accuracy remains +9.89% relative to the paper. C3 is not a port result and does not replace the primary verdict.

  • The port uses the released PyTorch checkpoint, a different model from the paper's TensorFlow ckpt-60. Released-code session-level tokenisation, reported separately, gives 0.5986 / 0.5054 versus the window-tokenised port's 0.6021 / 0.5152. The paper's fine-tuned cell was not run (fine-tuning configuration unavailable; the port exposes no next-token head).
  • The NEMAR input lacks three of the paper's training subjects; source space was rebuilt with maintained osl-dynamics routines rather than the original prepared files. An ICA ECG-rule control (C2) gives TF 0.6117 / 0.4952 and port 0.5970 / 0.5038, both within the band, while its baseline/PCA controls remain outside. Primary results above retain the paper-literal ICA rule.
  • Restricting C3's decoder to the 15 NEMAR training subjects gives baseline 0.5412 / 0.4313, PCA 0.5779 / 0.4507, and TF 0.6061 / 0.5076. Decoder-subject restriction alone does not recover the NEMAR baseline result. MRI/input-copy and sign-alignment differences remain; T1/coregistration is a possible explanation, not isolated by this control.
  • C2 trigger/reading preregistration is not independently verified by the retained history. C3 was an adaptive diagnostic selected after the primary outcomes, not original-protocol confirmation; available file timing is not immutable registration. Neither control replaces the six primary joint ESCALATE verdicts.
  • The unmatched NEMAR/openfmri comparison also changes sign-flip population (96 versus 114 sessions), template (mapped openfmri sub12_run01 versus sub12_run05), and mapped random seeds (42 + sorted session index). The signal-identity check covers one held-out participant/six runs, not all matched subjects. These confounds prevent causal attribution to T1/coregistration.
  • Final primary ICA means over 96 runs are EOG 0.8854166667 / ECG 0.2395833333 components per run; ECG 0.26 was an intermediate 90-run observation.
  • A packaged private execution canary has completed all five YAML stages: 12 real source reconstructions, 96-session covariance/template with selected parallel flips, paper-TF scripts, port/released-code decoding, and validation (container exit 0). It trains on one subject, so its scores are not full-population accuracy evidence. The receipt uses retained environments; clean-room installation and public CPU-wheel equivalence remain unverified. Raw data, 84 other frozen alignment sessions, FSL and checkpoints remain external requirements. No public/self-contained clean-room reproduction is claimed.

MEG-GPT replication on Wakeman-Henson

Figure. MEG-GPT downstream decoding on NEMAR on000117 v1.0.0 (Wakeman–Henson). (a) Four-way decoding accuracy, mean ± SEM over test sessions (within-subject: run 6 of 15 training subjects; new subject: 6 runs of the paper's held-out subject 19). Markers: paper Fig. 8 (values printed in Section 3.5; no error bar since the paper's 95% CIs are not printed), authors' paper-model TensorFlow code, released original code with the released PyTorch checkpoint, and the braindecode port (baseline and baseline+PCA rows use the NeuralBench features; no checkpoint is involved, so the released-PyTorch column is n/a). In the zero-shot rows the TensorFlow column is the paper's TF model (ckpt-60), whereas the released-PyTorch and port columns use the released PyTorch checkpoint, a different model. Port zero-shot 0.6021 ± 0.0097 / 0.5152 ± 0.0099, identical to the released PyTorch code. Red dotted line: chance (0.25). (b) Per-session zero-shot accuracy, port vs released PyTorch code (21 sessions; maximum absolute difference 0.0000); dashed line: identity.

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

Merge origin/master e031f8f into feat/meg-meggpt (2b54370).

Resolutions:
- braindecode/models/__init__.py: take master's lazy-import module (braindecode#1510)
  and re-add MEGGPT as one TYPE_CHECKING import line (`from .meggpt import MEGGPT`).
- docs/whats_new.rst: rebuilt from master; the MEGGPT entry moves to the
  current 2.1.0 Enhancements section.
- NOTICE.txt: auto-merged; the diff against master is only the
  `braindecode/models/meggpt.py` line in the MIT section.
- braindecode/models/meggpt.py: versionadded 1.9 -> 2.1 (master's current
  development version).
- Docstring and whats_new: describe the released Cam-CAN checkpoint as
  converted for this class in the braindecode Hub mirror
  braindecode/meggpt-pretrained, with the from_pretrained call, instead of
  saying the original files load key by key.
- Input notes: parcel order and sign-flip alignment matter (the channel
  embedding is indexed by position), 250 Hz is assumed and not checked, and
  with on_non_divisible="pad" the zero-padded segment counts fully in the
  feature mean.
- Drop the unused self.embed_dim; zip(..., strict=True) over the per-layer
  lists; einops layers instead of the segment and tokenizer reshapes.
Copilot AI balanced review requested due to automatic review settings November 8, 2026 12:16

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.

🟡 Changes recommended

Banded attention fails to offset retained suffix queries by the discarded input length, causing them to attend to the wrong patches.

3 open issues
What changed in this PR

Adds MEGGPT, a source-space MEG foundation model, to Braindecode’s model API as part of the MEG integration effort in #1392.

Changes:

  • Implements a frozen tokenizer, causal patched-attention decoder, feature extraction, and replaceable classification head.
  • Registers the model and documents input requirements, upstream licensing, and pending converted-weight availability.
  • Adds shared feature-return test coverage and registers the private attention block.
File Description
test/​unit_tests/​models/​test_return_features.py Adds MEGGPT to shared model-contract tests.
test/​unit_tests/​models/​test_private_blocks.py Allowlists the private attention block.
NOTICE.txt Lists the model under MIT-licensed components.
docs/​whats_new.rst Announces the model and checkpoint status.
docs/​api.rst Adds MEGGPT to the public API listing.
braindecode/​models/​util.py Registers required model parameters.
braindecode/​models/​summary.csv Adds model metadata and an example configuration.
braindecode/​models/​meggpt.py Implements and documents the tokenizer, decoder, and downstream head.
braindecode/​models/​__init__.py Exposes MEGGPT through the models namespace.

Review effort: Balanced

Comment thread braindecode/models/meggpt.py Resolved
Comment thread braindecode/models/meggpt.py Resolved
Comment thread braindecode/models/meggpt.py Resolved
Copilot AI balanced review requested due to automatic review settings November 8, 2026 14:16

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.

🔵 Needs a closer look

The model can silently broadcast inputs with an incorrect channel count, and attention bands use truncated query indices, selecting the wrong temporal patches.

3 open issues
2 previously missed issues

In code that hasn't changed since last review

Medium severity Reject inputs with a channel count different from n_chans

braindecode/​models/​meggpt.py:250

With n_chans=52, an input shaped (batch, 1, n_times) passes the tokenizer and broadcasts here to 52 channels, silently treating the same parcel signal as every parcel and producing plausible logits. The mixin does not validate the forward input's channel count. Please reject inputs whose channel dimension differs from self.n_chans before applying the embeddings.

Medium severity Center patch bands on the query’s original sequence position

braindecode/​models/​meggpt.py:392

The band is centered on the truncated query index rather than its position in the input sequence. For example, with the default final-layer dimensions and patch_band=(8, None, None, None, 1), the last query represents timestep 63, but this selects patches 0–2 instead of the recent patches 6–7. Offset the query by the discarded prefix before computing the band center; this leaves the released default masks unchanged.

Review effort: Balanced

@codecov

codecov Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1555      +/-   ##
==========================================
+ Coverage   91.54%   91.66%   +0.11%     
==========================================
  Files         172      176       +4     
  Lines       22623    22998     +375     
==========================================
+ Hits        20711    21081     +370     
- Misses       1912     1917       +5     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI balanced review requested due to automatic review settings November 8, 2026 15:20

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.

🔵 Needs a closer look

The model silently broadcasts single-channel input across all 52 channel embeddings, producing apparently valid logits instead of rejecting the incompatible channel count.

3 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Reject inputs with a channel count that mismatches the embeddings

braindecode/​models/​meggpt.py:257

For a model built or loaded with 52 channels, an input shaped (batch, 1, n_times) silently broadcasts here to all 52 channel embeddings. The classifier therefore returns apparently valid logits from one signal duplicated across every parcel, rather than rejecting the incompatible input. Check the channel count against the embedding table before this addition.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 9, 2026 09:50

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.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 10:45

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.

Merge29c230e9 (braindecode#1558). Resolve whats_new by retaining master's restored RST headings and model-card entry plus MEGGPT's entry.
Copilot AI balanced review requested due to automatic review settings November 9, 2026 12:18

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.

Merge master 0f1cce2 (braindecode#1551, CORTEG).
Conflicts resolved:
- NOTICE.txt: master's file plus the meggpt.py MIT line after corteg.py.
- test/unit_tests/models/test_pretrained_compat.py: NO_STRATEGY keeps
  master's CORTEG and this branch's MEGGPT.
docs/whats_new.rst, docs/api.rst, summary.csv, __init__.py, util.py and the
shared test registries merged without conflict, keeping both entries.
braindecode/models/meggpt.py is unchanged from b289953.
Copilot AI balanced review requested due to automatic review settings November 9, 2026 13:28

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.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 16:22

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.

Copilot AI balanced review requested due to automatic review settings November 10, 2026 06:22

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.

Copilot AI balanced review requested due to automatic review settings November 10, 2026 06:46

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 759f643 into braindecode:master Nov 10, 2026
6 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