Repository navigation
Bounded chronological cropped trial inference (iter_trial_predictions, chunks) and RNG restore in PostEpochTrainScoring - #1505
Conversation
Codecov Report❌ Patch coverage is 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:
|
antonsoo
left a comment
There was a problem hiding this comment.
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.
49a003c to
cda03b8
Compare
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_trialsreconstructs through the same streaming code, and its return values do not change.Changes
braindecode.training, implemented inbraindecode.training.scoringwith 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, ...)yieldsTrialPredictionChunk(trial_index, prediction_start, prediction, target):windows_per_chunksource windows and never crosses a trial;EEGClassifier/EEGRegressor:predict_trialstakes an optional keyword-onlyloader_kwargs. The estimators get no iterator methods:iter_trial_predictions(net.module_, X)anditer_trial_prediction_chunks(net.module_, X, ...)serve fitted estimators.loader_kwargsaccepts only order-preserving DataLoader settings:batch_size,num_workers,pin_memory,persistent_workers,prefetch_factor,worker_init_fnandgenerator. Shuffling, samplers,drop_lastand custom collation are rejected, because reconstruction depends on chronological order.no_gradand set the model to eval mode;close()and on errors, also when cleanup itself fails;itertools.teehistory.predict_trialsnow 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.PostEpochTrainScoringrestores the saved CPU Torch RNG state even when its reevaluation raises.AssertionError. The chunk generator now takes one target per prediction chunk, as documented.test_chunk_time_targets_wider_than_predictionscovers it.docs/user_guide/cropped_inference.rst, covering lifecycle, target and offset semantics, loader controls, memory bounds and early close;api.rstentries;whats_newentries.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
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 theAssertionErrorabove. 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_chunksvs materializing the trial)Iterator vs
predict_trialswhen outputs are discardedTests
test/unit_tests/training/test_trial_aggregation.py,test_trial_chunks.pyandtest_streaming_lifecycle.pyare new.test_post_epoch_train_scoring_rng.pyis new.test_scoring.pyandtest_eegneuralnet.pyare extended.Branch tip
cda03b812e1f(tree8559fffe6bcb) on upstreammaster0b39464, i.e. after #1504. The tree is byte-identical to the tip6e60148beb17that 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 inbdw3-stack-docs-1after a fix to the check script):pytest test/ -n 8from the repository root at this tip: 6,307 passed, 375 skipped, 1 xfailed, 0 failed. Upstreammasterunder 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.