File size: 3,946 Bytes
a7e82fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
89
#!/usr/bin/env python3
"""Verify a local Hugging Face snapshot against the Hub's file listing of one exact revision (stdlib only, public repos).

  python -m bench.verify_snapshot Qwen/Qwen3.8-27B 37561816e66b5b9153b1b64c10968c18c1e6f4a0 /workspace/weights/qwen3.8-27b [--manifest MANIFEST.sha256] [--only-present]

For every file of the revision: LFS files are checked by sha256 (the `lfs.oid` of the listing) and size, other files by their git blob
SHA-1 (the listing's `oid`). Missing files fail unless --only-present; extra local files are reported. Writes a sha256sum-style manifest
of the verified files. Exit 0 = every checked file matches. The revision must be a full 40-hex commit sha (no branch names).
"""
from __future__ import annotations

import argparse
import hashlib
import json
import re
import sys
import urllib.request
from pathlib import Path


def listing(repo: str, rev: str) -> list[dict]:
    if not re.fullmatch(r"[0-9a-f]{40}", rev):
        raise SystemExit(f"revision must be a full commit sha, got {rev!r}")
    out, url = [], f"https://huggingface.co/api/models/{repo}/tree/{rev}?recursive=true"
    while url:                                      # the listing is paged (Link: rel="next")
        with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "reax-engine-verify"}), timeout=60) as r:
            out += json.loads(r.read())
            m = re.search(r'<([^>]+)>;\s*rel="next"', r.headers.get("Link", ""))
            url = m.group(1) if m else None
    return [e for e in out if e["type"] == "file"]


def sha256_of(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(8 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def git_blob_sha1(path: Path) -> str:
    h = hashlib.sha1(f"blob {path.stat().st_size}\0".encode())
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(8 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def verify(files: list[dict], root: Path, only_present: bool = False) -> dict:
    ok, bad, missing, manifest = [], [], [], []
    for e in files:
        p = root / e["path"]
        if not p.is_file():
            if not only_present:
                missing.append(e["path"])
            continue
        lfs = e.get("lfs")
        if lfs:
            digest, want = sha256_of(p), lfs["oid"]
            good = digest == want and p.stat().st_size == e["size"]
        else:
            digest, want = None, e["oid"]
            good = git_blob_sha1(p) == want
        (ok if good else bad).append(e["path"])
        manifest.append(f"{digest or sha256_of(p)}  {e['path']}")
    extra = sorted(str(p.relative_to(root)) for p in root.rglob("*")
                   if p.is_file() and not any(part.startswith(".") for part in p.relative_to(root).parts)) if root.is_dir() else []
    extra = [x for x in extra if x not in {e["path"] for e in files}]
    return {"ok": len(ok), "bad": bad, "missing": missing, "extra": extra, "manifest": manifest}


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("repo")
    ap.add_argument("revision")
    ap.add_argument("directory")
    ap.add_argument("--manifest", default=None, help="write a sha256sum-style manifest of the verified files here")
    ap.add_argument("--only-present", action="store_true", help="do not fail on files that are not downloaded")
    a = ap.parse_args(argv)
    res = verify(listing(a.repo, a.revision), Path(a.directory), a.only_present)
    if a.manifest and not res["bad"] and not res["missing"]:
        Path(a.manifest).write_text("\n".join(res["manifest"]) + "\n")
    print(json.dumps({k: v for k, v in res.items() if k != "manifest"}, indent=1))
    return 1 if res["bad"] or res["missing"] else 0


if __name__ == "__main__":
    sys.exit(main())