Repository navigation
Add STEEGFormer model (#1040) - #1042
Conversation
This file defines the STEEGFormer class, a work-in-progress implementation based on Yang et al. (2025), which outlines the model's architecture and parameters.
The %(...)s substitution is an MNE-Python convention; braindecode does not register it, so the token would render literally. Shared signal parameters are inherited automatically from EEGModuleMixin.
Rewrite the reference to full APA (all authors, full title, venue) and fix the year/label: the paper is Yang et al., ICLR 2026, not 2025. The in-text citation label is updated to match ([Yang2026]).
Adds the Enhancements bullet for braindecode.models.STEEGFormer so the check-whats-new CI check passes.
Add the private _PatchEmbedEEG module: split each EEG channel into non-overlapping temporal patches with an einops rearrange, then linearly project each patch to embed_dim. The (seq, channel) structure is kept in the output so temporal and channel positional embeddings can be added before the tokens are flattened.
Add _TemporalPositionalEncoding (fixed sinusoidal encoding over temporal patches, position 0 reserved for the CLS token) and _ChannelPositionalEmbed (learned per-channel embedding, zero-initialised). Both return broadcastable shapes so they can be added to the (batch, seq, channel, embed_dim) patch tokens.
Add _ResidualAdd and _TransformerEncoderBlock, a pre-norm ViT block reusing braindecode's MultiHeadAttention and FeedForwardBlock (same layout as EEGConformer). Not wired into the model yet.
Assemble the full model in __init__/forward: patch tokens + temporal/channel positional embeddings and a CLS token, the Transformer encoder, and an avg/cls-pooled linear head. Default hyperparameters follow the small variant (embed_dim=512, depth=8, num_heads=8). Validate global_pool and require an even embed_dim for the sinusoidal temporal encoding.
Export STEEGFormer from braindecode.models (__init__ + __all__), add it to the summary table and the mandatory-parameters test matrix, and fix the docstring categorization badges to the official ones (Attention/Transformer, Foundation Model). Rename drop_rate to drop_prob and add an activation parameter to match braindecode's model API conventions. Exempt STEEGFormer from the TorchScript test (einops.rearrange is not scriptable), like the other transformer/foundation models.
# Conflicts: # braindecode/models/summary.csv # docs/whats_new.rst
Make STEEGFormer reproduce the reference implementation and load the official ST-EEGFormer checkpoints (verified to numerical equivalence, max abs diff 3e-5, on the small and largeV2 weights). - load_state_dict: convert the official timm checkpoint (unwrap the ``model`` dict, drop the MAE decoder / pos_embed / fc_norm / head, remap block names, split the fused attn.qkv into queries/keys/values). - Faithful architecture: shared montage-vocabulary channel embedding, LayerNorm eps=1e-6, no final norm in average pooling. - Resolve chan_pos_idx from chs_info electrode names (BENDR/LaBraM convention) with identity fallback; add STEEGFORMER_CHANNEL_ORDER and the n_chans_pos / chan_pos_idx parameters. - Add reset_head for from_pretrained, the architecture figure, a variant table, and an enriched docstring. - Update summary.csv parameter count.
Without this entry the per-model page (with its schema figure) was never generated, leaving a dead link from the models table. CI stayed green because Sphinx does not fail on a model missing from the autosummary.
The model port is proven faithful, so the user-facing docstring should not ship a 'work in progress (draft)' note. Keep the technical note (numerical equivalence + channel-vocabulary mapping) and document forward's input.
|
hi @bruAristimunha ! |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 131158e7e6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
Pull request overview
Integrates the STEEGFormer (ViT-MAE) EEG foundation model into braindecode.models, wiring it into the public API and updating docs/testing metadata so it appears alongside existing model implementations.
Changes:
- Added new
STEEGFormermodel implementation, including checkpoint remapping logic for the upstream (timm/MAE) format. - Registered the model in the package exports, API docs, model summary CSV, and model test utilities.
- Excluded
STEEGFormerfrom TorchScript integration tests due toeinops.rearrangescripting limitations.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
braindecode/models/steegformer.py |
Adds the STEEGFormer model implementation and upstream checkpoint remapping logic. |
braindecode/models/__init__.py |
Exposes STEEGFormer in the models public API. |
braindecode/models/util.py |
Adds STEEGFormer to the test model initialization parameter registry. |
braindecode/models/summary.csv |
Adds the STEEGFormer entry to the model summary table. |
docs/api.rst |
Lists STEEGFormer in the generated API docs. |
docs/whats_new.rst |
Notes the addition of STEEGFormer in the changelog. |
test/unit_tests/models/test_integration.py |
Skips TorchScript coverage for STEEGFormer. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
The two chatgpt-codex-connector CI suggestions were incorrect vs the upstream reference; implementing them broke parity with the released checkpoints. Revert them while keeping the PatchTokenizer reuse: - Temporal patch positions back to 1..seq (CLS reserved at 0). The 0..seq-1 variant drifted encoder features ~16% from the released weights; restored to pre-encoder bit-exact, post-encoder rel-err 4.6e-6 vs the upstream encoder. - Average read-out applies no final LayerNorm (the reference fc_norm is commented out upstream); the cls read-out keeps the norm. Restore STEEGFORMER_CHANNEL_ORDER name mapping (chs_info -> vocab slot, vocab regenerated from the upstream channels_mapping, 142/142 exact) and the load_state_dict timm->braindecode remapper, so official MAE checkpoints load directly (0 unexpected keys) and the published braindecode/STEEGFormer-* repos stay consistent with the model.
- Move the 142-entry STEEGFORMER_CHANNEL_ORDER out of the module into a shipped steegformer_channels.json (loaded once at import, no network). The order is the authors' arbitrary channels_mapping and is not derivable from a montage. - Drop the load_state_dict timm->braindecode remapper. The re-hosted braindecode/STEEGFormer-* repos are already braindecode-format, so from_pretrained needs no conversion; the one-off converter is archived as convert_checkpoint.py in each Hub repo. - Keep exact-name chs_info resolution: MNE positional matching is coordinate- frame-fragile (same-name electrodes mismatch across frames) and name aliasing would collapse the vocab's deliberately-distinct T3/T7 (and T5/P7, T6/P8) slots.
The Hub repos archive convert_steegformer_checkpoints.py (all variants + hub-repo map); point the docstring at it instead of the duplicate name.
Like REVE's position bank, download steegformer_channels.json from the Hub (braindecode/STEEGFormer-small) on first use and cache it, instead of shipping it in the wheel. STEEGFORMER_CHANNEL_ORDER is now a lazy module attribute (PEP 562), so importing the module triggers no network call; the vocabulary is fetched only when a chs_info montage needs name-based slot resolution, with a graceful identity fallback + warning if it cannot be fetched. Drops the package_data file plus its MANIFEST.in / setup.cfg entries.
forward(return_features=True) returned PRE-norm tokens, so cls_token did not match the feature the "cls" head consumes (off by one LayerNorm vs the upstream ViT cls readout / MAE encoder output). Apply self.norm before exposing the tokens, matching the braindecode convention (e.g. LaBraM normalises the tokens it returns) and the reference. cls_token now equals the upstream cls feature (relerr 1.2e-6); the classification logits path is unchanged.
Code-review (max) hardening; classification parity unchanged (logits relerr 2.8e-7 vs upstream): - Explicit chan_pos_idx now survives the Hub/config round-trip. It was a numpy/tensor value the config layer drops, silently reverting a pretrained checkpoint to the identity channel mapping. The resolved slots are stored as a JSON-able list; auto-resolved (chs_info/identity) mappings stay None so chs_info re-resolves per montage on reload. - Warn on the silent identity fallback when no chs_info is given (the docstring promised a warning); a missing ch_name now falls back gracefully. - reset_head() re-applies the constructor's trunc_normal_ head init (was default kaiming-uniform, an init asymmetry vs construction). - forward() raises a clear channel-count error instead of an opaque broadcast failure; guard the chan_pos_idx range check against empty tensors. - Add the upstream head dropout (no-op at the default drop_prob=0). - STEEGFORMER_CHANNEL_ORDER returns a copy (was the cached mutable list). - mlp_ratio rejects bool (bool is an int subclass that slipped past the guard).
…kenizer state - STEEGFormer from-scratch init now matches the upstream MAE: xavier_uniform_ for Linear weights (was trunc_normal_) and normal_(std=0.02) for the CLS token, so random-init training reproduces the reference. Loaded-checkpoint parity is unaffected (init is overwritten on load). - PatchTokenizer: remove the orphaned self.padding_layer (forward pads/crops via _prepare_input at runtime, never read it) and the unused self.n_patches. Verified no consumer reads either across braindecode/ and test/ (the padding_layer hits in fbcnet/fbmsnet/ifnet/eegpt are each model's own attribute; eegpt.n_patches is EEGPT's own property).
- chs_info name resolution now applies only to the published 145-slot vocabulary (small/base/large). For other n_chans_pos (e.g. largeV2's 256-slot HBN vocabulary, whose electrode names are not published) it warns and falls back to identity instead of silently mapping names through the wrong vocabulary; pass chan_pos_idx explicitly there. - Clarify PatchTokenizer docstring: padding/cropping is applied at forward time to the actual input length, not the construction-time n_times. - Example: show STEEGFormer.from_pretrained with n_outputs and chs_info. - Update the outdated "BENDR requires n_outputs" test comment to include STEEGFormer.
…o warning The new identity-fallback warning is intended for real users loading pretrained weights without a montage; the tests construct without chs_info, so pass an explicit chan_pos_idx (identity) to keep them quiet and represent deliberate montage selection.
|
Thank you @adammounir 🙏 |
Context
Towards #1040 — integrating the model of the EEG 2025 competition winners,
STEEGFormer (Yang et al., 2025).
cc @bruAristimunha