bruAristimunha commited on
Commit
dd1bc1a
·
verified ·
1 Parent(s): a483f90

Rename the 6 channel-compressor keys (ffn_norm, FeedForwardBlock) and list projection_dims as the inner widths (braindecode#1748)

Browse files
Files changed (4) hide show
  1. README.md +46 -3
  2. config.json +7 -3
  3. convert.py +41 -11
  4. model.safetensors +2 -2
README.md CHANGED
@@ -45,9 +45,37 @@ marks a missing sample.
45
  ## Changes from the original release
46
 
47
  `convert.py` unwraps the `{"model", "config"}` payload, builds the model from its `config`, drops
48
- the two pretraining decoders (`hbo_to_hbr_decoder`, `hbr_to_hbo_decoder`) and writes the encoder
49
- with `save_pretrained`. No value is changed: the encoder gives the features of the original file
50
- bit for bit on CPU in float32.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  ## Evaluation
53
 
@@ -75,3 +103,18 @@ The source repository has no licence file; the weights are by the GeoNIRS author
75
  year = {2026},
76
  }
77
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  ## Changes from the original release
46
 
47
  `convert.py` unwraps the `{"model", "config"}` payload, builds the model from its `config`, drops
48
+ the two pretraining decoders (`hbo_to_hbr_decoder`, `hbr_to_hbo_decoder`: 122 of the 333
49
+ tensors), renames 6 tensors of the channel compressor and writes the encoder with `save_pretrained`.
50
+ The renames are plain prefix replacements: braindecode builds the compressor's feed-forward block from
51
+ a LayerNorm (`ffn_norm`) and its shared `FeedForwardBlock` (Linear, activation, dropout, Linear).
52
+
53
+ | original key | this repository | keys |
54
+ |---|---|---|
55
+ | `channel_compressor.ffn.0.{weight,bias}` (LayerNorm) | `channel_compressor.ffn_norm.{weight,bias}` | 2 |
56
+ | `channel_compressor.ffn.1.{weight,bias}` (Linear) | `channel_compressor.ffn.0.{weight,bias}` | 2 |
57
+ | `channel_compressor.ffn.4.{weight,bias}` (Linear) | `channel_compressor.ffn.3.{weight,bias}` | 2 |
58
+
59
+ The other 205 keys keep their names. `config.json` lists `projection_dims=[128, 96]`, the inner
60
+ widths of the chromophore projections: they run over `(embed_dim, *projection_dims, feature_dim)`, which is
61
+ the `projection_dimensions` `[192, 128, 96, 64]` of the original config. It also lists, at their defaults, the
62
+ numbers the original code fixes: `geometry_mlp_ratio` and `compressor_mlp_ratio` (2.0), `geometry_scale`
63
+ (0.02546058255683924, that is 25.46 mm), `time_embedding_init_std` and `latent_init_std` (0.02) and
64
+ `residual_init_scale` (0.1).
65
+
66
+ No value is changed: each of the 211 tensors is bitwise equal to its tensor in the original file (the six
67
+ renamed ones under their new names). This layout replaces revision `a483f904`, which holds the same
68
+ tensors under the authors' names.
69
+
70
+ ## Verification
71
+
72
+ `GeoNIRS.from_pretrained` on these files (braindecode `32850d0b`) against braindecode's `GeoNIRS` on
73
+ revision `a483f904` (master before the renames, `252a0172`), on CPU and the same seeded inputs: the pinned
74
+ input, a batch with NaN samples and a `ch_mask`, `pool="mean_std"` at 60 samples, MNE-ordered `chs_info`
75
+ and an explicit `geometry`. In float32 and in float64 the features, the outputs (same head), the tokens
76
+ and their validity, and the features and outputs in train mode under one seed (the dropout draws) are
77
+ bitwise equal: 60 of 60 comparisons, max abs difference 0.0. A change of 1e-3 in one value of each renamed
78
+ tensor shows as a difference of 1e-5 or more in the features.
79
 
80
  ## Evaluation
81
 
 
103
  year = {2026},
104
  }
105
  ```
106
+
107
+ ## Conversion
108
+
109
+ `convert.py` (in this repository) was run with braindecode at `32850d0b`:
110
+
111
+ ```
112
+ python convert.py geonirs_base.pt <out_dir>
113
+ ```
114
+
115
+ | file | sha256 |
116
+ |---|---|
117
+ | `model.safetensors` | `b60b1a7851ee762881ca4d0467a52c4383c9fa38642e28e0138d541df50dbb63` |
118
+ | `config.json` | `d3254e64e487566cd1f33fc3fe833973ddd08201066ca11e6329d1ea4ba7e0e5` |
119
+ | `convert.py` | `6e0e62f7f26b00143fed34aef3e6f95961598971df0fa66013654cf55747f8a5` |
120
+ | original `checkpoint/geonirs_base.pt` (GeoNIRS/GeoNIRS@81f8995, Git LFS) | `61e4d72221dd99225ac405124515c070a2ef0467df83a01f05e918e0941cd06a` |
config.json CHANGED
@@ -14,14 +14,15 @@
14
  "mlp_ratio": 4.0,
15
  "geometry_hidden_dim": 192,
16
  "geometry_heads": 8,
 
 
17
  "n_latent_channels": 16,
18
  "compressor_heads": 8,
 
19
  "feature_dim": 64,
20
  "projection_dims": [
21
- 192,
22
  128,
23
- 96,
24
- 64
25
  ],
26
  "use_channel_geometry": true,
27
  "pool": "flatten",
@@ -30,5 +31,8 @@
30
  "head_drop_prob": 0.1,
31
  "minimum_patch_valid_fraction": 0.8,
32
  "activation": "torch.nn.modules.activation.GELU",
 
 
 
33
  "braindecode_version": "2.1.0dev0"
34
  }
 
14
  "mlp_ratio": 4.0,
15
  "geometry_hidden_dim": 192,
16
  "geometry_heads": 8,
17
+ "geometry_mlp_ratio": 2.0,
18
+ "geometry_scale": 0.02546058255683924,
19
  "n_latent_channels": 16,
20
  "compressor_heads": 8,
21
+ "compressor_mlp_ratio": 2.0,
22
  "feature_dim": 64,
23
  "projection_dims": [
 
24
  128,
25
+ 96
 
26
  ],
27
  "use_channel_geometry": true,
28
  "pool": "flatten",
 
31
  "head_drop_prob": 0.1,
32
  "minimum_patch_valid_fraction": 0.8,
33
  "activation": "torch.nn.modules.activation.GELU",
34
+ "time_embedding_init_std": 0.02,
35
+ "latent_init_std": 0.02,
36
+ "residual_init_scale": 0.1,
37
  "braindecode_version": "2.1.0dev0"
38
  }
convert.py CHANGED
@@ -2,12 +2,14 @@
2
 
3
  usage: python convert.py <geonirs_base.pt or geonirs_large.pt> <out_dir>
4
 
5
- Unwraps the ``{"model", "config"}`` payload, builds the model from its
6
- ``config`` for the 30 s pretraining windows (150 samples at 5 Hz), drops the
7
- two pretraining decoders (``hbo_to_hbr_decoder``, ``hbr_to_hbo_decoder``) and
8
- writes ``config.json`` and ``model.safetensors`` with
9
- ``GeoNIRS.save_pretrained``. The release holds the encoder only: the head
10
- reads ``2 * n_latent_channels * n_patches * feature_dim`` features, so
 
 
11
  ``from_pretrained`` builds it for the caller's ``n_times`` and ``n_outputs``.
12
  """
13
 
@@ -19,15 +21,41 @@ from safetensors.torch import save_file
19
 
20
  from braindecode.models import GeoNIRS
21
 
 
 
 
 
 
 
 
 
 
22
  DECODERS = ("hbo_to_hbr_decoder.", "hbr_to_hbo_decoder.")
23
 
 
 
 
 
 
 
 
 
24
  if __name__ == "__main__":
25
  src, out_dir = sys.argv[1:]
26
  payload = torch.load(src, map_location="cpu", weights_only=True)
27
  data, config = payload["config"]["data"], payload["config"]["model"]
28
  # braindecode's GeoNIRS has a 6-D geometry and one geometry layer
29
  assert config["geometry_dim"] == 6 and config["geometry_spatial_layers"] == 1
30
- encoder = {k: v for k, v in payload["model"].items() if not k.startswith(DECODERS)}
 
 
 
 
 
 
 
 
 
31
  torch.manual_seed(0)
32
  model = GeoNIRS(
33
  n_chans=2,
@@ -46,12 +74,14 @@ if __name__ == "__main__":
46
  n_latent_channels=config["num_latent_sources"],
47
  compressor_heads=config["spatial_heads"],
48
  feature_dim=config["output_feature_dim"],
49
- projection_dims=tuple(config["projection_dimensions"]),
 
50
  )
51
- missing, unexpected = model.load_state_dict(encoder, strict=False)
52
- assert not unexpected, unexpected
53
- assert all(key.startswith("final_layer.") for key in missing), missing
54
  model.save_pretrained(out_dir)
 
55
  os.remove(os.path.join(out_dir, "pytorch_model.bin"))
56
  weights = {k: v for k, v in model.state_dict().items() if not k.startswith("final_layer.")}
57
  save_file(weights, os.path.join(out_dir, "model.safetensors"), metadata={"format": "pt"})
 
2
 
3
  usage: python convert.py <geonirs_base.pt or geonirs_large.pt> <out_dir>
4
 
5
+ Unwraps the ``{"model", "config"}`` payload and builds the model from its
6
+ ``config`` for the 30 s pretraining windows (150 samples at 5 Hz). It drops the
7
+ two pretraining decoders (``hbo_to_hbr_decoder``, ``hbr_to_hbo_decoder``),
8
+ renames the 6 keys of the compressor's feed-forward with the prefix pairs below,
9
+ loads the rest with ``strict=True`` and writes ``config.json`` and
10
+ ``model.safetensors`` with ``GeoNIRS.save_pretrained``. No value is changed.
11
+ The release holds the encoder only: the head reads
12
+ ``2 * n_latent_channels * n_patches * feature_dim`` features, so
13
  ``from_pretrained`` builds it for the caller's ``n_times`` and ``n_outputs``.
14
  """
15
 
 
21
 
22
  from braindecode.models import GeoNIRS
23
 
24
+ # (authors' prefix, braindecode's prefix) of the keys that change name. The
25
+ # feed-forward of the compressor is a LayerNorm and the shared FeedForwardBlock
26
+ # (Linear, activation, Dropout, Linear). The other keys keep their names.
27
+ RENAMES = (
28
+ ("channel_compressor.ffn.0.", "channel_compressor.ffn_norm."),
29
+ ("channel_compressor.ffn.1.", "channel_compressor.ffn.0."),
30
+ ("channel_compressor.ffn.4.", "channel_compressor.ffn.3."),
31
+ )
32
+ # The reconstruction decoders of the pretraining, not part of GeoNIRS
33
  DECODERS = ("hbo_to_hbr_decoder.", "hbr_to_hbo_decoder.")
34
 
35
+
36
+ def rename(key):
37
+ for old, new in RENAMES:
38
+ if key.startswith(old):
39
+ return new + key[len(old) :]
40
+ return key
41
+
42
+
43
  if __name__ == "__main__":
44
  src, out_dir = sys.argv[1:]
45
  payload = torch.load(src, map_location="cpu", weights_only=True)
46
  data, config = payload["config"]["data"], payload["config"]["model"]
47
  # braindecode's GeoNIRS has a 6-D geometry and one geometry layer
48
  assert config["geometry_dim"] == 6 and config["geometry_spatial_layers"] == 1
49
+ # braindecode's projection_dims lists the inner widths: the blocks run over
50
+ # (embed_dim, *projection_dims, feature_dim)
51
+ widths = config["projection_dimensions"]
52
+ assert widths[0] == config["embedding_dim"]
53
+ assert widths[-1] == config["output_feature_dim"]
54
+ encoder = {
55
+ rename(k): v
56
+ for k, v in payload["model"].items()
57
+ if not k.startswith(DECODERS)
58
+ }
59
  torch.manual_seed(0)
60
  model = GeoNIRS(
61
  n_chans=2,
 
74
  n_latent_channels=config["num_latent_sources"],
75
  compressor_heads=config["spatial_heads"],
76
  feature_dim=config["output_feature_dim"],
77
+ projection_dims=tuple(widths[1:-1]),
78
+ time_embedding_init_std=config["time_embedding_init_std"],
79
  )
80
+ # Every key of the encoder present, none left over; the head is new
81
+ head = {k: v for k, v in model.state_dict().items() if k.startswith("final_layer.")}
82
+ model.load_state_dict({**encoder, **head}, strict=True)
83
  model.save_pretrained(out_dir)
84
+ # The safetensors file is the release: no pickle next to it
85
  os.remove(os.path.join(out_dir, "pytorch_model.bin"))
86
  weights = {k: v for k, v in model.state_dict().items() if not k.startswith("final_layer.")}
87
  save_file(weights, os.path.join(out_dir, "model.safetensors"), metadata={"format": "pt"})
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0ce95f5b3ebcb1060a91b4e993dce0cc4914ff6cd06d27315675f65844c6c73d
3
- size 17798072
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b60b1a7851ee762881ca4d0467a52c4383c9fa38642e28e0138d541df50dbb63
3
+ size 17798088