# ruff: noqa
# Small-row analysis scratch, kept as run (docs/design/exl3-small-row-kernel.md).
"""Old vs new race chains: per (cell, M) the MMA arm's change, and ours-best vs upstream-best with the new arm.
usage: sr_ab.py OLD.json[,OLD2.json] NEW.json[,NEW2.json]"""
import json, statistics, sys
PEAK = 1008e9
OURS = ("mma", "mma_p3", "simt", "i8", "mma_group", "simt_group")
UP = ("served", "auto", "up_gemv", "members_served", "members_up_gemv")
def load(paths):
    acc = {}
    for p in paths.split(","):
        for r in json.load(open(p)):
            key = (r["in_f"], r.get("out_f") or tuple(r["widths"]), r["bits"], r["w_bytes"])
            for arm, us in r["us"].items():
                acc.setdefault(key, {}).setdefault(r["M"], {}).setdefault(arm, []).append(us)
    return {k: {m: {a: statistics.mean(v) for a, v in arms.items()} for m, arms in by.items()} for k, by in acc.items()}
old, new = load(sys.argv[1]), load(sys.argv[2])
print("| cell | M | mma old | mma new | change | ours best (new) | % roof | upstream best | ours/up | simt |")
print("|---|---|---|---|---|---|---|---|---|---|")
wins = []
for key in new:
    k, n, bits, wb = key
    roof = wb / PEAK * 1e6
    name = f"{k}x{n}" if isinstance(n, int) else str(k) + "x" + "+".join(map(str, n))
    mine = "mma" if isinstance(n, int) else "mma_group"
    for m in sorted(new[key]):
        if m > 8: continue
        a, o = new[key][m], old.get(key, {}).get(m, {})
        ob = min((a[x], x) for x in OURS if x in a); ub = min(((a[x] + o.get(x, a[x])) / 2, x) for x in UP if x in a)
        ch = f"{100 * (a[mine] / o[mine] - 1):+.1f}%" if mine in o and mine in a else "-"
        flag = "**" if ob[0] > ub[0] else ""
        if ob[0] > ub[0]: wins.append((name, m, ob, ub))
        sm = a.get("simt", a.get("simt_group"))
        print(f"| {name} K{bits} | {m} | {o.get(mine, float('nan')):.1f} | {a.get(mine, float('nan')):.1f} | {ch} | {ob[0]:.1f} ({ob[1]}) | {100 * roof / ob[0]:.0f}% | {ub[0]:.1f} ({ub[1]}) | {flag}{ob[0] / ub[0]:.3f}{flag} | {sm:.1f} |" if sm else
              f"| {name} K{bits} | {m} | {o.get(mine, float('nan')):.1f} | {a.get(mine, float('nan')):.1f} | {ch} | {ob[0]:.1f} ({ob[1]}) | {100 * roof / ob[0]:.0f}% | {ub[0]:.1f} ({ub[1]}) | {flag}{ob[0] / ub[0]:.3f}{flag} | - |")
print(f"\nupstream ahead at {len(wins)} (cell, M): " + "; ".join(f"{n}@{m} {o[0]:.1f}{o[1]} vs {u[0]:.1f}{u[1]}" for n, m, o, u in wins))
