Skip to content

Check the ch_mask contract on every registered model that takes it - #1548

Merged
bruAristimunha merged 4 commits into
braindecode:masterfrom
bruAristimunha:chmask-auto-contract
Nov 5, 2026
Merged

bruAristimunha merged 4 commits into
braindecode:masterfrom
bruAristimunha:chmask-auto-contract

Conversation

@bruAristimunha

Copy link
Copy Markdown
Collaborator

Follow-up to #1545. The ch_mask contract is now checked the way the other cross-model contracts in test_model_contract.py are: over models_mandatory_parameters, so a new model is covered without editing a test file.

test_registered_model_ch_mask_contract (test/unit_tests/models/test_model_contract.py)

  • Selects itself: a model whose forward takes no ch_mask is skipped.
  • Builds the model with _build_case. Two recordings with C - 1 and C real channels are padded to C with NaN. Recording i alone is x[i, :n_i], run through the same model without ch_mask.
  • Passes if (a) every batched output leaf of each recording equals its output alone (assert_close defaults), the input gradient on padded entries is exactly zero, and any tokens from return_features are zero on padded channels; or (b) forward raises a ValueError that names ch_mask.
  • The only per-model data is _CH_MASK_EXTRAS, for an input a model needs to run on fewer channels. Today it has one entry, PopulationTransformer coords. An entry returns a per-sample tensor (zero-padded in the batch) or a value the whole batch shares, e.g. Labram's ch_names in REVE, Labram: accept ch_mask #1539.

test_registered_model_ch_mask_training (test/unit_tests/training/test_ch_mask_training.py)

  • Selected the same way, for classifiers. One cross-entropy step on the padded batch must give the gradients of the per-recording losses. A fit through EEGClassifier with pad_channels_collate (train and valid iterators) must predict on the mixed set what it predicts on each recording alone.
  • PopulationTransformer is a strict xfail: the loader does not route its per-recording coords.
  • test_every_ch_mask_model_has_a_case and the _CASES parametrization are removed. The refusal test and the routing tests in test_util.py stay. test_ch_mask.py and its _CASES are unchanged.

Outcomes at the registry configurations

model contract training
BrainBERT, Brant, EpiNT, MVPFormer pass (a) pass
PopulationTransformer pass (a), with coords xfail (strict)
BaRISTA (pooling="learned"), DIVER1 (pooling="flatten") refuse (b) refuse (b)

The mean-pooling paths of BaRISTA and DIVER1 are still covered by test_ch_mask.py.

Stacked locally on the open ch_mask PRs (not pushed): BIOT (#1542) and LUNA (#1543) pass (a). CBraMod (#1544) and REVE (#1539) refuse at their registry defaults. Labram (#1539) needs "Labram": ("ch_names", lambda i, n: LABRAM_CHANNEL_ORDER[:n]) in _CH_MASK_EXTRAS and a training xfail, because the loader does not route ch_names. With those two lines it passes.

Copilot AI balanced review requested due to automatic review settings November 5, 2026 15:47

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 unrestricted xfail can hide gradient mismatches and unrelated runtime errors; restoring raises=ValueError would limit expected failures to the known missing-coords exception.

1 open issue
What changed in this PR

This follow-up to #1545 moves ch_mask checks to the model registry, automatically covering new models alongside the existing cross-model contracts.

Changes:

  • Adds registry-wide checks for padded-batch output equivalence, zero padding gradients, zero padded tokens, and explicit mask refusal.
  • Migrates training checks from hand-maintained cases to registered classifiers, retaining a strict PopulationTransformer xfail.
  • Updates the changelog to describe the expanded coverage.
File Description
test/​unit_tests/​training/​test_ch_mask_training.py Uses registry-driven gradient and fit/predict checks.
test/​unit_tests/​models/​test_model_contract.py Adds shared padded-batch helpers and the registry-wide mask contract test.
docs/​whats_new.rst Documents automatic mask-contract coverage.

Review effort: Balanced

[
pytest.param(
*case,
marks=[pytest.mark.xfail(reason=_FIT_XFAIL[case[0]], strict=True)]
@codecov

codecov Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.38%. Comparing base (619e703) to head (992aad8).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1548   +/-   ##
=======================================
  Coverage   91.38%   91.38%           
=======================================
  Files         170      170           
  Lines       22137    22137           
=======================================
+ Hits        20229    20231    +2     
+ Misses       1908     1906    -2     
🚀 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 5, 2026 16:11

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 broadened xfail accepts any exception and now covers gradient comparisons, allowing PopulationTransformer gradient regressions to pass CI as expected failures.

2 open issues

Review effort: Balanced

[
pytest.param(
*case,
marks=[pytest.mark.xfail(reason=_FIT_XFAIL[case[0]], strict=True)]
@bruAristimunha
bruAristimunha merged commit 55c928a into braindecode:master Nov 5, 2026
10 checks passed
bruAristimunha added a commit to bruAristimunha/braindecode that referenced this pull request Nov 9, 2026
bruAristimunha added a commit to bruAristimunha/braindecode that referenced this pull request Nov 9, 2026
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.
bruAristimunha added a commit to bruAristimunha/braindecode that referenced this pull request Nov 9, 2026
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.
bruAristimunha added a commit that referenced this pull request Nov 10, 2026
* refactor: share SEANet blocks in braindecode.modules

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).

* refactor: share SEANet blocks in braindecode.modules

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).

* feat: add BBL, the MEG encoder of The Brain's Bitter Lesson

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).

* refactor: let BrainOmni's RoPE attention take its cache length

_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).

* feat: add MEG-XL (MEGXL)

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).

* test: MEG-XL sensor typing, orientation and token count

* fix: BBL review follow-ups

* fix: MEG-XL review follow-ups

- 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.

* docs: mark MEG-XL Hub upload as pending

* fix: preserve MEG-XL batched geometry gradients

* fix: pad BBL input from the configured n_chans

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.

* docs: document BBL checkpoint preprocessing

* fix: gate BBL dataset slots without a host sync

* test: declare MEGXL in the pretrained geometry contract

* docs: point BBL to the braindecode/bbl-pretrained Hub weights

* docs: point MEGXL to the braindecode/megxl-pretrained Hub weights

* test: declare BBL in the pretrained geometry contract

* feat: BBL accepts ch_mask; shape comments in forward

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).

* feat: MEGXL refuses ch_mask by name; shape comments in forward

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, #1548). Every tensor line of tokenize/encode/forward/_fourier_features carries its shape; no other code change.

* docs: annotate the MEGXL orientation feature shapes

* feat: checkpoint BBL raw-time masking and temporal feature interface

* feat: MEGXL exposes masked-code temporal encoding

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.
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