Skip to content

Lazy imports: import braindecode in milliseconds, models on first use - #1510

Merged
bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-8-import-time
Oct 31, 2026
Merged

bruAristimunha merged 1 commit into
braindecode:masterfrom
bruAristimunha:pr/1489-8-import-time

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Part of #1489.

import braindecode imported 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, EEGRegressor and the subpackages resolve lazily;
    • import braindecode; braindecode.datasets still works for every subpackage;
    • dir() lists them.
  • braindecode/models/__init__.py:
    • the 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__;
    • each model module is imported on first access; __all__ is unchanged;
    • the file is 133 lines, shorter than upstream's 197.
  • braindecode/models/util.py:
    • models_dict is filled on first access and published at once, so a concurrent reader sees 0 or all models;
    • summary.csv is read on first use and kept as a module global;
    • scikit-learn and pandas are imported inside the functions that need them.
  • braindecode/util.py: one import is moved off the import path.
  • braindecode/models/config.py: drops the if not models_dict: _init_models_dict() refill, which can no longer run (importing models_dict fills the registry).
  • .github/PULL_REQUEST_TEMPLATE/add_new_model.md: a new model needs one import line, in the TYPE_CHECKING block.
  • test/unit_tests/test_lazy_imports.py (new):
    • fresh-process checks of what import braindecode loads, and that import braindecode.models loads no braindecode.models.* submodule;
    • every name in __all__ resolves;
    • models_dict has the same keys and classes;
    • subpackage attributes.
  • whats_new entry under Enhancements.

Defaults

Same public names, __all__, models_dict contents and order, and pickles, which are byte-identical. Only the import timing changes.

Inherent to PEP 562: vars(braindecode.models) and braindecode.models.__dict__ list a model only after its first access. dir(), inspect.getmembers, from braindecode.models import * and models_dict are complete, and a fresh-process probe shows them identical to eager upstream master. import braindecode.models reads its own source once to build the name map, so an install without .py files would fail there (as summary.csv already must sit next to the code).

Evidence

  • Setup: CPU node, 16 CPUs, torch 2.14.1+cpu; fresh processes, 7 rotated rounds. Median in ms [IQR], before → after:
Statement before after
import braindecode 3,073 [3,037–3,119] 5 [5–5]
import braindecode.models 3,190 [3,072–3,375] 6 [6–6]
from braindecode.models import EEGNet 3,128 [3,055–3,239] 1,592 [1,587–1,634]
import braindecode; braindecode.EEGClassifier 3,085 [3,039–3,136] 2,685 [2,654–2,930]
  • These were measured before this branch was rebased onto the current master, and before the name map was read back from the TYPE_CHECKING block. That read-back adds about 2.5 ms to import braindecode.models (another node, 15 alternating fresh-process rounds: median 20.8 → 23.4 ms); import braindecode and from braindecode.models import EEGNet are unchanged within noise.
  • Most of the remaining EEGNet import is torch itself, about 0.9 s. skorch imports scikit-learn, so EEGClassifier stays near 2.7 s.

Tests

Branch tip ccb6625425d9 (tree bf9671c8415d) on upstream master b74708f, after the earlier PRs of the series merged with exactly their verified trees. This tree is byte-identical to the one verified in bdw3-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 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,406 passed, 375 skipped, 2 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 95.38462% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.29%. Comparing base (0b39464) to head (ccb6625).
⚠️ Report is 6 commits behind head on master.

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:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.
@bruAristimunha
bruAristimunha marked this pull request as ready for review October 31, 2026 23:03
Copilot AI balanced review requested due to automatic review settings October 31, 2026 23:03

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.

@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 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.

@bruAristimunha
bruAristimunha merged commit ec07f32 into braindecode:master Oct 31, 2026
9 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