okami.mom/strata

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

Niko1221Merge f-dsv41-rel (0be62ccad) into v0.2.3.1: DeepSeek V4.1-Flash on top of the released 0.2.3 line28ce98bf1

main
3.7 KiB96 linesraw
1"""swap_compare.py - KL / NLL of Gyro-S swap variants against the Q8_0-swap reference, with paired differences.
2
3  python3 tools/trellis/swap_compare.py REF.tsv shipped=RUN.tsv plain=RUN.tsv diag=RUN.tsv [...] [--base shipped]
4
5Per run: mean KL(REF || run) over REF's top-64 (tools/quant_quality.py's definition), top-1 agreement with REF, mean negative
6log-likelihood of the text (and its difference to REF's), each with a standard error over segments.  Then the paired
7difference of every run against --base (same positions): mean +- standard error over segments, and the share of segments
8where the run is better.  Per text kind (english / multilingual / code / docs / agent) too.
9"""
10from __future__ import annotations
11
12import argparse
13import math
14import pathlib
15import sys
16
17import numpy as np
18
19HERE = pathlib.Path(__file__).resolve().parent
20sys.path.insert(0, str(HERE.parent))
21import quant_quality as QQ  # noqa: E402
22
23
24def per_position(ref, run):
25    """{segment: (kl[], nll[], agree[])} for positions both runs have."""
26    out = {}
27    for name, rr in ref.items():
28        ra = run.get(name, {})
29        kls, nll, ag = [], [], []
30        for q in sorted(set(rr) & set(ra)):
31            tr, lr, topr, kr = rr[q]
32            ta, la, topa, ka = ra[q]
33            if tr != ta:
34                raise SystemExit("%s pos %d: different text" % (name, q))
35            da = dict(ka)
36            floor = min(b for _, b in ka)
37            pr = np.array([math.exp(b) for _, b in kr])
38            pa = np.array([math.exp(da.get(i, floor)) for i, _ in kr])
39            pr /= pr.sum()
40            pa /= pa.sum()
41            kls.append(float(np.sum(pr * np.log(pr / pa))))
42            nll.append(-la)
43            ag.append(float(topr == topa))
44        if kls:
45            out[name] = (np.array(kls), np.array(nll), np.array(ag))
46    return out
47
48
49def kind(name):
50    return name.rsplit("_", 1)[0]
51
52
53def se(x):
54    return float(np.std(x, ddof=1) / math.sqrt(len(x))) if len(x) > 1 else float("nan")
55
56
57def main() -> int:
58    ap = argparse.ArgumentParser()
59    ap.add_argument("ref")
60    ap.add_argument("runs", nargs="+", help="label=file.tsv")
61    ap.add_argument("--base", default=None)
62    a = ap.parse_args()
63    ref = QQ.read_run(a.ref)
64    runs = {}
65    for r in a.runs:
66        lab, _, path = r.partition("=")
67        runs[lab] = per_position(ref, QQ.read_run(path))
68    runs.setdefault('ref', per_position(ref, ref))
69    base = a.base or next(iter(runs))
70    segs = sorted(set.intersection(*[set(v) for v in runs.values()]))
71    kinds = sorted({kind(s) for s in segs})
72    print("segments %d, positions %d (reference %s)\n" % (len(segs), sum(len(runs[base][s][0]) for s in segs), a.ref))
73
74    def seg_mean(lab, idx, ss):
75        return np.array([runs[lab][s][idx].mean() for s in ss])
76
77    for title, ss in [("ALL", segs)] + [(k, [s for s in segs if kind(s) == k]) for k in kinds]:
78        if not ss:
79            continue
80        print("== %s (%d segments)" % (title, len(ss)))
81        print("  %-10s %-22s %-14s %-20s %s" % ("run", "KL(ref||run)", "top-1 vs ref", "NLL of the text", "paired KL difference vs " + base))
82        for lab in runs:
83            kl, ag, nl = seg_mean(lab, 0, ss), seg_mean(lab, 2, ss), seg_mean(lab, 1, ss)
84            kb = seg_mean(base, 0, ss)
85            d = kl - kb
86            nb = seg_mean(base, 1, ss)
87            print("  %-10s %.5f +- %.5f      %.4f         %.4f +- %.4f   %s" % (
88                lab, kl.mean(), se(kl), ag.mean(), nl.mean(), se(nl),
89                "(base)" if lab == base else "%+.5f +- %.5f  better in %d/%d segments; NLL %+.4f +- %.4f" % (
90                    d.mean(), se(d), int((d < 0).sum()), len(d), (nl - nb).mean(), se(nl - nb))))
91        print()
92    return 0
93
94
95if __name__ == "__main__":
96    sys.exit(main())