"""Reads an A/B of the D3D12 runtime: numbers only, never log text. python -I tools/d3d12_ab_compare.py abba A: B: B: A: ... [--json] python -I tools/d3d12_ab_compare.py phases [--keep-draw-jumps] [--json] python -I tools/d3d12_ab_compare.py plan --pairs 4 [--switch] [--json] `abba` compares separate runs given in the order they were run (docs/measuring_fps.md, section 3). A run is a folder of the game gate (its summary.json: the median of the presents' frame times in the world, and a run whose verdict is not PASS is left out) or a log (the frame lines of tools/d3d12_run_fps.py with 1,000 draws a frame or more: the world). Each run gives one value, its median frame time in ms: frames within a run follow each other and are not independent samples, so a run is the unit. Neighbouring runs pair up, (1, 2), (3, 4), ...: each pair gives B - A. With an ABBA order a linear drift (a cache warming, a machine heating) adds as much to the pairs where A came first as it takes from those where B did, so the pairs must be balanced. The effect is the mean of the differences with its standard error and a 95 % t interval, from at least 4 pairs. With 3 runs a side and no balanced pairs it fits the side plus a linear trend instead. It says "B faster" or "B slower" only when the interval leaves 0 out and all but at most one pair agree in sign; otherwise "no clear difference", or why it could not tell. `phases` reads one run with LEONIDA_AB (section 2): each `A/B phase bits ` line, and the `A/B counters` line after it where the runtime writes one. For switch number s the phases come in blocks of 2^s off then 2^s on; each neighbouring pair of blocks gives one difference (on - off) of the median frame time and of each counter. A pair whose draws a frame differ by more than a tenth is a change of scene, not of the switch, and is left out (--keep-draw-jumps keeps it). `plan` prints a balanced order: warm-up runs, a discarded run of the first measured side, then ABBA pairs. Standard library only; reads files, never runs them; prints no log line, path or argument text. """ from __future__ import annotations import argparse import json import math import os import re import statistics import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import d3d12_run_fps # noqa: E402 (the frame line reader) # Two-sided 95 % Student t, by degrees of freedom. T95 = [12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160, 2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, 2.045, 2.042] WORLD_DRAWS = 1000 PHASE = re.compile(r"A/B phase (\d+) bits (\d+) on \[[^\]]*\]: (\d+) frames, mean ([\d.]+) ms, median ([\d.]+), " r"p90 ([\d.]+), ([\d.]+) draws a frame") COUNTERS = re.compile(r"A/B counters phase (\d+) bits (\d+): (.*)$") COUNTER = re.compile(r"([a-z_]+)=([\d.]+)") def t95(df): return T95[df - 1] if 1 <= df <= len(T95) else 1.96 def effect(diffs): """Mean, standard error, 95 % interval, median and sign agreement of pair differences.""" k = len(diffs) mean = statistics.fmean(diffs) se = statistics.stdev(diffs) / math.sqrt(k) if k > 1 else None half = t95(k - 1) * se if se is not None else None agree = max(sum(1 for d in diffs if d < 0), sum(1 for d in diffs if d > 0)) return {"k": k, "effect": mean, "se": se, "ci95": [mean - half, mean + half] if half is not None else None, "median": statistics.median(diffs), "agree": agree} def verdict(e, lower_is_faster=True): if e["ci95"] is None: return "not enough runs" lo, hi = e["ci95"] if (lo > 0 or hi < 0) and e["agree"] >= e["k"] - 1: faster = (hi < 0) == lower_is_faster return "B faster" if faster else "B slower" return "no clear difference" def solve3(m, v): """Solves a 3x3 system by Gauss-Jordan; also returns the inverse's diagonal.""" a = [row[:] + [v[i]] + [1.0 if j == i else 0.0 for j in range(3)] for i, row in enumerate(m)] for c in range(3): p = max(range(c, 3), key=lambda r: abs(a[r][c])) if abs(a[p][c]) < 1e-12: return None, None a[c], a[p] = a[p], a[c] pivot = a[c][c] a[c] = [x / pivot for x in a[c]] for r in range(3): if r != c: f = a[r][c] a[r] = [x - f * y for x, y in zip(a[r], a[c])] return [a[i][3] for i in range(3)], [a[i][4 + i] for i in range(3)] def trend_fit(runs): """value = a + b*[B] + c*position, least squares: the effect b, its standard error and interval.""" xs = [(1.0, 1.0 if arm == "B" else 0.0, float(pos)) for pos, arm, _ in runs] ys = [value for _, _, value in runs] xtx = [[sum(x[i] * x[j] for x in xs) for j in range(3)] for i in range(3)] xty = [sum(x[i] * y for x, y in zip(xs, ys)) for i in range(3)] beta, diag = solve3(xtx, xty) df = len(runs) - 3 if beta is None or df < 1: return None sse = sum((y - sum(b * xi for b, xi in zip(beta, x))) ** 2 for x, y in zip(xs, ys)) se = math.sqrt(sse / df * diag[1]) half = t95(df) * se return {"k": len(runs), "effect": beta[1], "se": se, "ci95": [beta[1] - half, beta[1] + half], "median": None, "agree": len(runs), "trend_per_run": beta[2], "df": df} def run_value(path): """(frame ms, draws a frame, why left out or None) of one run.""" summary = os.path.join(path, "summary.json") if os.path.isdir(path) else None if summary: if not os.path.exists(summary): return None, None, "no summary" with open(summary, encoding="utf-8") as f: s = json.load(f) fps = (s.get("fps") or {}).get("median") result = (s.get("verdict") or {}).get("result") if result != "PASS": return None, None, f"gate {result or 'unknown'}" if not fps: return None, None, "no frame rate" return 1000.0 / fps, (s.get("fps") or {}).get("draws_median"), None world = [x for x in d3d12_run_fps.read_samples(path) if x["draws"] >= WORLD_DRAWS] if not world: return None, None, "no frame line in the world" return statistics.median(x["frame_ms"] for x in world), statistics.median(x["draws"] for x in world), None def abba(items): """items: [(arm, frame ms or None, draws, why)] in run order.""" runs = [{"position": i + 1, "arm": arm, "frame_ms": ms, "draws": draws, "left_out": why} for i, (arm, ms, draws, why) in enumerate(items)] pairs = [] for a, b in zip(runs[0::2], runs[1::2]): if a["arm"] == b["arm"] or a["left_out"] or b["left_out"]: continue first, second = (a, b) if a["arm"] == "A" else (b, a) pairs.append({"positions": [a["position"], b["position"]], "a_first": a["arm"] == "A", "diff": second["frame_ms"] - first["frame_ms"]}) used = [r for r in runs if not r["left_out"]] out = {"metric": "world median frame time, ms (B - A; below 0: B faster)", "runs": runs, "pairs": pairs} a_first = sum(1 for p in pairs if p["a_first"]) balanced = bool(pairs) and a_first * 2 == len(pairs) if len(pairs) >= 4 and balanced: e = effect([p["diff"] for p in pairs]) out["method"] = "pairs" out["result"] = e out["verdict"] = verdict(e) elif sum(1 for r in used if r["arm"] == "A") >= 3 and sum(1 for r in used if r["arm"] == "B") >= 3: fit = trend_fit([(r["position"], r["arm"], r["frame_ms"]) for r in used]) out["method"] = "side and linear trend" out["result"] = fit out["verdict"] = verdict(fit) if fit else "not enough runs" else: out["method"] = None out["result"] = None out["verdict"] = "unbalanced pairs" if pairs and not balanced else "not enough runs" means = {arm: statistics.fmean(r["frame_ms"] for r in used if r["arm"] == arm) for arm in ("A", "B") if any(r["arm"] == arm for r in used)} out["means"] = means if out["result"] and "A" in means: out["percent"] = 100.0 * out["result"]["effect"] / means["A"] return out def read_phases(path): """{phase number: {"bits", "median", "draws", counters...}} from a LEONIDA_AB run's log.""" phases = {} for line in d3d12_run_fps._lines(path): text = d3d12_run_fps.ANSI.sub("", line) m = PHASE.search(text) if m: n = int(m.group(1)) phases[n] = {"bits": int(m.group(2)), "median": float(m.group(5)), "draws": float(m.group(7)), "counters": {}} continue m = COUNTERS.search(text) if m and int(m.group(1)) in phases: phases[int(m.group(1))]["counters"] = {k: float(v) for k, v in COUNTER.findall(m.group(3))} return phases def phase_effects(phases, keep_jumps=False): if not phases: return {"switches": []} switches = max(p["bits"] for p in phases.values()).bit_length() or 1 out = [] for s in range(switches): size = 1 << s blocks = {} for n, p in phases.items(): blocks.setdefault(n // size, []).append(p) diffs, jumps, names = [], 0, set() for j in sorted(blocks): if j % 2 or j + 1 not in blocks: continue off, on = blocks[j], blocks[j + 1] draws_off = statistics.fmean(p["draws"] for p in off) draws_on = statistics.fmean(p["draws"] for p in on) if not keep_jumps and abs(draws_on - draws_off) > 0.1 * max(draws_off, 1.0): jumps += 1 continue row = {"median": statistics.fmean(p["median"] for p in on) - statistics.fmean(p["median"] for p in off)} for p in off + on: names.update(p["counters"]) for name in names: row[name] = (statistics.fmean(p["counters"].get(name, 0.0) for p in on) - statistics.fmean(p["counters"].get(name, 0.0) for p in off)) diffs.append(row) effects = {} for name in ["median"] + sorted(names): values = [d[name] for d in diffs if name in d] if len(values) >= 2: effects[name] = effect(values) out.append({"switch": s, "pairs": len(diffs), "left_out_for_draws": jumps, "effects": effects, "verdict": verdict(effects["median"]) if "median" in effects else "not enough phases"}) return {"switches": out} def plan(pairs, switch): warm = ["warm-up A", "warm-up B"] discard = ["discarded A"] if switch else ["discarded B", "discarded A"] order = [] for i in range(pairs): order += ["A", "B"] if i % 2 == 0 else ["B", "A"] return {"warm_up_and_discarded": warm + discard, "measured": order, "note": "pairs (1,2), (3,4), ... of the measured runs; an even count balances the drift"} def number(x, digits=2): return "-" if x is None else f"{x:+.{digits}f}" if digits else f"{x}" def render_abba(r): lines = [f"metric: {r['metric']}"] for run in r["runs"]: value = "left out" if run["left_out"] else f"{run['frame_ms']:.2f} ms" lines.append(f" run {run['position']} {run['arm']}: {value}" + (f" ({run['left_out']})" if run["left_out"] else "")) for arm, mean in r["means"].items(): lines.append(f" mean {arm}: {mean:.2f} ms") e = r["result"] if e: ci = e["ci95"] lines.append(f"{r['method']}: effect {number(e['effect'])} ms ({number(r.get('percent'), 1)} %), standard error " f"{e['se']:.2f}, 95 % [{ci[0]:+.2f}, {ci[1]:+.2f}], {e['k']} " + ("pairs" if r["method"] == "pairs" else "runs") + (f", {e['agree']} of {e['k']} agree in sign" if r["method"] == "pairs" else "")) lines.append(f"verdict: {r['verdict']}") return "\n".join(lines) + "\n" def render_phases(r): lines = [] for s in r["switches"]: lines.append(f"switch {s['switch']}: {s['pairs']} pairs of blocks, {s['left_out_for_draws']} left out for a draw jump; " f"verdict on the median frame time: {s['verdict']}") for name, e in s["effects"].items(): lines.append(f" {name}: {number(e['effect'], 3)} +- {e['se']:.3f} ({e['k']} pairs)") return "\n".join(lines) + "\n" if lines else "no A/B phase lines\n" def main(argv=None): parser = argparse.ArgumentParser(description="Reads an A/B of the D3D12 runtime.") sub = parser.add_subparsers(dest="command", required=True) p = sub.add_parser("abba") p.add_argument("runs", nargs="+") p.add_argument("--json", action="store_true") p = sub.add_parser("phases") p.add_argument("log") p.add_argument("--keep-draw-jumps", action="store_true") p.add_argument("--json", action="store_true") p = sub.add_parser("plan") p.add_argument("--pairs", type=int, default=4) p.add_argument("--switch", action="store_true") p.add_argument("--json", action="store_true") args = parser.parse_args(argv) if args.command == "abba": items = [] for item in args.runs: arm, sep, path = item.partition(":") if not sep or arm not in ("A", "B") or not path: print("each run is A: or B:", file=sys.stderr) return 2 if not os.path.exists(path): print("a run given does not exist", file=sys.stderr) return 2 items.append((arm,) + run_value(path)) result = abba(items) print(json.dumps(result, indent=2) if args.json else render_abba(result), end="" if not args.json else "\n") return 0 if args.command == "phases": if not os.path.exists(args.log): print("the log given does not exist", file=sys.stderr) return 2 result = phase_effects(read_phases(args.log), args.keep_draw_jumps) print(json.dumps(result, indent=2) if args.json else render_phases(result), end="" if not args.json else "\n") return 0 result = plan(args.pairs, args.switch) if args.json: print(json.dumps(result, indent=2)) else: print("first: " + ", ".join(result["warm_up_and_discarded"])) print("then: " + " ".join(result["measured"])) print(result["note"]) return 0 if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())