Repository navigation
Add Du-IN: region-level sEEG speech decoder (Zheng et al., NeurIPS 2024) - #1269
Closed
adammounir wants to merge 2 commits into
Closed
adammounir wants to merge 2 commits into
adammounir wants to merge 2 commits into
Conversation
Port the Du-IN classification model (liulab-repository/Du-IN@c2e289c3, MIT): a linear channel projection, a per-patch Conv1d+BatchNorm tokenizer, fixed sinusoidal time embeddings, a post-norm Transformer with query/key layer norm, and the upstream flatten + MLP head (logits, no sigmoid). load_state_dict accepts the authors' per-subject Du-IN MAE checkpoints; on all 12 released subjects the encoder matches upstream duin_cls within 8.6e-6. Register the model, add its tests and the shared-suite entries.
Contributor
There was a problem hiding this comment.
🟢 Approval recommended
The implementation matches the referenced architecture and includes complete registration, licensing, documentation, and contract coverage.
0 open findings
What changed in this PR
Adds a Braindecode-native Du-IN sEEG speech decoder with upstream checkpoint conversion and standard model contracts.
Changes:
- Implements the Du-IN convolutional Transformer classifier.
- Adds checkpoint loading, geometry validation, feature extraction, and head resetting.
- Registers, documents, licenses, and comprehensively tests the model.
| File | Description |
|---|---|
braindecode/models/duin.py |
Implements Du-IN and upstream weight conversion. |
braindecode/models/__init__.py |
Exports DuIN. |
braindecode/models/util.py |
Registers default model geometry. |
braindecode/models/summary.csv |
Adds model metadata. |
docs/api.rst |
Adds API documentation entry. |
docs/whats_new.rst |
Adds release notes. |
NOTICE.txt |
Records MIT licensing. |
test/unit_tests/models/test_foundation_models.py |
Adds Du-IN-specific tests. |
test/unit_tests/models/test_pretrained_compat.py |
Adds geometry compatibility coverage. |
test/unit_tests/models/test_return_features.py |
Adds feature-return contract coverage. |
🧠 Review effort: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
6 tasks done
bruAristimunha
added a commit
that referenced
this pull request
Oct 13, 2026
* Add Du-IN: region-level sEEG speech decoder (Zheng et al., NeurIPS 2024) Port the Du-IN classification model (liulab-repository/Du-IN@c2e289c3, MIT): a linear channel projection, a per-patch Conv1d+BatchNorm tokenizer, fixed sinusoidal time embeddings, a post-norm Transformer with query/key layer norm, and the upstream flatten + MLP head (logits, no sigmoid). load_state_dict accepts the authors' per-subject Du-IN MAE checkpoints; on all 12 released subjects the encoder matches upstream duin_cls within 8.6e-6. Register the model, add its tests and the shared-suite entries. * DOC whats_new: Du-IN PR number (#1269) * MAINT DuIN: reuse MultiHeadAttention and FeedForwardBlock, drop redundant checks - modules.MultiHeadAttention: optional head_dim and qk_norm (defaults leave every caller unchanged); DuIN's private attention class is gone. - FeedForwardBlock replaces the hand-written FFN Sequential (same keys). - Patch conv blocks are plain Sequential(Conv1d, BatchNorm1d); upstream conversion maps the block/part indices directly. - Fold _init_weights into __init__; encoder is an nn.Sequential. - Drop checks that duplicate a loud downstream error or that the shared helpers already handle (n_chans in forward, list lengths -> zip strict, stride divisibility, even embed_dim), unused hyper-parameter attributes, and the converter's unknown-key raises (strict=False reports them). - Tests: keys follow the rename; reset/features covered by the shared suites. * DOC DuIN: train with the reference's sigmoid + cross-entropy to reproduce the paper (60.2% vs 55.6% top-1) * DOC DuIN: load the pretrained weights from braindecode/duin-pretrained on the Hub The 24 upstream checkpoints (12 subjects x mae/vqvae) are converted to braindecode/duin-pretrained (subj-<subject>/<stage>/model.safetensors, root = subj-001/mae). Every converted encoder matches the upstream duin_cls output to < 1e-5 and reloads bit for bit. Docstring example uses from_pretrained; DuIN is added to the hub integration tests. * MAINT DuIN, MultiHeadAttention: reject invalid patch geometry and head sizes Address the Copilot review on #1298: DuIN checks that patch_size and strides are positive and that prod(strides) divides patch_size (else embed_dim disagrees with the convolution output); MultiHeadAttention rejects non-positive num_heads / head_dim, and its num_heads docstring states the divisibility only when head_dim is None. --------- Co-authored-by: Adam Mounir <[email protected]>
Collaborator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Towards #1097.
Adds a braindecode-native port of Du-IN (Zheng et al., Du-IN: Discrete units-guided mask modeling for decoding speech from Intracranial Neural signals, NeurIPS 2024, arXiv:2405.11459). It is the fourth iEEG/sEEG model from #1097, after
Brant(#1100),BrainBERT(#1104) andPopulationTransformer(#1105), and the one cited there alongside them as a leading sEEG baseline.Upstream code and released weights:
c2e289c3)liulab-repository/Du-IN(CC BY 4.0, revision2c85b670), one Du-IN MAE checkpoint per subjectWhat it is
Du-IN decodes speech from sEEG with region-level tokens. It does not use one token per channel: the ~10 channels recorded in a language-related region (vSMC, STG) are fused into one token per 100 ms patch.
(B, C, T) → linear channel projection (C → 16) → per-patch Conv1d+BN stack (100 samples → 160-d token) → sinusoidal time embedding → 8-layer post-norm Transformer (QK layer norm) → flatten → MLP headPretraining has two stages per subject: a VQ-VAE codebook, then masked prediction of code indices (Du-IN MAE). The paper's best result, "Du-IN (mae)" with 62.70% top-1 on the 61-word task, fine-tunes the MAE encoder with the MLP head. This PR ports that classification model. The VQ-VAE, the codebook and the MAE token head are not included.
Design
DuIN(EEGModuleMixin, nn.Module)keeps the standard(batch, n_chans, n_times)input.n_timesmust be a multiple ofpatch_size(100 = 100 ms at 1 kHz).embed_dim=160, 8 layers, 8 heads × 64,ffn_dim=320, head hidden 128. Withn_chans=10, n_times=3000, n_outputs=61the model has 4.18M parameters.load_state_dictaccepts an upstreamduin_mae/duin_clsstate dict directly and renames its keys. Pretraining-only tensors (mask_emb, the codebook, the MAE token head) and the fixed time-embedding table are dropped, so load withstrict=False. The head is not pretrained.return_features=Truereturns the flattened encoded sequence that the head consumes (cls_token=None).reset_headswapsfinal_layer. The model is TorchScript-compatible.Deviations from the reference (documented in the docstring)
F.cross_entropy. The port returns logits, as every braindecode classifier does.n_subjects=1), so it reduces exactly to annn.Linear(spatial_projection). The multi-subject "poms" variant is not ported, and a multi-subject checkpoint is refused with a clear error.Conv1d((128, 16, 19)kernels). The port follows the code.Parity with the released weights
For each of the 12 released subject checkpoints (
pretrains/duin/<subj>/mae/model/checkpoint-399.pth), I built upstreamduin_clsat the downstream geometry (10 channels, 3000 samples at 1 kHz, 61 labels) and loaded it as upstreamload_weightdoes. I loaded the same file into the port withload_state_dict(..., strict=False)and ran both on identical random input in eval mode:1/sqrt(64)attention scales, 4 are pretraining-only (mask_emb,emb_time.time_encodings, MAE token head weight + bias)head_hidden.*,final_layer.*(not pretrained)The residual is float32 noise: upstream uses an unstabilised
exp/sumsoftmax, and the port usesF.scaled_dot_product_attention.Replication
The paper's numbers come from the authors' 61-word Chinese reading dataset. They released a preprocessed version of it (~3 h, 12 subjects) alongside the weights, so a fine-tuning replication of "Du-IN (mae)" with the port is possible. It will be posted here once run (see checklist).
Included
braindecode/models/duin.py: model, private conv/attention/Transformer blocks, upstream key conversion.models/__init__.py,models/util.py(3000 samples at 1 kHz),summary.csv,docs/api.rst,docs/whats_new.rst, MIT entry inNOTICE.txt.# Tests for DuINsection intest_foundation_models.pycovering released-config shapes, upstream key loading (and the subject-layer equivalenceX @ W.reshape(C, 16) + B), refusal of multi-subject checkpoints, time-major token layout, head/reset, geometry validation, and the sampling-rate warning. The model is also added to the shared suites:test_return_features, thetest_pretrained_compatgeometry contract, and the registry-driven integration/TorchScript/contract tests.Checklist
NOTICE.txt.braindecode/duin-pretrained, one revision/subfolder per subject?) — open question for maintainers, since the checkpoints are subject- and montage-specific.cc @bruAristimunha