Repository navigation
Add Du-IN region-level sEEG speech decoder (lands #1269) - #1298
Merged
Merged
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.
Conflicts resolved: - docs/whats_new.rst: keep master's entries and the DuIN entry (placed after Guetschel2026). - test/unit_tests/models/test_pretrained_compat.py, test_return_features.py: keep both DuIN and Guetschel2026 imports (sorted).
…dant 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.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #1298 +/- ##
==========================================
+ Coverage 90.09% 90.14% +0.04%
==========================================
Files 166 167 +1
Lines 21457 21572 +115
==========================================
+ Hits 19332 19446 +114
- Misses 2125 2126 +1 🚀 New features to boost your workflow:
|
…duce the paper (60.2% vs 55.6% top-1)
…d 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.
Collaborator
|
@bruAristimunha Independent replication of the port on CUDA (12 subjects × 6 seeds, mean ± SE):
Weights: braindecode/duin-pretrained. |
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
The referenced Hub repository is unavailable, and newly exposed geometry and attention arguments permit invalid configurations.
6 open findings
Network test references nonexistent Hub repository · New Validate patch geometry arguments before dimension construction · New Reject non-positive head_dim and num_heads values · New Module link targets nonexistent Hub repository · New num_heads documentation states an invalid unconditional constraint · New Release note falsely claims checkpoints were re-hosted · New
🧠 Review effort: Balanced
| ("MIRepNet", "braindecode/mirepnet-pretrained", 45), | ||
| ("STEEGFormer", "braindecode/STEEGFormer-small", 22), | ||
| ("BrainBERT", "braindecode/brainbert-pretrained", 1), | ||
| ("DuIN", "braindecode/duin-pretrained", 10), |
Comment on lines
+213
to
+222
| if self.n_times % patch_size or self.n_times < patch_size: | ||
| raise ValueError( | ||
| f"n_times ({self.n_times}) must be a positive multiple of " | ||
| f"patch_size ({patch_size}): it is not divisible." | ||
| ) | ||
| warn_if_sfreq_differs("DuIN", self._sfreq, 1000) | ||
|
|
||
| self.n_patches = self.n_times // patch_size | ||
| # Time-major flattening of the last convolution: (frames, filters). | ||
| self.embed_dim = n_filters[-1] * (patch_size // math.prod(strides)) |
Comment on lines
+882
to
+886
| if head_dim is None: | ||
| if emb_size % num_heads != 0: | ||
| raise ValueError( | ||
| f"emb_size ({emb_size}) must be divisible by num_heads ({num_heads})." | ||
| ) |
Comment on lines
+10
to
+11
| * weights: https://huggingface.co/braindecode/duin-pretrained (converted from | ||
| https://huggingface.co/datasets/liulab-repository/Du-IN) |
Comment on lines
+854
to
+856
| head_dim : int, optional | ||
| Width of each head. When ``None``, ``emb_size // num_heads``; otherwise | ||
| the query/key/value projections are ``num_heads * head_dim`` wide. |
Comment on lines
+41
to
+43
| per-subject Du-IN checkpoints (MAE and VQ-VAE stages, 12 subjects) are on | ||
| the Hub at ``braindecode/duin-pretrained`` and match the upstream encoder | ||
| to float precision. |
…d sizes Address the Copilot review on braindecode#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.
# Conflicts: # docs/whats_new.rst # test/unit_tests/models/test_return_features.py
4 of 6 tasks
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.



Lands #1269 by @adammounir (commits kept).
models/duinconflicted with master, so this branch is #1269's two commits, a master merge and a simplification pass.Our changes:
docs/whats_new.rst, the import lists oftest_pretrained_compat.pyandtest_return_features.py).braindecode.modules.MultiHeadAttentiongains optionalhead_dimandqk_normand replaces the private attention;FeedForwardBlockreplaces the FFN; the conv blocks are plainnn.Sequentials; checks that repeat a downstream error are dropped (duin.py510 -> 424 lines). The 5 existingMultiHeadAttentioncallers (CTNet, EEGConformer, MIRepNet, MSCFormer, STEEGFormer): same keys, seeded init, outputs and gradients, max-abs 0.0.encoder.*.attnandspatial_encoder; the upstream-key converter follows, so the authors' MAE and VQ-VAE checkpoints still load directly (only the head is missing).License: code adapted from liulab-repository/Du-IN (MIT):
license="mit", header link,NOTICE.txtMIT list. The per-subject weights (CC BY 4.0) are not bundled; their braindecode conversion is hosted atbraindecode/duin-pretrained, with attribution in the model card.Replication (braindecode maintainers)
Protocol: the authors' fine-tuning loop (
train/duin/run_cls.py@ c2e289c3: split, augmentation, AdamW schedule, 200 epochs, test accuracy at the best-validation epoch) run per subject and seed on their public 61-word sEEG data (HFliulab-repository/Du-IN, paper revision056a87b7), 12 subjects x 6 seeds (run.sh), fine-tuned from the released per-subject checkpoints. The port column swaps only the model class (same split, batch order, initial weights, loss); paper aggregation = subject means over seeds, mean ± SE over subjects. The port runs on Gaudi2, one card per subject, fp32 (recipe); the authors' model on Gaudi2 (eager) or CPU.duin_clsagree to 1e-14 in float64 (forward and gradients).Description from #1269 (@adammounir)
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 subfolder per subject and stage (subj-XXX/{mae,vqvae}/model.safetensors).cc @bruAristimunha
Co-authored-by: Adam Mounir [email protected]