#!/usr/bin/env python3 """GraphMem 模型权重来源登记与恢复工具。 权重本身不随项目上传 HuggingFace,全部登记在 weights_manifest.json 中。 模式: verify 检查项目内 / 备份目录中的权重是否齐全、大小是否正确(默认) list 打印每组权重的来源 manifest 重新生成 weights_manifest.json(含原路径、来源 URL、字节数) stash 上传前把项目内权重移动到备份目录(同盘 rename,零额外空间) restore 从备份目录恢复到项目内(默认硬链接,秒级、零额外空间) download 按登记的开源来源重新下载到项目内(换机器 / 无备份时使用) 示例: python download_weights.py --mode verify python download_weights.py --mode stash python download_weights.py --mode restore python download_weights.py --mode download --only echo-wm --jobs 2 python download_weights.py --mode download --token hf_xxx # gemma-3 为 gated 仓库 python download_weights.py --mode list --only WorldKV """ from __future__ import annotations import argparse import errno import json import os import shutil import signal import subprocess import sys from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone from pathlib import Path from urllib.parse import quote try: signal.signal(signal.SIGPIPE, signal.SIG_DFL) except (AttributeError, ValueError): pass ROOT = Path(__file__).resolve().parent DEFAULT_BACKUP = ROOT.parent / "checkpoint-backup" MANIFEST = ROOT / "weights_manifest.json" HF_BASE = "https://huggingface.co" DINO_BASE = "https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/" DREAMSIM_ZIP = ( "https://github.com/ssundaram21/dreamsim/releases/" "download/v0.2.0-checkpoints/dreamsim_ensemble_checkpoint.zip" ) def shards(prefix: str, total: int, suffix: str = "safetensors") -> list[str]: return [f"{prefix}{i:05d}-of-{total:05d}.{suffix}" for i in range(1, total + 1)] def named(*names: str) -> list[dict]: return [{"name": n} for n in names] GROUPS: list[dict] = [ { "id": "echo-wm", "project": "JoyAI-Echo", "target": "JoyAI-Echo/echo_wm/checkpoints", "source": {"type": "hf", "repo": "Echo-Team/Echo-WM", "revision": "main"}, "note": "官方命令: hf download Echo-Team/Echo-WM --local-dir checkpoints", "files": named("echo-wm-base.safetensors", "echo-wm-flash.safetensors"), }, { "id": "echo-wm-gemma", "project": "JoyAI-Echo", "target": "JoyAI-Echo/echo_wm/checkpoints/gemma-3", "source": { "type": "hf", "repo": "google/gemma-3-12b-it-qat-q4_0-unquantized", "revision": "main", "gated": True, }, "note": "gated 仓库,需同意许可并传 --token;必须用 unquantized 版本", "files": named(*shards("model-", 5), "tokenizer.model"), }, { "id": "lingbot-v2", "project": "lingbot-world-v2", "target": "lingbot-world-v2/ckpt", "source": { "type": "hf", "repo": "robbyant/lingbot-world-v2-14b-causal-fast", "revision": "main", }, "note": "官方命令: huggingface-cli download robbyant/lingbot-world-v2-14b-causal-fast --local-dir ./ckpt", "files": named( "models_t5_umt5-xxl-enc-bf16.pth", "Wan2.1_VAE.pth", "google/umt5-xxl/spiece.model", *[f"transformers/{n}" for n in shards("model-", 8)], ), }, { "id": "worldkv-base-cam", "project": "WorldKV", "target": "WorldKV/lingbot-world-base-cam", "source": {"type": "hf", "repo": "robbyant/lingbot-world-base-cam", "revision": "main"}, "note": "官方命令: huggingface-cli download robbyant/lingbot-world-base-cam --local-dir ./lingbot-world-base-cam", "files": named( "models_t5_umt5-xxl-enc-bf16.pth", "Wan2.1_VAE.pth", "google/umt5-xxl/spiece.model", *[f"high_noise_model/{n}" for n in shards("diffusion_pytorch_model-", 8)], *[f"low_noise_model/{n}" for n in shards("diffusion_pytorch_model-", 8)], ), }, { "id": "worldkv-fast", "project": "WorldKV", "target": "WorldKV/lingbot-world-base-cam/lingbot_world_fast", "source": {"type": "hf", "repo": "robbyant/lingbot-world-fast", "revision": "main"}, "note": "官方命令: huggingface-cli download robbyant/lingbot-world-fast --local-dir ./lingbot-world-base-cam/lingbot_world_fast", "files": named(*shards("model-", 16)), }, { "id": "dymemv2-cotracker", "project": "dymemv2", "target": "dymemv2/evaluation/models/checkpoints", "source": {"type": "hf", "repo": "facebook/cotracker", "revision": "main"}, "note": "VBench 轨迹评估: wget https://huggingface.co/facebook/cotracker/resolve/main/cotracker2.pth", "files": named("cotracker2.pth"), }, { "id": "dymemv2-dino", "project": "dymemv2", "target": "dymemv2/evaluation/models/checkpoints", "source": {"type": "direct", "base": DINO_BASE}, "note": "DINO 官方 ViT-B/16 预训练权重(VBench subject consistency 用)", "files": named("dino_vitbase16_pretrain.pth"), }, { "id": "dymemv2-dreamsim", "project": "dymemv2", "target": "dymemv2/evaluation/models", "source": {"type": "hf", "repo": "meituan-longcat/WBench-weights", "revision": "main"}, "note": "DreamSim ensemble 权重;官方原始包为 GitHub release v0.2.0-checkpoints/dreamsim_ensemble_checkpoint.zip", "files": [ {"name": "clip_vitb16_pretrain.pth.tar", "src": "dreamsim/clip_vitb16_pretrain.pth.tar"}, {"name": "open_clip_vitb16_pretrain.pth.tar", "src": "dreamsim/open_clip_vitb16_pretrain.pth.tar"}, {"name": "dino_vitb16_pretrain.pth", "src": "dreamsim/dino_vitb16_pretrain.pth"}, {"name": "ensemble_lora/adapter_model.safetensors", "src": "dreamsim/ensemble_lora/adapter_model.safetensors"}, {"name": "pretrained.zip", "url": DREAMSIM_ZIP, "optional": True}, ], }, { "id": "dymemv2-i3d", "project": "dymemv2", "target": "dymemv2/evaluation/utils/weights", "source": {"type": "hf", "repo": "Xiaodong/FVD_I3D", "revision": "main"}, "note": "VBench FVD 评估用 I3D 权重", "files": named("i3d_pretrained_400.pt"), }, { "id": "dymemv2-nudenet", "project": "dymemv2", "target": "dymemv2/evaluation/VBench/vbench2_beta_trustworthiness/third_party/nudenet", "source": {"type": "hf", "repo": "vladmandic/nudenet", "revision": "main"}, "note": "NudeNet ONNX 检测器,远端文件名 nudenet.onnx,本地名为 best.onnx", "files": [{"name": "best.onnx", "src": "nudenet.onnx"}], }, ] def build_entries() -> list[dict]: entries = [] for g in GROUPS: src = g["source"] gated = bool(src.get("gated")) for f in g["files"]: name = f["name"] src_name = f.get("src", name) url = f.get("url") if url is None and src["type"] == "hf": revision = src.get("revision", "main") url = f"{HF_BASE}/{src['repo']}/resolve/{revision}/{quote(src_name, safe='/')}?download=true" source_desc = f"huggingface:{src['repo']}@{revision}/{src_name}" elif url is None and src["type"] == "direct": url = src["base"] + quote(src_name, safe="/") source_desc = f"url:{url}" else: source_desc = f"url:{url}" entries.append( { "group": g["id"], "project": g["project"], "path": str(Path(g["target"]) / name), "size": None, "source": source_desc, "url": url, "gated": gated, "optional": bool(f.get("optional", False)), } ) return entries def human(n: float | int | None) -> str: if n is None: return "?" n = float(n) for unit in ("B", "KB", "MB", "GB", "TB"): if n < 1024 or unit == "TB": return f"{n:.1f}{unit}" n /= 1024 return f"{n:.1f}TB" def load_manifest() -> dict: if not MANIFEST.exists(): return {} try: return json.loads(MANIFEST.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: print(f"[warn] 无法读取 {MANIFEST}: {exc}", file=sys.stderr) return {} def with_sizes(entries: list[dict], backup: Path) -> list[dict]: known = {f["path"]: f.get("size") for f in load_manifest().get("files", [])} for e in entries: for base in (ROOT, backup): p = base / e["path"] if p.is_file(): e["size"] = p.stat().st_size break else: e["size"] = known.get(e["path"]) return entries def selected(entries: list[dict], only: list[str]) -> list[dict]: if not only: return entries keys = {k.lower() for k in only} return [e for e in entries if e["group"].lower() in keys or e["project"].lower() in keys] def status(p: Path, expected: int | None) -> tuple[bool, str]: if not p.is_file(): return False, "missing" size = p.stat().st_size if expected and size != expected: return False, f"size mismatch ({human(size)} != {human(expected)})" return True, human(size) def write_manifest(entries: list[dict], backup: Path) -> None: groups = [] for g in GROUPS: fs = [e for e in entries if e["group"] == g["id"]] groups.append( { "id": g["id"], "project": g["project"], "target": g["target"], "source": g["source"], "note": g.get("note", ""), "files": len(fs), "bytes": sum(e["size"] or 0 for e in fs), } ) data = { "generated": datetime.now(timezone.utc).isoformat(timespec="seconds"), "project_root": "脚本所在目录(可整体搬迁)", "default_backup_root": str(DEFAULT_BACKUP), "backup_root_used": str(backup), "total_files": len(entries), "total_bytes": sum(e["size"] or 0 for e in entries), "groups": groups, "files": [ {**e, "backup_path": e["path"], "note": "backup_path 相对备份根目录"} for e in entries ], } MANIFEST.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"已写入 {MANIFEST}:{len(entries)} 个文件,{human(data['total_bytes'])}") def mode_list(entries: list[dict]) -> None: for g in GROUPS: fs = [e for e in entries if e["group"] == g["id"]] if not fs: continue s = g["source"] src = s.get("repo") or s.get("base") or "mixed" print(f"\n[{g['id']}] {g['project']} -> {g['target']}") print(f" 来源: {s['type']} {src} 文件 {len(fs)} 个 / {human(sum(e['size'] or 0 for e in fs))}") if g.get("note"): print(f" 说明: {g['note']}") for e in fs[:3]: print(f" {e['path']} <- {e['source']}") if len(fs) > 3: print(f" ... 其余 {len(fs) - 3} 个文件见 weights_manifest.json") def mode_verify(entries: list[dict], backup: Path) -> None: by_group: dict[str, list[dict]] = {} for e in entries: by_group.setdefault(e["group"], []).append(e) print(f"项目根目录 : {ROOT}") print(f"备份目录 : {backup}") print(f"权重文件 : {len(entries)} 个 / {human(sum(e['size'] or 0 for e in entries))}\n") print(f"{'组':<26} {'项目内':>10} {'备份内':>10} 状态") for gid, fs in by_group.items(): in_proj = sum(status(ROOT / e["path"], e["size"])[0] for e in fs) in_bak = sum(status(backup / e["path"], e["size"])[0] for e in fs) state = "完整" if in_proj == len(fs) else ("已移出到备份" if in_bak == len(fs) else "不完整") print(f"{gid:<26} {in_proj:>4}/{len(fs):<5} {in_bak:>4}/{len(fs):<5} {state}") missing = [e for e in entries if not status(ROOT / e["path"], e["size"])[0]] if missing: print(f"\n项目内缺失/异常 {len(missing)} 个;用 --mode restore 或 --mode download 恢复。") def move_one(src: Path, dst: Path, dry_run: bool) -> str: if not src.is_file(): return "skip (源不存在)" if dst.is_file(): return "skip (备份已存在)" if dry_run: return "would move" dst.parent.mkdir(parents=True, exist_ok=True) try: os.rename(src, dst) except OSError as exc: if exc.errno != errno.EXDEV: raise shutil.move(str(src), str(dst)) return "moved" def restore_one(src: Path, dst: Path, copy: bool, dry_run: bool) -> str: if not src.is_file(): return "skip (备份不存在)" if dst.is_file(): return "skip (已存在)" if dry_run: return "would restore" dst.parent.mkdir(parents=True, exist_ok=True) if copy: shutil.copy2(src, dst) else: try: os.link(src, dst) except OSError: shutil.copy2(src, dst) return "restored" def download_one(e: dict, token: str | None, force: bool, dry_run: bool) -> str: dst = ROOT / e["path"] expected = e["size"] if dst.is_file() and not force and (expected is None or dst.stat().st_size == expected): return "skip (已存在)" if e["gated"] and not token: return "skip (gated 仓库,需 --token 或 HF_TOKEN)" if dry_run: return f"would download {human(expected)}" dst.parent.mkdir(parents=True, exist_ok=True) tmp = dst.with_name(dst.name + ".part") cmd = [ "curl", "-fL", "--retry", "5", "--retry-delay", "5", "--connect-timeout", "30", "--max-time", "86400", ] if tmp.is_file() and tmp.stat().st_size > 0: cmd += ["-C", "-"] if token: cmd += ["-H", f"Authorization: Bearer {token}"] cmd += ["-o", str(tmp), e["url"]] started = datetime.now() proc = subprocess.run(cmd, capture_output=True, text=True) if proc.returncode != 0: return f"FAILED: {proc.stderr.strip()[-300:]}" actual = tmp.stat().st_size if expected and actual != expected: return f"FAILED: 大小不符 {actual} != {expected}(保留 {tmp.name})" os.replace(tmp, dst) return f"downloaded {human(actual)} in {(datetime.now() - started).seconds}s" def main() -> int: ap = argparse.ArgumentParser(description="GraphMem 权重来源登记与恢复工具") ap.add_argument("--mode", choices=["verify", "list", "manifest", "stash", "restore", "download"], default="verify") ap.add_argument("--only", action="append", default=[], help="只处理指定组/项目,可重复") ap.add_argument("--backup-dir", type=Path, default=DEFAULT_BACKUP, help="权重备份根目录") ap.add_argument("--dry-run", action="store_true") ap.add_argument("--copy", action="store_true", help="restore 时用复制代替硬链接") ap.add_argument("--token", default=os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")) ap.add_argument("--jobs", type=int, default=2, help="download 并发数") ap.add_argument("--force", action="store_true", help="download 时忽略已存在文件,重新下载") ap.add_argument("--include-optional", action="store_true", help="download 时包含 optional 文件(如 pretrained.zip)") args = ap.parse_args() entries = with_sizes(build_entries(), args.backup_dir) if args.mode == "manifest": write_manifest(entries, args.backup_dir) return 0 entries = selected(entries, args.only) if not entries: print("没有匹配的权重组,可用 --mode list 查看组名", file=sys.stderr) return 1 if args.mode == "list": mode_list(entries) return 0 if args.mode == "verify": mode_verify(entries, args.backup_dir) return 0 print(f"mode={args.mode} files={len(entries)} dry_run={args.dry_run}") failures = 0 if args.mode in ("stash", "restore"): for e in entries: src, dst = (ROOT / e["path"], args.backup_dir / e["path"]) if args.mode == "stash" else (args.backup_dir / e["path"], ROOT / e["path"]) result = move_one(src, dst, args.dry_run) if args.mode == "stash" else restore_one(src, dst, args.copy, args.dry_run) print(f" [{result:<22}] {e['path']}") if result.startswith("FAILED"): failures += 1 elif args.mode == "download": todo = [e for e in entries if args.include_optional or not e["optional"]] with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as pool: futures = {pool.submit(download_one, e, args.token, args.force, args.dry_run): e for e in todo} for fut in as_completed(futures): e = futures[fut] result = fut.result() print(f" [{result}] {e['path']} <- {e['source']}", flush=True) if result.startswith("FAILED"): failures += 1 print(f"完成,异常 {failures} 项") return 1 if failures else 0 if __name__ == "__main__": sys.exit(main())