Repository navigation
Lazy imports: import braindecode in milliseconds, models on first use - #1510
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #1510 +/- ##
==========================================
+ Coverage 91.20% 91.29% +0.08%
==========================================
Files 169 170 +1
Lines 21916 22037 +121
==========================================
+ Hits 19989 20119 +130
+ Misses 1927 1918 -9 🚀 New features to boost your workflow:
|
import braindecode and import braindecode.models no longer import every model module, the estimators, scikit-learn and pandas at import time. Model classes, EEGClassifier/EEGRegressor, the subpackages and models_dict resolve on first access through PEP 562 module __getattr__; names, __all__, the model registry and static types are unchanged. Part of braindecode#1489.
9e702c5 to
ccb6625
Compare
antonsoo
left a comment
There was a problem hiding this comment.
Tested installed wheels from ccb6625425 and parent b74708f8 with Python 3.12, torch 2.7.0+cu128 and MNE 1.13.2.
On recorded PhysioNet S001R04 EEG, two epochs through the string-named ShallowFBCSPNet classifier give identical initial weights, losses, predictions, model parameters and Adam state on CPU and CUDA. Classifiers pickled after epoch one resume exactly in both directions between the wheels, with RNG restored. The 94 exported names and 85 model-registry mappings match; 89 focused tests pass, one skips. Bare-import median over three alternating fresh-process runs is 4.63 seconds on the parent and 2.5 ms on the head.
One reproducibility caveat: seeding Python before the first classifier access now advances its RNG during deferred dependency imports:
import random
import braindecode
random.seed(1510)
Classifier = braindecode.EEGClassifier
print(random.random())Parent: 0.39848940425239276; head: 0.47082970579932293. Profiling traces this to rich/style.py calling getrandbits(24) on import. Importing EEGClassifier before seeding preserves the parent control. Python-random-based augmentation after this point can therefore change, although the tested Torch/NumPy training and restored continuations agree.
This is a scoped compatibility/performance check, not a full-suite or model-accuracy claim.
Summary
Part of #1489.
import braindecodeimported every model module, the estimators, scikit-learn and pandas, and built the model registry. That took about 3 s before anything was used.Names now resolve on first access, through PEP 562 module
__getattr__. What users can import, and how, is unchanged.Changes
braindecode/__init__.py:EEGClassifier,EEGRegressorand the subpackages resolve lazily;import braindecode; braindecode.datasetsstill works for every subpackage;dir()lists them.braindecode/models/__init__.py:if TYPE_CHECKING:import block is the one list of public names: type checkers read it, so IDEs and mypy keep precise types and misspelled names stay mypy errors, and at runtime it is read back (ast) into the lazy name → submodule map and__all__;__all__is unchanged;braindecode/models/util.py:models_dictis filled on first access and published at once, so a concurrent reader sees 0 or all models;summary.csvis read on first use and kept as a module global;braindecode/util.py: one import is moved off the import path.braindecode/models/config.py: drops theif not models_dict: _init_models_dict()refill, which can no longer run (importingmodels_dictfills the registry)..github/PULL_REQUEST_TEMPLATE/add_new_model.md: a new model needs one import line, in theTYPE_CHECKINGblock.test/unit_tests/test_lazy_imports.py(new):import braindecodeloads, and thatimport braindecode.modelsloads nobraindecode.models.*submodule;__all__resolves;models_dicthas the same keys and classes;whats_newentry under Enhancements.Defaults
Same public names,
__all__,models_dictcontents and order, and pickles, which are byte-identical. Only the import timing changes.Inherent to PEP 562:
vars(braindecode.models)andbraindecode.models.__dict__list a model only after its first access.dir(),inspect.getmembers,from braindecode.models import *andmodels_dictare complete, and a fresh-process probe shows them identical to eager upstreammaster.import braindecode.modelsreads its own source once to build the name map, so an install without.pyfiles would fail there (assummary.csvalready must sit next to the code).Evidence
import braindecodeimport braindecode.modelsfrom braindecode.models import EEGNetimport braindecode; braindecode.EEGClassifiermaster, and before the name map was read back from theTYPE_CHECKINGblock. That read-back adds about 2.5 ms toimport braindecode.models(another node, 15 alternating fresh-process rounds: median 20.8 → 23.4 ms);import braindecodeandfrom braindecode.models import EEGNetare unchanged within noise.EEGNetimport is torch itself, about 0.9 s. skorch imports scikit-learn, soEEGClassifierstays near 2.7 s.Tests
Branch tip
ccb6625425d9(treebf9671c8415d) on upstreammasterb74708f, after the earlier PRs of the series merged with exactly their verified trees. This tree is byte-identical to the one verified inbdw3-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 inbdw3-stack-docs-1after a fix to the check script):pytest test/ -n 8from the repository root at this tip: 6,406 passed, 375 skipped, 2 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.