File size: 10,923 Bytes
a1ccb6c
 
 
 
 
 
 
 
 
 
 
 
8bec15c
 
 
 
 
a1ccb6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
---
license: other
library_name: braindecode
base_model: Dcode-AI/SAMBA-2s
tags:
- braindecode
- pytorch
- safetensors
- eeg
- samba
- mamba
- foundation-model
datasets:
- Emotiv
- HBN
- nm000287
- DICE
---

# SAMBA-2s (pretrained encoder)

Weights of SAMBA-2s, a checkpoint of SAMBA (Hong, Mackellar and Ghane, NeurReps 2026), for
[`braindecode.models.SAMBA`](https://braindecode.org/stable/generated/braindecode.models.SAMBA.html)
(braindecode 2.1): an EEG foundation model that reads electrode positions through a
coordinate-driven spatial embedding and models time with differential Mamba-2 blocks. The authors
pretrained it by masked reconstruction with a U-shaped encoder-decoder, on
2 s windows (256 samples at 128 Hz) from Emotiv (Alpha, Attention, Crowdsource,
DriverDistraction and STEW), HBN resting state, Muse sleep onset and DICE eyes closed,
with 4, 14, 19 and 129 EEG channels.
These files are the encoder of
[`Dcode-AI/SAMBA-2s`](https://huggingface.co/Dcode-AI/SAMBA-2s) at revision
`e5532879765b4809b77b3c6c605e41348e8887ba`,
converted to braindecode's parameter names by `convert.py`.

```python
from braindecode.models import SAMBA

# The 94 target electrodes of the weights are the default montage ("Intended input"
# gives another one)
model = SAMBA.from_pretrained("braindecode/samba-2s-pretrained", n_outputs=2).eval()
# x: (batch, 94, n_times) -> features: (batch, 256)
features = model(x, return_features=True)["features"]
```

The files hold no classification head: it is not pretrained, so `from_pretrained` builds a new one
(PyTorch's default init) for your `n_outputs`. Fine-tune or linear-probe before use. `features` are
the mean and the standard deviation over time of the encoder output, `(batch, 2 * 128)`; the first
128 are the authors' mean-pooled features.

## Intended input

- EEG at 128 Hz, each channel of each window divided by the 95th percentile of its absolute value,
  as in the authors' pretraining. `SAMBA` does not normalise.
- Electrode positions in `chs_info[i]["loc"][:3]`, in metres, in the frame of the `colin27_1005`
  template of MNE (`standard_1005` in older versions of MNE), which is the frame of the weights.
  `raw.set_montage` writes head-frame positions instead, a few centimetres away (up to 5.7 cm for
  these electrodes), so build `chs_info` from the template. The default `chs_info` of `config.json`
  is the 94 target electrodes of the weights (`Fp1`, `Fpz`, ..., `A2`); any other montage with
  positions is mapped onto them:

  ```python
  import mne
  import numpy as np

  template = mne.channels.make_standard_montage("colin27_1005").get_positions()["ch_pos"]
  names = ["Fp1", "Fp2", "C3", "C4", "O1", "O2"]
  chs_info = [{"ch_name": n, "kind": "eeg", "loc": np.r_[template[n], np.zeros(9)]} for n in names]
  model = SAMBA.from_pretrained(
      "braindecode/samba-2s-pretrained", chs_info=chs_info, n_outputs=2, n_times=512
  )
  ```
- Pretrained on windows of 256 samples (2 s); any window of at least 8 samples is read (the
  encoder keeps `n_times // 8` steps).

## Changes from the original release

`convert.py` renames the keys, drops the reconstruction decoder and writes the files with
`save_pretrained`. No value is changed.

- **Keys renamed.** The authors' network is `SAMBA.encoder`, so all 178 encoder keys gain that
  prefix; 173 of them also change a module name (plain prefix replacement, no pattern):

  | original prefix | braindecode (under `encoder.`) | keys |
  |---|---|---|
  | `cdse.net.` | `cdse.score.` | 4 |
  | `cdse.target_positions` | `cdse.target_positions` | 1 |
  | `input_embedding.0.` | `input_embedding.` | 8 |
  | `encoder1.0.` | `encoder1_linear.` | 2 |
  | `encoder1.1.mixer.` | `encoder1_mamba.` | 8 |
  | `encoder2.`, `encoder3.` | `encoder2.`, `encoder3.` | 2 + 2 |
  | `bottleneck.0.` | `bottleneck_in.` | 2 |
  | `bottleneck.1.` | `bottleneck_mamba.` | 147 |
  | `bottleneck.2.` | `bottleneck_out.` | 2 |

- **Decoder dropped.** The checkpoint also holds the reconstruction decoder, which the
  encoder-only `SAMBA` does not have: 29 of 207 tensors are left out
  (key counts per prefix):
  `decoder1.` 2, `decoder2.` 2, `decoder2_mixer.` 8, `decoder3.` 2, `decoder3_mixer.` 8,
  `output_embedding.` 2, `spatial_decoder.` 5.
- **Values unchanged.** Each of the 178 tensors (float32) is bitwise equal to its original tensor.
- **Config.** `config.json` is braindecode's, written by `save_pretrained`: the sizes are the
  authors', their `target_channel_names` and `target_positions` give the default `chs_info` and
  `target_positions`, and their `sampling_rate` and the window of the pretraining give `sfreq` and
  `n_times`. Their decoder fields (`reconstruction_mode`, `reconstruction_channels`) are not kept.

## Verification

`SAMBA.from_pretrained` on these files against the port of braindecode#1689 (commit `e108b378`),
whose `load_pretrained_encoder` reads the authors' original `model.safetensors` unchanged; CPU, eval
mode, the same seeded input. The encoder output, the pooled features and the outputs with a shared
head differ by 0.0 (max abs) in float32 and in float64, for the 94 target electrodes at
256 samples (2 s) and for 19 electrodes of the 10-20 system at 131 samples. A change of 1e-3
in one value of one block shows as a difference of 1e-5 or more, so the comparison would see it.

## Source and license

- Paper: J. Hong, G. Mackellar, S. Ghane. *SAMBA: Toward an EEG Foundation Model via Differential
  Mamba and Coordinate-Driven Spatial Embedding.* NeurReps 2026.
  [arXiv:2511.18571](https://arxiv.org/abs/2511.18571)
- Code: [Jiazhen-Hong/SAMBA](https://github.com/Jiazhen-Hong/SAMBA)
- Weights: [Dcode-AI/SAMBA-2s](https://huggingface.co/Dcode-AI/SAMBA-2s) at
  revision `e5532879765b4809b77b3c6c605e41348e8887ba`:
  `model.safetensors` (sha256 `b8bd7eeda94944872199b3604050cb1acc391c6d1d657a846554b0bd66f811d1`),
  `config.json` (sha256 `b453e7b9e3e4fa10477b367d0f8eea81e6b366d83b0e9bf2deaaa1c821dfe220`).
  The authors retrained SAMBA-2s and SAMBA-100s after the checkpoints of the paper were lost, and
  evaluate them separately from the paper's SAMBA-E and SAMBA-T.

Neither the authors' Hugging Face repository nor their GitHub repository has a licence file; the
weights are by the SAMBA authors. Please cite:

```bibtex
@inproceedings{hong2026samba,
  title     = {{SAMBA}: Toward an {EEG} Foundation Model via Differential Mamba and Coordinate-Driven Spatial Embedding},
  author    = {Hong, Jiazhen and Mackellar, Geoffrey and Ghane, Soheila},
  booktitle = {NeurReps 2026: Symmetry and Geometry in Neural Representations (Proceedings Track)},
  year      = {2026}
}
```

## Conversion

`convert.py` (in this repository, copied below) was run with braindecode at `4696bd5b`:

```
python convert.py <directory of Dcode-AI/SAMBA-2s> <out_dir>
```

| file | sha256 |
|---|---|
| `model.safetensors` | `4334a83ee2272cb3ef1e13395fd3d5b7dde0f5b7e84116172c99bd6edfa916ce` |
| `config.json` | `34f8aaca599cc65afe0558d896e41c47c02435c8aea266ee984f6b58ed6cc6f2` |
| `convert.py` | `1169c4ade79e832124f216f1863bc88fec44fe19fc442cee92df6741494188e8` |

<details>
<summary><code>convert.py</code></summary>

```python
"""Convert ``Dcode-AI/SAMBA-2s`` or ``Dcode-AI/SAMBA-100s`` to braindecode's ``SAMBA``.

usage: python convert.py <src_dir> <out_dir>

``src_dir`` holds ``config.json`` and ``model.safetensors`` of the authors'
release (SAMBA-2s at e553287, SAMBA-100s at 3a235a1). Builds ``SAMBA`` from that
config, with the 94 target electrodes as the default ``chs_info`` and the window
of the pretraining; renames the keys with the prefix pairs below, drops the
reconstruction decoder, loads the rest into ``SAMBA.encoder`` with ``strict=True``
and writes ``config.json`` and ``model.safetensors`` with ``SAMBA.save_pretrained``.
No value is changed. The release holds the encoder only: the head is not
pretrained, so ``from_pretrained`` builds it for the caller's ``n_outputs``.
"""

import json
import os
import sys

import numpy as np
from safetensors.torch import load_file, save_file

from braindecode.models import SAMBA

# Samples of one pretraining window at 128 Hz (2 s and 100 s), from the README of
# each release
N_TIMES = {"SAMBA-2s": 256, "SAMBA-100s": 12800}

# (authors' prefix, braindecode's prefix) of the encoder keys that change name.
# The others (cdse.target_positions, encoder2.*, encoder3.*) keep theirs.
RENAMES = (
    ("cdse.net.", "cdse.score."),
    ("input_embedding.0.", "input_embedding."),
    ("encoder1.0.", "encoder1_linear."),
    ("encoder1.1.mixer.", "encoder1_mamba."),
    ("bottleneck.0.", "bottleneck_in."),
    ("bottleneck.1.", "bottleneck_mamba."),
    ("bottleneck.2.", "bottleneck_out."),
)

# The reconstruction decoder of the pretraining, not part of SAMBA
DECODER = (
    "decoder1.",
    "decoder2.",
    "decoder2_mixer.",
    "decoder3.",
    "decoder3_mixer.",
    "output_embedding.",
    "spatial_decoder.",
)


def rename(key):
    for old, new in RENAMES:
        if key.startswith(old):
            return new + key[len(old) :]
    return key


if __name__ == "__main__":
    src_dir, out_dir = sys.argv[1:]
    with open(os.path.join(src_dir, "config.json")) as f:
        config = json.load(f)
    assert config["model_type"] == "samba" and config["mixer_backend"] == "mamba2"
    source = load_file(os.path.join(src_dir, "model.safetensors"))
    encoder = {rename(k): v for k, v in source.items() if not k.startswith(DECODER)}

    # Default montage: the target electrodes, in metres and in the frame of the
    # standard_1005 template of MNE, which is the frame of the weights
    chs_info = [
        {"ch_name": name, "kind": "eeg", "loc": np.r_[position, np.zeros(9)]}
        for name, position in zip(
            config["target_channel_names"], config["target_positions"]
        )
    ]
    model = SAMBA(
        n_outputs=2,
        chs_info=chs_info,
        n_times=N_TIMES[config["checkpoint_variant"]],
        sfreq=config["sampling_rate"],
        target_positions=config["target_positions"],
        base_channels=config["base_channels"],
        bottleneck_channels=config["bottleneck_channels"],
        d_state=config["d_state"],
        d_conv=config["d_conv"],
        expand=config["expand"],
        head_dim=config["head_dim"],
        cdse_hidden_dim=config["cdse_hidden_dim"],
    )
    # Every key of the encoder present, none left over
    model.encoder.load_state_dict(encoder, strict=True)

    model.save_pretrained(out_dir)
    # The safetensors file is the release: no pickle next to it
    pickle = os.path.join(out_dir, "pytorch_model.bin")
    if os.path.exists(pickle):
        os.remove(pickle)
    # The encoder only: the head is not pretrained
    weights = {
        k: v for k, v in model.state_dict().items() if not k.startswith("final_layer.")
    }
    save_file(weights, os.path.join(out_dir, "model.safetensors"), metadata={"format": "pt"})
```

</details>