okami.mom/strata

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

Niko1221Quality ids files: a token id outside the model's vocabulary fails loudly (the engine's --score / --profile-run / --spec-eval, and quant_quality.py run)b3e73dbfb

main
17.9 KiB400 linesraw
1#!/usr/bin/env python3
2"""The quant quality yardstick (MODEL-UPDATE.md, Phase 0): teacher-forced top-1 agreement and KL of a quant against
3Q8_0, on one fixed text set (data/quant_quality/v1: code, docs, English, other languages, an agent transcript).
4
5    python tools/quant_quality.py ids --tokenizer DIR [--set data/quant_quality/v1] [--out set.ids.json]
6        tokenizes the set (each segment cut to --seg-tokens, default 1000) - the ids file is committed with the set
7        (data/quant_quality/v1/set.ids.json), so a box without the tokenizer scores the same positions
8    python tools/quant_quality.py run --config CFG.json --out RUN.tsv [--ids set.ids.json] [--env K=V ...] [--gpu-experts]
9        one `strata --serve` engine (the config's exe and args), every segment one request whose tokens are all read
10        through the decode windows (--short-read), where STRATA_LOGPOS / STRATA_LOGPOS_TOPK=64 write, per position,
11        the log-probability of the text's next token and the 64 most likely tokens.  Fixed: the experts on the CPU
12        (one VRAM slot, --expert-cache 1: the verify windows need a profile-filled tier, so the config must have
13        --expert-profile; --gpu-experts: 1500 slots), no expert adaptation, no PCIe share, no suffix drafts, no prompt
14        cache, FP16 K/V, STRATA_ROUTE_TAIL_SKIP=0, STRATA_PREFILL_CPU_SHARE=0.  RUN.tsv + RUN.tsv.seg.json (line ranges).
15    python tools/quant_quality.py compare REF.tsv RUN.tsv [...]   (REF = the Q8_0 run)
16        per segment and overall: top-1 agreement (same argmax), mean / p99 KL(REF || RUN) over REF's 64 most likely
17        tokens (both renormalized to that set; a token RUN does not list gets RUN's 64th log-probability), and the
18        perplexity of the text under each.
19
20The RUN.tsv rows are the engine's STRATA_LOGPOS format: pos, target id, logp(target), argmax id, logp(argmax),
21argmax==target, logp(<|im_end|>), logp(target without <|im_end|>), then 64 `id:logp` fields (natural log).
22"""
23from __future__ import annotations
24
25import argparse
26import json
27import math
28import os
29import pathlib
30import subprocess
31import sys
32import time
33
34HERE = pathlib.Path(__file__).resolve().parent
35SET_DIR = HERE.parent / "data" / "quant_quality" / "v1"
36SEGMENTS = ["code", "docs", "english", "multilingual", "agent"]
37TOPK = 64
38FIXED = ["--expert-cache", "1", "--adapt-every", "100000", "--pcie-frac", "0", "--suffix-draft", "0",
39         "--prompt-cache", "0", "--kv", "fp16"]
40FIXED_ENV = {"STRATA_ROUTE_TAIL_SKIP": "0", "STRATA_PREFILL_CPU_SHARE": "0", "STRATA_PCIE_FRAC_DEFAULT": "old"}
41# config args the yardstick replaces (value-taking) or drops (flags)
42DROP_VALUE = {"--expert-cache", "--adapt-every", "--pcie-frac", "--suffix-draft", "--prompt-cache", "--max-context",
43              "--prefill", "--prompt-cache-every", "--short-read", "--conversation-cache-mib", "--eos-ids",
44              "--kv", "--kv-resident"}   # (--resident-budget-gib stays: a PC whose RAM does not hold the experts)
45DROP_FLAG = {"--serve", "--vision", "--resident-experts", "--resident-cpu-experts"}
46
47
48# ------------------------------------------------------------------------------------------------ ids
49def cmd_ids(a) -> int:
50    sys.path.insert(0, str(HERE))
51    import strata_tokenizer as ST  # noqa: E402
52    tp = pathlib.Path(a.tokenizer)
53    vocab = json.loads((tp / "vocab.json").read_text(encoding="utf-8"))
54    toks = [None] * len(vocab)
55    for t, i in vocab.items():
56        toks[i] = t
57    tok = ST.Tokenizer(toks, (tp / "merges.txt").read_text(encoding="utf-8").split("\n"),
58                       json.loads((tp / "token_type.json").read_text()))
59    segs = []
60    for name in SEGMENTS:
61        text = (pathlib.Path(a.set) / f"{name}.txt").read_text(encoding="utf-8")
62        ids = tok.encode(text, parse_special=(name == "agent"))
63        if len(ids) < a.seg_tokens:
64            raise SystemExit(f"{name}: only {len(ids)} tokens (< {a.seg_tokens})")
65        segs.append({"name": name, "ids": ids[:a.seg_tokens]})
66        print(f"{name}: {len(ids)} tokens, kept {a.seg_tokens}")
67    out = pathlib.Path(a.out or (pathlib.Path(a.set) / "set.ids.json"))
68    out.write_text(json.dumps({"version": pathlib.Path(a.set).name, "seg_tokens": a.seg_tokens, "vocab_size": len(toks), "segments": segs}))
69    print(f"wrote {out}")
70    return 0
71
72
73# ------------------------------------------------------------------------------------------------ run
74def mem_available_gb() -> float:
75    try:
76        for line in open("/proc/meminfo"):
77            if line.startswith("MemAvailable:"):
78                return int(line.split()[1]) / 1048576
79    except OSError:
80        pass
81    return float("inf")
82
83
84def engine_args(cfg: dict, gpu_experts, seg_tokens: int) -> list[str]:
85    base, out, i = list(cfg["args"]), [], 0
86    while i < len(base):
87        x = base[i]
88        if x in DROP_FLAG:
89            i += 1
90            continue
91        if x in DROP_VALUE:
92            i += 2
93            continue
94        out.append(x)
95        i += 1
96    fixed = list(FIXED)
97    if gpu_experts:
98        fixed[1] = gpu_experts if isinstance(gpu_experts, str) else "1500"
99    return [cfg["exe"], "--serve", *out, *fixed, "--max-context", str(seg_tokens + 512),
100            "--short-read", str(seg_tokens + 64), "--prefill", "512"]
101
102
103def check_ids_vocab(st: dict, cfg: dict, ids_path: str) -> None:
104    """A wrong ids file fails here, loudly: every id must be inside the model's vocabulary (the vocabulary of the config's tokenizer
105    folder when it names one, else the size the ids file recorded when `ids` made it), or the run reads nonsense - the committed
106    data/quant_quality/v1/set.ids.json is tokenized for Qwen (ids up to 248,069), not for DeepSeek's 129,280."""
107    vocab = None
108    tdir = cfg.get("tokenizer")
109    if tdir and (pathlib.Path(tdir) / "vocab.json").is_file():
110        vocab = len(json.loads((pathlib.Path(tdir) / "vocab.json").read_text(encoding="utf-8")))
111    elif st.get("vocab_size"):
112        vocab = int(st["vocab_size"])
113    if not vocab:
114        return
115    for s in st["segments"]:
116        mx = max(s["ids"]) if s["ids"] else -1
117        if mx >= vocab:
118            raise SystemExit(f"{ids_path}: segment '{s['name']}' has token id {mx} >= the model's vocabulary ({vocab}): this ids file was "
119                             f"made with another tokenizer; make one with `quant_quality.py ids --tokenizer <the model's tokenizer folder>`")
120
121
122def cmd_run(a) -> int:
123    cfg = json.load(open(a.config, encoding="utf-8-sig"))
124    st = json.load(open(a.ids))
125    check_ids_vocab(st, cfg, a.ids)
126    out = pathlib.Path(a.out).resolve()
127    out.parent.mkdir(parents=True, exist_ok=True)
128    if out.exists():
129        out.unlink()
130    env = dict(os.environ)
131    env.update(cfg.get("env", {}))
132    if cfg.get("lib_dirs"):
133        env["LD_LIBRARY_PATH"] = ":".join(cfg["lib_dirs"] + [env.get("LD_LIBRARY_PATH", "")])
134    env.update(FIXED_ENV)
135    for kv in a.env or []:
136        k, _, v = kv.partition("=")
137        env[k] = v
138    env["STRATA_LOGPOS"] = str(out)
139    env["STRATA_LOGPOS_TOPK"] = str(TOPK)
140    if mem_available_gb() < a.min_free_gb:
141        raise SystemExit(f"only {mem_available_gb():.0f} GB available (< {a.min_free_gb}): not starting an engine")
142    args = engine_args(cfg, a.gpu_experts, st["seg_tokens"])
143    if a.wrap:
144        args = a.wrap.split() + args
145    errf = open(str(out) + ".stderr.txt", "w")
146    print("engine:", " ".join(args), flush=True)
147    p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errf, text=True,
148                         cwd=cfg.get("cwd"), env=env, bufsize=1)
149    for line in p.stdout:
150        if line.startswith("READY"):
151            break
152    else:
153        raise SystemExit(f"the engine ended before READY (exit {p.wait()}); see {out}.stderr.txt")
154    segs, info = [], []
155
156    def lines() -> int:
157        return sum(1 for _ in open(out)) if out.exists() else 0
158
159    for s in st["segments"]:
160        n0, t0 = lines(), time.time()
161        p.stdin.write("GEN 1 " + ",".join(map(str, s["ids"])) + "\n")
162        p.stdin.flush()
163        done = None
164        for line in p.stdout:
165            if line.startswith(("DONE", "ERR")):
166                done = line.strip()
167                break
168        if done is None or not done.startswith("DONE") or "nonfinite" in done:
169            p.kill()
170            raise SystemExit(f"{s['name']}: the engine answered {done!r}; see {out}.stderr.txt")
171        n1 = lines()
172        segs.append({"name": s["name"], "first_line": n0, "end_line": n1})
173        info.append(f"{s['name']}: {n1 - n0} positions, {time.time() - t0:.1f} s")
174        print(info[-1], flush=True)
175        if n1 - n0 < len(s["ids"]) // 2:
176            p.kill()
177            raise SystemExit(f"{s['name']}: only {n1 - n0} positions were scored (the prompt took the batched path?)")
178    p.stdin.write("QUIT\n")
179    p.stdin.flush()
180    try:
181        p.wait(timeout=600)
182    except subprocess.TimeoutExpired:
183        p.kill()
184    errf.close()
185    err = pathlib.Path(str(out) + ".stderr.txt").read_text(errors="replace")
186    cache = [l for l in err.splitlines() if "expert cache" in l][:3]
187    pathlib.Path(str(out) + ".seg.json").write_text(json.dumps({"segments": segs, "config": a.config,
188                                                                 "args": args, "env": a.env or [],
189                                                                 "expert_cache_lines": cache}, indent=1))
190    return 0
191
192
193# ------------------------------------------------------------------------------------------------ prompt path
194PROMPT_LENS = (256, 512, 768, 1000)
195
196
197def cmd_prompt(a) -> int:
198    """The batched prompt path's answer: every segment's first 256 / 512 / 768 / 1000 tokens as a prompt (one request
199    each, no prompt cache), and the logits after it (STRATA_DUMP_FIRST_LOGITS: float32, the whole vocabulary)."""
200    cfg = json.load(open(a.config, encoding="utf-8-sig"))
201    st = json.load(open(a.ids))
202    out = pathlib.Path(a.out).resolve()
203    out.mkdir(parents=True, exist_ok=True)
204    for f in out.glob("first.*"):
205        f.unlink()
206    env = dict(os.environ)
207    env.update(cfg.get("env", {}))
208    if cfg.get("lib_dirs"):
209        env["LD_LIBRARY_PATH"] = ":".join(cfg["lib_dirs"] + [env.get("LD_LIBRARY_PATH", "")])
210    env.update(FIXED_ENV)
211    for kv in a.env or []:
212        k, _, v = kv.partition("=")
213        env[k] = v
214    env["STRATA_DUMP_FIRST_LOGITS"] = str(out / "first")
215    if mem_available_gb() < a.min_free_gb:
216        raise SystemExit(f"only {mem_available_gb():.0f} GB available (< {a.min_free_gb}): not starting an engine")
217    args = engine_args(cfg, a.gpu_experts, max(PROMPT_LENS))
218    k = args.index("--short-read")
219    del args[k:k + 2]                      # the default (64): these prompts take the batched prompt path
220    k = args.index("--prefill")
221    args[k + 1] = "auto"
222    if a.wrap:
223        args = a.wrap.split() + args
224    errf = open(out / "stderr.txt", "w")
225    print("engine:", " ".join(args), flush=True)
226    p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errf, text=True,
227                         cwd=cfg.get("cwd"), env=env, bufsize=1)
228    for line in p.stdout:
229        if line.startswith("READY"):
230            break
231    else:
232        raise SystemExit(f"the engine ended before READY (exit {p.wait()}); see {out}/stderr.txt")
233    index = []
234    for s in st["segments"]:
235        for n in PROMPT_LENS:
236            p.stdin.write("GEN 1 " + ",".join(map(str, s["ids"][:n])) + "\n")
237            p.stdin.flush()
238            done = None
239            for line in p.stdout:
240                if line.startswith(("DONE", "ERR")):
241                    done = line.strip()
242                    break
243            if done is None or not done.startswith("DONE") or "nonfinite" in done:
244                p.kill()
245                raise SystemExit(f"{s['name']} {n}: the engine answered {done!r}")
246            index.append({"segment": s["name"], "tokens": n})
247    p.stdin.write("QUIT\n")
248    p.stdin.flush()
249    try:
250        p.wait(timeout=600)
251    except subprocess.TimeoutExpired:
252        p.kill()
253    errf.close()
254    (out / "index.json").write_text(json.dumps({"requests": index, "args": args, "env": a.env or []}, indent=1))
255    print(f"{len(index)} prompts")
256    return 0
257
258
259def cmd_pcompare(a) -> int:
260    import numpy as np
261    ref = pathlib.Path(a.ref)
262    idx = json.loads((ref / "index.json").read_text())["requests"]
263
264    def logp(d, i):
265        x = np.fromfile(d / f"first.{i}", dtype=np.float32).astype(np.float64)
266        x -= x.max()
267        return x - np.log(np.exp(x).sum())
268
269    print(f"reference: {ref}")
270    for run in a.runs:
271        r = pathlib.Path(run)
272        kls, agree = [], 0
273        for i in range(len(idx)):
274            if not (r / f"first.{i}").exists():
275                continue
276            lr, la = logp(ref, i), logp(r, i)
277            pr = np.exp(lr)
278            kls.append(float((pr * (lr - la)).sum()))
279            agree += int(lr.argmax() == la.argmax())
280        kls.sort()
281        n = len(kls)
282        print(f"{r.name:40s} prompts {n:3d}  top-1 {100 * agree / max(n, 1):6.2f}%  KL mean {sum(kls) / max(n, 1):.5f}  "
283              f"median {kls[n // 2] if n else float('nan'):.5f}  max {kls[-1] if n else float('nan'):.5f}")
284    return 0
285
286
287# ------------------------------------------------------------------------------------------------ compare
288def read_run(path: str) -> dict:
289    rows = open(path).read().splitlines()
290    segs = json.load(open(path + ".seg.json"))["segments"]
291    out = {}
292    for s in segs:
293        d = {}
294        for line in rows[s["first_line"]:s["end_line"]]:
295            f = line.split("\t")
296            if len(f) < 8 + TOPK:
297                continue
298            d[int(f[0])] = (int(f[1]), float(f[2]), int(f[3]), [(int(x), float(y)) for x, y in
299                                                                (z.split(":") for z in f[8:8 + TOPK])])
300        out[s["name"]] = d
301    return out
302
303
304def compare(ref: dict, run: dict) -> dict:
305    res, allk, tot = {}, [], {"n": 0, "agree": 0, "nll_r": 0.0, "nll_a": 0.0, "kl": 0.0}
306    for name, rr in ref.items():
307        ra = run.get(name, {})
308        pos = sorted(set(rr) & set(ra))
309        n = agree = 0
310        kls, nll_r, nll_a = [], 0.0, 0.0
311        for q in pos:
312            tr, lr, topr, kr = rr[q]
313            ta, la, topa, ka = ra[q]
314            if tr != ta:
315                raise SystemExit(f"{name} pos {q}: target {tr} != {ta} (not the same text)")
316            n += 1
317            agree += topr == topa
318            nll_r -= lr
319            nll_a -= la
320            da = dict(ka)
321            floor = min(b for _, b in ka)
322            pr = [math.exp(b) for _, b in kr]
323            pa = [math.exp(da.get(i, floor)) for i, _ in kr]
324            sr, sa = sum(pr), sum(pa)
325            kls.append(sum((x / sr) * math.log((x / sr) / (y / sa)) for x, y in zip(pr, pa) if x > 0))
326        allk += kls
327        if n:
328            res[name] = {"positions": n, "top1": agree / n, "kl": sum(kls) / n,
329                         "ppl_ref": math.exp(nll_r / n), "ppl": math.exp(nll_a / n)}
330        tot["n"] += n
331        tot["agree"] += agree
332        tot["nll_r"] += nll_r
333        tot["nll_a"] += nll_a
334        tot["kl"] += sum(kls)
335    n = max(tot["n"], 1)
336    allk.sort()
337    res["all"] = {"positions": tot["n"], "top1": tot["agree"] / n, "kl": tot["kl"] / n,
338                  "kl_p99": allk[int(0.99 * (len(allk) - 1))] if allk else float("nan"),
339                  "ppl_ref": math.exp(tot["nll_r"] / n), "ppl": math.exp(tot["nll_a"] / n)}
340    return res
341
342
343def cmd_compare(a) -> int:
344    ref = read_run(a.ref)
345    print(f"reference: {a.ref}")
346    print(f"{'run':40s} {'segment':13s} {'pos':>5s} {'top1':>7s} {'KL':>8s} {'KL p99':>8s} {'PPL':>7s} {'PPL ref':>7s}")
347    allres = {}
348    for path in a.runs:
349        r = compare(ref, read_run(path))
350        allres[path] = r
351        for seg, v in r.items():
352            if seg != "all" and not a.segments:
353                continue
354            print(f"{pathlib.Path(path).name[:40]:40s} {seg:13s} {v['positions']:5d} {100 * v['top1']:6.2f}% "
355                  f"{v['kl']:8.5f} {v.get('kl_p99', float('nan')):8.4f} {v['ppl']:7.3f} {v['ppl_ref']:7.3f}")
356    if a.json:
357        pathlib.Path(a.json).write_text(json.dumps(allres, indent=1))
358    return 0
359
360
361def main() -> int:
362    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
363    sub = ap.add_subparsers(dest="cmd", required=True)
364    p = sub.add_parser("ids")
365    p.add_argument("--tokenizer", required=True)
366    p.add_argument("--set", default=str(SET_DIR))
367    p.add_argument("--seg-tokens", type=int, default=1000)
368    p.add_argument("--out")
369    p = sub.add_parser("run")
370    p.add_argument("--config", required=True)
371    p.add_argument("--out", required=True)
372    p.add_argument("--ids", default=str(SET_DIR / "set.ids.json"))
373    p.add_argument("--env", action="append")
374    p.add_argument("--gpu-experts", nargs="?", const=True, default=False,
375                   help="--expert-cache 1500 (or the N given, e.g. auto) instead of one slot (the experts on the GPU kernels)")
376    p.add_argument("--min-free-gb", type=float, default=16)
377    p.add_argument("--wrap", help="a command prefix for the engine, e.g. 'systemd-run --user --scope -p MemoryMax=200G'")
378    p = sub.add_parser("prompt", help="the batched prompt path's next-token logits after 20 prompts (a directory)")
379    p.add_argument("--config", required=True)
380    p.add_argument("--out", required=True)
381    p.add_argument("--ids", default=str(SET_DIR / "set.ids.json"))
382    p.add_argument("--env", action="append")
383    p.add_argument("--gpu-experts", action="store_true")
384    p.add_argument("--min-free-gb", type=float, default=16)
385    p.add_argument("--wrap")
386    p = sub.add_parser("compare")
387    p.add_argument("ref")
388    p.add_argument("runs", nargs="+")
389    p.add_argument("--segments", action="store_true")
390    p.add_argument("--json")
391    p = sub.add_parser("pcompare", help="full-vocabulary KL and top-1 of `prompt` directories against a reference one")
392    p.add_argument("ref")
393    p.add_argument("runs", nargs="+")
394    a = ap.parse_args()
395    return {"ids": cmd_ids, "run": cmd_run, "prompt": cmd_prompt, "compare": cmd_compare,
396            "pcompare": cmd_pcompare}[a.cmd](a)
397
398
399if __name__ == "__main__":
400    raise SystemExit(main())