okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-145-q36 (Qwen3.6 start that cannot fit its buffers says so; vision_cmp --dump-ngl)e79156ae2

main
8.3 KiB146 linesraw
1"""vcmp.py - the picture gate: strata-q36 against llama.cpp (mtmd) on the same GGUF + mmproj, same pictures.
2
3For each (picture, question): llama.cpp HIP (q36_mtmd_dump, encoder on the CPU like strata-vision's) gives the prompt's
4chunks, its greedy answer and every step's full logits; the encoder file of strata-vision (venc.py) is laid over the same
5ids; strata-q36 (--tokens ids --emb file --force llama's greedy ids) gives its logits on the same sequence.  Reported:
6the answer text agreement, the first token's logits (top-1/top-2 both, max |diff| over the top-5), the teacher-forced
7mean KL(P_llama || Q_strata) and top-1 agreement over the steps, and - the floor - the same numbers for llama.cpp's CPU
8backend against llama.cpp HIP.
9
10  python q36_vision_cmp.py --dump BIN --q36 BIN --vision BIN --model GGUF --mmproj F --out DIR --pic shapes.png --pic code4217.png
11                 [--lock "flock ..."] [--n 24] [--q36-args "--vision --max-context 4096"]
12"""
13from pathlib import Path
14import argparse, json, os, shlex, struct, subprocess, sys
15import numpy as np
16
17V = 248320
18QUESTIONS = {
19    "shapes.png": ["What text is written in the image? Answer with the text only.",
20                   "List every shape in the image with its colour, from left to right. One short line each."],
21    "code4217.png": ["What text is written in the image? Answer with the text only.",
22                     "Describe the shapes in the image with their colours and positions, one short line each."],
23}
24TEMPLATE = "<|im_start|>user\n<__media__>{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
25PAD = 248056
26TEMPLATE_PAIR = ("<|im_start|>user\nPicture 1: <__media__>\nPicture 2: <__media__>\n{q}<|im_end|>\n<|im_start|>assistant\n"
27                 "<think>\n\n</think>\n\n")
28PAIR_QUESTIONS = ["What text is written in each of the two pictures? One short line for each."]
29
30
31def run(cmd, lock, log, env=None):
32    full = (shlex.split(lock) if lock else []) + cmd
33    e = dict(os.environ)
34    e.update(env or {})
35    r = subprocess.run(full, capture_output=True, text=True, timeout=3600, env=e)
36    open(log, "w").write(r.stdout + "\n--- stderr ---\n" + r.stderr)
37    if r.returncode != 0:
38        raise SystemExit("%s failed (rc %d), see %s" % (cmd[0], r.returncode, log))
39    return r.stdout
40
41
42def parse_dump(out):
43    chunks, gen, first = [], [], None
44    for l in out.splitlines():
45        if l.startswith("text:"):
46            chunks.append(("text", [int(x) for x in l.split(":", 1)[1].split()]))
47        elif l.startswith("image:"):
48            chunks.append(("image", int(l.split()[1])))
49        elif l.startswith("gen:"):
50            gen = [int(x) for x in l.split(":", 1)[1].split()]
51        elif l.startswith("first:"):
52            first = l
53    return chunks, gen, first
54
55
56def log_softmax(x):
57    x = x.astype(np.float64)
58    m = x.max(axis=1, keepdims=True)
59    return x - m - np.log(np.exp(x - m).sum(axis=1, keepdims=True))
60
61
62def kl_stats(p_logits, q_logits):
63    n = min(len(p_logits), len(q_logits))
64    lp, lq = log_softmax(p_logits[:n]), log_softmax(q_logits[:n])
65    kl = (np.exp(lp) * (lp - lq)).sum(axis=1)
66    top1 = (p_logits[:n].argmax(axis=1) == q_logits[:n].argmax(axis=1))
67    return kl, top1
68
69
70def main():
71    ap = argparse.ArgumentParser()
72    ap.add_argument("--dump", required=True)
73    ap.add_argument("--q36", required=True)
74    ap.add_argument("--vision", required=True)
75    ap.add_argument("--venc", default=str(Path(__file__).resolve().parent / "q36_venc.py"))
76    ap.add_argument("--model", required=True)
77    ap.add_argument("--mmproj", required=True)
78    ap.add_argument("--out", required=True)
79    ap.add_argument("--pic", action="append", required=True, help="a picture, or a+b for one request with two pictures")
80    ap.add_argument("--lock", default="")
81    ap.add_argument("--n", type=int, default=24)
82    ap.add_argument("--q36-args", default="--vision --max-context 4096")
83    ap.add_argument("--floor", action="store_true", help="also llama.cpp CPU (ngl 0) vs HIP")
84    ap.add_argument("--dump-ngl", type=int, default=99, help="llama.cpp's offloaded layers (a quant larger than the card: fewer)")
85    a = ap.parse_args()
86    os.makedirs(a.out, exist_ok=True)
87    rows = []
88    for pic_spec in a.pic:
89        pics = pic_spec.split("+")            # "a.png+b.png": one request with two pictures (one <__media__> each)
90        name = "+".join(os.path.basename(p) for p in pics)
91        # the encoder's file (strata-vision, CPU): one record per picture, in prompt order
92        run([sys.executable, a.venc, a.vision, a.mmproj, a.model, *pics], "", os.path.join(a.out, name + ".venc.log"))
93        emb = os.path.join(a.out, name + ".sve")
94        with open(emb, "wb") as f:
95            for p in pics:
96                f.write(open(p + ".sve", "rb").read())
97        questions = QUESTIONS.get(name, ["Describe this image."] if len(pics) == 1 else PAIR_QUESTIONS)
98        for qi, q in enumerate(questions):
99            tag = "%s.q%d" % (name, qi)
100            prompt = TEMPLATE.format(q=q) if len(pics) == 1 else TEMPLATE_PAIR.format(q=q)
101            ref_log = os.path.join(a.out, tag + ".llama.log")
102            logit_f = os.path.join(a.out, tag + ".llama.logits")
103            out = run([a.dump, "--model", a.model, "--mmproj", a.mmproj, *sum([["--image", p] for p in pics], []),
104                       "--prompt", prompt, "--n", str(a.n),
105                       "--dump-full-logits", logit_f, "--mm-cpu", "1", "--max-tokens", "1024", "--ngl", str(a.dump_ngl)], a.lock, ref_log)
106            chunks, gen, first = parse_dump(out)
107            ids = []
108            for kind, v in chunks:
109                ids += v if kind == "text" else [PAD] * v
110            tot_rows, off, data = 0, 0, open(emb, "rb").read()
111            while off < len(data):                 # the records' row counts
112                h = struct.unpack("<5i", data[off:off + 20])
113                tot_rows += h[1]
114                off += 20 + 4 * h[1] * h[4]
115            assert tot_rows == sum(v for k, v in chunks if k == "image"), "the encoders disagree on the token count %d vs %s" % (tot_rows, chunks)
116            q_logit_f = os.path.join(a.out, tag + ".q36.logits")
117            qout = run([a.q36, "--model", a.model, "--tokens", ",".join(map(str, ids)), "--emb", emb, "--n", str(a.n),
118                        "--force", ",".join(map(str, gen[:-1])), "--dump-full-logits", q_logit_f, *shlex.split(a.q36_args)],
119                       a.lock, os.path.join(a.out, tag + ".q36.log"))
120            qgen = [int(x) for x in [l for l in qout.splitlines() if l.startswith("gen:")][0].split(":", 1)[1].split()]
121            P = np.fromfile(logit_f, dtype=np.float32).reshape(-1, V)
122            Q = np.fromfile(q_logit_f, dtype=np.float32).reshape(-1, V)
123            kl, top1 = kl_stats(P, Q)
124            d5 = np.abs(np.sort(P[0])[-5:] - np.sort(Q[0])[-5:]).max()
125            row = {"tag": tag, "prompt_tokens": len(ids), "llama_gen": gen, "strata_gen_forced": qgen,
126                   "first_top1_same": bool(P[0].argmax() == Q[0].argmax()), "first_max_top5_diff": float(d5),
127                   "kl_mean": float(kl.mean()), "kl_first": float(kl[0]), "top1": float(top1.mean()), "steps": int(len(kl))}
128            if a.floor:
129                fl = os.path.join(a.out, tag + ".cpu.logits")
130                run([a.dump, "--model", a.model, "--mmproj", a.mmproj, *sum([["--image", p] for p in pics], []),
131                     "--prompt", prompt, "--n", str(a.n),
132                     "--dump-full-logits", fl, "--mm-cpu", "1", "--max-tokens", "1024", "--ngl", "0", "--force",
133                     ",".join(map(str, gen[:-1]))], "", os.path.join(a.out, tag + ".cpu.log"))
134                C = np.fromfile(fl, dtype=np.float32).reshape(-1, V)
135                klc, t1c = kl_stats(P, C)
136                row.update({"floor_kl_mean": float(klc.mean()), "floor_kl_first": float(klc[0]), "floor_top1": float(t1c.mean()),
137                            "floor_first_max_top5_diff": float(np.abs(np.sort(P[0])[-5:] - np.sort(C[0])[-5:]).max())})
138            rows.append(row)
139            print(json.dumps({k: v for k, v in row.items() if k not in ("llama_gen", "strata_gen_forced")}), flush=True)
140            print("  llama  :", gen[:16], flush=True)
141            print("  strata :", qgen[:16], "(teacher-forced on llama's ids: its own greedy at each step)", flush=True)
142    json.dump(rows, open(os.path.join(a.out, "summary.json"), "w"), indent=1)
143
144
145if __name__ == "__main__":
146    main()