Skip to content

Opt-in coalesced reads for overlapping lazy FIF windows - #1511

Merged
bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-9-coalesced-reads
Oct 31, 2026
Merged

bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-9-coalesced-reads

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Part of #1489.

With overlapping windows, for example 4 s windows every 1 s, a DataLoader batch of consecutive windows from one lazy FIF recording reads most samples several times. BaseConcatDataset(..., coalesce_reads=True) reads such a batch as one bounded union of samples and cuts the windows out of it. The option is off by default.

Changes

  • benchmarks/acceleration/bench_coalesced_reads.py: the standalone benchmark behind the numbers below. It imports only braindecode, so this PR does not depend on the benchmark-tooling PR.
  • braindecode/datasets/base.py:
    • new keyword-only BaseConcatDataset(..., coalesce_reads=False); non-bool values are rejected;
    • when it is on, __getitems__ coalesces a batch only if (one check, _get_coalesced_items):
      • its indices are consecutive and all fall in one non-subclassed lazy-FIF EEGWindowsDataset;
      • the union [min start, max stop) of its crops is at most a third of the summed window samples, and at most 2 MiB;
    • every other batch takes the unchanged batch-prefetch path, including shuffled, adjacent, sparse or cross-recording batches, preloaded data, epochs, Zarr and WindowsDataset;
    • both paths share one window tail (_finish_window: float32 copy, transform, targets, channel mask), which __getitem__ now also calls, so they cannot drift apart; default outputs are byte-identical to upstream;
    • with False, outputs are unchanged;
    • pickles from before this change load with coalesce_reads=False.
  • whats_new entry under Enhancements.

Defaults

The default stays off, so nothing changes without coalesce_reads=True. With it on, samples, targets, crop indices, order and RNG use are equal to the default path.

Evidence

  • Setup: synthetic 22-channel, 250 Hz FIF; 4 s windows every 1 s (512 windows), batches of 32; 4 CPUs, Intel Xeon Gold 6230R; five paired fresh processes.
  • Median epoch time, default → coalesced:
DataLoader workers Overlapping windows
0 133.6 ms → 27.8 ms
2 132.2 ms → 66.7 ms
4 80.6 ms → 63.2 ms (one pair of five within its epoch-to-epoch spread)
  • With 2 workers, adjacent windows (median paired ratio 1.050) and batches spanning two recordings (1.042) were slower than the default. Both ratios are above their measured baseline-vs-baseline variation. So the option stays off by default.

Tests

  • test/unit_tests/datasets/test_coalesced_reads.py (new) covers:
    • an on/off equality matrix over lazy, preloaded, epochs and Zarr data, overlapping, adjacent and cross-recording batches, and DataLoader workers 0/2/4;
    • order, RNG, mutation and targets;
    • 11 ineligible batches, each built from an otherwise coalesced layout so that its own rule is the only reason it falls back (unordered, cross-recording, sequence, single, empty, preloaded, Zarr, subclass, byte budget, ratio, duplicates);
    • that the default never enters the candidate code, and flag validation.

Some variable-length batches with gaps now coalesce where the previous version of this PR did not; outputs are identical (the equality matrix covers variable and unsorted layouts), and none of the measured cells changes eligibility, but their speed is unmeasured.

Branch tip b51530f34999 (tree 6b541a30bf71) on upstream master ec07f32, after the earlier PRs of the series merged with exactly their verified trees. This tree is byte-identical to the one verified in bdw3-stack-verify-4-20261031t211836z-371a1219 (default suite, pre-commit, slow tier, CI collection and docs all passed). Every check ran in one Voyager CPU Job, bdw3-stack-verify-3-20261031t201512z-cca0e0cc (its docs step was re-run in bdw3-stack-docs-1 after a fix to the check script):

  • Environment: Python 3.12.15, torch 2.14.1+cpu, skorch 1.4.0, MNE 1.13.2, NumPy 2.5.4, MOABB 1.5.0 with real BNCI2014_001 fixtures; Intel Xeon Gold 6230R.
  • pytest test/ -n 8 from the repository root at this tip: 6,493 passed, 375 skipped, 2 xfailed, 0 failed. Upstream master under the same settings: 5,995 passed, 375 skipped, 1 xfailed.
  • pre-commit run --files <files changed by this PR>, with the repository's pinned hooks (Ruff, mypy, docstrfmt, blacken-docs, codespell, sphinx-lint): passed.
  • GitHub CI runs separately on the pushed head.

Open review point

The whats_new entry and the coalesce_reads docstring list the cells that failed the acceleration gate: 4 workers on overlapping windows; adjacent windows and cross-recording batches with 2 workers. Whether to keep that wording for the adjacent-window cell is still open, and it is left unchanged here.

@codecov

codecov Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.31%. Comparing base (0b39464) to head (b51530f).
⚠️ Report is 6 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1511      +/-   ##
==========================================
+ Coverage   91.20%   91.31%   +0.10%     
==========================================
  Files         169      170       +1     
  Lines       21916    22075     +159     
==========================================
+ Hits        19989    20158     +169     
+ Misses       1927     1917      -10     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

Tested the coalesced-read commit 2384f93b against stack parent 6b3dd995, with execution on final head 5dc4a91a. On recorded PhysioNet S001R04 converted to lazy FIF, a 16-window overlapping batch takes one reader call instead of 16. All 504 exported sample/target arrays match the parent byte-for-byte; unaugmented samples also match the standard MNE reader. Cases include cropped/reordered channels, variable window lengths and channel targets. Double-precision FIF, projections, preloaded data and adjacent windows retain the fallback behavior.

In-place stochastic augmentation preserves data and NumPy/Python/CPU-Torch RNG state with 0/2 DataLoader workers. Two Adam updates of ShallowFBCSPNet on each of CPU/CUDA give identical losses, model/optimizer/gradient hashes and next NumPy/Python/CPU-Torch RNG state with the option on/off and on the parent. Environment: torch 2.7.0+cu128, MNE 1.13.2, RTX 5070. The added test file passes 95 tests with 9 optional Zarr skips.

No additional defect found in these paths. This checks recorded-data/training parity; I did not reproduce timing/RSS claims or review the rest of the stack.

BaseConcatDataset(..., coalesce_reads=False) is keyword-only and off by
default. When enabled, a DataLoader batch of consecutive, overlapping windows
of one lazy FIF recording is read as one bounded union of samples instead of
one read per window; every other batch takes the unchanged default path.
Samples, targets, crop indices, order and RNG use are equal to the default.

Part of braindecode#1489.
@bruAristimunha
bruAristimunha force-pushed the pr/1489-9-coalesced-reads branch from 5dc4a91 to b51530f Compare October 31, 2026 23:25
@bruAristimunha
bruAristimunha marked this pull request as ready for review October 31, 2026 23:25
Copilot AI balanced review requested due to automatic review settings October 31, 2026 23:25

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 insufficient remaining quota. Try requesting a review at a lower effort level.

@bruAristimunha
bruAristimunha merged commit 605dfeb into braindecode:master Oct 31, 2026
10 checks passed
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.

3 participants