Repository navigation
Batches with varying channel counts (ch_mask) for the iEEG foundation models - #1487
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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:
|
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.
|
Small sanity benchmark: 16 recordings with 4–32 real channels, padded to 32 (57% real). The padded batch with
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.
|
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 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. |
# Conflicts: # braindecode/models/epint.py
Summary
Recordings with different numbers of channels can now share a batch: once padded (e.g. by
pad_channels_collate),forwardtakes ach_maskof shape(batch, n_chans),Truefor real channels, and each recording gives the output it would give alone. This covers BrainBERT, EpiNT, Brant, PopT, BaRISTA, DIVER1 and MVPFormer. Withoutch_mask, outputs are unchanged.Changes
braindecode.functional(check_ch_mask,pack_channels,unpack_channels,masked_mean,masked_group_norm), each takingch_mask=None, so models have one code path.learned, DIVER1flatten, MVPFormerconcat) refuse ach_mask.ch_mask, DIVER1 requires per-samplechan_metadata; BaRISTA takes per-samplespatial_indices; PopT'sch_maskreplaceskey_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.ch_maskare bit-identical to master.ch_maskand the helpersdocs/whats_new.rstNotes for reviewers
DuIN is not included: its first layer mixes channels with a dense layer tied to channel positions.