bruAristimunha commited on
Commit
4e6913e
·
verified ·
1 Parent(s): 2aebda4

Upload convert_diver1_weights.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. convert_diver1_weights.py +321 -0
convert_diver1_weights.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: Bruno Aristimunha <b.aristimunha@gmail.com>
2
+ # License: BSD (3-clause)
3
+ """Convert, check and publish the released DIVER-1 iEEG encoder on CPU.
4
+
5
+ Run from an editable Braindecode checkout with the ``hub`` extra installed::
6
+
7
+ python scripts/convert_diver1_weights.py \\
8
+ --checkpoint ieeg_pretrained_weights.pt \\
9
+ --reference-dir DIVER-1 --output-dir /tmp/diver1-converted
10
+
11
+ ``--checkpoint`` is ``weights/ieeg_pretrained_weights.pt`` of the official
12
+ repository. Its GitHub LFS object is no longer served, so download it from the
13
+ authors' Google Drive folder linked in their README; the SHA-256 below must
14
+ match. ``--reference-dir`` is a clone of the official repository at
15
+ ``REVISION``: its model runs on the same input as the converted port, and the
16
+ encoder features must agree within ``TOLERANCE``.
17
+
18
+ Add ``--push-to braindecode`` to upload the converted encoder with
19
+ :meth:`~braindecode.models.base.EEGModuleMixin.push_to_hub`, together with this
20
+ script, the MIT licence of the weights and a model card. The release holds
21
+ pretraining heads but no classification head, so the published files hold the
22
+ encoder alone and Braindecode initializes the head on load. Fine-tune it before
23
+ prediction.
24
+ """
25
+
26
+ import argparse
27
+ import hashlib
28
+ import json
29
+ import shutil
30
+ import sys
31
+ import types
32
+ from contextlib import contextmanager
33
+ from pathlib import Path
34
+
35
+ import mne
36
+ import numpy as np
37
+ import torch
38
+ from torch import nn
39
+
40
+ from braindecode.models import DIVER1
41
+
42
+ REPOSITORY = "https://github.com/DIVER-Project/DIVER-1"
43
+ REVISION = "25638eb38ef297b582ab79ae1c96260f57c155b3"
44
+ CHECKPOINT = "weights/ieeg_pretrained_weights.pt"
45
+ SHA256 = "b812093779fb5cf1b76e18f8307df4136b67b008b6cd94c6be75fa286a87864c"
46
+ DRIVE = "https://drive.google.com/drive/folders/1Wmv36jifjE0Jj6noGOFFsqRzK-4xnj1b"
47
+ REPO_NAME = "DIVER-1-0.1s-tiny"
48
+ # DIVER-1-0.1s Tiny: scripts/finetune_neuroprobe.sh (width 256, depth 12, patch
49
+ # 50 at 500 Hz) in the official repository.
50
+ CONFIG = dict(sfreq=500.0, patch_size=50, d_model=256, n_layers=12, mup_attention=True)
51
+ TOLERANCE = 1e-4
52
+ RENAMES = {
53
+ "token_manager.special_tokens.N_token.param": "patch_register",
54
+ "token_manager.special_tokens.C_token.param": "chan_register",
55
+ "token_manager.special_tokens.NC_token.param": "global_register",
56
+ "embedding.2.embedding.embedding2.models.0.embedding.weight": "chan_emb.type_emb.weight",
57
+ "embedding.2.embedding.embedding2.models.1.embedding.weight": "chan_emb.subtype_emb.weight",
58
+ }
59
+ PREFIXES = (
60
+ ("var_attn_bias.emb.weight", "channel_bias.weight"),
61
+ ("embedding.0.proj_in.", "patch_cnn.proj_in."),
62
+ ("embedding.1.embedding.spectral_proj.", "spectral_emb.spectral_proj."),
63
+ ("embedding.3.embedding.0.module.", "stcpe.down."),
64
+ ("embedding.3.embedding.2.module.", "stcpe.up."),
65
+ ("embedding.3.embedding.1.model.encoder.", "stcpe.encoder."),
66
+ ("encoder.encoder.", "encoder."),
67
+ )
68
+ # Pretraining-only tensors: the mask token and the reconstruction heads.
69
+ DROPPED = ("mask_encoding", "heads.")
70
+ LICENSE = """MIT License
71
+
72
+ Copyright (c) 2026 DIVER Project
73
+
74
+ Permission is hereby granted, free of charge, to any person obtaining a copy
75
+ of this software and associated documentation files (the "Software"), to deal
76
+ in the Software without restriction, including without limitation the rights
77
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
78
+ copies of the Software, and to permit persons to whom the Software is
79
+ furnished to do so, subject to the following conditions:
80
+
81
+ The above copyright notice and this permission notice shall be included in all
82
+ copies or substantial portions of the Software.
83
+
84
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
85
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
86
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
87
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
88
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
89
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
90
+ SOFTWARE.
91
+ """
92
+
93
+
94
+ def sha256(path):
95
+ digest = hashlib.sha256()
96
+ with open(path, "rb") as f:
97
+ for block in iter(lambda: f.read(1 << 20), b""):
98
+ digest.update(block)
99
+ return digest.hexdigest()
100
+
101
+
102
+ def rename(key):
103
+ """Braindecode name of a released tensor, or ``None`` if it is dropped."""
104
+ if key in RENAMES:
105
+ return RENAMES[key]
106
+ if key.startswith(DROPPED):
107
+ return None
108
+ for old, new in PREFIXES:
109
+ key = key.replace(old, new)
110
+ return key
111
+
112
+
113
+ def convert_weights(state, model):
114
+ """Load the released encoder into ``model``; its head keeps its own init."""
115
+ mapped = {rename(k): v.float() for k, v in state.items() if rename(k) is not None}
116
+ head = {k: v for k, v in model.state_dict().items() if k.startswith("final_layer.")}
117
+ model.load_state_dict({**mapped, **head}, strict=True)
118
+ return mapped
119
+
120
+
121
+ def load_reference(reference_dir):
122
+ """The official DIVER class, with stubs for its annotation-only imports."""
123
+ for name, attrs in (("jaxtyping", ("Float", "Int", "Bool")), ("mup", ())):
124
+ if name not in sys.modules:
125
+ module = types.ModuleType(name)
126
+ for attr in attrs:
127
+ setattr(module, attr, type("_Any", (), {"__class_getitem__": classmethod(lambda c, i: object)}))
128
+ sys.modules[name] = module
129
+ # MuReadout is only used by the pretraining heads, which are dropped.
130
+ sys.modules["mup"].MuReadout = type("MuReadout", (nn.Linear,), {
131
+ "__init__": lambda self, i, o, output_mult=1.0, **kw: nn.Linear.__init__(self, i, o)
132
+ })
133
+ sys.path.insert(0, str(reference_dir))
134
+ from models.diver import DIVER
135
+
136
+ return DIVER
137
+
138
+
139
+ def check_against_reference(state, reference_dir, n_times, n_chans=6, batch=3):
140
+ """Largest encoder-feature difference between the port and the reference."""
141
+ reference = load_reference(reference_dir)(
142
+ d_model=CONFIG["d_model"], e_layer=CONFIG["n_layers"], mup=True,
143
+ patch_size=CONFIG["patch_size"],
144
+ )
145
+ reference.load_state_dict({k: v.float() for k, v in state.items()}, strict=False)
146
+ for module in reference.modules():
147
+ # The reference keeps attention dropout active in eval mode.
148
+ if hasattr(module, "attn_dropout_p"):
149
+ module.attn_dropout_p = 0.0
150
+ reference.eval()
151
+ rng = np.random.default_rng(0)
152
+ xyz_mm = torch.tensor(rng.uniform(-60, 60, size=(n_chans, 3)), dtype=torch.float32)
153
+ chs = mne.create_info([f"C{i}" for i in range(n_chans)], CONFIG["sfreq"], "seeg")["chs"]
154
+ for ch, xyz in zip(chs, xyz_mm):
155
+ ch["loc"][:3] = (xyz / 1e3).numpy() # MNE metres; the reference takes millimetres
156
+ model = DIVER1(chs_info=chs, n_times=n_times, n_outputs=2, **CONFIG).eval()
157
+ convert_weights(state, model)
158
+ x = torch.randn(batch, n_chans, n_times)
159
+ info = [{"xyz_id": xyz_mm, "modality": "iEEG", "coord_subtype": ["depth"] * n_chans}] * batch
160
+ with torch.no_grad():
161
+ expected = reference(x, data_info_list=info, use_mask=False)[
162
+ "token_manager_output"]["org_x_position_features"]
163
+ features = {}
164
+ handle = model.final_layer.register_forward_hook(
165
+ lambda m, args, out: features.setdefault("x", args[0])
166
+ )
167
+ try:
168
+ with torch.no_grad():
169
+ model(x)
170
+ finally:
171
+ handle.remove()
172
+ got = features["x"].reshape(expected.shape)
173
+ return (got - expected).abs().max().item()
174
+
175
+
176
+ @contextmanager
177
+ def without_head(model):
178
+ """Hide the untrained classifier so only encoder tensors get serialized."""
179
+ head, model.final_layer = model.final_layer, nn.Identity()
180
+ try:
181
+ yield
182
+ finally:
183
+ model.final_layer = head
184
+
185
+
186
+ def model_card(report):
187
+ return f"""---
188
+ library_name: braindecode
189
+ license: mit
190
+ pipeline_tag: feature-extraction
191
+ tags:
192
+ - braindecode
193
+ - DIVER-1
194
+ - ieeg
195
+ - seeg
196
+ - foundation-model
197
+ - pytorch_model_hub_mixin
198
+ ---
199
+
200
+ # DIVER-1, 0.1 s Tiny (iEEG)
201
+
202
+ The released iEEG encoder of [Han et al. (2025)](https://arxiv.org/abs/2512.19097),
203
+ DIVER-1-0.1s Tiny (12.7M parameters, patches of 0.1 s at 500 Hz), converted to
204
+ [`braindecode.models.DIVER1`](https://braindecode.org/stable/generated/braindecode.models.DIVER1.html).
205
+
206
+ Source: `{CHECKPOINT}` of [DIVER-Project/DIVER-1]({REPOSITORY}/tree/{REVISION}),
207
+ sha256 `{SHA256}` (the GitHub LFS object is no longer served; the same file is in
208
+ the authors' [Google Drive folder]({DRIVE})). Conversion casts the bfloat16
209
+ tensors to float32, renames them and drops the pretraining-only mask token and
210
+ reconstruction heads; `convert_diver1_weights.py` in this repository reproduces
211
+ it. Encoder features match the official model to {report["max_abs_diff"]:.1e} in
212
+ float32 on CPU, with muP attention scaling (`mup_attention=True`).
213
+
214
+ ## Usage
215
+
216
+ Resample to 500 Hz and pass the electrode positions in `chs_info` (metres, as in MNE):
217
+
218
+ ```python
219
+ import torch
220
+ from braindecode.models import DIVER1
221
+
222
+ model = DIVER1.from_pretrained(
223
+ "braindecode/{REPO_NAME}", chs_info=raw.info["chs"], n_times=500, n_outputs=2
224
+ )
225
+ logits = model(torch.randn(8, len(raw.ch_names), 500))
226
+ ```
227
+
228
+ `n_times` must be a multiple of 50. The saved geometry is {report["n_chans"]}
229
+ channels and {report["n_times"]} samples; the encoder does not depend on it, so
230
+ pass your own montage, `n_times` and `n_outputs` when loading.
231
+
232
+ ## Limitations
233
+
234
+ These files hold the encoder only; the release has no classification head.
235
+ Braindecode initializes the head on load, so it needs fine-tuning, as in the
236
+ paper's protocol (`scripts/finetune_neuroprobe.sh`). The check above covers
237
+ float32 CPU encoder features, not downstream accuracy, GPU kernels or mixed
238
+ precision.
239
+
240
+ ## Citation
241
+
242
+ ```bibtex
243
+ @article{{han2025diver,
244
+ title={{DIVER-1: Scaling intracranial EEG foundation models for transferable representations}},
245
+ author={{Han, Danny Dongyeop and Gwon, Yonghyeon and Lee, Ahhyun Lucy and Lee, Taeyang and Lee, Seong Jin and Choi, Jubin and Lee, Sebin and Bang, Jihyun and Lee, Seungju and Park, David Keetae and Yoo, Shinjae and Chung, Chun Kee and Cha, Jiook}},
246
+ journal={{arXiv preprint arXiv:2512.19097}},
247
+ year={{2025}}
248
+ }}
249
+ ```
250
+
251
+ ## License
252
+
253
+ The weights are released by the DIVER Project under the MIT licence (`LICENSE`).
254
+ Braindecode's code is BSD-3-Clause.
255
+ """
256
+
257
+
258
+ def main():
259
+ parser = argparse.ArgumentParser(description=__doc__)
260
+ parser.add_argument("--checkpoint", type=Path, required=True)
261
+ parser.add_argument("--reference-dir", type=Path, required=True)
262
+ parser.add_argument("--output-dir", type=Path, required=True)
263
+ parser.add_argument("--n-chans", type=int, default=6)
264
+ parser.add_argument("--n-times", type=int, default=500)
265
+ parser.add_argument("--n-outputs", type=int, default=2)
266
+ parser.add_argument("--push-to", help="Hub namespace to publish the model to")
267
+ args = parser.parse_args()
268
+ torch.set_num_threads(1)
269
+ torch.manual_seed(0)
270
+ if sha256(args.checkpoint) != SHA256:
271
+ raise SystemExit(f"{args.checkpoint} is not the released checkpoint (sha256 mismatch)")
272
+ state = torch.load(args.checkpoint, map_location="cpu", weights_only=True)["module"]
273
+ state = {k: v for k, v in state.items() if torch.is_tensor(v)}
274
+ max_abs_diff = check_against_reference(
275
+ state, args.reference_dir, args.n_times, n_chans=args.n_chans
276
+ )
277
+ if max_abs_diff > TOLERANCE:
278
+ raise SystemExit(f"encoder features differ by {max_abs_diff:.2e} > {TOLERANCE}")
279
+ # A placeholder montage without positions: users pass their own chs_info
280
+ # when loading, and the encoder weights do not depend on it.
281
+ chs = mne.create_info([f"C{i}" for i in range(args.n_chans)], CONFIG["sfreq"], "seeg")["chs"]
282
+ model = DIVER1(
283
+ chs_info=chs, n_times=args.n_times, n_outputs=args.n_outputs, **CONFIG
284
+ ).eval()
285
+ mapped = convert_weights(state, model)
286
+ report = {
287
+ "source": f"{REPOSITORY}@{REVISION}:{CHECKPOINT}",
288
+ "sha256": SHA256,
289
+ "tensors_loaded": len(mapped),
290
+ "tensors_dropped": sorted(k for k in state if rename(k) is None),
291
+ "max_abs_diff": max_abs_diff,
292
+ "n_chans": args.n_chans,
293
+ "n_times": args.n_times,
294
+ "torch_version": torch.__version__,
295
+ }
296
+ print(json.dumps(report, indent=2))
297
+ destination = args.output_dir / REPO_NAME
298
+ destination.mkdir(parents=True, exist_ok=True)
299
+ with without_head(model):
300
+ model.save_pretrained(destination)
301
+ shutil.copyfile(Path(__file__).resolve(), destination / Path(__file__).name)
302
+ (destination / "LICENSE").write_text(LICENSE)
303
+ (destination / "report.json").write_text(json.dumps(report, indent=2))
304
+ # Written last: save_pretrained leaves a placeholder card behind.
305
+ (destination / "README.md").write_text(model_card(report))
306
+ if args.push_to:
307
+ from huggingface_hub import HfApi
308
+
309
+ repo_id = f"{args.push_to}/{REPO_NAME}"
310
+ with without_head(model):
311
+ model.push_to_hub(repo_id)
312
+ api = HfApi()
313
+ for name in ("README.md", "LICENSE", "report.json", Path(__file__).name):
314
+ api.upload_file(
315
+ path_or_fileobj=str(destination / name), path_in_repo=name, repo_id=repo_id
316
+ )
317
+ print(f"published https://huggingface.co/{repo_id}")
318
+
319
+
320
+ if __name__ == "__main__":
321
+ main()