File size: 3,876 Bytes
a483f90
 
 
 
dd1bc1a
 
 
 
 
 
 
 
a483f90
 
 
 
 
 
 
 
 
 
 
dd1bc1a
 
 
 
 
 
 
 
 
a483f90
 
dd1bc1a
 
 
 
 
 
 
 
a483f90
 
 
 
 
 
dd1bc1a
 
 
 
 
 
 
 
 
 
a483f90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1bc1a
 
a483f90
dd1bc1a
 
 
a483f90
dd1bc1a
a483f90
 
 
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
"""Convert ``checkpoint/geonirs_{base,large}.pt`` (GeoNIRS/GeoNIRS@81f8995) to braindecode's ``GeoNIRS``.

usage: python convert.py <geonirs_base.pt or geonirs_large.pt> <out_dir>

Unwraps the ``{"model", "config"}`` payload and builds the model from its
``config`` for the 30 s pretraining windows (150 samples at 5 Hz). It drops the
two pretraining decoders (``hbo_to_hbr_decoder``, ``hbr_to_hbo_decoder``),
renames the 6 keys of the compressor's feed-forward with the prefix pairs below,
loads the rest with ``strict=True`` and writes ``config.json`` and
``model.safetensors`` with ``GeoNIRS.save_pretrained``. No value is changed.
The release holds the encoder only: the head reads
``2 * n_latent_channels * n_patches * feature_dim`` features, so
``from_pretrained`` builds it for the caller's ``n_times`` and ``n_outputs``.
"""

import os
import sys

import torch
from safetensors.torch import save_file

from braindecode.models import GeoNIRS

# (authors' prefix, braindecode's prefix) of the keys that change name. The
# feed-forward of the compressor is a LayerNorm and the shared FeedForwardBlock
# (Linear, activation, Dropout, Linear). The other keys keep their names.
RENAMES = (
    ("channel_compressor.ffn.0.", "channel_compressor.ffn_norm."),
    ("channel_compressor.ffn.1.", "channel_compressor.ffn.0."),
    ("channel_compressor.ffn.4.", "channel_compressor.ffn.3."),
)
# The reconstruction decoders of the pretraining, not part of GeoNIRS
DECODERS = ("hbo_to_hbr_decoder.", "hbr_to_hbo_decoder.")


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


if __name__ == "__main__":
    src, out_dir = sys.argv[1:]
    payload = torch.load(src, map_location="cpu", weights_only=True)
    data, config = payload["config"]["data"], payload["config"]["model"]
    # braindecode's GeoNIRS has a 6-D geometry and one geometry layer
    assert config["geometry_dim"] == 6 and config["geometry_spatial_layers"] == 1
    # braindecode's projection_dims lists the inner widths: the blocks run over
    # (embed_dim, *projection_dims, feature_dim)
    widths = config["projection_dimensions"]
    assert widths[0] == config["embedding_dim"]
    assert widths[-1] == config["output_feature_dim"]
    encoder = {
        rename(k): v
        for k, v in payload["model"].items()
        if not k.startswith(DECODERS)
    }
    torch.manual_seed(0)
    model = GeoNIRS(
        n_chans=2,
        n_outputs=2,
        n_times=round(data["window_seconds"] * data["sampling_rate_hz"]),
        sfreq=data["sampling_rate_hz"],
        patch_size=data["patch_samples"],
        minimum_patch_valid_fraction=data["minimum_patch_valid_fraction"],
        embed_dim=config["embedding_dim"],
        depth=config["temporal_layers"],
        num_heads=config["num_heads"],
        mlp_ratio=config["mlp_ratio"],
        drop_prob=config["dropout"],
        geometry_hidden_dim=config["geometry_hidden_dim"],
        geometry_heads=config["geometry_heads"],
        n_latent_channels=config["num_latent_sources"],
        compressor_heads=config["spatial_heads"],
        feature_dim=config["output_feature_dim"],
        projection_dims=tuple(widths[1:-1]),
        time_embedding_init_std=config["time_embedding_init_std"],
    )
    # Every key of the encoder present, none left over; the head is new
    head = {k: v for k, v in model.state_dict().items() if k.startswith("final_layer.")}
    model.load_state_dict({**encoder, **head}, strict=True)
    model.save_pretrained(out_dir)
    # The safetensors file is the release: no pickle next to it
    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"), metadata={"format": "pt"})