"""The MMA arm with the activation rotated once in a prologue launch (prestage=1) against the plan's choice (auto: per-CTA
rotation through AG_MMA_PRESTAGE_ROWS rows), per cell and row count, timed as the L2-swept race times them. Bitwise:
the same calls on the same values, which this asserts per (cell, rows)."""
import os, random, statistics, sys, pathlib, json
sys.path.insert(0, os.getcwd())
import torch
import arbi_serve._prebake_loader  # noqa
from arbi_serve.weight_quant.exl3.gemv_route import arbi_gemv_ext
from tools.exl3_pack_census import census, load_one
from tools.gpu_measure import make_l2_scrub
ag = arbi_gemv_ext(); ag.set_pipeline(True, True)
dev = "cuda:0"; model = pathlib.Path(sys.argv[1])
props = torch.cuda.get_device_properties(dev); l2 = props.L2_cache_size
_buf, scrub = make_l2_scrub(dev, "read")
rows = [int(v) for v in os.environ.get("PRE_ROWS", "1,2,3,4,6,8").split(",")]
reps = int(os.environ.get("PRE_REPS", "11")); only = os.environ.get("PRE_CELLS", "").split(",") if os.environ.get("PRE_CELLS") else None
print("card", props.name, "SMs", props.multi_processor_count, "L2 MiB", l2 >> 20, flush=True)
out = []
for c in census(model):
    name = f"{c.in_f}x{c.out_f}"
    if only and name not in only: continue
    b = load_one(c.shard, c.example, dev); K, N = c.in_f, c.out_f
    copies = max(2, min(64, -(-3 * l2 // (b["trellis"].numel() * 2))))
    trs = [b["trellis"]] + [b["trellis"].clone() for _ in range(copies - 1)]
    line = []
    for m in rows:
        x = torch.randn(m, K, dtype=torch.float16, device=dev) * 0.5
        call = lambda t, pre: ag.gemv_exl3_mma(x, t, b["suh"], b["svh"], c.bits, c.cb, K, N, m, torch.float16, 0, 1, None, True, 0, 0, pre)
        assert torch.equal(call(trs[0], -1), call(trs[0], 1)), (name, m)
        gs = {}
        for pre in (-1, 1):
            def f(pre=pre):
                for t in trs: call(t, pre)
            f(); f(); torch.cuda.synchronize()
            g = torch.cuda.CUDAGraph()
            with torch.cuda.graph(g): f()
            g.replay(); torch.cuda.synchronize(); gs[pre] = g
        ts = {k: [] for k in gs}
        for _ in range(reps):
            order = list(gs); random.shuffle(order)
            for k in order:
                e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
                scrub(); gs[k].replay(); e0.record(); gs[k].replay(); e1.record(); e1.synchronize()
                ts[k].append(e0.elapsed_time(e1) * 1e3 / copies)
        a, p = statistics.median(ts[-1]), statistics.median(ts[1])
        line.append(f"M{m} {a:.1f}->{p:.1f} ({100*(p/a-1):+.1f}%)")
        out.append({"card": props.name, "cell": name, "bits": c.bits, "M": m, "auto_us": round(a, 3), "prestage_us": round(p, 3)})
        del gs
    print(f"{name:12s} K{c.bits} " + " | ".join(line), flush=True)
    del b, trs; torch.cuda.empty_cache()
if len(sys.argv) > 2: open(sys.argv[2], "w").write("\n".join(json.dumps(r) for r in out) + "\n")
