Skip to content

Opt-in activation checkpointing for EEGConformer - #1507

Merged
bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-5-conformer-checkpointing
Oct 31, 2026
Merged

bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-5-conformer-checkpointing

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Part of #1489.

EEGConformer(..., activation_checkpointing=True) recomputes the transformer blocks during backward instead of storing their activations. It trades extra step time for training memory, so it is off by default.

Changes

  • braindecode/models/eegconformer.py: new keyword-only argument activation_checkpointing=False.
    • What is recomputed: in eager, grad-enabled training, each pure transformer block runs through torch.utils.checkpoint.checkpoint(..., use_reentrant=False, preserve_rng_state=True), so dropout draws are reproduced. The BatchNorm stem is never recomputed.
    • What is checked: before every checkpointed forward, the model checks that no module inside the transformer has buffers or hooks, and that no global module hooks are set; recomputation would run those side effects twice. Otherwise it raises a clear error. There is no list of allowed module types, so any pure activation passed through activation_transfor (for example nn.Tanh) can be checkpointed.
    • What is rejected: scripting, tracing, export and compilation with checkpointing enabled, through model.compile(), torch.compile(model) or EEGClassifier(compile=True), raise activation_checkpointing requires eager execution. They do not silently fall back. compile(disable=True) keeps working.
    • How torch.compile(model) is caught: the eager-only boundary carries Dynamo's forbidden marker (_dynamo_forbidden = True, the attribute torch._dynamo.forbid_in_graph sets), set once in the class body. Dynamo checks it before tracing any call, so it fails instead of falling back to eager, for every route: construction, later flag changes, unpickling and deepcopy. There are no __setattr__/__setstate__ hooks and no runtime registration, and import braindecode and models never import torch._dynamo; a fresh-process test checks the import, and a unit test checks Dynamo's own is_forbidden on the boundary, so a rename in torch fails a test rather than a user.
    • What does not change: eval and no_grad forwards run the usual code. Parameter names, buffers and state-dict keys are unchanged. Pickled models from before this change still load: the class-level default is False.
  • test_integration.py: the activation-class test no longer treats activation_checkpointing as an activation constructor.
  • whats_new entry under Enhancements.

Defaults

Nothing changes with the default activation_checkpointing=False. A byte-parity probe against the pre-change source shows identical initialized state, outputs, input and parameter gradients, SGD update, buffers and RNG.

Evidence

Exactness, checkpointing on vs off (torch 2.14.1+cpu)

  • Identical outputs, loss, input gradients, all parameter gradients, the state after one SGD step, buffers, and the RNG state after forward and after backward (torch.equal).
  • Covered in FP32 and FP64, with dropout, with return_features on and off, and at the measured shape [8, 22, 8192].

Memory and time

  • Setup: Xeon Gold 6230R, 4 threads, FP32; EEGConformer with embedding 64, 8 heads, depth 6 and dropout; input [8, 22, 8192]; five alternating fresh-process pairs.
Off On On/off (median paired ratio)
Peak process RSS 2,188.7 MiB 976.3 MiB 0.446 (−55.4%, all 5 pairs)
Train step 2.096 s 3.652 s 1.731 (+73.1%)
  • Capacity: under a 4 GiB peak-RSS budget, the largest passing batch went from 17 to 68 (fresh process per batch size).

Tests

  • test/unit_tests/models/test_eegconformer_checkpointing.py is new and covers:
    • the exactness matrix above;
    • unsafe-boundary rejections (module hooks of each kind, buffers, a BatchNorm swapped into a block);
    • a non-default activation (nn.Tanh): outputs and gradients equal with checkpointing on and off;
    • estimator, native and wrapper compile rejection: 42 configurations, in-process (nothing is registered at runtime, so a missing route cannot be hidden by an earlier test);
    • is_forbidden on the checkpoint boundary;
    • scripting and export with the default;
    • legacy pickle loading.
  • The test's pickle round-trips (models it builds itself) and its fresh-interpreter run (a constant script under sys.executable) carry per-line # nosec markers with the reason, as test_compile_estimator.py does in PR 4.

Branch tip 3f0219be9baf (tree a4818c0efb54) on upstream master e92940d, i.e. after #1504, #1505 and #1506. The tree is byte-identical to the verified tip 90e3581996bf, which sat on a78824d plus the then-open #1504 to #1506; all three merged with those same trees. The default suite was re-run on this tree in bdw3-stack-verify-4-20261031t211836z-371a1219 (6,376 passed, 0 failed). 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,376 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 96.77419% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 91.28%. Comparing base (0b39464) to head (3f0219b).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1507      +/-   ##
==========================================
+ Coverage   91.20%   91.28%   +0.08%     
==========================================
  Files         169      170       +1     
  Lines       21916    22072     +156     
==========================================
+ Hits        19989    20149     +160     
+ Misses       1927     1923       -4     
🚀 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 checkpointing commit 3a7132cf against its stack parent 30f278e7, using recorded PhysioNet S001R04 EEG, torch 2.7.0+cu128, MNE 1.13.2 and an RTX 5070.

Eight CPU/CUDA configurations cover classifier/features output, a frozen stem or transformer, FP32, FP16 with GradScaler, and BF16. Three AdamW updates with two accumulated microbatches per update, gradient clipping and a model/optimizer state restore after the first update give identical outputs, losses, input/parameter gradients, model/optimizer/scaler state, BatchNorm buffers and Python/NumPy/CPU-Torch/all-CUDA RNG states. Checkpointing on/off is exact, as is the default against the parent.

For [8, 22, 8192], embedding 64, depth 6 and 8 heads, three alternating fresh-process GPU pairs reduce peak allocated memory from 379.07 to 290.53 MiB in every pair (23.4%). The median paired steady-step time ratio is 1.216, with a noisy 1.16-1.47 range. All four updates in each pair preserve the same outputs, updated model/optimizer and RNG state hashes. This is GPU allocated memory; I did not reproduce the CPU RSS or batch-capacity figures.

The added checkpointing test file passes 59 tests with 1 skip. No additional defect found in this scope. This review covers the checkpointing commit, not the rest of the stack or a dataset accuracy benchmark.

Keyword-only activation_checkpointing=False. When enabled, the pure
transformer blocks are recomputed during backward with non-reentrant,
RNG-preserving checkpointing. Compiled/traced execution with checkpointing
is rejected explicitly. Default unchanged; old pickles load.

Part of braindecode#1489.
@bruAristimunha
bruAristimunha force-pushed the pr/1489-5-conformer-checkpointing branch from 3a7132c to 3f0219b Compare October 31, 2026 22:04
@bruAristimunha
bruAristimunha marked this pull request as ready for review October 31, 2026 22:04
Copilot AI balanced review requested due to automatic review settings October 31, 2026 22:04

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 3e61179 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