okami.mom/strata

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

Niko1221Merge f-qwen36 into f-144-rel (geometry: #2179's read_geometry guard kept for qwen4exp, Qwen3.6's family guard on top)4cfeaa0f4

main
5.2 KiB106 linesraw
1"""tools/qwen35/kl.py - teacher-forced KL for Qwen3.6-35B-A3B (NEW-MODELS-PLAN.md T1/T2): on one token sequence per
2prompt (the prompt + llama.cpp GPU's greedy answer, from a parity.py run), the next-token distributions of
3llama.cpp HIP (the reference P), llama.cpp CPU (the noise floor) and strata-q36ref.  Reported: mean KL(P || Q) and
4the top-1 agreement over all steps, per engine; the plan's gate is Strata's KL within 1.5x of the floor.
5
6    python tools/qwen35/kl.py --ref BIN --dump BIN --model GGUF --parity DIR --out DIR [--lock "..."] [--cpu-lock "..."]
7"""
8from __future__ import annotations
9
10import argparse
11import shlex
12import subprocess
13import sys
14from pathlib import Path
15
16import numpy as np
17
18V = 248320
19EOS = 248046                                    # <|im_end|>
20
21
22def ids(path: Path, key: str) -> list[int]:
23    for line in path.read_text(encoding="utf-8").splitlines():
24        if line.startswith(key + ":"):
25            return [int(x) for x in line.split(":", 1)[1].split()]
26    raise SystemExit(f"no {key}: in {path}")
27
28
29def run(cmd: list[str], lock: str, log: Path) -> None:
30    r = subprocess.run((shlex.split(lock) if lock else []) + cmd, capture_output=True, text=True, timeout=3600)
31    log.write_text(r.stdout + "\n--- stderr ---\n" + r.stderr, encoding="utf-8")
32    if r.returncode != 0:
33        raise SystemExit(f"{cmd[0]} failed (rc {r.returncode}), see {log}")
34
35
36def log_softmax(x: np.ndarray) -> np.ndarray:
37    x = x.astype(np.float64)
38    m = x.max(axis=1, keepdims=True)
39    return x - m - np.log(np.exp(x - m).sum(axis=1, keepdims=True))
40
41
42def main() -> int:
43    ap = argparse.ArgumentParser()
44    ap.add_argument("--ref", required=True)
45    ap.add_argument("--dump", required=True)
46    ap.add_argument("--model", required=True)
47    ap.add_argument("--parity", required=True, help="a parity.py output dir (its llama.cpp logs give the sequences)")
48    ap.add_argument("--out", required=True)
49    ap.add_argument("--lock", default="")
50    ap.add_argument("--cpu-lock", default="")
51    ap.add_argument("--cache", default="", help="where llama.cpp's logits are kept between runs (default --out)")
52    ap.add_argument("--ref-args", default="", help="extra strata-q36ref arguments (e.g. '--act f32')")
53    a = ap.parse_args()
54    out, par = Path(a.out), Path(a.parity)
55    out.mkdir(parents=True, exist_ok=True)
56    tags = sorted(p.name.split(".")[0] for p in par.glob("p*.llama.log"))
57    kl = {"cpu": [], "strata": []}
58    top1 = {"cpu": [], "strata": []}
59    kl_ans = {"cpu": [], "strata": []}
60    top1_ans = {"cpu": [], "strata": []}
61    for tag in tags:
62        prompt, gen = ids(par / f"{tag}.llama.log", "prompt"), ids(par / f"{tag}.llama.log", "gen")
63        force = ",".join(map(str, gen))
64        toks = ",".join(map(str, prompt))
65        cache = Path(a.cache) if a.cache else out
66        f = {k: (out if k == "strata" else cache) / f"{tag}.{k}.full" for k in ("gpu", "cpu", "strata")}
67        # llama.cpp's two runs depend only on the model and the sequence: kept in --out and reused (64 MB each)
68        if not f["gpu"].exists():
69            run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "99", "--dump-full-logits",
70                 str(f["gpu"])], a.lock, cache / f"{tag}.gpu.log")
71        if not f["cpu"].exists():
72            run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "0", "--dump-full-logits",
73                 str(f["cpu"])], a.cpu_lock, cache / f"{tag}.cpu.log")
74        run([a.ref, "--model", a.model, "--tokens", toks, "--force", force, "--dump-full-logits", str(f["strata"]),
75             *shlex.split(a.ref_args)], a.lock, out / f"{tag}.strata.log")
76        P = log_softmax(np.fromfile(f["gpu"], dtype=np.float32).reshape(-1, V))
77        # the answer: the steps up to and including the first <|im_end|> of the forced sequence (past it the context is
78        # one no chat reaches, and its distributions are the noisiest); "all" keeps every step
79        ans = gen.index(EOS) + 1 if EOS in gen else len(P)
80        line = f"{tag}: {len(P)} steps ({ans} answer)"
81        per = {}
82        for k in ("cpu", "strata"):
83            Q = log_softmax(np.fromfile(f[k], dtype=np.float32).reshape(-1, V))
84            n = min(len(P), len(Q))
85            d = (np.exp(P[:n]) * (P[:n] - Q[:n])).sum(axis=1)
86            t1 = P[:n].argmax(axis=1) == Q[:n].argmax(axis=1)
87            kl[k].extend(d.tolist())
88            top1[k].extend(t1.tolist())
89            kl_ans[k].extend(d[:ans].tolist())
90            top1_ans[k].extend(t1[:ans].tolist())
91            per[k] = d
92            line += f"; {k}: KL {d.mean():.5f} (answer {d[:ans].mean():.5f}) top-1 {t1.mean():.3f}"
93        np.savez(out / f"{tag}.kl.npz", answer=ans, **per)
94        f["strata"].unlink(missing_ok=True)
95        print(line, flush=True)
96    for name, K, T in (("all steps", kl, top1), ("answers only", kl_ans, top1_ans)):
97        print(f"-- {name}")
98        for k in ("cpu", "strata"):
99            print(f"{k:6s} vs llama.cpp HIP: mean KL {np.mean(K[k]):.5f} (median {np.median(K[k]):.6f}, p99 "
100                  f"{np.percentile(K[k], 99):.4f}), top-1 {np.mean(T[k]):.4f} over {len(K[k])} steps")
101        print(f"ratio strata / floor: {np.mean(K['strata']) / max(np.mean(K['cpu']), 1e-12):.2f}")
102    return 0
103
104
105if __name__ == "__main__":
106    sys.exit(main())