Skip to content

Add Du-IN region-level sEEG speech decoder (lands #1269) - #1298

Merged
bruAristimunha merged 8 commits into
braindecode:masterfrom
bruAristimunha:w41/land-1269
Oct 13, 2026
Merged

bruAristimunha merged 8 commits into
braindecode:masterfrom
bruAristimunha:w41/land-1269

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Lands #1269 by @adammounir (commits kept). models/duin conflicted with master, so this branch is #1269's two commits, a master merge and a simplification pass.

Our changes:

  • Merge of master: conflicts only where both sides append (docs/whats_new.rst, the import lists of test_pretrained_compat.py and test_return_features.py).
  • braindecode.modules.MultiHeadAttention gains optional head_dim and qk_norm and replaces the private attention; FeedForwardBlock replaces the FFN; the conv blocks are plain nn.Sequentials; checks that repeat a downstream error are dropped (duin.py 510 -> 424 lines). The 5 existing MultiHeadAttention callers (CTNet, EEGConformer, MIRepNet, MSCFormer, STEEGFormer): same keys, seeded init, outputs and gradients, max-abs 0.0.
  • Docstring: training with the reference's sigmoid + cross-entropy is what reproduces the paper (numbers below).
  • Against Add Du-IN: region-level sEEG speech decoder (Zheng et al., NeurIPS 2024) #1269's head e128ccd: outputs, gradients and BatchNorm buffers max-abs 0.0 (float32 and float64, random init and the released checkpoints). Keys change only under encoder.*.attn and spatial_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.txt MIT list. The per-subject weights (CC BY 4.0) are not bundled; their braindecode conversion is hosted at braindecode/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 (HF liulab-repository/Du-IN, paper revision 056a87b7), 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.

Table 2 cell paper authors' code port (this PR) port vs paper
Du-IN (mae) 62.70 ± 4.69 60.52 ± 4.58 60.16 ± 4.62 −4.1 %
Du-IN (vqvae) 58.24 ± 4.83 55.10 ± 4.51 55.00 ± 4.51 −5.6 %
Du-IN (no pretraining) 56.29 ± 5.20 54.06 ± 5.12 53.73 ± 5.13 −4.5 %
  • Port vs authors' code: within 0.4 points in every cell (CPU check on mae: 60.32 vs 60.57). Numerically, port and duin_cls agree to 1e-14 in float64 (forward and gradients).
  • The authors' code itself lands 2–3 points under the paper on 11 of 12 subjects. Cross-entropy on the logits instead of the reference's sigmoid + cross-entropy gives 55.64 on mae (now in the docstring).
  • Data: the authors replaced subjects 002/005/007/011 on the Hub in April 2025 without new checkpoints; we used the original revision as they advise (on the current files these four subjects score 1.5–1.7 points lower).

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) and PopulationTransformer (#1105), and the one cited there alongside them as a leading sEEG baseline.

Upstream code and released weights:

What 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 head

Pretraining 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_times must be a multiple of patch_size (100 = 100 ms at 1 kHz).
  • The defaults are the released configuration: embed_dim=160, 8 layers, 8 heads × 64, ffn_dim=320, head hidden 128. With n_chans=10, n_times=3000, n_outputs=61 the model has 4.18M parameters.
  • load_state_dict accepts an upstream duin_mae/duin_cls state 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 with strict=False. The head is not pretrained.
  • return_features=True returns the flattened encoded sequence that the head consumes (cls_token=None). reset_head swaps final_layer. The model is TorchScript-compatible.

Deviations from the reference (documented in the docstring)

  • The upstream head ends with a sigmoid before F.cross_entropy. The port returns logits, as every braindecode classifier does.
  • The upstream "subject layer" maps a one-hot subject id to a channel→neural matrix. All released checkpoints are single-subject (n_subjects=1), so it reduces exactly to an nn.Linear (spatial_projection). The multi-subject "poms" variant is not ported, and a multi-subject checkpoint is refused with a clear error.
  • The paper calls the patch convolutions depthwise, but the released code and weights use full 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 upstream duin_cls at the downstream geometry (10 channels, 3000 samples at 1 kHz, 61 labels) and loaded it as upstream load_weight does. I loaded the same file into the port with load_state_dict(..., strict=False) and ran both on identical random input in eval mode:

value
upstream tensors used 183 / 195 loaded; 8 are the fixed 1/sqrt(64) attention scales, 4 are pretraining-only (mask_emb, emb_time.time_encodings, MAE token head weight + bias)
port missing keys only head_hidden.*, final_layer.* (not pretrained)
encoder output, max abs diff 5.2e-6 to 8.6e-6 across subjects (activations up to ~15)
head output (upstream head copied, sigmoid applied), max abs diff ≤ 4.2e-7

The residual is float32 noise: upstream uses an unstabilised exp/sum softmax, and the port uses F.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.
  • Registration: models/__init__.py, models/util.py (3000 samples at 1 kHz), summary.csv, docs/api.rst, docs/whats_new.rst, MIT entry in NOTICE.txt.
  • Tests: a # Tests for DuIN section in test_foundation_models.py covering released-config shapes, upstream key loading (and the subject-layer equivalence X @ 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, the test_pretrained_compat geometry contract, and the registry-driven integration/TorchScript/contract tests.

Checklist

  • Implement and register the architecture.
  • Enforce braindecode model and feature contracts (shared suites pass).
  • Upstream-checkpoint loading + numerical parity on all 12 released subjects.
  • MIT attribution in source and NOTICE.txt.
  • Re-host converted weights on the braindecode HF Hub: braindecode/duin-pretrained, one subfolder per subject and stage (subj-XXX/{mae,vqvae}/model.safetensors).
  • Fine-tuning replication of "Du-IN (mae)" on the released 61-word data (see Replication above).

cc @bruAristimunha

Co-authored-by: Adam Mounir [email protected]

adammounir and others added 4 commits October 9, 2026 19:27
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.
Copilot AI balanced review requested due to automatic review settings October 10, 2026 13:07

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 reached their quota limit.

@bruAristimunha bruAristimunha added model Adds a new model needs-replication Model PR: paper number must be replicated (NeuralBench) before merge labels Oct 10, 2026
@codecov

codecov Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.18033% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 90.14%. Comparing base (c4f2b9f) to head (ac4d17a).
⚠️ Report is 4 commits behind head on master.

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

Copilot AI balanced review requested due to automatic review settings October 10, 2026 16:29

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 reached their quota limit.

…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.
Copilot AI balanced review requested due to automatic review settings October 11, 2026 17:42

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 reached their quota limit.

@adammounir

Copy link
Copy Markdown
Collaborator

@bruAristimunha Independent replication of the port on CUDA (12 subjects × 6 seeds, mean ± SE):

paper authors' code (#23) port (#23) port (this run)
mae 62.70 60.52 60.16 59.37 ± 4.69
vqvae 58.24 55.10 55.00 54.02 ± 4.57
scratch 56.29 54.06 53.73 53.77 ± 5.10

Weights: braindecode/duin-pretrained.

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.

🟡 Changes recommended

The referenced Hub repository is unavailable, and newly exposed geometry and attention arguments permit invalid configurations.

6 open findings

🧠 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 thread docs/whats_new.rst
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.
Copilot AI balanced review requested due to automatic review settings October 13, 2026 09:12

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 reached their quota limit.

# Conflicts:
#	docs/whats_new.rst
#	test/unit_tests/models/test_return_features.py
Copilot AI balanced review requested due to automatic review settings October 13, 2026 10:51

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 reached their quota limit.

@bruAristimunha
bruAristimunha merged commit e2b8f2d into braindecode:master Oct 13, 2026
11 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

model Adds a new model needs-replication Model PR: paper number must be replicated (NeuralBench) before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants