File size: 3,391 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
"""J2: which checkpoint tensors does the native class not use, and which model tensors are not from the checkpoint?

Exact match by (shape, sha1 of the bf16 bytes), so renamed keys still match. Checkpoint tensors with no matching model
tensor were dropped by the loader (not instantiated or ignored on load); model tensors with no matching checkpoint
tensor were created or changed by the loader (random init, fused, split or tied differently).
usage: keyaudit.py MODELS_DIR OUT_DIR short [short ...]
"""
import hashlib
import json
import os
import sys

os.environ["HF_HUB_OFFLINE"] = "1"
import torch
import transformers
from safetensors import safe_open

models_dir, out_dir = sys.argv[1:3]
shorts = sys.argv[3:]
os.makedirs(out_dir, exist_ok=True)
CARD_CLASS = {"lightonocr_3_0_8b": "Qwen3_5ForConditionalGeneration", "lightonocr_3_1b": "LightOnOcrForConditionalGeneration"}


def fp(t):
    t = t.detach().contiguous().cpu()
    if t.dtype == torch.bfloat16:
        raw = t.view(torch.int16).numpy().tobytes()
    else:
        raw = t.numpy().tobytes()
    return (tuple(t.shape), str(t.dtype), hashlib.sha1(raw).hexdigest())


def group(names_numel):
    g = {}
    for n, k in names_numel:
        key = ".".join(n.split(".")[:3])
        a = g.setdefault(key, [0, 0])
        a[0] += 1
        a[1] += k
    return {k: v for k, v in sorted(g.items(), key=lambda kv: -kv[1][1])}


for short in shorts:
    path = os.path.join(models_dir, short)
    rec = {"short": short}
    cls = getattr(transformers, CARD_CLASS.get(short, ""), None) or transformers.AutoModelForImageTextToText
    model = cls.from_pretrained(path, dtype=torch.bfloat16, trust_remote_code=False, use_safetensors=True)
    mfp = {}
    for n, p in model.named_parameters():
        mfp.setdefault(fp(p), []).append(n)
    ck = []
    cfp = set()
    for fn in sorted(os.listdir(path)):
        if fn.endswith(".safetensors"):
            with safe_open(os.path.join(path, fn), "pt") as f:
                for k in f.keys():
                    t = f.get_tensor(k)
                    h = fp(t)
                    cfp.add(h)
                    ck.append((k, t.numel(), h))
    dropped = [(k, n) for k, n, h in ck if h not in mfp]
    created = [(names[0], int(torch.tensor(h[0]).prod())) for h, names in mfp.items() if h not in cfp]
    rec["ckpt_tensors"] = len(ck)
    rec["ckpt_params"] = sum(n for _, n, _ in ck)
    rec["model_unique_param_tensors"] = len(mfp)
    rec["ckpt_tensors_not_in_model_count"] = len(dropped)
    rec["ckpt_tensors_not_in_model_params"] = sum(n for _, n in dropped)
    rec["ckpt_not_in_model_groups"] = group(dropped)
    rec["ckpt_not_in_model_examples"] = [k for k, _ in dropped[:15]]
    rec["model_tensors_not_in_ckpt_count"] = len(created)
    rec["model_tensors_not_in_ckpt_params"] = sum(n for _, n in created)
    rec["model_not_in_ckpt_groups"] = group(created)
    rec["model_not_in_ckpt_examples"] = [k for k, _ in created[:15]]
    rec["tie_word_embeddings_config"] = getattr(model.config, "tie_word_embeddings", None)
    json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1)
    print(short, "ckpt params", rec["ckpt_params"], "dropped tensors", len(dropped), "params", rec["ckpt_tensors_not_in_model_params"],
          "| model tensors not from ckpt", len(created), "params", rec["model_tensors_not_in_ckpt_params"], flush=True)
    del model