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
6.1 KiB112 linesraw
1"""tools/qwen35/parity.py - NEW-MODELS-PLAN.md T1's exit gate for Qwen3.6-35B-A3B: strata-q36ref against llama.cpp
2(tools/qwen35/q36_llama_dump.cpp) on the same GGUF, the same box and the same token ids.
3
4For each prompt (parity_prompts.json, ChatML with thinking off): llama.cpp tokenizes it and runs it (the reference
5ids, layer outputs and greedy tokens); strata-q36ref runs the same ids.  Reported per prompt: the greedy tokens that
6agree (of --n), the first divergence with both engines' top-1/top-2 logit margins (a near tie is a margin < 0.05), and
7the per-layer hidden-state error max over positions of ||strata - llama|| / ||llama||.
8
9    python tools/qwen35/parity.py --ref BIN --dump BIN --model GGUF --out DIR [--n 64] [--ngl 99] [--lock "flock ..."]
10"""
11from __future__ import annotations
12
13import argparse
14import json
15import shlex
16import subprocess
17import sys
18from pathlib import Path
19
20import numpy as np
21
22HERE = Path(__file__).resolve().parent
23TEMPLATE = "<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
24N_EMBD, N_LAYER = 2048, 40
25EOS = 248046                                    # <|im_end|>
26
27
28def run(cmd: list[str], lock: str, log: Path) -> str:
29    full = shlex.split(lock) + cmd if lock else cmd
30    r = subprocess.run(full, capture_output=True, text=True, timeout=1800)
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    return r.stdout
35
36
37def ids_of(out: str, key: str) -> list[int]:
38    for line in out.splitlines():
39        if line.startswith(key + ":"):
40            return [int(x) for x in line.split(":", 1)[1].split()]
41    raise SystemExit(f"no '{key}:' line")
42
43
44def main() -> int:
45    ap = argparse.ArgumentParser()
46    ap.add_argument("--ref", required=True, help="strata-q36ref")
47    ap.add_argument("--dump", required=True, help="q36_llama_dump")
48    ap.add_argument("--model", required=True)
49    ap.add_argument("--out", required=True)
50    ap.add_argument("--n", type=int, default=64)
51    ap.add_argument("--ngl", type=int, default=99, help="llama.cpp's GPU layers (0 = its CPU backend)")
52    ap.add_argument("--lock", default="", help="a command prefix for the GPU runs (the box's flock)")
53    ap.add_argument("--prompts", default=str(HERE / "parity_prompts.json"))
54    ap.add_argument("--skip-ref", action="store_true", help="reuse strata-q36ref's outputs in --out")
55    ap.add_argument("--past-eos", action="store_true", help="compare all --n tokens, not only up to the answer's end")
56    a = ap.parse_args()
57    out = Path(a.out)
58    out.mkdir(parents=True, exist_ok=True)
59    prompts = json.loads(Path(a.prompts).read_text(encoding="utf-8"))
60    summary = []
61    for i, p in enumerate(prompts):
62        tag = f"p{i:02d}"
63        lo = run([a.dump, "--model", a.model, "--prompt", TEMPLATE.format(p=p), "--n", str(a.n), "--ngl", str(a.ngl),
64                  "--dump-layers", str(out / f"{tag}.llama.layers"), "--dump-logits", str(out / f"{tag}.llama.logits")],
65                 a.lock, out / f"{tag}.llama.log")
66        prompt_ids, lgen = ids_of(lo, "prompt"), ids_of(lo, "gen")
67        if not a.skip_ref:
68            so = run([a.ref, "--model", a.model, "--tokens", ",".join(map(str, prompt_ids)), "--n", str(a.n),
69                      "--dump-layers", str(out / f"{tag}.strata.layers"), "--dump-logits", str(out / f"{tag}.strata.logits")],
70                     a.lock, out / f"{tag}.strata.log")
71            (out / f"{tag}.strata.gen").write_text(so, encoding="utf-8")
72        sgen = ids_of((out / f"{tag}.strata.gen").read_text(encoding="utf-8"), "gen")
73        # the answer ends at llama.cpp's first <|im_end|> (included); past it both engines run on in a context no chat
74        # ever reaches, so the comparison stops there (--past-eos compares all --n tokens)
75        upto = min(len(sgen), len(lgen))
76        if not a.past_eos and EOS in lgen[:upto]:
77            upto = lgen.index(EOS) + 1
78        same = 0
79        while same < upto and sgen[same] == lgen[same]:
80            same += 1
81        sl = np.fromfile(out / f"{tag}.strata.logits", dtype=np.float32).reshape(-1, 4)
82        ll = np.fromfile(out / f"{tag}.llama.logits", dtype=np.float32).reshape(-1, 4)
83        div = None
84        if same < upto:
85            div = {"step": same, "strata": [int(sl[same, 0]), float(sl[same, 1] - sl[same, 3])],
86                   "llama": [int(ll[same, 0]), float(ll[same, 1] - ll[same, 3])]}
87        # the layer outputs up to the divergence (after it the two engines read different tokens)
88        sL = np.fromfile(out / f"{tag}.strata.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD)
89        lL = np.fromfile(out / f"{tag}.llama.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD)
90        npos = min(len(sL), len(lL), len(prompt_ids) + same)
91        ln = np.linalg.norm(lL[:npos], axis=2)
92        err = np.linalg.norm(sL[:npos] - lL[:npos], axis=2) / np.maximum(ln, 1e-30)   # [pos, layer]
93        # llama.cpp keeps only the output rows of the last layer of a prompt batch: rows it did not compute are 0
94        err = np.where(ln > 0, err, np.nan)
95        per_layer = np.nanmax(err, axis=0)
96        rec = {"prompt": i, "tokens": len(prompt_ids), "same": same, "of": upto,
97               "divergence": div, "max_rel_err": float(np.nanmax(per_layer)), "worst_layer": int(np.nanargmax(per_layer)),
98               "median_rel_err": float(np.nanmedian(err)), "per_layer_max": [round(float(x), 5) for x in per_layer]}
99        summary.append(rec)
100        print(f"{tag}: {same}/{rec['of']} greedy tokens equal; layers max rel err {rec['max_rel_err']:.4f} (layer "
101              f"{rec['worst_layer']}), median {rec['median_rel_err']:.5f}" + (f"; diverges at {div}" if div else ""),
102              flush=True)
103    (out / "summary.json").write_text(json.dumps(summary, indent=1), encoding="utf-8")
104    full = sum(r["same"] == r["of"] for r in summary)
105    print(f"identical greedy answers (up to {a.n} tokens{'' if a.past_eos else ' or the end of the answer'}): {full} of "
106          f"{len(summary)} prompts; worst layer error "
107          f"{max(r['max_rel_err'] for r in summary):.4f}")
108    return 0
109
110
111if __name__ == "__main__":
112    sys.exit(main())