okami.mom/strata

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

Niko1221Merge f-029-par-harness1fb3e9a32

main
5.8 KiB126 linesraw
1#!/usr/bin/env python3
2"""Paired-block analysis for par_load.py ledgers (standard library only).
3
4A pair = one A block and one B block of the same workload/level, run on the same hardware and cache regime and labelled
5with the same --pair id (--arm A|B).  For every (workload, level, metric) it prints the per-pair ratios B/A, their
6geometric mean and a paired bootstrap 95% interval (seeded), how many pairs B won, and the decision label from the
7plan (screening = few pairs: <5% in every pair low priority, >=10% keep; confirmation = 20+ pairs, lower bound vs --target).
8
9    python3 tools/par_analyze.py a1.json b1.json a2.json b2.json ...           (arm/pair read from the ledgers)
10    python3 tools/par_analyze.py runs/*.json --metric agg_tps --target 2.0 --json out.json
11
12Metrics where lower is better (ttft_*, tpot_*, max_gap_*, latency_*) are inverted so ratio > 1 always means B is better.
13`--baseline-arm`/`--cand-arm` choose the arms (default A and B).  A pair missing either arm, an invalid ledger
14(no server usage) or a block with errors is reported and left out.
15"""
16import argparse, glob, json, math, random, sys
17from collections import defaultdict
18
19LOWER_BETTER = ("ttft", "tpot", "max_gap", "latency", "lag", "joiner_ttft", "incumbent_gap", "makespan")
20
21
22def lower_is_better(metric):
23    return metric.startswith(LOWER_BETTER)
24
25
26def geomean(xs):
27    return math.exp(sum(math.log(x) for x in xs) / len(xs))
28
29
30def boot(ratios, n=10000, seed=1):
31    rng = random.Random(seed)
32    k = len(ratios)
33    gm = sorted(geomean([ratios[rng.randrange(k)] for _ in range(k)]) for _ in range(n))
34    return gm[int(0.025 * n)], gm[int(0.975 * n) - 1]
35
36
37def load(paths):
38    rows, skipped = [], []
39    for p in paths:
40        try:
41            L = json.load(open(p))
42        except Exception as e:  # noqa: BLE001
43            skipped.append((p, f"unreadable {e}"))
44            continue
45        if not L.get("valid", True):
46            skipped.append((p, "invalid ledger: " + str(L.get("invalid_reason"))))
47            continue
48        for b in L.get("blocks", []):
49            if b.get("errors"):
50                skipped.append((p, f"block has {b['errors']} errors"))
51                continue
52            rows.append((p, b))
53    return rows, skipped
54
55
56def analyze(rows, metric, a_arm="A", b_arm="B", target=None, min_confirm=20, boot_n=10000):
57    groups = defaultdict(lambda: defaultdict(dict))
58    for p, b in rows:
59        if metric not in b or b[metric] is None or not b.get("pair"):
60            continue
61        key = (b.get("workload"), b.get("level", b.get("offered_rate")), b.get("share"), b.get("round"))
62        groups[key][b["pair"]][b["arm"]] = b[metric]
63    out = []
64    for key, pairs in sorted(groups.items(), key=lambda kv: str(kv[0])):
65        ratios, used = [], []
66        for pid, arms in pairs.items():
67            if a_arm in arms and b_arm in arms and arms[a_arm] and arms[b_arm]:
68                r = arms[b_arm] / arms[a_arm]
69                ratios.append(1 / r if lower_is_better(metric) else r)
70                used.append(pid)
71        if not ratios:
72            continue
73        gm = geomean(ratios)
74        lo, hi = boot(ratios, boot_n) if len(ratios) > 1 else (gm, gm)
75        n = len(ratios)
76        faster = sum(1 for r in ratios if r > 1.0)
77        if n < min_confirm:
78            kind = "screen"
79            if all(r < 1.05 for r in ratios):
80                label = "low priority (<5% in every pair)" if all(r > 0.95 for r in ratios) else "reject/regression in every pair" if all(r < 1.0 for r in ratios) else "low priority"
81            elif gm >= 1.10 and faster == n:
82                label = "keep (>=10%)"
83            elif gm >= 1.05:
84                label = "investigate (5-10%)"
85            else:
86                label = "mixed, investigate"
87        else:
88            kind = "confirm"
89            label = "n/a"
90            if target is not None:
91                label = f"PASS (lower bound {lo:.3f} >= {target})" if lo >= target else f"NOT PROVEN (lower bound {lo:.3f} < {target})"
92        out.append({"workload": key[0], "level": key[1], "share": key[2], "round": key[3], "metric": metric, "pairs": n,
93                    "ratios": [round(r, 4) for r in ratios], "geomean": gm, "ci95": [lo, hi], "pairs_better": faster,
94                    "kind": kind, "decision": label, "mean_A": sum(pairs[p][a_arm] for p in used) / n, "mean_B": sum(pairs[p][b_arm] for p in used) / n})
95    return out
96
97
98def main(argv=None):
99    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
100    ap.add_argument("ledgers", nargs="+")
101    ap.add_argument("--metric", action="append", default=None, help="repeatable; default agg_tps ttft_p95 max_gap_p95")
102    ap.add_argument("--baseline-arm", default="A")
103    ap.add_argument("--cand-arm", default="B")
104    ap.add_argument("--target", type=float, default=None, help="confirmation: the lower bound must clear this ratio")
105    ap.add_argument("--min-confirm", type=int, default=20)
106    ap.add_argument("--json", default=None)
107    a = ap.parse_args(argv)
108    paths = [p for g in a.ledgers for p in (glob.glob(g) or [g])]
109    rows, skipped = load(paths)
110    res = []
111    for m in a.metric or ["agg_tps", "ttft_p95", "max_gap_p95"]:
112        res += analyze(rows, m, a.baseline_arm, a.cand_arm, a.target, a.min_confirm)
113    for s in skipped:
114        print("skipped:", *s)
115    print(f"{'workload':8} {'level':>6} {'metric':14} {'pairs':>5} {'geomean':>8} {'95% CI':>17} {'better':>7}  decision")
116    for r in res:
117        lvl = r["level"] if r["share"] is None else f"{r['level']}/s{r['share']}"
118        print(f"{r['workload']:8} {str(lvl):>6} {r['metric']:14} {r['pairs']:>5} {r['geomean']:>8.3f} [{r['ci95'][0]:.3f},{r['ci95'][1]:.3f}] "
119              f"{r['pairs_better']:>3}/{r['pairs']:<3}  {r['kind']}: {r['decision']}")
120    if a.json:
121        json.dump(res, open(a.json, "w"), indent=1)
122    return 0
123
124
125if __name__ == "__main__":
126    sys.exit(main())