File size: 3,741 Bytes
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 | """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"})
|