Skip to content

Opt-in compile in EEGClassifier/EEGRegressor keeps canonical checkpoint keys and Parameter identity - #1506

Merged
bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-4-estimator-compile
Oct 31, 2026
Merged

bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-4-estimator-compile

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Part of #1489.

skorch's compile=True wraps the module in torch.compile(module), which saves state dicts with _orig_mod.-prefixed keys. For braindecode estimators, these checkpoints no longer load into an eager model.

EEGClassifier and EEGRegressor now compile in place with nn.Module.compile. The module and the state dict keep their names, and caller-supplied modules keep their Parameter objects.

Changes

  • _EEGNeuralNet.torch_compile uses native in-place Module.compile(**compile__*) for the module and the criterion.
  • Ownership is tracked per estimator in _compile_ownership_, which records only the compiled call the estimator installed (its identity is enough: Module.compile binds it to that module):
    • turning compile off, or compile__disable=True, clears only the compiled call that this estimator installed;
    • a module the user compiled independently is never replaced or cleared;
    • modules and criteria that share Parameters keep sharing them, and the optimizer sees the caller's Parameters.
  • __getstate__ drops the ownership record. Pickle, joblib and deepcopy give an eager estimator, as native Module serialization already does. The next explicit initialize() compiles again.
  • TORCHDYNAMO_DISABLE=1 is honoured: the estimator runs eagerly.
  • Docs:
    • "Opt-in compilation and checkpoint migration" section in the cropped inference guide, which explains how to migrate older _orig_mod. wrapper checkpoints;
    • whats_new entry under API changes.

Defaults

compile=False remains the default, and nothing changes without compile=True. With compile=True:

  • checkpoints use canonical keys;
  • legacy _orig_mod. keys are not rewritten automatically on load;
  • warm start and partial_fit after unpickling run eagerly until initialize() is called.

Evidence

Correctness, CPU (torch 2.14.1+cpu, skorch 1.4.0, Python 3.12)

  • Real models IFNet, ShallowFBCSPNet, EEGNet and EEGConformer, compiled with Inductor vs eager, in FP32 with Dropout disabled, at rtol 2e-4 / atol 2e-5.
  • Final maximum probability error: 5.96e-8, 2.38e-7, 2.98e-8 and 5.96e-8.
  • Resume from save_params/load_params with SGD momentum, warm start, partial_fit, parameter gradients, and compiled chunked trial inference all hold within the same tolerance.

Time per epoch, compiled ÷ eager (median of 5 paired fresh processes)

Model CPU¹ A100²
IFNet 0.908 0.790
EEGNet 0.767 0.751
EEGConformer 0.728 0.594
ShallowFBCSPNet 1.255 0.859

¹ Xeon Gold 6230R, 4 threads, FP32; synthetic 8 × 512 inputs, batch 16.
² A100-PCIE-40GB, torch 2.14.1+cu130, FP32 with TF32 off.

  • First-use compilation costs 24–44 s on CPU and 16–51 s on A100.
  • On these small fixtures, compilation pays off after about 2,800–15,000 epochs. ShallowFBCSPNet on CPU never pays off, because its compiled epoch is slower.
  • So compilation stays opt-in.
  • With torch 2.6 on CPU, Inductor cannot compile EEGConformer training with attention dropout (BackendCompilerFailed; it already happens on upstream master). It works on torch >= 2.7, with dropout 0, in eval mode and with aot_eager. The parity and timing cells above ran on torch 2.14.1.

Tests

  • test/unit_tests/test_compile_estimator.py is new and covers:
    • key names, ownership toggles, shared criterion Parameters, user-compiled modules, global disable, pickle/deepcopy and clone;
    • Inductor parity, resume and warm start, which are marked slow.
  • Eager-backend tests of the same ownership logic stay in the default tier.

Branch tip 8a99ac8ef35d (tree 2ce524053d21) on upstream master 50d6d59, i.e. after #1504 and #1505. The tree is byte-identical to the verified tip bcb361ce08c1, which sat on a78824d plus the then-open #1504 and #1505; both merged with those same trees. The default suite was re-run on this tree in bdw3-stack-verify-4-20261031t211836z-371a1219 (6,317 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,317 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

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

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1506      +/-   ##
==========================================
+ Coverage   91.20%   91.28%   +0.07%     
==========================================
  Files         169      170       +1     
  Lines       21916    22042     +126     
==========================================
+ Hits        19989    20120     +131     
+ Misses       1927     1922       -5     
🚀 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 30f278e7 against its stack parent 49a003c0 on recorded PhysioNet S001R04 EEG with PyTorch 2.7.0+cu128, skorch 1.4.0, CPU and RTX 5070. This reviews the compile commit only.

With native Inductor execution confirmed, EEGClassifier/EEGNet and EEGRegressor/ShallowFBCSPNet now save canonical keys and load strictly into eager estimators. The parent emits _orig_mod. keys and rejects those eager loads in all four cases. After restoring parameters, SGD momentum, criterion and history, two further updates agree with uninterrupted compiled training. Four-update model/optimizer/gradient/prediction comparisons against eager references pass rtol=3e-4, atol=5e-5; the largest absolute difference on this head is 4.0e-5. The added test file also passes all 15 cases with --run-slow.

ShallowFBCSPNet pickle/deepcopy resume eagerly and preserve the continuation. EEGNet pickle and estimator deepcopy still raise PyTorch's parametrized-module serialization error in both eager and compiled modes; save_params works. I would qualify the whole-estimator serialization paragraph with this existing native limitation. One parent CPU regression-gradient comparison exceeded the stated tolerance; I am not claiming parent parity or a general numerical improvement here. No new compile defect found, and no speed or full-stack approval claim.

With compile=True the estimators compile modules in place
(nn.Module.compile), so state dicts keep canonical keys (no `_orig_mod.`)
and caller-supplied Parameters keep their identity. Default (compile=False)
unchanged.

Part of braindecode#1489.
@bruAristimunha
bruAristimunha force-pushed the pr/1489-4-estimator-compile branch from 30f278e to 8a99ac8 Compare October 31, 2026 21:45
@bruAristimunha
bruAristimunha marked this pull request as ready for review October 31, 2026 21:45
Copilot AI balanced review requested due to automatic review settings October 31, 2026 21:45

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 e92940d 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