Randyhan commited on
Commit
349db7d
·
verified ·
1 Parent(s): f6c2ba5

Add download_weights.py

Browse files
Files changed (1) hide show
  1. download_weights.py +440 -0
download_weights.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """GraphMem 模型权重来源登记与恢复工具。
3
+
4
+ 权重本身不随项目上传 HuggingFace,全部登记在 weights_manifest.json 中。
5
+ 模式:
6
+ verify 检查项目内 / 备份目录中的权重是否齐全、大小是否正确(默认)
7
+ list 打印每组权重的来源
8
+ manifest 重新生成 weights_manifest.json(含原路径、来源 URL、字节数)
9
+ stash 上传前把项目内权重移动到备份目录(同盘 rename,零额外空间)
10
+ restore 从备份目录恢复到项目内(默认硬链接,秒级、零额外空间)
11
+ download 按登记的开源来源重新下载到项目内(换机器 / 无备份时使用)
12
+
13
+ 示例:
14
+ python download_weights.py --mode verify
15
+ python download_weights.py --mode stash
16
+ python download_weights.py --mode restore
17
+ python download_weights.py --mode download --only echo-wm --jobs 2
18
+ python download_weights.py --mode download --token hf_xxx # gemma-3 为 gated 仓库
19
+ python download_weights.py --mode list --only WorldKV
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import errno
26
+ import json
27
+ import os
28
+ import shutil
29
+ import signal
30
+ import subprocess
31
+ import sys
32
+ from concurrent.futures import ThreadPoolExecutor, as_completed
33
+ from datetime import datetime, timezone
34
+ from pathlib import Path
35
+ from urllib.parse import quote
36
+
37
+ try:
38
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
39
+ except (AttributeError, ValueError):
40
+ pass
41
+
42
+ ROOT = Path(__file__).resolve().parent
43
+ DEFAULT_BACKUP = ROOT.parent / "checkpoint-backup"
44
+ MANIFEST = ROOT / "weights_manifest.json"
45
+ HF_BASE = "https://huggingface.co"
46
+ DINO_BASE = "https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/"
47
+ DREAMSIM_ZIP = (
48
+ "https://github.com/ssundaram21/dreamsim/releases/"
49
+ "download/v0.2.0-checkpoints/dreamsim_ensemble_checkpoint.zip"
50
+ )
51
+
52
+
53
+ def shards(prefix: str, total: int, suffix: str = "safetensors") -> list[str]:
54
+ return [f"{prefix}{i:05d}-of-{total:05d}.{suffix}" for i in range(1, total + 1)]
55
+
56
+
57
+ def named(*names: str) -> list[dict]:
58
+ return [{"name": n} for n in names]
59
+
60
+
61
+ GROUPS: list[dict] = [
62
+ {
63
+ "id": "echo-wm",
64
+ "project": "JoyAI-Echo",
65
+ "target": "JoyAI-Echo/echo_wm/checkpoints",
66
+ "source": {"type": "hf", "repo": "Echo-Team/Echo-WM", "revision": "main"},
67
+ "note": "官方命令: hf download Echo-Team/Echo-WM --local-dir checkpoints",
68
+ "files": named("echo-wm-base.safetensors", "echo-wm-flash.safetensors"),
69
+ },
70
+ {
71
+ "id": "echo-wm-gemma",
72
+ "project": "JoyAI-Echo",
73
+ "target": "JoyAI-Echo/echo_wm/checkpoints/gemma-3",
74
+ "source": {
75
+ "type": "hf",
76
+ "repo": "google/gemma-3-12b-it-qat-q4_0-unquantized",
77
+ "revision": "main",
78
+ "gated": True,
79
+ },
80
+ "note": "gated 仓库,需同意许可并传 --token;必须用 unquantized 版本",
81
+ "files": named(*shards("model-", 5), "tokenizer.model"),
82
+ },
83
+ {
84
+ "id": "lingbot-v2",
85
+ "project": "lingbot-world-v2",
86
+ "target": "lingbot-world-v2/ckpt",
87
+ "source": {
88
+ "type": "hf",
89
+ "repo": "robbyant/lingbot-world-v2-14b-causal-fast",
90
+ "revision": "main",
91
+ },
92
+ "note": "官方命令: huggingface-cli download robbyant/lingbot-world-v2-14b-causal-fast --local-dir ./ckpt",
93
+ "files": named(
94
+ "models_t5_umt5-xxl-enc-bf16.pth",
95
+ "Wan2.1_VAE.pth",
96
+ "google/umt5-xxl/spiece.model",
97
+ *[f"transformers/{n}" for n in shards("model-", 8)],
98
+ ),
99
+ },
100
+ {
101
+ "id": "worldkv-base-cam",
102
+ "project": "WorldKV",
103
+ "target": "WorldKV/lingbot-world-base-cam",
104
+ "source": {"type": "hf", "repo": "robbyant/lingbot-world-base-cam", "revision": "main"},
105
+ "note": "官方命令: huggingface-cli download robbyant/lingbot-world-base-cam --local-dir ./lingbot-world-base-cam",
106
+ "files": named(
107
+ "models_t5_umt5-xxl-enc-bf16.pth",
108
+ "Wan2.1_VAE.pth",
109
+ "google/umt5-xxl/spiece.model",
110
+ *[f"high_noise_model/{n}" for n in shards("diffusion_pytorch_model-", 8)],
111
+ *[f"low_noise_model/{n}" for n in shards("diffusion_pytorch_model-", 8)],
112
+ ),
113
+ },
114
+ {
115
+ "id": "worldkv-fast",
116
+ "project": "WorldKV",
117
+ "target": "WorldKV/lingbot-world-base-cam/lingbot_world_fast",
118
+ "source": {"type": "hf", "repo": "robbyant/lingbot-world-fast", "revision": "main"},
119
+ "note": "官方命令: huggingface-cli download robbyant/lingbot-world-fast --local-dir ./lingbot-world-base-cam/lingbot_world_fast",
120
+ "files": named(*shards("model-", 16)),
121
+ },
122
+ {
123
+ "id": "dymemv2-cotracker",
124
+ "project": "dymemv2",
125
+ "target": "dymemv2/evaluation/models/checkpoints",
126
+ "source": {"type": "hf", "repo": "facebook/cotracker", "revision": "main"},
127
+ "note": "VBench 轨迹评估: wget https://huggingface.co/facebook/cotracker/resolve/main/cotracker2.pth",
128
+ "files": named("cotracker2.pth"),
129
+ },
130
+ {
131
+ "id": "dymemv2-dino",
132
+ "project": "dymemv2",
133
+ "target": "dymemv2/evaluation/models/checkpoints",
134
+ "source": {"type": "direct", "base": DINO_BASE},
135
+ "note": "DINO 官方 ViT-B/16 预训练权重(VBench subject consistency 用)",
136
+ "files": named("dino_vitbase16_pretrain.pth"),
137
+ },
138
+ {
139
+ "id": "dymemv2-dreamsim",
140
+ "project": "dymemv2",
141
+ "target": "dymemv2/evaluation/models",
142
+ "source": {"type": "hf", "repo": "meituan-longcat/WBench-weights", "revision": "main"},
143
+ "note": "DreamSim ensemble 权重;官方原始包为 GitHub release v0.2.0-checkpoints/dreamsim_ensemble_checkpoint.zip",
144
+ "files": [
145
+ {"name": "clip_vitb16_pretrain.pth.tar", "src": "dreamsim/clip_vitb16_pretrain.pth.tar"},
146
+ {"name": "open_clip_vitb16_pretrain.pth.tar", "src": "dreamsim/open_clip_vitb16_pretrain.pth.tar"},
147
+ {"name": "dino_vitb16_pretrain.pth", "src": "dreamsim/dino_vitb16_pretrain.pth"},
148
+ {"name": "ensemble_lora/adapter_model.safetensors", "src": "dreamsim/ensemble_lora/adapter_model.safetensors"},
149
+ {"name": "pretrained.zip", "url": DREAMSIM_ZIP, "optional": True},
150
+ ],
151
+ },
152
+ {
153
+ "id": "dymemv2-i3d",
154
+ "project": "dymemv2",
155
+ "target": "dymemv2/evaluation/utils/weights",
156
+ "source": {"type": "hf", "repo": "Xiaodong/FVD_I3D", "revision": "main"},
157
+ "note": "VBench FVD 评估用 I3D 权重",
158
+ "files": named("i3d_pretrained_400.pt"),
159
+ },
160
+ {
161
+ "id": "dymemv2-nudenet",
162
+ "project": "dymemv2",
163
+ "target": "dymemv2/evaluation/VBench/vbench2_beta_trustworthiness/third_party/nudenet",
164
+ "source": {"type": "hf", "repo": "vladmandic/nudenet", "revision": "main"},
165
+ "note": "NudeNet ONNX 检测器,远端文件名 nudenet.onnx,本地名为 best.onnx",
166
+ "files": [{"name": "best.onnx", "src": "nudenet.onnx"}],
167
+ },
168
+ ]
169
+
170
+
171
+ def build_entries() -> list[dict]:
172
+ entries = []
173
+ for g in GROUPS:
174
+ src = g["source"]
175
+ gated = bool(src.get("gated"))
176
+ for f in g["files"]:
177
+ name = f["name"]
178
+ src_name = f.get("src", name)
179
+ url = f.get("url")
180
+ if url is None and src["type"] == "hf":
181
+ revision = src.get("revision", "main")
182
+ url = f"{HF_BASE}/{src['repo']}/resolve/{revision}/{quote(src_name, safe='/')}?download=true"
183
+ source_desc = f"huggingface:{src['repo']}@{revision}/{src_name}"
184
+ elif url is None and src["type"] == "direct":
185
+ url = src["base"] + quote(src_name, safe="/")
186
+ source_desc = f"url:{url}"
187
+ else:
188
+ source_desc = f"url:{url}"
189
+ entries.append(
190
+ {
191
+ "group": g["id"],
192
+ "project": g["project"],
193
+ "path": str(Path(g["target"]) / name),
194
+ "size": None,
195
+ "source": source_desc,
196
+ "url": url,
197
+ "gated": gated,
198
+ "optional": bool(f.get("optional", False)),
199
+ }
200
+ )
201
+ return entries
202
+
203
+
204
+ def human(n: float | int | None) -> str:
205
+ if n is None:
206
+ return "?"
207
+ n = float(n)
208
+ for unit in ("B", "KB", "MB", "GB", "TB"):
209
+ if n < 1024 or unit == "TB":
210
+ return f"{n:.1f}{unit}"
211
+ n /= 1024
212
+ return f"{n:.1f}TB"
213
+
214
+
215
+ def load_manifest() -> dict:
216
+ if not MANIFEST.exists():
217
+ return {}
218
+ try:
219
+ return json.loads(MANIFEST.read_text(encoding="utf-8"))
220
+ except (OSError, json.JSONDecodeError) as exc:
221
+ print(f"[warn] 无法读取 {MANIFEST}: {exc}", file=sys.stderr)
222
+ return {}
223
+
224
+
225
+ def with_sizes(entries: list[dict], backup: Path) -> list[dict]:
226
+ known = {f["path"]: f.get("size") for f in load_manifest().get("files", [])}
227
+ for e in entries:
228
+ for base in (ROOT, backup):
229
+ p = base / e["path"]
230
+ if p.is_file():
231
+ e["size"] = p.stat().st_size
232
+ break
233
+ else:
234
+ e["size"] = known.get(e["path"])
235
+ return entries
236
+
237
+
238
+ def selected(entries: list[dict], only: list[str]) -> list[dict]:
239
+ if not only:
240
+ return entries
241
+ keys = {k.lower() for k in only}
242
+ return [e for e in entries if e["group"].lower() in keys or e["project"].lower() in keys]
243
+
244
+
245
+ def status(p: Path, expected: int | None) -> tuple[bool, str]:
246
+ if not p.is_file():
247
+ return False, "missing"
248
+ size = p.stat().st_size
249
+ if expected and size != expected:
250
+ return False, f"size mismatch ({human(size)} != {human(expected)})"
251
+ return True, human(size)
252
+
253
+
254
+ def write_manifest(entries: list[dict], backup: Path) -> None:
255
+ groups = []
256
+ for g in GROUPS:
257
+ fs = [e for e in entries if e["group"] == g["id"]]
258
+ groups.append(
259
+ {
260
+ "id": g["id"],
261
+ "project": g["project"],
262
+ "target": g["target"],
263
+ "source": g["source"],
264
+ "note": g.get("note", ""),
265
+ "files": len(fs),
266
+ "bytes": sum(e["size"] or 0 for e in fs),
267
+ }
268
+ )
269
+ data = {
270
+ "generated": datetime.now(timezone.utc).isoformat(timespec="seconds"),
271
+ "project_root": "脚本所在目录(可整体搬迁)",
272
+ "default_backup_root": str(DEFAULT_BACKUP),
273
+ "backup_root_used": str(backup),
274
+ "total_files": len(entries),
275
+ "total_bytes": sum(e["size"] or 0 for e in entries),
276
+ "groups": groups,
277
+ "files": [
278
+ {**e, "backup_path": e["path"], "note": "backup_path 相对备份根目录"}
279
+ for e in entries
280
+ ],
281
+ }
282
+ MANIFEST.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
283
+ print(f"已写入 {MANIFEST}:{len(entries)} 个文件,{human(data['total_bytes'])}")
284
+
285
+
286
+ def mode_list(entries: list[dict]) -> None:
287
+ for g in GROUPS:
288
+ fs = [e for e in entries if e["group"] == g["id"]]
289
+ if not fs:
290
+ continue
291
+ s = g["source"]
292
+ src = s.get("repo") or s.get("base") or "mixed"
293
+ print(f"\n[{g['id']}] {g['project']} -> {g['target']}")
294
+ print(f" 来源: {s['type']} {src} 文件 {len(fs)} 个 / {human(sum(e['size'] or 0 for e in fs))}")
295
+ if g.get("note"):
296
+ print(f" 说明: {g['note']}")
297
+ for e in fs[:3]:
298
+ print(f" {e['path']} <- {e['source']}")
299
+ if len(fs) > 3:
300
+ print(f" ... 其余 {len(fs) - 3} 个文件见 weights_manifest.json")
301
+
302
+
303
+ def mode_verify(entries: list[dict], backup: Path) -> None:
304
+ by_group: dict[str, list[dict]] = {}
305
+ for e in entries:
306
+ by_group.setdefault(e["group"], []).append(e)
307
+ print(f"项目根目录 : {ROOT}")
308
+ print(f"备份目录 : {backup}")
309
+ print(f"权重文件 : {len(entries)} 个 / {human(sum(e['size'] or 0 for e in entries))}\n")
310
+ print(f"{'组':<26} {'项目内':>10} {'备份内':>10} 状态")
311
+ for gid, fs in by_group.items():
312
+ in_proj = sum(status(ROOT / e["path"], e["size"])[0] for e in fs)
313
+ in_bak = sum(status(backup / e["path"], e["size"])[0] for e in fs)
314
+ state = "完整" if in_proj == len(fs) else ("已移出到备份" if in_bak == len(fs) else "不完整")
315
+ print(f"{gid:<26} {in_proj:>4}/{len(fs):<5} {in_bak:>4}/{len(fs):<5} {state}")
316
+ missing = [e for e in entries if not status(ROOT / e["path"], e["size"])[0]]
317
+ if missing:
318
+ print(f"\n项目内缺失/异常 {len(missing)} 个;用 --mode restore 或 --mode download 恢复。")
319
+
320
+
321
+ def move_one(src: Path, dst: Path, dry_run: bool) -> str:
322
+ if not src.is_file():
323
+ return "skip (源不存在)"
324
+ if dst.is_file():
325
+ return "skip (备份已存在)"
326
+ if dry_run:
327
+ return "would move"
328
+ dst.parent.mkdir(parents=True, exist_ok=True)
329
+ try:
330
+ os.rename(src, dst)
331
+ except OSError as exc:
332
+ if exc.errno != errno.EXDEV:
333
+ raise
334
+ shutil.move(str(src), str(dst))
335
+ return "moved"
336
+
337
+
338
+ def restore_one(src: Path, dst: Path, copy: bool, dry_run: bool) -> str:
339
+ if not src.is_file():
340
+ return "skip (备份不存在)"
341
+ if dst.is_file():
342
+ return "skip (已存在)"
343
+ if dry_run:
344
+ return "would restore"
345
+ dst.parent.mkdir(parents=True, exist_ok=True)
346
+ if copy:
347
+ shutil.copy2(src, dst)
348
+ else:
349
+ try:
350
+ os.link(src, dst)
351
+ except OSError:
352
+ shutil.copy2(src, dst)
353
+ return "restored"
354
+
355
+
356
+ def download_one(e: dict, token: str | None, force: bool, dry_run: bool) -> str:
357
+ dst = ROOT / e["path"]
358
+ expected = e["size"]
359
+ if dst.is_file() and not force and (expected is None or dst.stat().st_size == expected):
360
+ return "skip (已存在)"
361
+ if e["gated"] and not token:
362
+ return "skip (gated 仓库,需 --token 或 HF_TOKEN)"
363
+ if dry_run:
364
+ return f"would download {human(expected)}"
365
+ dst.parent.mkdir(parents=True, exist_ok=True)
366
+ tmp = dst.with_name(dst.name + ".part")
367
+ cmd = [
368
+ "curl", "-fL", "--retry", "5", "--retry-delay", "5",
369
+ "--connect-timeout", "30", "--max-time", "86400",
370
+ ]
371
+ if tmp.is_file() and tmp.stat().st_size > 0:
372
+ cmd += ["-C", "-"]
373
+ if token:
374
+ cmd += ["-H", f"Authorization: Bearer {token}"]
375
+ cmd += ["-o", str(tmp), e["url"]]
376
+ started = datetime.now()
377
+ proc = subprocess.run(cmd, capture_output=True, text=True)
378
+ if proc.returncode != 0:
379
+ return f"FAILED: {proc.stderr.strip()[-300:]}"
380
+ actual = tmp.stat().st_size
381
+ if expected and actual != expected:
382
+ return f"FAILED: 大小不符 {actual} != {expected}(保留 {tmp.name})"
383
+ os.replace(tmp, dst)
384
+ return f"downloaded {human(actual)} in {(datetime.now() - started).seconds}s"
385
+
386
+
387
+ def main() -> int:
388
+ ap = argparse.ArgumentParser(description="GraphMem 权重来源登记与恢复工具")
389
+ ap.add_argument("--mode", choices=["verify", "list", "manifest", "stash", "restore", "download"], default="verify")
390
+ ap.add_argument("--only", action="append", default=[], help="只处理指定组/项目,可重复")
391
+ ap.add_argument("--backup-dir", type=Path, default=DEFAULT_BACKUP, help="权重备份根目录")
392
+ ap.add_argument("--dry-run", action="store_true")
393
+ ap.add_argument("--copy", action="store_true", help="restore 时用复制代替硬链接")
394
+ ap.add_argument("--token", default=os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN"))
395
+ ap.add_argument("--jobs", type=int, default=2, help="download 并发数")
396
+ ap.add_argument("--force", action="store_true", help="download 时忽略已存在文件,重新下载")
397
+ ap.add_argument("--include-optional", action="store_true", help="download 时包含 optional 文件(如 pretrained.zip)")
398
+ args = ap.parse_args()
399
+
400
+ entries = with_sizes(build_entries(), args.backup_dir)
401
+ if args.mode == "manifest":
402
+ write_manifest(entries, args.backup_dir)
403
+ return 0
404
+
405
+ entries = selected(entries, args.only)
406
+ if not entries:
407
+ print("没有匹配的权重组,可用 --mode list 查看组名", file=sys.stderr)
408
+ return 1
409
+ if args.mode == "list":
410
+ mode_list(entries)
411
+ return 0
412
+ if args.mode == "verify":
413
+ mode_verify(entries, args.backup_dir)
414
+ return 0
415
+
416
+ print(f"mode={args.mode} files={len(entries)} dry_run={args.dry_run}")
417
+ failures = 0
418
+ if args.mode in ("stash", "restore"):
419
+ for e in entries:
420
+ src, dst = (ROOT / e["path"], args.backup_dir / e["path"]) if args.mode == "stash" else (args.backup_dir / e["path"], ROOT / e["path"])
421
+ result = move_one(src, dst, args.dry_run) if args.mode == "stash" else restore_one(src, dst, args.copy, args.dry_run)
422
+ print(f" [{result:<22}] {e['path']}")
423
+ if result.startswith("FAILED"):
424
+ failures += 1
425
+ elif args.mode == "download":
426
+ todo = [e for e in entries if args.include_optional or not e["optional"]]
427
+ with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as pool:
428
+ futures = {pool.submit(download_one, e, args.token, args.force, args.dry_run): e for e in todo}
429
+ for fut in as_completed(futures):
430
+ e = futures[fut]
431
+ result = fut.result()
432
+ print(f" [{result}] {e['path']} <- {e['source']}", flush=True)
433
+ if result.startswith("FAILED"):
434
+ failures += 1
435
+ print(f"完成,异常 {failures} 项")
436
+ return 1 if failures else 0
437
+
438
+
439
+ if __name__ == "__main__":
440
+ sys.exit(main())