Skip to content

on_non_divisible='pad' by default for every patch-based model - #1399

Merged
bruAristimunha merged 14 commits into
braindecode:masterfrom
bruAristimunha:fix/flex-pad-default
Oct 14, 2026
Merged

bruAristimunha merged 14 commits into
braindecode:masterfrom
bruAristimunha:fix/flex-pad-default

Conversation

@bruAristimunha

Copy link
Copy Markdown
Collaborator

Every patch-based model now takes on_non_divisible={"pad", "crop", "error"} with the default "pad", like CBraMod and LaBraM already do. A window that isn't a multiple of patch_size is right-padded with zeros instead of being cropped or rejected.

model before now (default)
STEEGFormer, Brant, BaRISTA, SleepFM, SleepFMStager always cropped pad ("crop" = old behaviour)
NeuroRVQ, NeuroRVQTokenizer, DuIN, CSBrain ValueError pad ("error" = old behaviour)
REVE (overlapping patches) dropped the tail without warning pad until patches tile ("crop" = old behaviour)
  • One shared helper in braindecode/modules computes the patch count (rounded up for pad, down for crop). Position tables, flatten heads and the max_patches checks all use it.
  • Configs and checkpoints saved before this option existed have no on_non_divisible key. They still rebuild with "crop" in the models that cropped, through both from_config and from_pretrained, so saved fine-tunes load unchanged.
  • DuIN still requires patch_size % prod(strides) == 0, because that one comes from the architecture.

Tests (Voyager CPU Jobs)

  • New test/unit_tests/models/test_on_non_divisible.py. It checks every mode per model and that a config without the key loads the old model.
  • Touched-model suites: 279 + 302 passed, covering forward, TorchScript, export, compile, config and Hugging Face loading.
  • Parity against e1fe4ca5, with each model built in a separate process on both trees: windows that patches divide evenly give bit-identical state dicts and outputs with the new default, and the old crop models give identical results under "crop" (21/21).
  • Legacy loading: 117 passed.

…ble pad/crop/error

EinopsError dividing 480 by 200 blocked 236 matrix cells. Use shared PatchTokenizer like CBraMod (default pad, zero-pad at forward), head counts padded patches. Divisible inputs bit-identical.
…tches

_patch_count gives ceil (pad) / floor (crop) / exact-or-raise (error) patch counts, also for overlapping patches (step < patch_size); _pad_or_crop_to_patches right zero-pads or crops the time axis so patches tile it and returns a tiled input untouched. PatchTokenizer.n_patches uses the same count.
…test

_n_patch uses modules.blocks._patch_count, so on_non_divisible='crop' with a window shorter than one patch raises at construction instead of building a zero-width head. The construction-geometry test asked for the old 'multiple of patch_size' error; it now expects it only with on_non_divisible='error'.
The patch tokenizer was built with on_non_divisible='crop'. It is now a constructor argument, default 'pad' (right zero-pad the last patch); 'crop' keeps the reference behaviour, 'error' rejects the window. The temporal encoding counts the patches the tokenizer returns. Windows that are a multiple of patch_size give the same model and output as before.
seq_len (the learned temporal position table) and the patch tokenizer use the same count: ceil(n_times / patch_size) for 'pad', floor for 'crop' (the reference), exact for 'error'. A window shorter than one patch now builds under 'pad' (one padded patch). Windows that are a multiple of patch_size give the same model and output as before.
n_patches (and with it the learned token pooling, n_tokens) and the patch tokenizer use the same count: ceil(n_times / patch_size) for 'pad', floor for 'crop' (the reference, trailing samples dropped), exact for 'error'. The 'at least one full patch' check now only applies to 'crop'. Windows that are a multiple of patch_size give the same model and output as before.
…d-coded crop

The tokenizer's max_seq_length guard, the channel/temporal masks and the stager's chunking all count patches with the tokenizer's own count (PatchTokenizer.n_patches): ceil(n_times / patch_size) for 'pad', floor for 'crop' (the reference), exact for 'error'. A window shorter than one patch now builds under 'pad'. Windows that are a multiple of patch_size give the same model and output as before.
…f a divisibility error

n_times no longer has to be a multiple of patch_size: patching goes through PatchTokenizer (a pure reshape, no parameters, same state dict), which right zero-pads the last patch by default; 'crop' drops the tail, 'error' keeps the former ValueError. num_patches, the temporal embedding indices, the flatten head and the max_patches guard use the padded count. Windows that are a multiple of patch_size give the same model and output as before.
The window is padded/cropped/rejected by PatchTokenizer.prepare_input before the spatial projection; n_patches (temporal table, flatten head) uses the same count. The architectural check that patch_size is a multiple of prod(strides) stays. Windows that are a multiple of patch_size give the same model and output as before.
The window is right zero-padded so the overlapping patches (step patch_size - patch_overlap) tile it: (n_times - patch_size) % step == 0, and a window shorter than one patch gives one padded patch. 'crop' is the former unfold behaviour (tail dropped), 'error' raises. _get_flattened_output_dim uses the same count, construction warns when padding. patch_overlap >= patch_size (non-positive step) now raises at construction. Tiled windows give the same model and output as before; note that the default patch_size=200/patch_overlap=20 does not tile n_times=1000 (5 patches before, 6 now).
Per model (STEEGFormer, Brant, BaRISTA, SleepFM, SleepFMStager, NeuroRVQ, NeuroRVQTokenizer, DuIN, CSBrain, REVE overlapping): a divisible window gives a bit-identical state dict and output in pad/crop/error; 'pad' equals the same weights on the zero-padded window (state dict loads strictly into a model built at the padded length), also for windows shorter than one patch; 'crop' equals the same weights on the cropped window; 'error' raises; the mode round-trips through get_config/from_config.
…s that cropped

from_config and from_pretrained fill on_non_divisible='crop' when the saved
config has no such key, for STEEGFormer, Brant, BaRISTA, SleepFM,
SleepFMStager and REVE, so fine-tunes saved with a non-divisible n_times load
with the same head and position-table shapes. New models still default to pad.
Copilot AI balanced review requested due to automatic review settings October 14, 2026 10:36

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 reached their quota limit.

Copilot AI balanced review requested due to automatic review settings October 14, 2026 10:37

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 reached their quota limit.

@bruAristimunha
bruAristimunha merged commit 25aa682 into braindecode:master Oct 14, 2026
2 checks passed
bruAristimunha added a commit to bruAristimunha/braindecode that referenced this pull request Oct 14, 2026
@codecov

codecov Bot commented Oct 14, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.92308% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.10%. Comparing base (d0d6d95) to head (d1132a8).
⚠️ Report is 6 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff            @@
##           master    #1399    +/-   ##
========================================
  Coverage   90.10%   90.10%            
========================================
  Files         166      167     +1     
  Lines       21475    21740   +265     
========================================
+ Hits        19350    19589   +239     
- Misses       2125     2151    +26     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

bruAristimunha added a commit that referenced this pull request Oct 14, 2026
…1400)

* Add resolve_channel_positions: place a montage in a name -> position bank

One rule per channel, first match wins: montage-qualified bank name
(montage="biosemi128" -> biosemi128_A1), exact name, normalised name
(case, EEG prefix, -REF/-LE/-AR, legacy T3-T6 and MNE's location
aliases), the channel's loc, the midpoint of a bipolar A-B pair, then
on_missing ("error" with difflib suggestions that are never applied,
"drop", or "nearest" to snap positioned channels to a bank entry).
Returns the positions, the kept indices and per-channel provenance
(rule, bank name, distance). A position is never invented.

raw.set_montage gives loc in the head frame while REVE's bank holds the
montage files' own frames (46-57 mm apart for standard_1005), so loc is
registered onto the bank (trimmed similarity fit on the channels named
in both, else MNE's standard_1005 template). A named channel whose
registered loc lies more than 30 mm from its bank entry is a name
collision (BioSemi-128 A1/A2/C1-C6 against REVE's 10-20 entries) and
keeps its loc, with a warning.

Tests run offline on a copy of REVE's released bank.

* REVE: place chs_info with resolve_channel_positions (montage, on_missing)

REVE(montage=None, on_missing="error") resolves its default positions
with the shared rule: exact bank names give the same default_pos and
outputs as before (bank rows round-trip float32 -> float64 -> float32),
channels outside the bank are placed from their loc or as bipolar
midpoints instead of raising, and model.channel_provenance records the
rule per channel. on_missing="drop" leaves channels out; forward then
reads only the kept input channels when it gets no pos (TorchScript
keeps working). The pos= forward override is unchanged.

Fixes BioSemi-128 A1/A2 (and C1-C6) landing on the bank's 10-20 sites of
the same names: their loc is used with a warning, and
montage="biosemi128" reads the bank's biosemi128_* entries.
RevePositionBank.forward raises for an unknown name instead of returning
fewer rows than channels.

* whats_new: PR number (#1400)

* tests: REVE resolver window tiles the overlapping patches (no pad warning after #1399)

* channels: narrow both bipolar ends for mypy

* ponytail: resolve_channel_positions in one function (no registration, no provenance, no 2.7k-line bank fixture)
bruAristimunha added a commit that referenced this pull request Oct 14, 2026
…); trim #1399 (#1407)

* ponytail: trim #1399 (patch helpers, on_non_divisible tests, changelog)

* ponytail: one REVE padding warning

* Legacy on_non_divisible fill only for an __init__ that takes it

A subclass with its own signature (neuraltrain's STEEGFormerEncoderCompatible)
got on_non_divisible='crop' injected by from_pretrained and raised TypeError:
1,163 NeuralBench matrix cells (all four STEEGFormer configs) on master.

* whats_new: subclasses note
bruAristimunha added a commit that referenced this pull request Nov 2, 2026
…when untiled) (#1517)

#1399 switched REVE from cropping (torch unfold, the reference and braindecode 1.8.1) to zero-padding a window its overlapping patches do not tile. Code built for 1.8.1 got one more patch per channel, a different encoder output and head size: neuraltrain test_reve.py fails 5 tests (2 -> 3 patches for n_times=100, patch 50, overlap 10). Unset now means crop, with a FutureWarning on untiled windows; "pad" stays available.

Co-authored-by: bd2-downstream <bd2-downstream@local>
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