File size: 1,563 Bytes
812892c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Convert ``checkpoint/jung_mae.pt`` (GeoNIRS/GeoNIRS@81f8995) to braindecode's ``JungMAE``.

usage: python convert.py <jung_mae.pt> <out_dir>

Unwraps the ``{"model", "model_config", ...}`` payload (its configuration equals
the class defaults), drops the pretraining decoder (input projection, mask token,
layers, prediction layer) and writes ``config.json`` and ``model.safetensors``
with ``JungMAE.save_pretrained`` for the paper's 40 channels of 60 samples at
5 Hz. The release holds the encoder only: the head reads ``C * P * D`` features,
so ``from_pretrained`` builds it for the caller's montage and ``n_outputs``.
"""

import os
import sys

import torch
from safetensors.torch import save_file

from braindecode.models import JungMAE

DECODER = ("decoder_embed.", "mask_token", "decoder.", "prediction.")

if __name__ == "__main__":
    src, out_dir = sys.argv[1:]
    payload = torch.load(src, map_location="cpu", weights_only=True)
    encoder = {k: v for k, v in payload["model"].items() if not k.startswith(DECODER)}
    torch.manual_seed(0)
    model = JungMAE(n_chans=40, n_outputs=2, n_times=60, sfreq=5.0)
    missing, unexpected = model.load_state_dict(encoder, strict=False)
    assert not unexpected, unexpected
    assert all(key.startswith("final_layer.") for key in missing), missing
    model.save_pretrained(out_dir)
    os.remove(os.path.join(out_dir, "pytorch_model.bin"))
    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"))