Skip to content

Add BBL (The Brain's Bitter Lesson MEG encoder) and share SEANet blocks in modules - #1553

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

bruAristimunha merged 15 commits into
braindecode:masterfrom
bruAristimunha:feat/meg-bbl

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Adds braindecode.models.BBL, the MEG encoder of The Brain's Bitter Lesson: Scaling Speech Decoding With Self-Supervised Learning (Jayalath et al., ICML 2025, arXiv:2406.04328). Code: neural-processing-lab/the-brains-bitter-lesson @ 3965a2be, License (MIT).

Related: #1392.

Changes

  1. refactor: share SEANet blocks in braindecode.modules. BrainOmni's private EnCodec SEANet blocks move to braindecode/modules/seanet.py (SEANetConv1d, SEANetConvTranspose1d, SEANetLSTM, SEANetResBlock, SEANetEncoder, SEANetDecoder). New options (in_channels/out_channels, n_residual_layers, dilation_base, compress, true_skip, causal) cover BBL and MEG-XL's BioCodec tokenizer (Add MEG-XL (long-context MEG brain-to-text foundation model) #1554). The defaults leave BrainOmni unchanged.

  2. feat: add BBL. The model is:

    • zero-pad the channels to n_sensors=306, as the reference collator does;
    • a dataset-conditional projector: Conv1d -> GELU -> Conv1d(stride 2) into n_datasets * model_dim, gated one-hot by dataset_index;
    • SEANetEncoder, then a mean over time;
    • concatenate the subject embedding;
    • final_layer, a linear layer (the paper's probe).

    forward(x, subject_index=None, dataset_index=None, return_features=False). Without subject_index it uses the paper's novel-subject fallback: the mean of the trained subject embeddings, kept in a saved trained_subjects buffer. The original keeps that set in an unsaved attribute, and its fallback fails for batch > 1.

Not ported: the SSL projector and the band/amp/phase pretext heads (training only).

Checks

SEANet move: BrainOmni and BrainTokenizer, master e031f8ff vs this branch, seeded.

  • Sorted state_dict keys are identical.
  • Every state tensor, eval output, tokenize, train loss and gradient matches exactly (torch.equal).
  • test_brainomni.py --run-network: 67 passed.

Released CamCAN checkpoint: port vs the original Backbone, same weights and input, CPU float32, eval. load_state_dict reports only final_layer.* missing.

quantity max-abs
features, logits, loss (306 sensors, dataset slots 0-3) 0.0
input gradient + all 55 parameter gradients 0.0
204 sensors (original fed the zero-padded 306) 0.0
mean-subject fallback (batch 1) 3.7e-8

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

  • test_models/test_return_features/test_integration: 1824 passed.
  • test_private_blocks/test_modules/test_brainomni/categorization/lazy imports: 609 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): the released checkpoint's speech-detection probe, using the paper's protocol, on public data. Results will be added here.

Open decisions

  • Name: BBL (the authors' acronym).
  • Channels are matched by position, as in the reference, so the pretrained weights expect CamCAN's 306 Elekta channels in FIF order.
  • Converted weights: braindecode/bbl-pretrained @ 5a19a369 (card: code MIT; the authors distribute the checkpoint through their MIT repository's README without a separate weight licence; re-hosted unmodified in converted form with attribution, removed on request). BBL.from_pretrained("braindecode/bbl-pretrained") matches the authors' code to 0.0 after a fresh download.

Replication (braindecode maintainers)

Protocol. Cell: Fig. 3 (left) of the paper, speech detection on Gwilliams (MEG-MASC) with the released Cam-CAN checkpoint. Paper value: 0.5429 ± 0.0031 test ROC AUC (SEM over up to 5 pretraining seeds). We ran the authors' released backbone and the braindecode BBL port in the same NeuralBench pipeline. Windows, labels, splits, head initialisation, batch order and probe seeds 42-46 were identical between the two runs. Both used the released probe recipe (SEANet encoder frozen). The metric is the pooled test ROC AUC at the best validation epoch. The paper's App. A split and the split in the released datasets.yaml differ. We ran both and report them separately; no number is averaged across them. As a cross-check, the authors' own probe.py ran on their OSF preprocessing with seed 42. Pre-registration: verdict rules fixed in git at 16:14:12Z, before training; protocol.md prose only from 16:56:49Z (file timestamp) / 17:48:10Z (git).

test ROC AUC App. A split (paper's split; test: subjects 23-27, 14,934 windows) released datasets.yaml split (code as released; test: 27 subjects, 74,735 windows)
Paper, Fig. 3 (SEM over pretraining seeds) 0.5429 ± 0.0031 not reported
Authors' probe.py, OSF data, seed 42 0.6403 0.6132
Authors' backbone in NeuralBench, 5 seeds, mean ± SD 0.6453 ± 0.0058 0.6139 ± 0.0062
braindecode BBL port in NeuralBench, 5 seeds, mean ± SD 0.6453 ± 0.0058 0.6120 ± 0.0045
Port − authors' backbone, seeds 42-46 0, 0, 0, 0, 0 (predictions byte-identical for 5/5 seeds) 0, 0, 0, −0.0094, 0 (byte-identical for 4/5 seeds)
Authors' backbone − paper +0.102 (+18.9%) +0.071 (+13.1%)
Port − paper +0.102 (+18.9%) +0.069 (+12.7%)

Per seed:

seed App. A: authors' backbone App. A: port released: authors' backbone released: port
42 0.6452 0.6452 0.6142 0.6142
43 0.6526 0.6526 0.6104 0.6104
44 0.6403 0.6403 0.6177 0.6177
45 0.6390 0.6390 0.6215 0.6121
46 0.6491 0.6491 0.6056 0.6056

The two splits follow the order of the protocol (App. A first). This order does not rank them; which split leads the report is still open. Our SD is over probe seeds with one released pretraining run. The paper's SEM is over pretraining seeds, so the two spreads are not compared.

  • Port vs authors' code. On the App. A split the test predictions are byte-identical for 5/5 seeds. On the released split they are byte-identical for 4/5 seeds. At seed 45 the two CPU training runs diverged from the first logged step (floating-point nondeterminism, reproduced with identical code), and the kept checkpoint is epoch 14 for the authors' backbone and 9 for the port.
  • Authors' code vs paper. The authors' released code and checkpoint do not reproduce the Fig. 3 value on either split. The gap is not in the data pipeline: all 412,188 windows are within 2.3e-6 of the authors' preprocessing, and the labels are identical. It is not in the training loop either: the authors' probe.py result falls inside the 5-seed range on both splits. Not isolated:
    • the probe recipe (encoder-only freeze, 14.5 M trainable parameters);
    • the released checkpoint and architecture vs the paper's description;
    • bad-channel interpolation.

Deviations:

  • The released code freezes only the SEANet encoder, so the projector, the subject embedding and the head train. The paper says "we backpropagate only through the classifier" and "A trainable dataset-specific linear layer can be introduced for a novel dataset". The released architecture also differs from the paper's Table 4 (SEANet ratios [4,2,2] vs (5,5,1)). We ran the released code.
  • Bad-channel interpolation (paper §4.1) is not in the released code, and we did not add it.
  • We used one released pretraining run. The paper averages over up to 5 pretraining seeds.
  • Compute: CPU with torch 2.6.0. The paper used V100/A100 GPUs.

Figure bbl_replication.png: one panel per split. Each panel shows the paper value (± SEM), the authors' probe.py (seed 42), and the authors' backbone and the port (points = seeds, bar = mean ± SD). The dashed line marks chance (0.5).

BBL replication: speech detection on MEG-MASC, both splits

Evidence (figure as PNG/SVG/PDF and plotted values): replication-evidence/bbl-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).
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).
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.

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

The runtime channel count is not checked before padding, allowing inputs with more than n_sensors channels to be silently cropped and lose sensor data instead of raising an error.

1 open issue
What changed in this PR

Adds BBL, the MEG encoder from The Brain’s Bitter Lesson, to Braindecode’s model API and extracts reusable SEANet components from BrainOmni.

Changes:

  • Implements BBL with dataset conditioning, subject embeddings, feature extraction, and a replaceable linear head.
  • Shares configurable SEANet blocks while preserving BrainOmni’s default architecture.
  • Adds model registration, documentation, license notices, and test coverage.
File Description
test/​unit_tests/​models/​test_return_features.py Adds BBL to feature-return tests.
test/​unit_tests/​models/​test_private_blocks.py Removes the moved private SEANet block entry.
test/​unit_tests/​models/​test_modules.py Tests shared SEANet padding behavior.
test/​unit_tests/​models/​test_models.py Tests BBL padding, dataset gating, and subject averaging.
test/​unit_tests/​models/​test_integration.py Exempts BBL from the dropout-parameter requirement.
test/​unit_tests/​models/​test_brainomni.py Uses the shared SEANet convolution in existing tests.
NOTICE.txt Records MIT licensing and shared-code provenance.
docs/​whats_new.rst Announces BBL and shared SEANet modules.
docs/​api.rst Lists BBL and the public SEANet classes.
braindecode/​modules/​seanet.py Introduces reusable SEANet encoder, decoder, and blocks.
braindecode/​modules/​__init__.py Exports SEANet classes.
braindecode/​models/​util.py Registers BBL’s standard signal parameters.
braindecode/​models/​summary.csv Adds BBL model metadata.
braindecode/​models/​brainomni.py Replaces private SEANet implementations with shared classes.
braindecode/​models/​bbl.py Implements the BBL encoder and prediction head.
braindecode/​models/​__init__.py Adds BBL to model imports.

Review effort: Balanced

Comment thread braindecode/models/bbl.py Resolved
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.
Copilot AI balanced review requested due to automatic review settings November 8, 2026 12:49

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 replacement head fails to preserve eval mode, violating the registered-model contract, and the input documentation omits preprocessing needed to match checkpoint training data.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Replacement head remains in training mode after eval

braindecode/​models/​bbl.py:215

Replacing the head after model.eval() leaves the new nn.Linear in training mode because .to() does not preserve the parent’s mode. This fails the registered-model contract in test/unit_tests/models/test_model_contract.py:580–602, which requires every submodule to remain in eval mode after reset_head. Apply .train(self.training) to the replacement, as BrainOmni.reset_head does in braindecode/models/brainomni.py:504.

Low severity Document required input preprocessing and scaling

braindecode/​models/​bbl.py:70

The input documentation omits filtering and does not specify how scaling and baseline correction are applied, although #1392 requires filters, normalization and units. Since forward performs none of this preprocessing, users following this description can supply inputs that differ from the checkpoint's training data. Document the pipeline from source 3965a2be: 0.1–125 Hz band-pass and 50/100 Hz notches before resampling, recording-fitted per-channel median/interquartile-range scaling, clipping, and subtraction of each window's first 0.5 s mean, yielding dimensionless inputs.

1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 8, 2026 13:29

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.

🟢 Approval recommended

No active review issues are identified for the BBL integration and shared SEANet refactor.

No open issues 🎉

Review effort: Balanced

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.

🟡 Changes recommended

Out-of-range dataset IDs silently produce an all-zero gate, discarding the sample’s MEG projection and making predictions independent of the recording instead of raising an error.

1 open issue

Review effort: Balanced

Comment thread braindecode/models/bbl.py Outdated
Comment on lines +194 to +197
# Compare with arange instead of F.one_hot, which reads the index range
# on the host.
slots = torch.arange(self.n_datasets, device=x.device)
gate = (dataset_index[:, None] == slots).to(x.dtype)
@codecov

codecov Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.58%. Comparing base (1aea042) to head (9fc5f55).
⚠️ Report is 4 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1553      +/-   ##
==========================================
+ Coverage   91.54%   91.58%   +0.03%     
==========================================
  Files         172      174       +2     
  Lines       22623    22709      +86     
==========================================
+ Hits        20711    20797      +86     
  Misses       1912     1912              
🚀 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.

🟡 Changes recommended

Invalid dataset IDs silently zero the projected MEG signal instead of raising an error, making predictions independent of that input and blocking projector gradients.

2 open issues

Review effort: Balanced

Comment thread braindecode/models/bbl.py
Comment on lines +79 to +81
on the mean-subject fallback. The converted checkpoint is on the
Hugging Face Hub at ``braindecode/bbl-pretrained`` (revision
``5a19a369``)::
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).
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 11:10

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.

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.
Copilot AI balanced review requested due to automatic review settings November 9, 2026 12:30

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 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.
Copilot AI balanced review requested due to automatic review settings November 9, 2026 13: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.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 16: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.

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 2b0e1d6 into braindecode:master Nov 10, 2026
9 checks passed
bruAristimunha added a commit to bruAristimunha/braindecode that referenced this pull request Nov 18, 2026
…f-version 1.2.0

The 1.3.0 release bump (braindecode#875) also rewrote the schema version of the
Citation File Format, which has no 1.3.0; cffconvert rejects it, and the
file validates against 1.2.0.
bruAristimunha added a commit that referenced this pull request Nov 19, 2026
… concept DOI (#1571)

* Prepare the 2.1.0 release: cite the 2.0.0 contributors and the Zenodo concept DOI

* DOC whats_new: PR number for #1571; CITATION.cff: add the message field

* Citation: year and punctuation of the APA entries, one BibTeX entry

- APA in the model card and docs/cite.rst: (2026) after the authors, the
  double period after Schirrmeister gone, [Computer software] in both.
- docs/cite.rst uses the same @software entry as the README and the card
  (publisher instead of howpublished).
- test_citation.py: the BibTeX and APA author lists of the README, the docs
  and the card match CITATION.cff, the file Zenodo reads.

* Citation: @misc entry and the global DOI only

- BibTeX in the README, docs/cite.rst and the model card is the @misc entry
  with howpublished = {Zenodo}: @software breaks too many LaTeX setups.
- APA entries carry no year, which would tie them to one release; the card
  links the concept DOI (all versions), not the Zenodo record, which
  redirects to the latest version.

* test: the model card exports the @misc BibTeX entry

* CITATION: ORCID and affiliation of the 2.0.0 contributors who replied; Fashad Ahmed Siddique

* DOC Preserve Alma Mater Studiorum spelling; format the citation

* docs: link #1553 in the changelog; CITATION.cff back to cff-version 1.2.0

The 1.3.0 release bump (#875) also rewrote the schema version of the
Citation File Format, which has no 1.3.0; cffconvert rejects it, and the
file validates against 1.2.0.

* TEST Verify the citations downloaded from model summaries
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