Jeveration-GGUF / scripts /quant_compare.py
Meshwa's picture
Model card, CPU inference code (llama.cpp helper + Python), set-up scripts, examples
6a8ca2a verified
Raw History Blame Contribute Delete
10.7 kB
"""Compare the GGUF quantizations with the f16 GGUF on the same inputs, to choose one.
text-to-image hidden-state cosine, KL(f16 || quant) of the 128 code distributions, top-1 code agreement,
and a picture grid where every format uses the same random draws (rows: prompts, columns: formats)
depth AbsRel / delta1 against NYUv2 ground truth, and the mean relative change from the f16 depth map
python scripts/quant_compare.py # every jeveration-backbone-*.gguf found
python scripts/quant_compare.py --quants Q2_K,Q4_K_M,Q8_0 --nyu 3
Three phases so that RAM peaks stay small (the f16 backbone alone is 8.4 GB): (1) build all inputs with the
PyTorch side, then free it; (2) run each GGUF on them, one helper process at a time; (3) heads + decoder.
Phase 2 is resumable: hidden states are cached per format in <out>/hidden_<quant>.npz.
"""
import argparse
import gc
import glob
import json
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from jev_gguf import WORK, Backbone, default_gguf, embd_entries, text_entries # also puts the Jeveration repo on sys.path
from jeveration import config # noqa: E402
from jeveration.random_state import sample_random_state # noqa: E402
ORDER = ["Q2_K", "Q3_K_S", "Q3_K_M", "Q3_K_L", "Q4_0", "Q4_K_S", "Q4_K_M", "Q5_K_S", "Q5_K_M", "Q6_K", "Q8_0", "f16"]
PROMPTS = ["A red fox sitting in fresh snow, golden hour.",
"A bowl of ramen with a soft-boiled egg, top view, on a wooden table.",
"A lighthouse on a rocky cliff under a stormy sky."]
def find_quants():
found = {Path(p).stem.split("jeveration-backbone-")[-1] for p in glob.glob(str(WORK / "jeveration-backbone-*.gguf"))
+ glob.glob(str(WORK / "gguf" / "jeveration-backbone-*.gguf"))}
return [q for q in ORDER if q in found]
@torch.no_grad()
def build_inputs(seed, n_nyu):
"""phase 1: every backbone request (text-to-image decision tokens; dense depth queries) as numpy"""
from safetensors import safe_open
from transformers import AutoTokenizer
from t2i_gguf import DecisionSide
from jeveration.prompts import PromptTokenizer
tok = AutoTokenizer.from_pretrained(str(WORK / "qwen3.5-4b"))
side = DecisionSide(2560).eval()
lat_mean, lat_std = side.load(WORK / "jeveration-weights" / "jeveration.pt")
with safe_open(str(WORK / "tatitok" / "model.safetensors"), "pt") as f:
cb = f.get_tensor("quantize.embedding.weight").float().to(torch.float16).float() # as Jeveration.set_codebook
codebook_std = (cb - lat_mean.float().view(1, -1)) / lat_std.float().view(1, -1)
ptok = PromptTokenizer(tok)
t2i = []
for i, prompt in enumerate(PROMPTS):
ids = ptok.encode(prompt)
state, t = sample_random_state(side.mask_emb, codebook_std, 1, torch.Generator().manual_seed(seed + i))
tc = (side.t_mlp(t) + side.h_mlp(torch.zeros_like(t)))[:, None]
tail = side.z_in(state.float()) + side.z_pos + tc
p = len(ids) + np.arange(tail.shape[1])
t2i.append(dict(prefix=text_entries(ids), decision=embd_entries(p, p, p), decision_embd=tail[0].numpy(),
state=state.float(), t=t, prompt=prompt))
del side
gc.collect()
dense = []
if n_nyu:
import pyarrow.parquet as pq
from dense_gguf import DenseSide, dense_request, load_vision_tower
from jeveration.dense import resize_for_vision
from jeveration.prompts import SourcePromptTokenizer, vision_tokens
from nyu_eval import rows
dside = DenseSide(2560).eval()
dside.load(WORK / "jeveration-weights" / "jeveration.pt")
visual = load_vision_tower(WORK / "qwen3.5-4b")
sptok = SourcePromptTokenizer(tok)
for g, img, d_gt, _, _ in rows(sorted(glob.glob(str(WORK / "nyuv2" / "val-*.parquet"))), n_nyu):
vis, _ = vision_tokens(visual, resize_for_vision(torch.from_numpy(img.copy())[None]))
prefix, decision, pe, de = dense_request(dside, sptok, vis.float(), "depth")
dense.append(dict(prefix=prefix, decision=decision, prefix_embd=pe, decision_embd=de, gt=d_gt, index=int(g)))
del dside, visual
gc.collect()
return t2i, dense
def run_backbone(gguf, t2i, dense, threads):
"""phase 2: one GGUF on every request -> {"t2i": [n, 128, H], "dense": [m, 432, H]}"""
bb = Backbone(gguf, threads, n_ubatch=512)
try:
h_t = [bb(c["prefix"], c["decision"], decision_embd=c["decision_embd"]) for c in t2i]
h_d = [bb(c["prefix"], c["decision"], prefix_embd=c["prefix_embd"], decision_embd=c["decision_embd"]) for c in dense]
finally:
bb.close()
return {"t2i": np.stack(h_t), "dense": np.stack(h_d) if h_d else np.zeros((0, 1, 1), np.float32)}
@torch.no_grad()
def evaluate(quants, hidden, t2i, dense, ref, seed, out):
"""phase 3: logits/codes/pictures for text-to-image, depth maps for dense -> rows of the table"""
from PIL import Image, ImageDraw
from t2i_gguf import DecisionSide
from dense_gguf import DenseSide, depth_metrics
from jeveration.dense import to_predictions
from jeveration.images import to_uint8
from jeveration.tokenizer import ImageCodec
side = DecisionSide(2560).eval()
side.load(WORK / "jeveration-weights" / "jeveration.pt")
logits = {}
for q in quants:
logits[q] = [(side.code_head(pr) + side.code_wide(u)).float()[0]
for c, h in zip(t2i, hidden[q]["t2i"])
for pr, u in [side.head(torch.from_numpy(h.copy())[None], c["state"], side.cond(c["t"]))]]
del side
gc.collect()
rows = {q: {"format": q} for q in quants}
ref_lp = [F.log_softmax(l, -1) for l in logits[ref]]
codes = {}
for q in quants:
lp = [F.log_softmax(l, -1) for l in logits[q]]
r = rows[q]
r["hidden_cos"] = float(np.mean([F.cosine_similarity(torch.from_numpy(a), torch.from_numpy(b), dim=-1).mean()
for a, b in zip(hidden[q]["t2i"], hidden[ref]["t2i"])]))
r["code_KL"] = float(np.mean([(a.exp() * (a - b)).sum(-1).mean() for a, b in zip(ref_lp, lp)]))
r["top1_agree"] = float(np.mean([(a.argmax(-1) == b.argmax(-1)).float().mean() for a, b in zip(ref_lp, lp)]))
codes[q] = [torch.multinomial(l.exp(), 1, generator=torch.Generator().manual_seed(seed + i)).view(1, -1)
for i, l in enumerate(lp)] # the same draws for every format
if dense:
dside = DenseSide(2560).eval()
dside.load(WORK / "jeveration-weights" / "jeveration.pt")
depth = {}
for q in quants:
depth[q] = []
for c, h in zip(dense, hidden[q]["dense"]):
raw = F.interpolate(dside.readout("depth", torch.from_numpy(h.copy())[None]).float(), size=c["gt"].shape,
mode="bilinear", align_corners=False)
depth[q].append(to_predictions("depth", raw)[0].numpy())
for q in quants:
ms = [depth_metrics(d, c["gt"], crop=False) for d, c in zip(depth[q], dense)]
rows[q]["depth_AbsErr_m"] = float(np.mean([m["AbsErr"] for m in ms]))
rows[q]["depth_AbsRel"] = float(np.mean([m["AbsRel"] for m in ms]))
rows[q]["depth_d1"] = float(np.mean([m["d1"] for m in ms]))
rows[q]["depth_change_vs_ref"] = float(np.mean([np.mean(np.abs(d - r) / np.maximum(r, 1e-3))
for d, r in zip(depth[q], depth[ref])]))
del dside
gc.collect()
codec = ImageCodec(str(WORK / "tatitok"), str(WORK / "clip")).eval()
codec.load_decoder(str(WORK / "jeveration-weights" / "decoder512.pt"))
cell, pad = 256, 28
grid = Image.new("RGB", (cell * len(quants), pad + cell * len(t2i)), "white")
draw = ImageDraw.Draw(grid)
for j, q in enumerate(quants):
draw.text((j * cell + 8, 8), q, fill="black")
for i, c in enumerate(t2i):
img = Image.fromarray(to_uint8(codec.decode(codes[q][i], [c["prompt"]]))[0])
img.save(out / f"t2i_{i}_{q}.png")
grid.paste(img.resize((cell, cell), Image.LANCZOS), (j * cell, pad + i * cell))
grid.save(out / "grid.png")
return [rows[q] for q in quants]
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--quants", default="", help="comma list; default every GGUF found")
ap.add_argument("--ref", default="f16")
ap.add_argument("--nyu", type=int, default=3, help="NYUv2 test images for depth (0 = skip)")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--threads", type=int, default=4)
ap.add_argument("--out", default=str(WORK / "quant_compare"))
a = ap.parse_args()
torch.set_num_threads(a.threads)
quants = [q for q in a.quants.split(",") if q] or find_quants()
if a.ref not in quants:
quants.append(a.ref)
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
t0 = time.time()
t2i, dense = build_inputs(a.seed, a.nyu)
print(f"inputs ready in {time.time() - t0:.0f}s: {len(t2i)} prompts, {len(dense)} NYUv2 images", flush=True)
hidden = {}
for q in quants:
cache = out / f"hidden_{q}.npz"
if cache.exists():
hidden[q] = dict(np.load(cache))
else:
t1 = time.time()
hidden[q] = run_backbone(default_gguf(q), t2i, dense, a.threads)
np.savez(cache, **hidden[q])
print(f"{q}: backbone {time.time() - t1:.0f}s", flush=True)
rows = evaluate(quants, hidden, t2i, dense, a.ref, a.seed, out)
sizes = {q: Path(default_gguf(q)).stat().st_size / 2 ** 30 for q in quants}
for r in rows:
r["GiB"] = round(sizes[r["format"]], 2)
(out / "results.json").write_text(json.dumps(rows, indent=1))
cols = ["format", "GiB", "hidden_cos", "code_KL", "top1_agree"] + \
(["depth_AbsErr_m", "depth_AbsRel", "depth_d1", "depth_change_vs_ref"] if dense else [])
lines = ["| " + " | ".join(cols) + " |", "|" + "---|" * len(cols)]
for r in rows:
lines.append("| " + " | ".join(f"{r[c]:.4f}" if isinstance(r[c], float) else str(r[c]) for c in cols) + " |")
(out / "table.md").write_text("\n".join(lines) + "\n")
print("\n".join(lines))
print(f"grid: {out / 'grid.png'} (reference: {a.ref}; {len(dense)} NYUv2 images)")
if __name__ == "__main__":
main()