Skip to content

Route pad_channels_collate batches by forward signature; test the ch_mask contract in training - #1545

Merged
bruAristimunha merged 2 commits into
braindecode:masterfrom
bruAristimunha:chmask-train-contract
Nov 5, 2026
Merged

bruAristimunha merged 2 commits into
braindecode:masterfrom
bruAristimunha:chmask-train-contract

Conversation

@bruAristimunha

Copy link
Copy Markdown
Collaborator

Bug

ThrowAwayIndexLoader turned every batch from pad_channels_collate / set_return_ch_pos into {"x": X, "pos": ..., "ch_mask": ...}, and skorch calls module_(**x). Training failed with a TypeError when:

  • the signal argument is not named x (REVE.forward(eeg, pos), LUNA.forward(X, ...));
  • return_ch_pos=True is used with a model that does not take pos;
  • ch_mask reaches a model without it (e.g. ShallowFBCSPNet, or SleepFM, whose channel_mask uses the opposite polarity).

Fix

The loader reads the module's forward signature once per iteration:

  • the signal goes to the first parameter;
  • pos and ch_mask are passed only under those names, and only to a forward that takes them (or takes **kwargs);
  • anything else raises a ValueError, e.g. ShallowFBCSPNet.forward takes no ch_mask: this model needs a constant channel count; do not use pad_channels_collate.

It adds no name mapping to coords, channel_locations, spatial_indices or chan_metadata, because those mean different things.

Tests

test/unit_tests/training/test_ch_mask_training.py is parametrised over _CASES from test_ch_mask.py, so new cases are covered automatically:

  • Fit + predict. EEGClassifier is fit with pad_channels_collate on two recordings with n_chans - 1 and n_chans channels. A forward spy checks the per-sample real-channel counts in ch_mask. predict_proba on the mixed set must equal predict_proba of each recording alone. Cases with a pos input get their positions through set_return_ch_pos.
    • PopulationTransformer, BaRISTA and DIVER1 are xfail(strict=True, raises=ValueError): they need per-recording coords / spatial_indices / chan_metadata, which the loader does not route.
  • Gradients. With the model in eval mode, one loss on the NaN-padded batch gives the same parameter gradients as the mean of the per-recording losses computed alone.
  • Guard. Every class in braindecode.models whose forward takes ch_mask must appear in _CASES or _FIXED_HEADS.
  • Refusal. ShallowFBCSPNet fit with pad_channels_collate raises the routing ValueError.
  • Routing units in test_util.py: the signal goes under eeg and X, **kwargs accepts everything, and both error messages are checked.

test_ch_mask.py moves its batch building into _padded_batch / _padded_case / _assert_matches_alone. These are the same helpers, under the same names, as in #1539, so that PR merges without a conflict there.

Verification (Voyager CPU Job, torch 2.14.1, skorch 1.4.0)

  • On this branch, the new tests plus test_ch_mask.py, test_util.py, test_eegneuralnet.py and test/unit_tests/training give 498 passed, 3 xfailed, 1 skipped (CUDA).
  • plot_heterogeneous_montage_training.py runs.
  • pre-commit run --files <changed> passes.
  • On master, only the refusal test fails, as expected: master raises a TypeError.
  • Each open ch_mask PR, merged locally with this branch, passes the new training tests (--run-network for REVE):

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

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 adapter inspects the channel-strategy wrapper instead of the backbone’s forward signature, causing extended batches with non-native channel strategies to raise KeyError when resolving the signal argument.

1 open issue
What changed in this PR

This PR routes extended dataset batches by model forward signatures, supporting different signal argument names and clearer errors for unsupported channel metadata.

Changes:

  • Route signals by parameter name and validate support for pos and ch_mask.
  • Add training, prediction, gradient, and routing tests for padded-channel batches.
  • Share channel-mask test helpers and document the changes.
File Description
test/​unit_tests/​training/​test_ch_mask_training.py Adds training integration, gradient equivalence, coverage, and refusal tests.
test/​unit_tests/​test_util.py Tests signature-based routing and unsupported-input errors.
test/​unit_tests/​models/​test_ch_mask.py Extracts reusable padded-batch and comparison helpers.
docs/​whats_new.rst Documents routing fixes and channel-mask test coverage.
braindecode/​util.py Adds signature inspection and extended-batch keyword routing.

Review effort: Balanced

Comment thread braindecode/util.py
Comment on lines +425 to +426
if self._forward_params is None:
self._forward_params = inspect.signature(module.forward).parameters
@bruAristimunha
bruAristimunha merged commit 619e703 into braindecode:master Nov 5, 2026
9 checks passed
@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 (0d9cd36) to head (15ef709).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1545   +/-   ##
=======================================
  Coverage   91.37%   91.38%           
=======================================
  Files         170      170           
  Lines       22123    22137   +14     
=======================================
+ Hits        20214    20229   +15     
+ Misses       1909     1908    -1     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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