Skip to content

Add codebrain - #964

Merged
bruAristimunha merged 28 commits into
braindecode:masterfrom
ShahVandit:add-codebrain
Apr 14, 2026
Merged

bruAristimunha merged 28 commits into
braindecode:masterfrom
ShahVandit:add-codebrain

Conversation

@ShahVandit

@ShahVandit ShahVandit commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

Add CodeBrain Foundation Model

Adds the CodeBrain EEG foundation model (paper, code) to braindecode.

CodeBrain is a foundation model pre-trained on large unlabelled EEG corpora using a vector-quantised masking strategy. The backbone combines a multi-scale structured state-space model (_GConv) with sliding-window self-attention. Pre-trained weights are available at YjMajy/CodeBrain on HuggingFace (19 channels, 200 Hz, 30s segments).

Notes on implementation

  • Input: Accepts standard braindecode 3D input (batch, n_chans, n_times) — split into patches internally
  • Classifier head: Original repo has dataset-specific hardcoded MLP heads; replaced with a general 3-layer LazyLinear MLP matching the paper's description
  • Weight loading: Pre-trained checkpoint has DataParallel module. prefix — stripped automatically in load_state_dict
  • p_seq_len: Original hardcodes 200; we compute it from conv params so any patch_size works

Benchmark (BNCI2014_001, WithinSessionEvaluation, 100 epochs)

CodeBrain scores ~52% vs BrainModule 79% / EEGNeX 77%. The gap may reflect a data mismatch (19ch/200Hz pretraining vs 22ch/160Hz fine-tuning), but could also indicate an implementation issue. Happy to read further and correct if something is wrong.

References

@bruAristimunha

Copy link
Copy Markdown
Collaborator

there is some mistake between the paper link and the reference

@bruAristimunha bruAristimunha left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wrote mostly of my comment below, more iterations, and we'll be ready! I had the impression, quickly looking at the paper, that some parts are missing. Is it my impression?

About the benchmark, what i suggest is to try to reproduce the paper with the some dataloader. You can check some recent work that @PierreGtch has been doing that allows you to easily load these benchmark datasets.

https://huggingface.co/braindecode

doing this:

from braindecode.datasets import BaseConcatDataset

Load from Hugging Face Hub

dataset = BaseConcatDataset.pull_from_hub("braindecode/dataset-name")

you should be able to load the dataset and run the benchmark in some colab, check the dataset avaliable here:

https://huggingface.co/datasets/braindecode/

Comment thread braindecode/models/codebrain.py Resolved
Comment thread braindecode/models/codebrain.py Resolved
Comment thread braindecode/models/codebrain.py Resolved
Comment thread braindecode/models/codebrain.py Outdated
Comment on lines +543 to +547
def load_state_dict(self, state_dict, strict=True):
# Strip DataParallel 'module.' prefix if present (checkpoint from YjMajy/CodeBrain)
if all(k.startswith("module.") for k in state_dict.keys()):
state_dict = {k[len("module."):]: v for k, v in state_dict.items()}
return super().load_state_dict(state_dict, strict=strict)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can re-host the weight without the module part in the braindecode hugging face. I would not put this function

Comment thread braindecode/models/codebrain.py Resolved
Comment thread braindecode/models/codebrain.py Resolved
Comment thread braindecode/models/codebrain.py Resolved
Comment thread braindecode/models/codebrain.py Resolved
Comment thread braindecode/models/codebrain.py Resolved
Comment thread braindecode/models/codebrain.py Resolved
@PierreGtch

Copy link
Copy Markdown
Collaborator

Thanks @ShahVandit for this update.

The failed test on Ubuntu is for compiling the new Codebrain model. This is quite a strange error as the same test passes on macOS.

  • If you have a linux machine, it would be awesome if you could try to reproduce and fix it locally
  • otherwise, you can just modify the test to add a purest.skipif for the case Codebrain+ubuntu

But please fix the pre-commit errors. Pro tip: if you install pre-commit by following the contributing guidelines, these formatting issues will be automatically fixed for you, right before you push :)

@ShahVandit

Copy link
Copy Markdown
Contributor Author

The paper describes Sliding Window Attention (SWA) as part of each ResidualBlock, but the original released code omitted it. We added it back, exposed via swa_window_size (default=1 to match the pretrained checkpoint, set to an odd number >1 to enable). Let me know if you guys feel some changes are needed with the model :)

@PierreGtch

Copy link
Copy Markdown
Collaborator

@ShahVandit Great that you solved the compilation issue!

There is still bruno's comment regarding load_state_dict. To solve it, can you:

  1. load the weights using the custom model.load_state_dict() method you implemented
  2. push the weights using model.push_to_hub("braindecode/codebrain-pretrained") (you should have write rights now)
  3. remove method def load_state_dict(self...
  4. check if you can load the weights using model = CodeBrain.from_pretrained("braindecode/codebrain-pretrained")

Sounds good to follow the paper's description of SWA.
But before merging, please re-run the benchmark using the latest version of the code and the weights you will have pushed on HF

Thanks for all your work :)

bruAristimunha and others added 11 commits April 3, 2026 14:06
- Add return_features support to match foundation model API pattern
- Replace assert with raise ValueError for window_size validation
- Remove no-op rearrange identity operation
- Remove unused contract alias and shift parameter
- Standardize super() calls
- Fix duplicate Sphinx citation reference
- Add tests for pretrain mode and return_features
- Add PR number to whats_new.rst
- Rename self.h -> self.d_model, remove unused self.n
- Rename single-letter vars: L -> seq_len, u -> x, k -> kernel,
  y -> out, C -> n_channels, h_t -> h_ssm, h_s -> h_attn
- Add shape comments throughout all forward methods
- self.D -> self.skip_weight
- self.sn -> self.rms_norm
- self.s41 -> self.sgconv

Pretrained weights will be re-hosted with updated keys.
Replace pretrain_mode documentation with pre-trained weights loading
example. Remove internal pretraining params from public docstring.
Replace string-based activation dispatch with braindecode convention
of accepting an nn.Module class and instantiating it.
Structure every __init__ with clear sections:
Parameters -> Derived attributes -> Buffers -> Learnable parameters -> Layers
with section headers for quick scanning.
- Move CodeBrain to top of file for immediate visibility
- Prefix all helper classes with _: _GConv, _Conv, _ZeroConv1d,
  _RMSNorm, _ResidualBlock, _ResidualGroup, _PatchEmbedding
- Add section separator between public and private classes
The spectral projection was computing FFT on the unmasked input x,
but the original CodeBrain computes it on mask_x so that masked
patches contribute zero spectral signal during pretraining.
Override load_state_dict to handle key differences from the upstream
YjMajy/CodeBrain checkpoint on HuggingFace:
- module. prefix from DataParallel
- S41 -> sgconv, sn -> rms_norm, .D -> .skip_weight
- KernelModule wrapper: kernel_list.N.kernel -> kernel_list.N
- Old weight_norm API: weight_g/weight_v -> parametrizations.*

Add scripts/check_codebrain_weights.py to verify loading.
Add CodeBrain to the unified API table, checkpoints chart, and
braindecode organization listing in plot_load_pretrained_models.py.
The input is 3D (batch, channels, seq_len), so Dropout1d is correct
for channel-wise dropout on 1D signal data. Fixes PyTorch warning
about future behavior change of Dropout2d on 3D inputs.
@bruAristimunha

Copy link
Copy Markdown
Collaborator

I am benchmarking the model, and the results are not good.... i want to release today, so I release now, and i do a small append with this model

@ShahVandit

Copy link
Copy Markdown
Contributor Author

Hi @bruAristimunha , just wanted to check in on the benchmark results for the model. Do you think it still needs improvement, or is it good to proceed with the merging? Let me know if more iterations are needed.

@bruAristimunha

Copy link
Copy Markdown
Collaborator

hey!

The model is giving chance level unf. @PierreGtch, can you debug this one more?

@ShahVandit

Copy link
Copy Markdown
Contributor Author

So until then should I start looking into next model? @PierreGtch also mentioned Uni-NTFM along with CodeBrain

@ShahVandit

Copy link
Copy Markdown
Contributor Author

Hi @bruAristimunha , I am trying to debug this issue on my end. What dataset did you use for benchmarking?

@bruAristimunha

Copy link
Copy Markdown
Collaborator

hey @ShahVandit,

Any small dataset is fine from the open eeg bench! @PierreGtch released this new cool library that will make the benchmark much easier!

https://github.com/braindecode/OpenEEGBench

@PierreGtch

PierreGtch commented Apr 14, 2026 •

Copy link
Copy Markdown
Collaborator

I loader the weights in the original architecture and in @ShahVandit re-implementation. Both architectures produce identical outputs up to 6.7e-6 for identical inputs.

However, I also benchmarked both implementations in open-eeg-bench with the following arguments:

  • one seed
  • linear classification head
  • frozen backbone
Dataset Braindecode (Vandit) Original Δ (BD − Orig)
arithmetic_zyma2019 0.5521 0.6563 −0.1042
bcic2020-3 0.2720 0.2213 +0.0507
bcic2a 0.3264 0.3275 −0.0011
mdd_mumtaz2016 0.8545 0.7901 +0.0644

We observe relatively important differences on some downstream scores.

I suppose this is due to differences in the linear head initialisation. Indeed, the inner layers of the two backbones are not strictly identical so the linear head is not initialised with the same RNG in both cases.

Running for 5 seeds on arithmetic_zyma2019 (largest delta) gives the following results:

  Braindecode Original
Avg. 0.6042 0.6250
Std. 0.0466 0.0461
Seeds 0.552, 0.594, 0.677, 0.583, 0.615 0.656, 0.566, 0.590, 0.677, 0.635

A Welch test (p=0.50) suggests that the implementations are not statistically different.

Considering all this, I think we can merge the PR 👍🏼

Thanks a lot @ShahVandit for your work!!

@bruAristimunha
bruAristimunha merged commit f6384d8 into braindecode:master Apr 14, 2026
9 of 10 checks passed
@bruAristimunha

Copy link
Copy Markdown
Collaborator

many thanks @ShahVandit

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