File size: 6,524 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""J2 step 2b: fetch root-level safetensors weights of the run candidates and test the native weight load on CPU.

No token, no .py file, trust_remote_code is never set. A model passes the load gate only if from_pretrained with the
native class reports no missing key and no mismatched key; unexpected keys are listed for reading.

usage: fetch_weights_loadtest.py MODELS_DIR OUT_DIR short [short ...]
"""
import json
import os
import struct
import sys
import time

os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
    os.environ.pop(k, None)

models_dir, out_dir = sys.argv[1:3]
shorts = sys.argv[3:]
os.makedirs(out_dir, exist_ok=True)

import torch
import transformers
from huggingface_hub import HfApi, snapshot_download

CFG = [
    "config.json", "generation_config.json", "preprocessor_config.json", "processor_config.json",
    "video_preprocessor_config.json", "tokenizer*", "special_tokens_map.json", "added_tokens.json",
    "vocab*", "merges.txt", "chat_template*", "README.md",
]
REPO = {}
for line in open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "models.tsv"), encoding="utf-8").read().splitlines()[1:]:
    s, r, _, _ = line.split("\t")
    REPO[s] = r

# class used for loading: the one the card names, else the auto class that maps the config's model_type
CARD_CLASS = {
    "lightonocr_3_0_8b": "Qwen3_5ForConditionalGeneration",
    "lightonocr_3_1b": "LightOnOcrForConditionalGeneration",
}


def header_params(path):
    """Total elements and tensor count from a safetensors header (data only)."""
    with open(path, "rb") as f:
        n = struct.unpack("<Q", f.read(8))[0]
        h = json.loads(f.read(n))
    tot, cnt = 0, 0
    for k, v in h.items():
        if k == "__metadata__":
            continue
        p = 1
        for d in v["shape"]:
            p *= d
        tot += p
        cnt += 1
    return tot, cnt


api = HfApi(token=False)
for short in shorts:
    rec = {"short": short, "repo": REPO[short], "transformers": transformers.__version__, "errors": []}
    t0 = time.time()
    try:
        info = api.model_info(REPO[short], files_metadata=True, token=False)
        rec["revision"] = info.sha
        root = [(s.rfilename, s.size) for s in info.siblings if "/" not in s.rfilename]
        wl = [n for n, _ in root if n.endswith(".safetensors") or n.endswith(".safetensors.index.json")]
        rec["root_safetensors_files"] = [f"{n}:{s}" for n, s in root if n.endswith(".safetensors")]
        rec["root_safetensors_bytes"] = sum(s or 0 for n, s in root if n.endswith(".safetensors"))
        rec["root_pickle_or_other_weights_not_downloaded"] = [
            f"{n}:{s}" for n, s in root if n.endswith((".bin", ".pt", ".pth", ".pdparams", ".ckpt", ".onnx", ".gguf"))]
        local = os.path.join(models_dir, short)
        snapshot_download(REPO[short], revision=info.sha, local_dir=local, allow_patterns=CFG + wl, token=False)
        got = []
        for r, _, fs in os.walk(local):
            for fn in fs:
                got.append(os.path.relpath(os.path.join(r, fn), local))
        got = [g for g in got if not g.startswith(".cache")]
        assert not any(g.endswith(".py") for g in got), "a .py file is present"
        rec["files_in_dir"] = sorted(got)
        ck_params, ck_tensors = 0, 0
        for g in got:
            if g.endswith(".safetensors") and "/" not in g:
                a, b = header_params(os.path.join(local, g))
                ck_params += a
                ck_tensors += b
        rec["ckpt_params_header"] = ck_params
        rec["ckpt_tensors_header"] = ck_tensors
        rec["download_seconds"] = round(time.time() - t0, 1)
    except Exception as e:  # noqa: BLE001
        rec["errors"].append("fetch: " + repr(e)[:400])
        json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1)
        print(short, "FETCH ERROR", repr(e)[:300], flush=True)
        continue

    t1 = time.time()
    try:
        cls_name = CARD_CLASS.get(short)
        cls = getattr(transformers, cls_name, None) if cls_name else None
        rec["card_class"] = cls_name
        rec["card_class_in_transformers"] = cls is not None
        if cls is None:
            if cls_name:
                rec["errors"].append(f"card class {cls_name} is not in transformers {transformers.__version__}; using AutoModelForImageTextToText")
            cls = transformers.AutoModelForImageTextToText
        model, li = cls.from_pretrained(local, dtype=torch.bfloat16, trust_remote_code=False, use_safetensors=True,
                                        output_loading_info=True)
        rec["load_class_used"] = cls.__name__ + " -> " + type(model).__module__ + "." + type(model).__name__
        rec["missing_keys"] = sorted(li.get("missing_keys", []))[:50]
        rec["n_missing_keys"] = len(li.get("missing_keys", []))
        rec["unexpected_keys"] = sorted(li.get("unexpected_keys", []))[:50]
        rec["n_unexpected_keys"] = len(li.get("unexpected_keys", []))
        rec["mismatched_keys"] = [str(x)[:200] for x in li.get("mismatched_keys", [])][:50]
        rec["n_mismatched_keys"] = len(li.get("mismatched_keys", []))
        rec["error_msgs"] = [str(x)[:300] for x in li.get("error_msgs", [])][:20]
        seen, n = set(), 0
        for p in model.parameters():
            if id(p) in seen:
                continue
            seen.add(id(p))
            n += p.numel()
        rec["model_params_unique"] = n
        rec["tied_weights_note"] = "checkpoint header total minus model unique params = %d" % (ck_params - n)
        rec["generation_config"] = model.generation_config.to_dict() if getattr(model, "generation_config", None) else None
        rec["load_gate"] = ("PASS" if rec["n_missing_keys"] == 0 and rec["n_mismatched_keys"] == 0 and not rec["error_msgs"]
                            else "FAIL")
        rec["load_seconds"] = round(time.time() - t1, 1)
        del model
    except Exception as e:  # noqa: BLE001
        rec["load_gate"] = "FAIL"
        rec["errors"].append("load: " + repr(e)[:500])
    json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str)
    print(short, "gate", rec.get("load_gate"), "missing", rec.get("n_missing_keys"), "unexpected", rec.get("n_unexpected_keys"),
          "mismatched", rec.get("n_mismatched_keys"), "ckpt_params", rec.get("ckpt_params_header"), "model_params", rec.get("model_params_unique"),
          "errors", len(rec["errors"]), flush=True)