Skip to content

Batches with varying channel counts (ch_mask) for the iEEG foundation models - #1487

Merged
bruAristimunha merged 14 commits into
masterfrom
feat/brainbert-ch-mask
Oct 25, 2026
Merged

bruAristimunha merged 14 commits into
masterfrom
feat/brainbert-ch-mask

Conversation

@julien-gadonneix

@julien-gadonneix julien-gadonneix commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Recordings with different numbers of channels can now share a batch: once padded (e.g. by pad_channels_collate), forward takes a ch_mask of shape (batch, n_chans), True for real channels, and each recording gives the output it would give alone. This covers BrainBERT, EpiNT, Brant, PopT, BaRISTA, DIVER1 and MVPFormer. Without ch_mask, outputs are unchanged.

Changes

  • Shared helpers in braindecode.functional (check_ch_mask, pack_channels, unpack_channels, masked_mean, masked_group_norm), each taking ch_mask=None, so models have one code path.
  • Channels encoded on their own are dropped before encoding (BrainBERT, EpiNT, Brant, MVPFormer); padded channels are masked in cross-channel attention (Brant, PopT, BaRISTA, DIVER1, MVPFormer) and left out of the pooling.
  • Heads tied to the construction-time channels (BaRISTA learned, DIVER1 flatten, MVPFormer concat) refuse a ch_mask.
  • With ch_mask, DIVER1 requires per-sample chan_metadata; BaRISTA takes per-sample spatial_indices; PopT's ch_mask replaces key_padding_mask (not released yet).

Testing

  • test_ch_mask.py: for every model, each recording of a NaN-padded batch matches its output alone, eager and scripted, with zero gradient on padding.
  • Model suites pass, including TorchScript and export; outputs without ch_mask are bit-identical to master.
  • Regression tests for ch_mask and the helpers
  • docs/whats_new.rst

Notes for reviewers

DuIN is not included: its first layer mixes channels with a dense layer tied to channel positions.

BrainBERT encodes each channel independently, so recordings with different
numbers of channels can share a batch once padded to a common count.

- forward takes an optional ch_mask of shape (batch, n_chans), True for real
  channels, the convention of pad_channels_collate (routed by the training
  loop as ch_mask=). Padded channels are zeroed and left out of the mean over
  channels, so each sample gives the output it would give alone.
- The runtime channel count may differ from the construction n_chans; the
  strict check is dropped and the fixed-size split_channels layer replaced by
  a reshape.
- New _check_ch_mask helper in braindecode.models.util validates the mask
  (shape, and in eager mode at least one real channel per sample), for reuse
  by the other models.

Without ch_mask the outputs are unchanged.
@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.15%. Comparing base (19fa784) to head (e47a8bd).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1487      +/-   ##
==========================================
+ Coverage   91.09%   91.15%   +0.06%     
==========================================
  Files         167      168       +1     
  Lines       21706    21822     +116     
==========================================
+ Hits        19773    19892     +119     
+ Misses       1933     1930       -3     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Channels never attend to each other, so with ch_mask the padded channels are
removed before the spectrogram instead of being encoded and masked out of the
mean. Same outputs, no compute spent on padding (1.7-1.8x faster at 57% real
channels with the released configuration), and no zeroing of the input needed.
Add check_ch_mask (moved from braindecode.models.util), pack_channels,
unpack_channels and masked_mean in braindecode.functional.channel_mask.
Each takes ch_mask=None for a batch without padding, so a model has one
code path for both; they support TorchScript, which einops functions do not.

BrainBERT uses them: pack_channels drops the padded channels before the
spectrogram, unpack_channels and masked_mean pool over the real channels.
Without ch_mask the output is bit-identical to before.
The six other iEEG foundation models take a ch_mask, built on the shared
helpers of braindecode.functional.channel_mask:

- EpiNT and Brant drop the padded channels before their per-channel stages
  (pack_channels / unpack_channels), and MVPFormer before its patch
  embedding; Brant masks them in its spatial attention.
- PopT, BaRISTA and DIVER1 mask the padded channels in attention (PopT's
  ch_mask replaces key_padding_mask, unreleased); DIVER1 computes its
  patch-CNN GroupNorm statistics over the real channels with masked_mean.
- Every model pools with masked_mean; heads tied to the construction-time
  channels (BaRISTA learned, DIVER1 flatten, MVPFormer concat) refuse a mask.
- DIVER1 takes per-sample chan_metadata, BaRISTA per-sample spatial_indices.

test_ch_mask.py checks, for every model, that each recording of a padded
batch gives the output it gives alone, eager and scripted. Without ch_mask
the outputs are bit-identical to before.
@julien-gadonneix julien-gadonneix changed the title BrainBERT: accept batches with varying channel counts (ch_mask) Batches with varying channel counts (ch_mask) for the iEEG foundation models Oct 21, 2026
@julien-gadonneix

Copy link
Copy Markdown
Collaborator Author

Small sanity benchmark: 16 recordings with 4–32 real channels, padded to 32 (57% real). The padded batch with ch_mask is compared with running each recording alone. Setup: CPU (Xeon Platinum 8488C, 16 threads), torch 2.14.1, eval mode, default configurations, best of 7 runs.

Model One at a time Padded + ch_mask Speed-up Padded, no mask Rel. error ch_mask Rel. error no mask
BrainBERT 33 ms 15 ms 2.1x 23 ms 5.4e-07 6.5e-01
EpiNT 183 ms 91 ms 2.0x 178 ms 6.8e-07 1.6e+00
Brant 50 ms 39 ms 1.3x 23 ms 1.9e-06 1.0e+00
PopulationTransformer 41 ms 21 ms 1.9x 17 ms 9.4e-07 9.8e-01
BaRISTA 106 ms 113 ms 0.9x 106 ms 2.5e-07 6.8e-01
DIVER1 193 ms 55 ms 3.5x 51 ms 4.6e-07 6.4e-01
MVPFormer 79 ms 13 ms 5.9x 21 ms 2.8e-07 1.5e+00
  • Correctness: with ch_mask, each recording matches its unpadded output (relative error ≤ 2e-6). Without the mask, padding changes the outputs by 64–160%.
  • Speed: batching mixed montages is 1.3–5.9x faster than one recording at a time, except BaRISTA (0.9x). Dropping padded channels before encoding makes BrainBERT, EpiNT and MVPFormer faster than plain padding.
  • Brant: its masked path is slower than plain padding. The masked spatial attention takes PyTorch's nested-tensor fast path, which is about 2x slower here. With it off (enable_nested_tensor=False), the masked path runs as fast as the unmasked one (23 vs 24 ms) with the same outputs. PopT uses the same encoder and is barely affected (22 vs 19 ms).
Script
"""Sanity benchmark: padded batch + ch_mask vs. one recording at a time."""
import time, warnings
import mne, numpy as np, torch
warnings.filterwarnings("ignore")
from braindecode.models import DIVER1, BaRISTA, BrainBERT, Brant, EpiNT, MVPFormer, PopulationTransformer
from braindecode.models.diver1 import channel_metadata_from_chs_info

torch.set_num_threads(16)
BATCH, MAX_CH = 16, 32
rng = np.random.default_rng(0)
n_real = rng.integers(4, MAX_CH + 1, BATCH)
n_real[0] = MAX_CH

def seeg_chs(n, seed):
    r = np.random.default_rng(seed)
    info = mne.create_info([f"E{i}" for i in range(n)], 500.0, "seeg")
    for ch in info["chs"]:
        ch["loc"][:3] = r.uniform(-0.05, 0.05, 3)
    return info["chs"]

g = lambda i: torch.Generator().manual_seed(int(i))
EXTRAS = {  # per-recording inputs: (name, builder, alone call needs a batch axis)
    "PopulationTransformer": ("coords", lambda i, c: torch.randint(0, 200, (c, 3), generator=g(i)), True),
    "BaRISTA": ("spatial_indices", lambda i, c: torch.randint(0, 121, (c,), generator=g(i)), False),
    "DIVER1": ("chan_metadata", lambda i, c: channel_metadata_from_chs_info(seeg_chs(c, i)), False),
}
MODELS = {
    "BrainBERT": (lambda: BrainBERT(n_chans=MAX_CH, n_outputs=2, n_times=2048), 2048),
    "EpiNT": (lambda: EpiNT(n_chans=MAX_CH, n_outputs=2, n_times=3072), 3072),
    "Brant": (lambda: Brant(n_chans=MAX_CH, n_outputs=2, n_times=2500), 2500),
    "PopulationTransformer": (lambda: PopulationTransformer(n_chans=MAX_CH, n_outputs=2, n_times=768), 768),
    "BaRISTA": (lambda: BaRISTA(n_chans=MAX_CH, n_outputs=2, n_times=2048, spatial_scale="parcels", pooling="mean"), 2048),
    "DIVER1": (lambda: DIVER1(chs_info=seeg_chs(MAX_CH, 99), n_outputs=2, n_times=1000, pooling="mean"), 1000),
    "MVPFormer": (lambda: MVPFormer(n_chans=MAX_CH, n_outputs=2, n_times=5120), 5120),
}

def best_of(fn, reps=7):
    fn()  # warm-up
    times = []
    for _ in range(reps):
        t = time.perf_counter(); out = fn(); times.append(time.perf_counter() - t)
    return min(times), out

print(f"{BATCH} recordings, {int(n_real.sum())} real channels of {BATCH * MAX_CH} ({n_real.sum() / (BATCH * MAX_CH):.0%})")
print("| Model | One at a time | Padded + `ch_mask` | Speed-up | Padded, no mask | Rel. error `ch_mask` | Rel. error no mask |")
print("|---|---|---|---|---|---|---|")
for name, (make, n_times) in MODELS.items():
    torch.manual_seed(0)
    model = make().eval()
    xs = [torch.randn(int(c), n_times) for c in n_real]
    x = torch.zeros(BATCH, MAX_CH, n_times)
    mask = torch.arange(MAX_CH)[None] < torch.as_tensor(n_real)[:, None]
    for i, xi in enumerate(xs):
        x[i, : len(xi)] = xi
    batch_kw, alone_kw = {}, [{} for _ in xs]
    if name in EXTRAS:
        key, build, batched = EXTRAS[name]
        values = [build(i, int(c)) for i, c in enumerate(n_real)]
        padded = torch.zeros((BATCH, MAX_CH) + values[0].shape[1:], dtype=values[0].dtype)
        for i, v in enumerate(values):
            padded[i, : len(v)] = v
        batch_kw = {key: padded}
        alone_kw = [{key: v[None] if batched else v} for v in values]
    with torch.no_grad():
        t_loop, ref = best_of(lambda: torch.cat([model(xi[None], **kw) for xi, kw in zip(xs, alone_kw)]))
        t_mask, out = best_of(lambda: model(x, ch_mask=mask, **batch_kw))
        t_naive, naive = best_of(lambda: model(x, **batch_kw))
    scale = ref.abs().max()
    rel = lambda o: f"{((o - ref).abs().max() / scale).item():.1e}"
    print(f"| {name} | {1e3 * t_loop:.0f} ms | {1e3 * t_mask:.0f} ms | {t_loop / t_mask:.1f}x | {1e3 * t_naive:.0f} ms | {rel(out)} | {rel(naive)} |", flush=True)

Add masked_group_norm to braindecode.functional.channel_mask: group norm
whose statistics only count the entries a mask flags; mask=None is
torch.nn.functional.group_norm. DIVER1's patch CNN uses it in a single
loop over its layers instead of its private _masked_group_norm. Without
ch_mask the outputs are bit-identical to before.
@bruAristimunha

Copy link
Copy Markdown
Collaborator

Integrated the three reviewed corrections: low-precision masked means accumulate in FP32; masked group normalization sanitizes excluded values before differentiable arithmetic; BaRISTA rejects mismatched per-sample metadata batch sizes.

Fresh Voyager CPU integration validation at 8a97ac56: 90 passed, 2 skipped for masks/helpers, plus 74 passed in affected shared/foundation-model selections. The only subsequent change in current head 2590b675 is DIVER1 documentation: parity assumes dropout-disabled execution, and explicit metadata currently prevents torch.export (eager and TorchScript remain supported). No accelerator validation is claimed.

Landing still requires current-head CI and combined verification with #1488 so EpiNT normalizes the full window before truncating patches while excluding padded channels. The combined-source test is running separately; this comment does not claim that gate has passed.

@bruAristimunha
bruAristimunha merged commit 5ce1688 into master Oct 25, 2026
10 checks passed
@bruAristimunha bruAristimunha mentioned this pull request Nov 5, 2026
2 tasks done
@bruAristimunha
bruAristimunha deleted the feat/brainbert-ch-mask branch November 22, 2026 23:01
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