#!/usr/bin/env python3
# check_gguf.py: look inside GGUF and safetensors model files for the hiding places used by malicious model uploads
# (a program appended after the weights, data hidden in padding, gaps or dead weight blocks, chat templates that tell a model
# or an agent to run something) WITHOUT loading or running the model. Shoggoth Analytics, 2026. Apache-2.0.
#
# What it checks:
#   1. PADDING. Every byte between the header and the first tensor, and between tensors, must be zero (a payload can sit there).
#   2. DEAD BLOCKS. A weight block whose scale is zero decodes to zeros whatever else it holds, so its other bytes are free
#      space for a payload "without touching a functional weight". Those bytes must be zero. Also: no NaN or Inf anywhere in a
#      scale or a float weight (a payload read as numbers is full of them), and the largest scale is reported.
#   3. EMBEDDED PROGRAMS. The whole file is searched for the signatures of Windows, Linux and Mac programs, zip/7z/rar archives,
#      and for script text (PowerShell, shell, URLs) inside the weights.
#   4. THE TEMPLATE, COMPARED, NOT JUST SEARCHED. A word list misses an instruction written in plain French. So every chat template
#      is compared byte for byte with every version the lab itself ever published (fetched from the lab's own repo, all commits).
#      Identical = clean by construction. Anything else gets a diff written out, to be read by hand, line by line.
#   5. Every other text value in the header is searched too (a template could hide under another name), and the Python
#      template-escape tricks (CVE-2024-34359) are searched for.
#   6. Folders: tokenizer_config.json templates, chat_template.json, config.json "auto_map" (remote code), and any program,
#      script or pickle file sitting beside the weights.
# Tensor sizes come from each format's own gguf-py tables (stock llama.cpp, then PrismML's and llamAmpere's forks for their
# custom types), never from numbers typed here. The block layouts below were read from ggml-common.h (llama.cpp b12129) and are
# asserted against those tables on every run.
#
# RUNS ON: anything with Python 3 + numpy.   python3 check_gguf.py --refs <folder of official templates> --out <report folder>
#                       --gguf-py <dir> [--gguf-py <dir> ...] <model folder or file> [...]
import argparse, difflib, hashlib, importlib.util, json, os, re, struct, sys, time
import numpy as np

CHUNK = 64 << 20

# Scale fields per block type, from ggml-common.h: (block bytes, [byte offsets of the f16 scale fields]).
LAYOUT = {"Q4_0": (18, [0]), "Q4_1": (20, [0, 2]), "Q5_0": (22, [0]), "Q8_0": (34, [0]), "Q2_K": (84, [80, 82]),
          "Q3_K": (110, [108]), "Q4_K": (144, [0, 2]), "Q5_K": (176, [0, 2]), "Q6_K": (210, [208]), "IQ2_XS": (74, [0]),
          "IQ4_XS": (136, [0])}
FLOATS = {"F32": np.float32, "F16": np.float16, "BF16": "bf16", "F64": np.float64}

# Binary signatures, searched in the whole file. Each has a validator so random weight bytes do not count.
def _v_pe(b, i):  return True
def _v_elf(b, i): return len(b) >= i + 7 and b[i+4] in (1, 2) and b[i+5] in (1, 2) and b[i+6] == 1
def _v_zip(b, i):
    if len(b) < i + 30: return False
    ver, flg, meth = struct.unpack_from("<HHH", b, i + 4); nlen = struct.unpack_from("<H", b, i + 26)[0]
    name = b[i+30:i+30+nlen]
    return ver < 64 and meth in (0, 8, 9, 12, 14, 93, 95, 98, 99) and 0 < nlen < 256 and len(name) == nlen and all(32 <= c < 127 for c in name)
def _v_true(b, i): return True
def _v_macho(b, i): return len(b) >= i + 8 and struct.unpack_from("<I", b, i + 4)[0] in (0x01000007, 0x0100000C)
BIN_SIGS = [(b"This program cannot be run in DOS mode", "Windows program (PE stub)", _v_pe),
            (b"MZ\x90\x00\x03\x00\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00", "Windows program (DOS header)", _v_pe),
            (b"\x7fELF", "Linux program (ELF)", _v_elf), (b"PK\x03\x04", "zip archive", _v_zip),
            (b"7z\xbc\xaf\x27\x1c", "7z archive", _v_true), (b"Rar!\x1a\x07", "rar archive", _v_true),
            (b"\xcf\xfa\xed\xfe", "Mac program (Mach-O)", _v_macho)]
# Script text, searched only inside the weights (the header has a vocabulary in it, where words like these can legitimately be).
TXT_SIGS = [b"powershell", b"PowerShell", b"POWERSHELL", b"Invoke-Expression", b"FromBase64String", b"#!/bin/sh", b"#!/bin/bash",
            b"cmd.exe", b"https://", b"http://", b"<script", b"/dev/tcp/", b"Start-Process"]
MAXSIG = max(len(s) for s, _, _ in BIN_SIGS) + 64

# Words a template or header text has no business containing. A hit means READ it, not that it is harmful.
SUSPECT = re.compile(r"powershell|cmd\.exe|cmd /c|\biex\b|invoke-(expression|webrequest|restmethod)|certutil|mshta|rundll32|regsvr32|\bcurl\b|\bwget\b|"
                     r"https?://|base64|frombase64|system directive|directive|bash -c|/bin/sh|\bchmod\b|expand-archive|start-process|\.exe\b|\.ps1\b|\.bat\b|"
                     r"eval\(|__import__|subprocess|os\.system|downloadstring|net\.webclient|hidden|-windowstyle|-enc\b|-nop\b|"
                     r"__class__|__globals__|__subclasses__|__builtins__|__init__|__mro__|\.mro\b|lipsum|cycler|joiner|\bconfig\.|request\.|\bself\.|attr\(", re.I)
NON_ASCII_WORD = re.compile(r"[A-Za-z]*[À-ÖØ-öø-ÿ][A-Za-z]*")      # accented Latin words (the armed Mir2k template spoke French)
SKIP_KV_ARRAYS = ("tokenizer.ggml.tokens", "tokenizer.ggml.merges", "tokenizer.ggml.token_type", "tokenizer.ggml.scores")

def load_type_tables(dirs):
    """name/size tables from each gguf-py constants.py; the first that knows a type id wins."""
    tables = []
    for i, d in enumerate(dirs):
        spec = importlib.util.spec_from_file_location(f"ggufconst{i}", os.path.join(d, "gguf", "constants.py"))
        m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
        tables.append((d, {int(t): (t.name, *m.GGML_QUANT_SIZES[t]) for t in m.GGMLQuantizationType if t in m.GGML_QUANT_SIZES}))
    for name, (bs, offs) in LAYOUT.items():                                          # assert the layouts against the format's own table
        sizes = {n: ts for _, tb in tables for (n, blk, ts) in tb.values()}
        assert name in sizes and sizes[name] == bs, f"layout for {name} says {bs} bytes, gguf-py says {sizes.get(name)}"
    return tables

def type_info(tables, tid):
    for d, tb in tables:
        if tid in tb: return tb[tid] + (os.path.basename(os.path.dirname(d.rstrip('/'))) or d,)
    return None

# ---------------- GGUF: our own header walk (no runtime involved) ----------------
def _rd(f, fmt): return struct.unpack("<" + fmt, f.read(struct.calcsize("<" + fmt)))
def _str(f):
    n, = _rd(f, "Q"); b = f.read(n)
    if len(b) != n: raise EOFError("header ends early")
    return b.decode("utf-8", "replace")
SCALAR = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"}
def _val(f, t):
    if t in SCALAR: return _rd(f, SCALAR[t])[0]
    if t == 8: return _str(f)
    if t == 9:
        at, n = _rd(f, "I") + _rd(f, "Q")
        if at in SCALAR:
            sz = struct.calcsize("<" + SCALAR[at]); f.seek(n * sz, 1); return f"<array of {n} numbers>"
        return [_val(f, at) for _ in range(n)]
    raise ValueError(f"unknown GGUF value type {t}")

def gguf_header(p):
    with open(p, "rb") as f:
        return gguf_header_f(f)

def gguf_header_f(f):
    """the header walk on any readable file object (a file on disk, or the first bytes fetched over the network)"""
    if True:
        assert f.read(4) == b"GGUF", "not a GGUF file"
        ver, = _rd(f, "I"); nt, nkv = _rd(f, "QQ")
        kv = {}
        for _ in range(nkv):
            k = _str(f); t, = _rd(f, "I"); kv[k] = _val(f, t)
        tensors = []
        for _ in range(nt):
            name = _str(f); nd, = _rd(f, "I"); dims = _rd(f, "Q" * nd); tt, off = _rd(f, "IQ")
            tensors.append({"name": name, "dims": dims, "type": tt, "offset": off})
        hdr_end = f.tell()
    align = int(kv.get("general.alignment", 32))
    data_start = (hdr_end + align - 1) // align * align
    return ver, kv, tensors, hdr_end, align, data_start

class Scan:
    """one pass over a byte range: signatures, with a carry so nothing is missed at chunk edges"""
    def __init__(self, txt): self.carry, self.base, self.hits, self.txt = b"", 0, [], txt
    def feed(self, pos, buf):
        b = self.carry + bytes(buf); start = pos - len(self.carry)
        for sig, what, ok in BIN_SIGS:
            i = b.find(sig)
            while i >= 0:
                if ok(b, i) and len(self.hits) < 50: self.hits.append((start + i, what, b[i:i+48]))
                i = b.find(sig, i + 1)
        if self.txt:
            for sig in TXT_SIGS:
                i = b.find(sig)
                while i >= 0:
                    if len(self.hits) < 50: self.hits.append((start + i, "script text " + sig.decode(), b[max(0, i-16):i+64]))
                    i = b.find(sig, i + 1)
        self.carry = b[-MAXSIG:]
    def reset(self): self.carry = b""

def _f16(u16): return u16.view(np.float16).astype(np.float32)

# A dead block can hold data INNOCENTLY: the quantizer writes the quants from the float scale, then stores the scale in half
# precision, which rounds to zero when the weights are tiny (ggml-quants.c, quantize_row_q6_K_impl / quantize_row_q8_0_ref;
# proven on Qwen3.8-27B-heretic-ara Q4_K_M 2026-12-03: 102 such blocks, all in six near-dead channels, predicted from the
# full weights). Those blocks still carry the quantizer's own fingerprint, which random payload bytes almost never do:
#   Q6_K: the largest sub-block scale is always written as exactly -128.
#   Q8_0: the largest weight is always written as +/-127, and -128 is never written (roundf of a value within +/-127).
# A single planted block can still pass by chance (Q8_0 about 1 in 5, Q6_K about 1 in 16); a real payload spans thousands of
# blocks, so it cannot. Every dead block that holds data is also listed by tensor and row, for a human to check.
def _fits_quantizer(name, blocks):
    if name == "Q6_K": return (blocks[:, 192:208].view(np.int8) == -128).any(axis=1)
    if name == "Q8_0":
        q = blocks[:, 2:34].view(np.int8).astype(np.int16)
        return (np.abs(q) == 127).any(axis=1) & ~(q == -128).any(axis=1)
    return np.zeros(len(blocks), bool)

def block_check(raw, layout, name="", first_block=0, where=None):
    bs, offs = layout
    a = np.frombuffer(raw, dtype=np.uint8).reshape(-1, bs)
    sc = np.stack([a[:, o].astype(np.uint16) | (a[:, o + 1].astype(np.uint16) << 8) for o in offs], 1)
    vals = _f16(sc)
    dead = np.all((sc & 0x7FFF) == 0, axis=1)                                         # +0 or -0 in every scale field
    rest = np.ones(bs, bool)
    for o in offs: rest[o:o+2] = False
    dwd, unexplained = 0, 0
    if dead.any():
        d = a[dead]; has = d[:, rest].any(axis=1); dwd = int(has.sum())
        if dwd:
            unexplained = int((has & ~_fits_quantizer(name, d)).sum())
            if where is not None and len(where) < 200: where.extend((first_block + np.flatnonzero(dead)[has]).tolist()[:200 - len(where)])
    fin = np.isfinite(vals)
    return {"blocks": len(a), "dead": int(dead.sum()), "dead_with_data": dwd, "dead_with_data_unexplained": unexplained,
            "nonfinite": int((~fin).sum()), "max_abs_scale": float(np.abs(vals[fin]).max()) if fin.any() else 0.0}

def float_check(raw, kind):
    if kind == "bf16": v = (np.frombuffer(raw, dtype=np.uint16).astype(np.uint32) << 16).view(np.float32)
    else: v = np.frombuffer(raw, dtype=kind)
    fin = np.isfinite(v)
    return {"values": len(v), "nonfinite": int((~fin).sum()), "max_abs": float(np.abs(v[fin]).max()) if fin.any() else 0.0}

def merge(acc, r):
    for k, v in r.items():
        acc[k] = max(acc.get(k, 0.0), v) if k.startswith("max") else acc.get(k, 0) + v

def zero_check(f, a, b):
    """are all bytes in [a, b) zero? returns (count of nonzero bytes, first nonzero offset)"""
    if b <= a: return 0, None
    f.seek(a); d = np.frombuffer(f.read(b - a), dtype=np.uint8); nz = np.flatnonzero(d)
    return int(len(nz)), (a + int(nz[0])) if len(nz) else None

def gguf_file(p, tables):
    ver, kv, tensors, hdr_end, align, data_start = gguf_header(p)
    size = os.path.getsize(p); out = {"kind": "gguf", "version": ver, "tensors": len(tensors), "size": size, "alignment": align, "look": []}
    unknown = sorted({t["type"] for t in tensors if type_info(tables, t["type"]) is None})
    if unknown: out["look"].append(f"tensor types no reader knows: {unknown}"); return out, kv
    for t in tensors:
        name, blk, ts, src = type_info(tables, t["type"])
        n = int(np.prod(t["dims"], dtype=np.int64)) if t["dims"] else 1
        assert n % blk == 0, f'{t["name"]}: {n} values is not a whole number of {name} blocks'
        t.update(tname=name, nbytes=n // blk * ts, reader=src)
    ts_sorted = sorted(tensors, key=lambda t: t["offset"])
    types = {}
    for t in tensors: types[t["tname"]] = types.get(t["tname"], 0) + 1
    out["types"] = types; out["readers"] = sorted({t["reader"] for t in tensors})
    sc, stats, gaps_nz, overlaps = Scan(txt=False), {}, 0, 0
    with open(p, "rb") as f:
        f.seek(0); sc.feed(0, f.read(hdr_end))                                          # header: program/archive signatures only
        nz, first = zero_check(f, hdr_end, data_start)
        out["header_padding"] = {"bytes": data_start - hdr_end, "nonzero": nz}
        if nz: out["look"].append(f"{nz} nonzero bytes in the padding after the header (first at {first})")
        pos = data_start; sc.txt = True
        for t in ts_sorted:
            a = data_start + t["offset"]
            if a < pos: overlaps += 1
            gz, gfirst = zero_check(f, pos, a); gaps_nz += gz
            if gz: out["look"].append(f'{gz} nonzero bytes in the gap before {t["name"]} (first at {gfirst})')
            lay = LAYOUT.get(t["tname"]); fk = FLOATS.get(t["tname"])
            step = (CHUNK // lay[0] * lay[0]) if lay else CHUNK
            st = stats.setdefault(t["tname"], {}); where = []
            f.seek(a); left = t["nbytes"]; q = a
            while left > 0:
                raw = f.read(min(step, left)); left -= len(raw)
                sc.feed(q, raw); q += len(raw)
                if lay: merge(st, block_check(raw, lay, t["tname"], (q - len(raw) - a) // lay[0], where))
                elif fk is not None: merge(st, float_check(raw, fk))
                else: merge(st, {"unchecked_bytes": len(raw)})
            if where:
                bpr = t["dims"][0] // type_info(tables, t["type"])[1]
                out.setdefault("dead_blocks_with_data", {})[t["name"]] = {"count_listed": len(where), "rows": sorted(set(b // bpr for b in where))[:40]}
            pos = a + t["nbytes"]
        out["data_end"] = pos; out["trailing"] = size - pos
        if size > pos:
            f.seek(pos); sc.feed(pos, f.read(min(size - pos, 1 << 30)))
            out["look"].append(f"{size - pos} bytes after the end of the model data")
    out["gap_nonzero_bytes"] = gaps_nz; out["overlaps"] = overlaps; out["blocks"] = stats
    if overlaps: out["look"].append(f"{overlaps} tensors overlap")
    for tn, st in stats.items():
        if st.get("dead_with_data_unexplained"): out["look"].append(f'{st["dead_with_data_unexplained"]} dead {tn} blocks hold data WITHOUT the quantizer\'s fingerprint')
        elif st.get("dead_with_data"): out.setdefault("notes", []).append(f'{st["dead_with_data"]} dead {tn} blocks hold data, all with the quantizer\'s fingerprint (weights too small for half precision)')
        if st.get("nonfinite"): out["look"].append(f'{st["nonfinite"]} NaN/Inf values in {tn}')
    out["signatures"] = [(o, w, s.hex()) for o, w, s in sc.hits]
    for o, w, s in sc.hits: out["look"].append(f"{w} at byte {o}")
    return out, kv

# ---------------- safetensors ----------------
ST_FLOAT = {"F32": np.float32, "F16": np.float16, "BF16": "bf16", "F64": np.float64}
def safetensors_file(p):
    size = os.path.getsize(p); out = {"kind": "safetensors", "size": size, "look": []}
    with open(p, "rb") as f:
        n, = struct.unpack("<Q", f.read(8)); assert n < 200_000_000, "header length is absurd"
        rawh = f.read(n); head = json.loads(rawh)
    stripped = rawh.rstrip(b" ")
    if not stripped.endswith(b"}"): out["look"].append("header has something other than spaces after the JSON")
    meta = head.pop("__metadata__", {}) or {}
    out["metadata"] = {k: (v if len(str(v)) < 300 else str(v)[:300] + "…") for k, v in meta.items()}
    for k, v in meta.items():
        hits = sorted({m.group(0).lower() for m in SUSPECT.finditer(str(v))})
        if hits: out["look"].append(f"metadata {k}: {hits}")
    spans = sorted((v["data_offsets"][0], v["data_offsets"][1], k, v["dtype"]) for k, v in head.items())
    base = 8 + n; pos = 0; gaps = 0; overlaps = 0; stats = {}; sc = Scan(txt=True)
    with open(p, "rb") as f:
        for a, b, k, dt in spans:
            if a < pos: overlaps += 1
            if a > pos: gaps += a - pos; out["look"].append(f"{a - pos} unclaimed bytes before {k}")
            st = stats.setdefault(dt, {}); f.seek(base + a); left = b - a; q = base + a
            esz = {"F32": 4, "F16": 2, "BF16": 2, "F64": 8}.get(dt, 1)
            while left > 0:
                raw = f.read(min(CHUNK // esz * esz, left)); left -= len(raw); sc.feed(q, raw); q += len(raw)
                if dt in ST_FLOAT: merge(st, float_check(raw, ST_FLOAT[dt]))
                else: merge(st, {"bytes": len(raw)})
            pos = max(pos, b)
        out.update(tensors=len(spans), data_end=base + pos, trailing=size - base - pos, gaps=gaps, overlaps=overlaps, blocks=stats)
        if size > base + pos: out["look"].append(f"{size - base - pos} bytes after the end of the model data")
    for dt, st in stats.items():
        if st.get("nonfinite"): out["look"].append(f'{st["nonfinite"]} NaN/Inf values in {dt}')
    out["signatures"] = [(o, w, s.hex()) for o, w, s in sc.hits]
    for o, w, s in sc.hits: out["look"].append(f"{w} at byte {o}")
    return out

# ---------------- templates ----------------
def load_refs(d):
    refs = {}
    for fn in sorted(os.listdir(d)):
        if fn.endswith(".jinja"): refs[fn] = open(os.path.join(d, fn), encoding="utf-8").read()
    return refs

def judge_template(text, refs, outdir, label):
    h = hashlib.sha256(text.encode("utf-8")).hexdigest()
    same = [n for n, r in refs.items() if r == text]
    if same: return {"sha256": h, "chars": len(text), "verdict": "IDENTICAL", "matches": same[:6] + ([f"+{len(same)-6} more"] if len(same) > 6 else [])}
    trimmed = [n for n, r in refs.items() if r.strip() == text.strip()]
    if trimmed: return {"sha256": h, "chars": len(text), "verdict": "IDENTICAL apart from blank lines at the ends", "matches": trimmed[:6]}
    tl = text.splitlines(keepends=True)
    best = max(refs, key=lambda n: difflib.SequenceMatcher(None, refs[n].splitlines(), text.splitlines(), autojunk=False).ratio())
    diff = list(difflib.unified_diff(refs[best].splitlines(keepends=True), tl, fromfile=best, tofile=label, n=2))
    dp = os.path.join(outdir, re.sub(r"[^\w.@-]+", "_", label) + ".diff")
    open(dp, "w", encoding="utf-8").write("".join(diff))
    added = [l for l in diff if l.startswith("+") and not l.startswith("+++")]
    removed = [l for l in diff if l.startswith("-") and not l.startswith("---")]
    return {"sha256": h, "chars": len(text), "verdict": "DIFFERS", "closest": best, "lines_added": len(added), "lines_removed": len(removed), "diff": dp}

# ---------------- automatic lab references (--auto-refs) ----------------
_LAB_CACHE = {}
def repos_named(p, kv=None):
    """the Hugging Face repos a model file says it came from: GGUF general.* fields, a README's base_model, an HF cache path"""
    out = []
    for k, v in (kv or {}).items():
        if isinstance(v, str) and k.startswith("general.") and ("repo_url" in k or k.endswith("source.url") or k == "general.url"):
            m = re.match(r"https?://huggingface\.co/([^/\s]+/[^/\s?#]+)", v)
            if m: out.append(m.group(1))
    d = os.path.dirname(p); rd = os.path.join(d, "README.md")
    if os.path.exists(rd):
        txt = open(rd, encoding="utf-8", errors="replace").read(20000)
        fm = txt.split("---")[1] if txt.startswith("---") and txt.count("---") >= 2 else ""
        m = re.search(r"^base_model:\s*(.*)$((?:\n\s*-\s*.*)*)", fm, re.M)
        if m: out += [x.strip().strip("'\"") for x in re.findall(r"[\w.-]+/[\w.-]+", m.group(1) + m.group(2))]
    m = re.search(r"models--([^/]+?)--([^/]+)", p)                                  # Hugging Face cache
    if m: out.append(m.group(1) + "/" + m.group(2))
    m = re.search(r"\.lmstudio/models/([^/]+)/([^/]+)/", p)                         # LM Studio's own folders
    if m: out.append(m.group(1) + "/" + m.group(2))
    m = re.search(r"/([\w.-]+?)__([\w.-]+)/[^/]+$", p)                              # folders named uploader__repo
    if m: out.append(m.group(1) + "/" + m.group(2))
    return list(dict.fromkeys(out))

_CHAIN_CACHE = {}
def lab_refs_for(repos, cache_dir):
    """walk each repo's base_model chain to the lab(s) and load every template those labs ever published (cached per lab)"""
    import precheck_hub as P
    key = tuple(repos)
    if key in _CHAIN_CACHE: return _CHAIN_CACHE[key]
    labs, chains = [], {}
    for r in repos:
        ch = P.chain(r, {}); chains[r] = ch
        labs += [x for x in ch if x.split("/")[0] in P.LABS]
    refs = {}
    for lab in dict.fromkeys(labs):
        if lab not in _LAB_CACHE:
            d = os.path.join(cache_dir, lab.replace("/", "__")); n = P.lab_templates([lab], d) if not os.path.isdir(d) else -1
            _LAB_CACHE[lab] = load_refs(d) if os.path.isdir(d) else {}
        refs.update(_LAB_CACHE[lab])
    _CHAIN_CACHE[key] = (refs, list(dict.fromkeys(labs)), chains)
    return _CHAIN_CACHE[key]

def text_hits(s):
    hits = sorted({m.group(0).lower() for m in SUSPECT.finditer(s)})
    accented = sorted({w for w in NON_ASCII_WORD.findall(s)})[:20]
    return hits, accented

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--refs"); ap.add_argument("--out", required=True)
    ap.add_argument("--auto-refs", action="store_true", help="also find each file's lab from its own metadata and compare with that lab's templates")
    ap.add_argument("--gguf-py", action="append", required=True); ap.add_argument("paths", nargs="+")
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True); tpl_dir = os.path.join(a.out, "templates"); os.makedirs(tpl_dir, exist_ok=True)
    tables = load_type_tables(a.gguf_py); refs = load_refs(a.refs) if a.refs else {}
    lab_dir = os.path.join(a.out, "lab-refs")
    def refs_for(p, kv=None):
        if not a.auto_refs: return refs, []
        try: extra, labs, _ = lab_refs_for(repos_named(p, kv), lab_dir)
        except Exception as e: extra, labs = {}, [f"(lab lookup failed: {e!r})"[:120]]
        return {**refs, **extra}, labs
    def judge(v, rf, label):
        if not rf: return {"sha256": hashlib.sha256(v.encode()).hexdigest(), "chars": len(v), "verdict": "NO LAB REFERENCE"}
        return judge_template(v, rf, tpl_dir, label)
    print(f"{len(refs)} official template versions loaded; readers: {[d for d, _ in tables]}", flush=True)
    files = []
    for root in a.paths:
        if os.path.isfile(root): files.append(root); continue
        for dp, dn, fs in os.walk(root):
            dn.sort()
            for fn in sorted(fs): files.append(os.path.join(dp, fn))
    def _is_weights(p):
        if p.endswith((".gguf", ".safetensors")): return True
        try: return p.endswith((".bin", ".pt", ".pth", ".ckpt")) and os.path.getsize(p) > 50_000_000      # pickled weights
        except OSError: return False
    model_dirs = {os.path.dirname(p) for p in files if _is_weights(p)}
    rows, nlook = [], 0
    for p in files:
        fn = os.path.basename(p); t0 = time.time(); r = None
        try:
            if fn.endswith(".gguf"):
                r, kv = gguf_file(p, tables)
                r["templates"] = {}; rf, r["labs"] = refs_for(p, kv)
                for k, v in kv.items():
                    if isinstance(v, str) and "template" in k.lower():
                        label = fn + "." + k
                        open(os.path.join(tpl_dir, label + ".jinja"), "w", encoding="utf-8").write(v)
                        j = judge(v, rf, label); hits, acc = text_hits(v); j["words"] = hits; j["accented_words"] = acc
                        r["templates"][k] = j
                        if j["verdict"] == "DIFFERS": r["look"].append(f'template {k} differs from every official version: read {j["diff"]}')
                        if j["verdict"] == "NO LAB REFERENCE": r["look"].append(f"template {k}: no lab template to compare with (words: {hits}, accented: {acc}); read {os.path.join(tpl_dir, label + '.jinja')}")
                    elif k not in SKIP_KV_ARRAYS:
                        s = v if isinstance(v, str) else (" ".join(x for x in v if isinstance(x, str)) if isinstance(v, list) else "")
                        hits, acc = text_hits(s)
                        hits = [h for h in hits if h not in ("https://", "http://")]  # source links in general.* fields are normal
                        if hits: r["look"].append(f"header text {k}: {hits}: {s[:160]!r}")
                r["general"] = {k: v for k, v in kv.items() if k.startswith("general.") and isinstance(v, (str, int, float)) and len(str(v)) < 200}
            elif fn.endswith(".safetensors"):
                r = safetensors_file(p)
            elif fn in ("chat_template.jinja", "chat_template.json", "tokenizer_config.json") and os.path.dirname(p) in model_dirs:
                raw = open(p, encoding="utf-8").read(); r = {"kind": fn, "size": len(raw), "look": [], "templates": {}}
                if fn == "chat_template.jinja": items = {"chat_template.jinja": raw}
                else:
                    d = json.loads(raw); ct = d.get("chat_template")
                    items = ({"chat_template": ct} if isinstance(ct, str) else
                             {f'chat_template[{x.get("name")}]': x.get("template", "") for x in ct} if isinstance(ct, list) else {})
                rf, r["labs"] = refs_for(p) if items else ({}, [])
                for k, v in items.items():
                    label = os.path.basename(os.path.dirname(p)) + "__" + k
                    open(os.path.join(tpl_dir, label + ".jinja"), "w", encoding="utf-8").write(v)
                    j = judge(v, rf, label); hits, acc = text_hits(v); j["words"] = hits; j["accented_words"] = acc
                    r["templates"][k] = j
                    if j["verdict"] == "DIFFERS": r["look"].append(f'template {k} differs from every official version: read {j["diff"]}')
                    if j["verdict"] == "NO LAB REFERENCE": r["look"].append(f"template {k}: no lab template to compare with (words: {hits}, accented: {acc}); read {os.path.join(tpl_dir, label + '.jinja')}")
            elif fn == "config.json" and os.path.dirname(p) in model_dirs:
                d = json.load(open(p)); r = {"kind": "config.json", "size": os.path.getsize(p), "look": []}
                if "auto_map" in d: r["look"].append(f'auto_map (custom code would run with trust_remote_code): {d["auto_map"]}')
            elif os.path.dirname(p) in model_dirs and re.search(r"\.(py|pkl|pickle|pt|pth|ckpt|bin|sh|exe|dll|ps1|bat|cmd|so|dylib|jar)$", fn, re.I):
                r = {"kind": "program/pickle beside the weights", "size": os.path.getsize(p), "look": [f"{fn}: a file that can run code"]}
            else:
                continue
        except Exception as e:
            r = {"kind": "UNREADABLE", "size": os.path.getsize(p), "look": [f"could not read: {e!r}"[:300]]}
        r["file"] = p; r["seconds"] = round(time.time() - t0, 1); rows.append(r)
        flag = bool(r["look"]); nlook += flag
        tv = "; ".join(f'{k.split(".")[-1]}={j["verdict"]}' for k, j in r.get("templates", {}).items())
        print(f'{"⚠ LOOK" if flag else "ok    "} {r["kind"][:14]:14} {r["size"]/1e9:7.2f} GB {r["seconds"]:6.1f}s  {tv}  {p}', flush=True)
        for l in r["look"][:12]: print("         - " + l, flush=True)
        for l in r.get("notes", []): print("         · " + l, flush=True)
    json.dump(rows, open(os.path.join(a.out, "MODEL-CHECK-v2.json"), "w"), indent=1, default=str)
    print(f"\n{len(rows)} files looked at, {nlook} to look at by hand. Report: {os.path.join(a.out, 'MODEL-CHECK-v2.json')}")
    sys.exit(1 if nlook else 0)

if __name__ == "__main__":
    main()
