File size: 10,699 Bytes
6a8ca2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()