okami.mom/strata

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

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
5.2 KiB135 linesraw
1#!/usr/bin/env python3
2"""dgx_compare - side-by-side medians and ratios of two dgx_bench result folders (or .jsonl files).
3
4    python research/tools/dgx-spark-2026-10/dgx_compare.py bench/results/dgx-.../base.jsonl bench/results/dgx-.../gu.jsonl
5
6Prints, per cell, the median prompt and decode tokens/s of both arms, their ratio, and the geometric mean of the
7ratios over the cells (the "aggregate" the DGX Spark acceptance target is stated on).  A request whose prompt was
8served from the conversation cache (cache_n > 0) is not counted.
9"""
10from __future__ import annotations
11
12import json
13import math
14import random
15import statistics
16import sys
17from pathlib import Path
18
19
20def load(path: Path) -> list[dict]:
21    rows = []
22    for line in path.read_text().splitlines():
23        line = line.strip()
24        if not line:
25            continue
26        try:
27            rows.append(json.loads(line))
28        except ValueError:
29            continue
30    return rows
31
32
33def cells(rows: list[dict]) -> list[tuple]:
34    return sorted({(r["len"], r["temp"], r["max_new"]) for r in rows})
35
36
37def med(rows: list[dict], key: str):
38    vals = [float(r[key]) for r in rows if r.get(key) and not r.get("cache_n")]
39    return statistics.median(vals) if vals else None
40
41
42def arm_stats(rows: list[dict]) -> dict:
43    out = {}
44    for c in cells(rows):
45        sel = [r for r in rows if (r["len"], r["temp"], r["max_new"]) == c]
46        out[c] = (med(sel, "prompt_per_second"), med(sel, "predicted_per_second"), med(sel, "ttft_s"),
47                  len([r for r in sel if not r.get("cache_n")]))
48    return out
49
50
51
52def _by_cell(rows, key):
53    out = {}
54    for r in rows:
55        if r.get(key) and not r.get("cache_n"):
56            out.setdefault((r["len"], r["temp"], r["max_new"]), []).append(float(r[key]))
57    return out
58
59
60def bootstrap(rows_a, rows_b, iters, seed=7):
61    """Per-cell and aggregate ratio confidence intervals, resampling each arm's rows within a cell."""
62    rng = random.Random(seed)
63    res = {}
64    for key in ("prompt_per_second", "predicted_per_second"):
65        a, b = _by_cell(rows_a, key), _by_cell(rows_b, key)
66        cells = sorted(set(a) & set(b))
67        if not cells:
68            continue
69        draws = {c: [] for c in cells}
70        agg = []
71        for _ in range(iters):
72            logs = []
73            for c in cells:
74                va, vb = a[c], b[c]
75                ra = statistics.median([rng.choice(va) for _ in va])
76                rb = statistics.median([rng.choice(vb) for _ in vb])
77                if ra <= 0 or rb <= 0:
78                    continue
79                draws[c].append(rb / ra)
80                logs.append(math.log(rb / ra))
81            if logs:
82                agg.append(math.exp(sum(logs) / len(logs)))
83        pct = lambda xs, p: sorted(xs)[min(len(xs) - 1, max(0, int(p * len(xs))))]
84        res[key] = {c: (statistics.median(draws[c]), pct(draws[c], 0.05), pct(draws[c], 0.95)) for c in cells}
85        res[key]["aggregate"] = (statistics.median(agg), pct(agg, 0.05), pct(agg, 0.95)) if agg else None
86    return res
87
88def main() -> int:
89    if len(sys.argv) < 3:
90        print(__doc__)
91        return 2
92    ci = int(sys.argv[3]) if len(sys.argv) > 3 else 0
93    a_path, b_path = Path(sys.argv[1]), Path(sys.argv[2])
94    a, b = load(a_path), load(b_path)
95    sa, sb = arm_stats(a), arm_stats(b)
96    name_a, name_b = a_path.stem, b_path.stem
97    print(f"A = {name_a}   B = {name_b}\n")
98    print(f"| cell | A prompt | B prompt | ratio | A decode | B decode | ratio | A ttft | B ttft |")
99    print("|---|---|---|---|---|---|---|---|---|")
100    pr, dr = [], []
101    for c in sorted(set(sa) | set(sb)):
102        pa, da, ta, na = sa.get(c, (None, None, None, 0))
103        pb, db, tb, nb = sb.get(c, (None, None, None, 0))
104        f = lambda v, w="{:.1f}": "-" if v is None else w.format(v)
105        rp = (pb / pa) if (pa and pb) else None
106        rd = (db / da) if (da and db) else None
107        if rp:
108            pr.append(rp)
109        if rd:
110            dr.append(rd)
111        print(f"| {c[0]} T={c[1]} n={c[2]} | {f(pa)} | {f(pb)} | {f(rp, '{:.3f}')}x | {f(da)} | {f(db)} | "
112              f"{f(rd, '{:.3f}')}x | {f(ta, '{:.2f}')} | {f(tb, '{:.2f}')} |")
113    gm = lambda xs: math.exp(sum(math.log(x) for x in xs) / len(xs)) if xs else float("nan")
114    print(f"\nprompt aggregate (geomean of ratios over {len(pr)} cells): {gm(pr):.3f}x")
115    print(f"decode aggregate (geomean of ratios over {len(dr)} cells): {gm(dr):.3f}x")
116    if pr:
117        print(f"lowest prompt ratio: {min(pr):.3f}x   lowest decode ratio: {min(dr) if dr else float('nan'):.3f}x")
118    if ci > 0:
119        bs = bootstrap(a, b, ci)
120        print(f"\nbootstrap 90% intervals over {ci} resamples (5th .. 95th percentile of the ratio):")
121        for key, label in (("prompt_per_second", "prompt"), ("predicted_per_second", "decode")):
122            if key not in bs:
123                continue
124            for c, v in sorted(bs[key].items(), key=lambda kv: str(kv[0])):
125                if c == "aggregate":
126                    continue
127                print(f"  {label:6s} {c[0]:6d}/{c[1]}/{c[2]:4d}: {v[0]:.3f}x  [{v[1]:.3f}, {v[2]:.3f}]")
128            agg = bs[key].get("aggregate")
129            if agg:
130                print(f"  {label:6s} aggregate: {agg[0]:.3f}x  [{agg[1]:.3f}, {agg[2]:.3f}]")
131    return 0
132
133
134if __name__ == "__main__":
135    sys.exit(main())