Skip to content

Bounded chronological cropped trial inference (iter_trial_predictions, chunks) and RNG restore in PostEpochTrainScoring - #1505

Merged
bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-3-trial-inference
Oct 31, 2026
Merged

bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-3-trial-inference

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Part of #1489.

Cropped inference can now consume predictions one trial at a time, or one bounded chunk of a trial at a time, instead of materializing every trial first. predict_trials reconstructs through the same streaming code, and its return values do not change.

Changes

  • New public API in braindecode.training, implemented in braindecode.training.scoring with the private helper _trial_aggregation.py:
    • iter_trial_predictions(module, dataset, return_targets=True, batch_size=1, num_workers=0, *, loader_kwargs=None) yields one float32 trial prediction, or a (prediction, target) pair, at a time.
    • iter_trial_prediction_chunks(module, dataset, *, windows_per_chunk, ...) yields TrialPredictionChunk(trial_index, prediction_start, prediction, target):
      • each chunk covers at most windows_per_chunk source windows and never crosses a trial;
      • overlap removal is carried across chunk boundaries;
      • concatenating the chunks of a trial reproduces the per-trial output byte for byte.
    • Both functions are served by one generator: per-trial iteration is the chunk pipeline with no window limit.
  • EEGClassifier/EEGRegressor: predict_trials takes an optional keyword-only loader_kwargs. The estimators get no iterator methods: iter_trial_predictions(net.module_, X) and iter_trial_prediction_chunks(net.module_, X, ...) serve fitted estimators.
  • Loader controls: loader_kwargs accepts only order-preserving DataLoader settings: batch_size, num_workers, pin_memory, persistent_workers, prefetch_factor, worker_init_fn and generator. Shuffling, samplers, drop_last and custom collation are rejected, because reconstruction depends on chronological order.
  • Lifecycle:
    • the iterators run under no_grad and set the model to eval mode;
    • they restore each submodule's original mode on exhaustion, on close() and on errors, also when cleanup itself fails;
    • they shut down persistent workers;
    • completed trials are released: no retained itertools.tee history.
  • predict_trials now reconstructs through the streaming implementation before materializing its return value. Output order, overlap removal, float32 conversion and its historical leave-in-eval behaviour are unchanged. The single-window warning is now raised at exhaustion, after inference, instead of before the first forward.
  • Fix: PostEpochTrainScoring restores the saved CPU Torch RNG state even when its reevaluation raises.
  • Fix in this PR's own chunk API, found in review: with time targets wider than the predictions (the normal cropped case, where the model output is shorter than its window), every trial with more than one chunk raised a bare AssertionError. The chunk generator now takes one target per prediction chunk, as documented. test_chunk_time_targets_wider_than_predictions covers it.
  • Docs:
    • new user guide page docs/user_guide/cropped_inference.rst, covering lifecycle, target and offset semantics, loader controls, memory bounds and early close;
    • api.rst entries;
    • whats_new entries.

Defaults

No default output changes. Existing calls to predict_trials, the estimators and the scoring callbacks return the same values. The new arguments are keyword-only and default to the previous behaviour.

Evidence

All on CPU, torch 2.14.1+cpu, Python 3.12.

Exactness

  • 24 byte-parity cells against the pre-change source: 120 unequal trials, with time, scalar, vector and no targets, per trial and with chunk sizes 1/2/3/7/100.
  • Shape, dtype and raw bytes are identical, including NaN, signed zero, infinities, repeated or decreasing stops and window targets that differ within a trial.
  • After the review refactor (one generator), the new code was compared with the previous version of this PR in fresh processes over 222 cases (predict_trials, both iterators with chunk sizes 1/2/3/7/100, scalar, vector, time and no targets, batches 1/3/16, NaN/inf/−0.0, unequal trials, the single-window warning). Digests (dtype, shape, bytes, record fields, warnings) are identical wherever the previous version returns; the only mismatches are the 48 cells where it raised the AssertionError above. In all 90 chunk configurations, concatenated chunks equal the previous per-trial output byte for byte.

The memory and latency numbers below were measured on the previous version of this PR (tip 25320199), before the review refactor. A quick re-check of the refactor on the same CPU (400 trials of 1 to 40 windows, batch 64, medians of new/previous time) gave 0.97–1.02 per trial and 0.89 for chunks of 32 with scalar targets; it is informational, not re-measured at the scale below.

Long trials (iter_trial_prediction_chunks vs materializing the trial)

  • Setup: 1 dedicated CPU, 1 thread; synthetic lazy 250 Hz trials, 8 outputs; windows of 1024 samples with stride 512; 32 windows per chunk, batch 16.
  • Five alternating fresh-process pairs per duration. Medians:
Trial Peak RSS, materialized → chunked Latency, materialized → chunked
1 h (1,757 windows) 613 MB → 387 MB (0.632) 0.117 s → 0.089 s (0.760)
4 h (7,031 windows) 1,306 MB → 387 MB (0.297) 0.488 s → 0.361 s (0.739)
  • All 10 pairs favour chunks on both measures.
  • Chunked peak RSS stays at about 387 MB from 1 h to 4 h.

Iterator vs predict_trials when outputs are discarded

  • Setup: one CPU node, 2 physical cores, 1 thread; 12 configurations × 5 runs.
  • Fixed-length trials: 17.6% (batch 16) and 21.7% (batch 64) less full-consumption time.
  • Variable-length trials, batch 64: 13.6% more time, with lower process peak RSS.

Tests

  • test/unit_tests/training/test_trial_aggregation.py, test_trial_chunks.py and test_streaming_lifecycle.py are new.
  • test_post_epoch_train_scoring_rng.py is new.
  • test_scoring.py and test_eegneuralnet.py are extended.
  • The lifecycle tests (bounded consumption, mode restore, worker shutdown, cleanup despite close errors) run on both the per-trial and the chunk API.

Branch tip cda03b812e1f (tree 8559fffe6bcb) on upstream master 0b39464, i.e. after #1504. The tree is byte-identical to the tip 6e60148beb17 that was verified on a78824d plus the then-open #1504; #1504 merged with that same tree. 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,307 passed, 375 skipped, 1 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.

@codecov

codecov Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.40120% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 91.25%. Comparing base (0b39464) to head (cda03b8).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1505      +/-   ##
==========================================
+ Coverage   91.20%   91.25%   +0.05%     
==========================================
  Files         169      170       +1     
  Lines       21916    22025     +109     
==========================================
+ Hits        19989    20100     +111     
+ Misses       1927     1925       -2     
🚀 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.

Scoped runtime check of 49a003c0 against its stack parent 81270cff, using torch 2.7.0+cu128 on an RTX 5070, Python 3.12, deterministic algorithms and TF32 off.

Used recorded PhysioNet S001R04 EEG: 15 trials, 20 channels at 256 Hz, unequal trial lengths, 60 overlapping 512-sample windows. Trained dense ShallowFBCSPNet for three Adam updates first. Parent/head predict_trials predictions and scalar/vector/time targets are byte-identical and match independent chronological placement of the window outputs.

On head, chunk sizes 1/2/7 with 0/2 workers preserve those values and offsets. Persistent-worker cleanup, early close of both public iterators, mixed child modes and caller gradients pass. Model state, Adam state and existing parameter gradients stay identical through inference.

Also exercised the actual PostEpochTrainScoring on these EEG data with a target-extraction exception, then continued from the same model/Adam state. Parent changes the next random training order and resulting update; head restores the CPU RNG and matches the no-error control's order, loss, model and Adam hashes exactly. The four exception regressions fail on the import-pinned parent and pass on head.

Selected scoring/aggregation/chunk/lifecycle/RNG tests: 332 passed. No additional finding in these paths. I did not run the full suite or memory/speed benchmarks, and make no decoding-accuracy claim.

Add braindecode.training.iter_trial_predictions,
iter_trial_prediction_chunks and TrialPredictionChunk, and explicit
loader_kwargs for predict_trials on EEGClassifier/EEGRegressor in cropped
mode. predict_trials reconstructs through the same streaming code;
its outputs are unchanged. PostEpochTrainScoring restores the saved CPU
Torch RNG state when its reevaluation raises. Adds the cropped inference
user guide page.

Part of braindecode#1489.
@bruAristimunha
bruAristimunha force-pushed the pr/1489-3-trial-inference branch from 49a003c to cda03b8 Compare October 31, 2026 21:20
@bruAristimunha
bruAristimunha marked this pull request as ready for review October 31, 2026 21:20
Copilot AI balanced review requested due to automatic review settings October 31, 2026 21:20

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 50d6d59 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