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
3.1 KiB67 linesraw
1"""tools/qwen35/compare_dumps.py - two runs of the Qwen3.6 parity dumps against each other (e.g. llama.cpp GPU vs
2llama.cpp CPU: the noise floor the strata-q36ref comparison is judged against).
3
4    python tools/qwen35/compare_dumps.py DIR_A KIND_A DIR_B KIND_B      (KIND: llama or strata)
5Per prompt: greedy tokens equal up to the answer's end (llama.cpp's first <|im_end|> in run A), the first divergence's
6top-1/top-2 margins, and the layer outputs' median and max ||a-b||/||b|| over the positions before the divergence.
7"""
8from __future__ import annotations
9
10import sys
11from pathlib import Path
12
13import numpy as np
14
15N_EMBD, N_LAYER, EOS = 2048, 40, 248046
16
17
18def gen_of(d: Path, tag: str, kind: str) -> list[int]:
19    f = d / (f"{tag}.strata.gen" if kind == "strata" else f"{tag}.llama.log")
20    for line in f.read_text(encoding="utf-8").splitlines():
21        if line.startswith("gen:"):
22            return [int(x) for x in line.split(":", 1)[1].split()]
23    raise SystemExit(f"no gen line in {f}")
24
25
26def prompt_len(d: Path, tag: str) -> int:
27    for line in (d / f"{tag}.llama.log").read_text(encoding="utf-8").splitlines():
28        if line.startswith("prompt:"):
29            return len(line.split(":", 1)[1].split())
30    raise SystemExit("no prompt line")
31
32
33def main() -> int:
34    da, ka, db, kb = Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3]), sys.argv[4]
35    tags = sorted({p.name.split(".")[0] for p in da.glob(f"p*.{ka}.layers")})
36    rows = []
37    for tag in tags:
38        ga, gb = gen_of(da, tag, ka), gen_of(db, tag, kb)
39        upto = min(len(ga), len(gb))
40        if EOS in ga[:upto]:
41            upto = ga.index(EOS) + 1
42        same = 0
43        while same < upto and ga[same] == gb[same]:
44            same += 1
45        la = np.fromfile(da / f"{tag}.{ka}.logits", dtype=np.float32).reshape(-1, 4)
46        lb = np.fromfile(db / f"{tag}.{kb}.logits", dtype=np.float32).reshape(-1, 4)
47        A = np.fromfile(da / f"{tag}.{ka}.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD)
48        B = np.fromfile(db / f"{tag}.{kb}.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD)
49        npos = min(len(A), len(B), prompt_len(da, tag) + same)
50        nb = np.linalg.norm(B[:npos], axis=2)
51        na = np.linalg.norm(A[:npos], axis=2)
52        err = np.where((nb > 0) & (na > 0), np.linalg.norm(A[:npos] - B[:npos], axis=2) / np.maximum(nb, 1e-30), np.nan)
53        div = ""
54        if same < upto:
55            div = (f"; step {same}: A {int(la[same, 0])} (margin {la[same, 1] - la[same, 3]:.3f}) vs B {int(lb[same, 0])} "
56                   f"(margin {lb[same, 1] - lb[same, 3]:.3f})")
57        per_layer = np.nanmedian(err, axis=0)
58        rows.append((same == upto, np.nanmedian(err), np.nanmax(err)))
59        print(f"{tag}: {same}/{upto} equal; layer err median {np.nanmedian(err):.4f} max {np.nanmax(err):.4f}; "
60              f"median by layer 0/10/20/30/39: " + " ".join(f"{per_layer[i]:.4f}" for i in (0, 10, 20, 30, 39)) + div)
61    print(f"answers identical: {sum(r[0] for r in rows)} of {len(rows)}; layer err median of medians "
62          f"{np.median([r[1] for r in rows]):.4f}, worst max {max(r[2] for r in rows):.4f}")
63    return 0
64
65
66if __name__ == "__main__":
67    sys.exit(main())