Skip to content

Add Du-IN: region-level sEEG speech decoder (Zheng et al., NeurIPS 2024) - #1269

Closed
adammounir wants to merge 2 commits into
masterfrom
models/duin
Closed

adammounir wants to merge 2 commits into
masterfrom
models/duin

Conversation

@adammounir

Copy link
Copy Markdown
Collaborator

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 revision/subfolder per subject?) — open question for maintainers, since the checkpoints are subject- and montage-specific.
  • Fine-tuning replication of "Du-IN (mae)" on the released 61-word data.

cc @bruAristimunha

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

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.

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

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]>
@bruAristimunha

Copy link
Copy Markdown
Collaborator

Thank you for the Du-IN contribution! This is now superseded by #1298 (landed as e2b8f2d), which carries the model forward on current master. Closing as superseded — your original work is credited in the history.

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