gpu-head-to-head
aien-dev/gpu-head-to-head
Brought by drakestapleton
gpu-head-to-head / q35-9b / tools / cmp_weights.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Throwaway check (host tool): are llama.cpp's BF16 GGUF tensors byte-identical to the HF safetensors? |
| 3 | Matches tensors by element count + bytes; reports identical, transformed (same count, different bytes), |
| 4 | and unmatched, by name. Run inside the vLLM container (torch, safetensors) with gguf-py installed.""" |
| 5 | import hashlib, json, sys, glob |
| 6 | from safetensors import safe_open |
| 7 | import torch |
| 8 | import gguf |
| 9 | |
| 10 | HF, GG = sys.argv[1], sys.argv[2] |
| 11 | hf = {} |
| 12 | for f in sorted(glob.glob(HF + "/model.safetensors-*.safetensors")): |
| 13 | with safe_open(f, "pt") as s: |
| 14 | for k in s.keys(): |
| 15 | if ".visual." in k or k.startswith("mtp.") or "model.visual" in k: |
| 16 | continue |
| 17 | t = s.get_tensor(k) |
| 18 | hf[k] = t |
| 19 | by_hash = {} |
| 20 | for k, t in hf.items(): |
| 21 | b = t.contiguous().view(torch.uint8).numpy().tobytes() if t.dtype == torch.bfloat16 else None |
| 22 | if b is not None: |
| 23 | by_hash.setdefault(hashlib.sha256(b).hexdigest(), []).append(k) |
| 24 | |
| 25 | r = gguf.GGUFReader(GG) |
| 26 | out = {"identical": [], "not_identical": []} |
| 27 | for t in r.tensors: |
| 28 | h = hashlib.sha256(bytes(t.data.tobytes())).hexdigest() |
| 29 | name = t.name |
| 30 | typ = t.tensor_type.name |
| 31 | if h in by_hash: |
| 32 | out["identical"].append([name, typ, by_hash[h][0]]) |
| 33 | else: |
| 34 | out["not_identical"].append([name, typ, [int(x) for x in t.shape]]) |
| 35 | print(json.dumps({"gguf_tensors": len(r.tensors), "hf_text_tensors": len(hf), |
| 36 | "identical": len(out["identical"]), "not_identical": len(out["not_identical"])})) |
| 37 | kinds = {} |
| 38 | for name, typ, shape in out["not_identical"]: |
| 39 | key = (name.split(".", 2)[-1] if name.startswith("blk.") else name, typ) |
| 40 | kinds[key] = kinds.get(key, 0) + 1 |
| 41 | for (k, typ), n in sorted(kinds.items()): |
| 42 | print("NOT_IDENTICAL", k, typ, "x%d" % n) |
| 43 | json.dump(out, open(sys.argv[3], "w"), indent=0) |