Repository navigation
Add codebrain - #964
Add codebrain#964
Conversation
|
there is some mistake between the paper link and the reference |
bruAristimunha
left a comment
There was a problem hiding this comment.
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:
| 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) |
There was a problem hiding this comment.
we can re-host the weight without the module part in the braindecode hugging face. I would not put this function
…oad_state_dict override
|
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.
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 :) |
…mode rename, rfft fix, api.rst update
3e105b4 to
b7e787c
Compare
|
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 :) |
|
@ShahVandit Great that you solved the compilation issue! There is still bruno's comment regarding
Sounds good to follow the paper's description of SWA. Thanks for all your work :) |
- 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.
|
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 |
|
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. |
|
hey! The model is giving chance level unf. @PierreGtch, can you debug this one more? |
|
So until then should I start looking into next model? @PierreGtch also mentioned Uni-NTFM along with CodeBrain |
|
Hi @bruAristimunha , I am trying to debug this issue on my end. What dataset did you use for benchmarking? |
|
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! |
|
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
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:
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!! |
|
many thanks @ShahVandit |
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 atYjMajy/CodeBrainon HuggingFace (19 channels, 200 Hz, 30s segments).Notes on implementation
(batch, n_chans, n_times)— split into patches internallyLazyLinearMLP matching the paper's descriptionmodule.prefix — stripped automatically inload_state_dictp_seq_len: Original hardcodes 200; we compute it from conv params so anypatch_sizeworksBenchmark (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