File size: 13,059 Bytes
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff88a82
 
 
 
 
9f66d08
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff88a82
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
ff88a82
 
 
 
fb6b9a8
 
 
 
 
 
 
 
ff88a82
 
fb6b9a8
 
 
ff88a82
 
 
 
 
 
 
 
 
 
 
 
 
fb6b9a8
 
 
 
 
 
 
 
ff88a82
 
fb6b9a8
 
 
ff88a82
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
ff88a82
fb6b9a8
ff88a82
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6b9a8
ff88a82
 
 
 
fb6b9a8
 
 
 
 
 
 
 
ff88a82
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff88a82
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
"""Collect per-repo evidence for classification without downloading weights.

Everything here is read through small requests: the file list (with LFS sha256),
safetensors / GGUF headers via HTTP Range, a few hundred values of one tensor,
model_index.json and the README. Results are cached by repo sha.
"""
import json
import re
import struct

import numpy as np
import requests
from huggingface_hub import get_token, hf_hub_url

from . import hub

def is_weight(name):
    """A weight file, also one split into byte parts for the upload limit (x.gguf.part1of3)."""
    return re.sub(r"\.part\d+of\d+$", "", name.lower()).endswith(WEIGHT_EXT)


WEIGHT_EXT = (".safetensors", ".gguf", ".bin", ".pt", ".pth", ".ckpt", ".onnx", ".npz", ".sft", ".tflite",
              ".mlmodel", ".engine", ".pte")
MEDIA_VIDEO = (".mp4", ".webm", ".mov", ".gif", ".mkv")
MEDIA_IMAGE = (".png", ".jpg", ".jpeg", ".webp")
README_MAX = 12_000

_S = requests.Session()


def _auth():
    t = get_token()
    return {"Authorization": f"Bearer {t}"} if t else {}


def _range(repo, fname, start, end, kind="model", revision=None):
    url = hf_hub_url(repo, fname, repo_type=None if kind == "model" else kind, revision=revision)
    r = hub.retry(_S.get, url, headers={**_auth(), "Range": f"bytes={start}-{end}"}, timeout=60)
    r.raise_for_status()
    return r.content


def st_header(repo, fname, revision=None):
    n = struct.unpack("<Q", _range(repo, fname, 0, 7, revision=revision))[0]
    if n > 50_000_000:
        raise ValueError("header too large")
    h = json.loads(_range(repo, fname, 8, 8 + n - 1, revision=revision))
    return n, h


_DT = {"BF16": ("bf16", 2), "F16": (np.float16, 2), "F32": (np.float32, 4)}


def st_values(repo, fname, n_header, info, count=256, revision=None):
    dt = info["dtype"]
    if dt not in _DT:
        return None
    kind, size = _DT[dt]
    start = 8 + n_header + info["data_offsets"][0]
    raw = _range(repo, fname, start, start + count * size - 1, revision=revision)
    if kind == "bf16":
        u = np.frombuffer(raw, dtype=np.uint16).astype(np.uint32) << 16
        return u.view(np.float32)
    return np.frombuffer(raw, dtype=kind).astype(np.float32)


def gguf_header(repo, fname, limit=8_000_000):
    """Parse GGUF metadata + tensor names from the first `limit` bytes (best effort)."""
    buf = _range(repo, fname, 0, limit - 1)
    if buf[:4] != b"GGUF":
        return None
    p = 4
    ver, = struct.unpack_from("<I", buf, p); p += 4
    nt, nkv = struct.unpack_from("<QQ", buf, p); p += 16
    out = {"version": ver, "n_tensors": nt, "kv": {}, "tensors": []}
    sizes = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
    fmt = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i", 6: "<f", 7: "<?", 10: "<Q", 11: "<q", 12: "<d"}

    def rstr(p):
        n, = struct.unpack_from("<Q", buf, p)
        return buf[p + 8:p + 8 + n].decode("utf-8", "replace"), p + 8 + n

    def rval(t, p):
        if t == 8:
            return rstr(p)
        if t == 9:
            at, n = struct.unpack_from("<IQ", buf, p); p += 12
            if at == 8:
                vals = []
                for _ in range(n):
                    s, p = rstr(p)
                    if len(vals) < 4:
                        vals.append(s)
                return vals, p
            return None, p + sizes[at] * n
        return struct.unpack_from(fmt[t], buf, p)[0], p + sizes[t]
    try:
        for _ in range(nkv):
            k, p = rstr(p)
            t, = struct.unpack_from("<I", buf, p); p += 4
            if t == 9:                     # arrays: keep their length (tokenizer.ggml.tokens = vocabulary size)
                out["kv"][k + ".count"] = struct.unpack_from("<Q", buf, p + 4)[0]
            v, p = rval(t, p)
            if isinstance(v, (str, int, float, bool)) and len(str(v)) < 300:
                out["kv"][k] = v
        for _ in range(nt):
            name, p = rstr(p)
            nd, = struct.unpack_from("<I", buf, p); p += 4
            dims = list(struct.unpack_from(f"<{nd}Q", buf, p)); p += 8 * nd + 4 + 8
            out["tensors"].append(name)
            out.setdefault("shapes", {})[name] = dims
    except (struct.error, IndexError):
        out["truncated"] = True
    return out


def _pick_weight(files, fam=None):
    """Main weight file: prefer DiT / LoRA files over VAE, text encoder, embeddings, and a file
    named after the family over extras bundled next to it."""
    w = [f for f in files if is_weight(f["name"])]
    if not w:
        return None

    def score(f):
        n = f["name"].lower()
        s = f["size"] or 0
        bad = any(x in n for x in ("vae", "text_encoder", "text_encoders/", "tokenizer", "embeddings/",
                                    "clip", "t5", "qwen", "encoder", "tae", "upscal"))
        named = bool(fam and fam.archs and fam.family_text and fam.family_text.search(n))
        return (0 if bad else 1, named, s)
    return max(w, key=score)


def _first_shard(name, names):
    """A split GGUF keeps its metadata in part 1 only (...-00001-of-00004.gguf, ....gguf.part1of3)."""
    m = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", name)
    if m and m.group(1) != "00001":
        first = name[:m.start()] + f"-00001-of-{m.group(2)}.gguf"
        return first if first in names else name
    m = re.search(r"\.part(\d+)of(\d+)$", name)
    if m and m.group(1) != "1":
        first = name[:m.start()] + f".part1of{m.group(2)}"
        return first if first in names else name
    return name


def enrich_model(repo_id, fam):
    i = hub.info("model", repo_id, files_metadata=True)
    files = [{"name": s.rfilename, "size": s.size or 0,
              "sha256": (s.lfs.sha256 if getattr(s, "lfs", None) else None)} for s in (i.siblings or [])]
    ev = {"repo_id": repo_id, "sha": i.sha, "files": files, "config": _small(i.config),
          "card": (i.card_data.to_dict() if i.card_data else {}), "errors": []}
    names = [f["name"] for f in files]
    lower = [n.lower() for n in names]
    ev["n_weight_files"] = sum(is_weight(n) for n in lower)
    ev["weight_bytes"] = sum(f["size"] for f in files if is_weight(f["name"]))
    ev["has_video_media"] = any(n.endswith(MEDIA_VIDEO) for n in lower)
    ev["has_image_media"] = any(n.endswith(MEDIA_IMAGE) for n in lower)
    ev["has_adapter_config"] = any(n.endswith("adapter_config.json") for n in lower)
    ev["has_gguf"] = any(".gguf" in n and is_weight(n) for n in lower)

    for small in [n for n in names if n.endswith("model_index.json")][:1]:
        try:
            ev["model_index"] = _small(json.loads(_range(repo_id, small, 0, 200_000)))
        except Exception as e:
            ev["errors"].append(f"model_index: {e}")
    if "README.md" in names:
        try:
            ev["readme"] = _range(repo_id, "README.md", 0, README_MAX).decode("utf-8", "replace")
        except Exception as e:
            ev["errors"].append(f"readme: {e}")

    main = _pick_weight(files, fam)
    ev["main_weight"] = main["name"] if main else None
    # The config that describes the weights: the repo's own, else the one next to the main weight
    # (language_model/config.json in a pipeline repo). The API's config omits sizes.
    folder = main["name"].rsplit("/", 1)[0] + "/" if main and "/" in main["name"] else ""
    cfg_name = folder + "config.json" if folder + "config.json" in names else "config.json"
    if cfg_name in names:
        try:
            c = json.loads(_range(repo_id, cfg_name, 0, 300_000))
            t = c.get("text_config") or {}
            ev["hidden_size"] = c.get("hidden_size") or t.get("hidden_size")
            ev["vocab_size"] = c.get("vocab_size") or t.get("vocab_size")
            ev["file_config"] = {"model_type": c.get("model_type"), "architectures": c.get("architectures")}
        except Exception as e:
            ev["errors"].append(f"config: {e}")
    if main and re.search(r"\.gguf(\.part\d+of\d+)?$", main["name"].lower()):
        try:
            # Families told apart by architecture need only the metadata at the start of the file;
            # tensor shapes (DiT signatures, markers) sit after the tokenizer, megabytes in.
            g = gguf_header(repo_id, _first_shard(main["name"], names),
                            limit=512_000 if fam.archs and not fam.marker_rules else 8_000_000)
            if g:
                ev["gguf"] = {"kv": g["kv"], "n_tensors": g["n_tensors"],
                              "tensor_names": _summarise_keys(g["tensors"]), "truncated": g.get("truncated")}
                ev["dit_sig"] = dit_signature(g.get("shapes", {}), fam)
        except Exception as e:
            ev["errors"].append(f"gguf: {e}")
    elif main and main["name"].lower().endswith((".safetensors", ".sft")):
        ev.update(_safetensors_evidence(repo_id, main["name"], files, fam))
        if fam.meta_rules and (not ev.get("st_meta") or len(json.dumps(ev["st_meta"])) < 40):
            ev["st_meta"] = {**_other_meta(repo_id, files, main["name"]), **(ev.get("st_meta") or {})}
    return ev


def _other_meta(repo_id, files, main_name, n=2):
    """Training metadata often sits in a sibling file (kohya/musubi output next to a
    diffusers conversion), so read the headers of a couple of other safetensors."""
    others = sorted([f for f in files if f["name"].lower().endswith(".safetensors") and f["name"] != main_name
                     and 0 < f["size"] < 10e9], key=lambda f: f["size"])[:n]
    meta = {}
    for f in others:
        try:
            _, h = st_header(repo_id, f["name"])
        except Exception:
            continue
        for k, v in (h.get("__metadata__") or {}).items():
            if k not in meta:
                meta[k] = v if len(str(v)) < 600 else str(v)[:600]
    return meta


def _safetensors_evidence(repo_id, fname, files, fam):
    out = {}
    try:
        n, h = st_header(repo_id, fname)
    except Exception as e:
        return {"errors": [f"st_header: {e}"]}
    meta = h.pop("__metadata__", {}) or {}
    keys = list(h.keys())
    # Sharded checkpoints: the index lists every tensor name.
    def folder(p):
        return p.rsplit("/", 1)[0] if "/" in p else ""
    idx = [f["name"] for f in files if fam.marker_rules         # every tensor name, for the marker rules
           and f["name"].endswith(".safetensors.index.json") and folder(f["name"]) == folder(fname)]
    all_keys = keys
    if idx:
        try:
            all_keys = list(json.loads(_range(repo_id, idx[0], 0, 20_000_000))["weight_map"].keys())
        except Exception:
            pass
    dtypes = {}
    for v in h.values():
        dtypes[v["dtype"]] = dtypes.get(v["dtype"], 0) + 1
    out["st_meta"] = {k: (v if len(str(v)) < 600 else str(v)[:600]) for k, v in meta.items()}
    out["st_dtypes"] = dtypes
    out["st_n_tensors"] = len(all_keys)
    out["st_keys"] = _summarise_keys(all_keys)
    out["dit_sig"] = dit_signature({k: v["shape"] for k, v in h.items()}, fam)
    # Value probe on one block tensor, if this file holds it in a plain float dtype.
    for pre in fam.probe_prefixes:
        for pn in fam.probe_names:
            k = pre + pn
            if k in h and h[k]["dtype"] in _DT:
                try:
                    v = st_values(repo_id, fname, n, h[k])
                    out["probe"] = {"key": pn, "dtype": h[k]["dtype"], "shape": h[k]["shape"],
                                    "values": [float(x) for x in v]}
                except Exception as e:
                    out.setdefault("errors", []).append(f"probe: {e}")
                return out
    return out


def dit_signature(shapes, fam):
    """How many block-level tensors carry the family's characteristic sizes.

    For H3 this separates the H3 / H3-Image DiT (hidden 5376) from Wan (5120), LTX (4096),
    Flux/Hunyuan (3072) and from LLMs that also use 5376 (they name layers model.layers.N...).
    It cannot tell members that share one shape apart; that is left to markers and probes.
    """
    if not fam.sig_names or not fam.sig_dims:
        return None
    hit = tot = 0
    for k, shp in shapes.items():
        if not fam.sig_names.search(k):
            continue
        tot += 1
        if any(d in fam.sig_dims for d in shp):
            hit += 1
    return {"block_tensors": tot, "sig_hits": hit}


def _summarise_keys(keys):
    """Keep what classification needs: marker keys and a de-duplicated key pattern sample."""
    markers = [k for k in keys if re.search(r"audio|pdd|lora|lokr|loha|alpha|controlnet|control_|video_out|"
                                            r"proj_out|patch_proj|final_layer", k, re.I)]
    patterns = sorted({re.sub(r"\.\d+\.", ".N.", k) for k in keys})
    return {"n": len(keys), "markers": markers[:60], "patterns": patterns[:120]}


def _small(x, limit=4000):
    if x is None:
        return None
    s = json.dumps(x, default=str)
    if len(s) <= limit:
        return json.loads(s)
    if isinstance(x, dict):
        return {k: (v if len(json.dumps(v, default=str)) < 500 else "…") for k, v in x.items()}
    return None