Skip to content

Add NICE (EEG/MEG image-decoding encoder, Song et al. ICLR 2024) - #1556

Merged
bruAristimunha merged 11 commits into
braindecode:masterfrom
bruAristimunha:feat/meg-nice
Nov 9, 2026
Merged

bruAristimunha merged 11 commits into
braindecode:masterfrom
bruAristimunha:feat/meg-nice

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Adds braindecode.models.NICE, the brain branch of NICE: Decoding Natural Images from EEG for Object Recognition (Song et al., ICLR 2024, arXiv:2308.13234). It contains the TSConv encoder (Enc_eeg) and the projector into the CLIP ViT-L/14 space (Proj_eeg). Code: eeyhsong/NICE-EEG @ a7709d81, License (MIT).

Related: #1392.

  • Interface. Input (batch, n_chans, n_times). return_features=True returns the aligned 768-d embedding. final_layer is a linear head on it, and reset_head replaces it.
  • Paper configurations. THINGS-EEG2: n_chans=63, n_times=250 (250 Hz, 0-1 s). THINGS-MEG (appendix A.6): n_chans=271, n_times=200. The TSConv sizes are constructor arguments.
  • Reuse. The projector's residual + LayerNorm is modules.PostNormResidual. EEGConformer's patch embedding doesn't match: NICE pools before the spatial convolution and has two BatchNorms.
  • Checkpoint keys. The authors' keys load through mapping. The architecture follows the training script nice_stand.py, which includes the 1x1 projection convolution that eeg_encoder.py's forward skips.
  • Not included. NICE-SA and NICE-GA, the optional spatial modules.

Parity

Original nice_stand.py Enc_eeg + Proj_eeg vs port, CPU float32, eval:

case weights features input grad 16 parameter grads
EEG 63 x 250 released file, see note 0.0 0.0 0.0
EEG 63 x 250 seeded random 0.0 0.0 0.0
MEG 271 x 200 seeded random 0.0 0.0 0.0

Note: the released encoder file on eeyhsong/NICE (rev 7f98b08) is truncated. It is 76 KB, torch.load fails, and 3 of its 16 tensors are incomplete. This is already reported upstream in eeyhsong/NICE-EEG#27. The first parity row reads the 13 complete tensors and fills the rest with seeded values. That is an architecture check, not a validation of pretrained weights. The projector file is complete.

Tests (CPU, -k "not compiled"):

  • test_models/test_return_features/test_integration plus categorization/modality/contract: 2632 passed.
  • pre-commit clean.

Replication (braindecode maintainers)

Protocol. We use the intra-subject 200-way zero-shot classification on THINGS-EEG2 from Song et al., ICLR 2024 (arXiv 2308.13234 v3, Table 2, row NICE). The data come from NEMAR nm000232 v1.1.1. Its BrainVision recordings are rebuilt into the authors' raw format, which matches the Figshare release in all 80 recordings, then preprocessed with the authors' preprocessing.py unchanged. The preprocessed arrays are byte-identical to the ones built from Figshare for all 10 subjects. Both arms train on the same arrays with the same splits, seeds and batch order. The first arm is the authors' nice_stand.py at a7709d81. The second is the same script with Enc_eeg + Proj_eeg replaced by braindecode.models.NICE at 04d85efe; nice.py is unchanged at the current head. All hyperparameters are the authors': Adam with lr 2e-4 and betas (0.5, 0.999), batch 1000, 200 epochs, and the released CLIP ViT-L/14 features. We report two aggregations:

  • (a) one training per subject, following the script's seed chain;
  • (b) the mean of 5 trainings per subject (NumPy seeds 2023 to 2027, fixed before any run), which is how the README describes Table 2.

The comparison rule, fixed before the reported full runs, is that both arms' 10-subject means must lie within 5 % (relative) of the paper's values.

NICE replication: per-subject and group top-1/top-5 accuracies. Authors' code and port overlap exactly; error bars show subject SD. Gray bands show the ±5% paper tolerance.

Figure. Top panels: five-training means for each subject. Bottom panels: across-subject means ± SD for the paper and both replication aggregations. Blue circles and hollow squares overlap exactly (authors' code and port); orange diamonds show paper targets. Gray bands are ±5% relative tolerance, not confidence intervals. Public figure, plotting source and aggregate results.

Each cell is top-1 / top-5 accuracy (%).

Subject Paper (a) authors' code (a) port (b) authors' code (b) port
1 12.3 / 36.6 11.5 / 33.0 11.5 / 33.0 11.1 / 34.8 11.1 / 34.8
2 10.4 / 33.9 11.0 / 32.0 11.0 / 32.0 10.5 / 33.7 10.5 / 33.7
3 13.1 / 39.0 12.0 / 38.5 12.0 / 38.5 12.8 / 38.9 12.8 / 38.9
4 16.4 / 47.0 16.5 / 46.5 16.5 / 46.5 16.5 / 46.7 16.5 / 46.7
5 8.0 / 26.9 9.0 / 27.5 9.0 / 27.5 7.9 / 26.4 7.9 / 26.4
6 14.1 / 40.6 15.5 / 39.5 15.5 / 39.5 14.3 / 40.4 14.3 / 40.4
7 15.2 / 42.1 17.0 / 40.0 17.0 / 40.0 15.2 / 40.2 15.2 / 40.2
8 20.0 / 49.9 19.5 / 51.5 19.5 / 51.5 19.6 / 48.8 19.6 / 48.8
9 13.3 / 37.1 13.0 / 40.0 13.0 / 40.0 12.9 / 38.8 12.9 / 38.8
10 14.9 / 41.9 16.0 / 44.0 16.0 / 44.0 15.0 / 45.1 15.0 / 45.1
mean (SD) 13.8 (3.3) / 39.5 (6.5) 14.10 (3.28) / 39.25 (7.12) 14.10 (3.28) / 39.25 (7.12) 13.58 (3.31) / 39.38 (6.66) 13.58 (3.31) / 39.38 (6.66)
  • Port vs authors' code: in all 50 subject × training pairs, the initial weights, the 200-epoch training logs and the test accuracies are identical (difference 0.0).

  • vs paper: the means differ from the paper by:

    • (a) +2.2 % top-1 and -0.6 % top-5;
    • (b) -1.6 % top-1 and -0.3 % top-5.

    Both aggregations fall within the 5 % band. The 10-subject means of the 5 trainings range from 12.95 to 14.10 (top-1) and from 38.50 to 41.05 (top-5).

Deviations from the authors' setup:

  • We trained on CPU (PyTorch 2.14.1, float32), while the authors used a GPU. Device calls were adapted for CPU; instrumentation records results without drawing random numbers. Library versions were not published by the authors.
  • The script takes its first seed from an unseeded NumPy RNG, and the paper's seeds are not published. We seed it with the --seed default (2023), plus 2024 to 2027 for (b).
  • As released, the test reloads the best-validation checkpoint with strict=False onto the DataParallel wrapper, which loads no weights. The test therefore uses the epoch-200 weights, whereas the paper says it saves the best-validation model.

The targets above were independently verified against arXiv v3; the proceedings PDF was not verified. This run tests the encoder/projector, not the classification head.

Open decisions

Copilot AI balanced review requested due to automatic review settings November 8, 2026 12:16

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

Checkpoint loading skips the pinned script’s TSConv weights and BatchNorm statistics, while head replacement lacks output-count validation and fails to preserve device, dtype, and evaluation mode.

3 open issues
What changed in this PR

Adds NICE’s EEG/MEG brain encoder to Braindecode’s model API, supporting image-aligned embeddings and classification as part of the model-integration work tracked in #1392.

Changes:

  • Implements TSConv and the CLIP-space projector, with feature returns, a replaceable classification head, and checkpoint-key mapping.
  • Registers NICE in model metadata, API documentation, release notes, and MIT license notices.
  • Adds checkpoint-loading coverage and includes NICE in shared feature-return tests.
File Description
test/​unit_tests/​models/​test_return_features.py Adds NICE to shared feature-return tests.
test/​unit_tests/​models/​test_models.py Tests checkpoint-key mapping and EEG/MEG embedding shapes.
NOTICE.txt Lists NICE under MIT-licensed components.
docs/​whats_new.rst Announces the NICE integration.
docs/​api.rst Adds NICE to the public model documentation.
braindecode/​models/​util.py Registers NICE’s required signal parameters.
braindecode/​models/​summary.csv Records visual-decoding metadata and EEG/MEG support.
braindecode/​models/​nice.py Implements the encoder, projector, classifier, and checkpoint mapping.
braindecode/​models/​__init__.py Exposes NICE through the models package.

Review effort: Balanced


# Keys of the released pretrain_Enc_eeg_cls.pth / pretrain_Proj_eeg_cls.pth.
self.mapping = {
**{f"0.shallownet.{k}": f"tsconv.{k}" for k in self.tsconv.state_dict()},
Comment thread braindecode/models/nice.py Resolved
"""Replace the classification head; the encoder is kept."""
self._n_outputs = n_outputs
self._update_init_kwargs(n_outputs=n_outputs)
self.final_layer = nn.Linear(self.embed_dim, n_outputs)
Copilot AI balanced review requested due to automatic review settings November 8, 2026 12:54

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.

🔵 Needs a closer look

The checkpoint mapping omits the pinned training script’s 0.tsconv.* keys, causing strict=False loads to silently leave TSConv weights randomly initialized.

2 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Generate nonnegative BatchNorm variances and check finite features

test/​unit_tests/​models/​test_models.py:6078

Both BatchNorm running_var buffers are sampled from a signed normal distribution here. Negative variances produce NaNs during the subsequent eval-mode forward, but the shape-only assertion still passes. Generate nonnegative variances and assert finite features so this post-load forward checks a usable model rather than accepting NaN embeddings.

1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 8, 2026 13: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.

🔵 Needs a closer look

Checkpoint loading omits the upstream 0.tsconv.* keys, leaving the convolutional encoder randomly initialized, and reset_head fails to preserve the model’s device and dtype.

2 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity reset_head creates replacement head on default device and dtype

braindecode/​models/​nice.py:161

Calling reset_head after model.double() or model.to('cuda') creates a new head with the default dtype and CPU device, while the projector retains its converted dtype/device. The next forward therefore fails with a dtype or device mismatch, including with return_features=True because that path also evaluates the head. Preserve the old head's device and dtype when constructing its replacement.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 8, 2026 14:16

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.

🔵 Needs a closer look

Checkpoint loading silently leaves the encoder randomly initialized for reference-script checkpoints, and replacing the head loses its device and dtype, causing subsequent forward passes to fail.

2 open issues

Review effort: Balanced

@codecov

codecov Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.67442% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 91.54%. Comparing base (0f1cce2) to head (fc5d446).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1556      +/-   ##
==========================================
+ Coverage   91.53%   91.54%   +0.01%     
==========================================
  Files         171      172       +1     
  Lines       22580    22623      +43     
==========================================
+ Hits        20669    20711      +42     
- Misses       1911     1912       +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 November 9, 2026 09:55

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 insufficient remaining quota. Try requesting a review at a lower effort level.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 10:43

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 insufficient remaining quota. Try requesting a review at a lower effort level.

# Conflicts:
#	docs/whats_new.rst
Copilot AI balanced review requested due to automatic review settings November 9, 2026 11:24

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 insufficient remaining quota. Try requesting a review at a lower effort level.

Brings in 0f1cce2 (braindecode#1551 CORTEG). Conflicts resolved by keeping both sides:
- docs/whats_new.rst: master's file plus the NICE entry after CORTEG's.
- NOTICE.txt: master's file plus braindecode/models/nice.py.
- test_pretrained_compat.py: NO_STRATEGY lists both CORTEG and NICE.
Copilot AI balanced review requested due to automatic review settings November 9, 2026 13:36

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 insufficient remaining quota. Try requesting a review at a lower effort level.

@bruAristimunha
bruAristimunha merged commit 1aea042 into braindecode:master Nov 9, 2026
10 checks passed
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.

2 participants