"""Why the MMA arm reads one of two values a capture in the route race. One (cell, rows): the MMA arm and the stock
exl3_gemm, each captured into graphs over cold weight copies as the race captures them, then replayed in chosen orders
with every replay timed. Shows (1) the arm's time follows the graph replayed before it, for as long as it is replayed;
(2) idle time does not reset it; (3) a sweep of L2 (tools.gpu_measure.make_l2_scrub) does."""
import argparse, os, pathlib, sys, time
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 arbi_serve.weight_quant.exl3 import shim
from tools.exl3_pack_census import census, load_one
from tools.gpu_measure import make_l2_scrub
ap = argparse.ArgumentParser()
ap.add_argument("--model", type=pathlib.Path, required=True)
ap.add_argument("--cell", required=True)
ap.add_argument("--rows", type=int, nargs="+", default=[4])
ap.add_argument("--prec", type=int, default=1)
ap.add_argument("--trials", type=int, default=3)
a = ap.parse_args()
ag = arbi_gemv_ext(); ag.set_pipeline(True, True)
shim.load_ext()
from arbi_serve.weight_quant.exl3 import custom_op as co
ext = co._exllamav3_ext()
dev = "cuda:0"
props = torch.cuda.get_device_properties(dev); l2 = props.L2_cache_size
for c in census(a.model):
    if f"{c.in_f}x{c.out_f}" != a.cell: continue
    b = load_one(c.shard, c.example, dev)
    K, N = c.in_f, c.out_f
    copies = max(2, min(64, -(-3 * l2 // c.w_bytes)))
    trs = [b["trellis"].clone() for _ in range(copies)]
    print(f"# {props.name} ({props.multi_processor_count} SMs, L2 {l2 >> 20} MiB) {a.cell} K{c.bits} cb{c.cb} plan={ag.gemv_exl3_mma_plan(K, N, 0)} copies={copies}; us a call", flush=True)
    scrubs = {mode: make_l2_scrub(dev, mode)[1] for mode in ("read", "write")}
    for m in a.rows:
        x = torch.randn(m, K, dtype=torch.float16, device=dev) * 0.5
        xh = torch.empty_like(x); y0 = torch.empty(m, N, dtype=torch.float16, device=dev)
        def make(arm):
            def fn():
                for t in trs:
                    if arm == "mma": ag.gemv_exl3_mma(x, t, b["suh"], b["svh"], c.bits, c.cb, K, N, m, torch.float16, 0, a.prec)
                    else: ext.exl3_gemm(x, t, y0, b["suh"], xh, b["svh"], -1, b["mcg"], b["mul1"], 0, N)
            s = torch.cuda.Stream(); s.wait_stream(torch.cuda.current_stream())
            with torch.cuda.stream(s): fn(); fn()
            torch.cuda.current_stream().wait_stream(s); torch.cuda.synchronize()
            g = torch.cuda.CUDAGraph()
            with torch.cuda.graph(g): fn()
            g.replay(); torch.cuda.synchronize()
            return g
        G = {"mma": make("mma"), "mma'": make("mma"), "up": make("up"), "up'": make("up")}
        def run(k, n):
            ev = [torch.cuda.Event(enable_timing=True) for _ in range(n + 1)]
            ev[0].record()
            for j in range(n):
                G[k].replay(); ev[j + 1].record()
            ev[n].synchronize()
            return [round(ev[j].elapsed_time(ev[j + 1]) * 1e3 / copies, 1) for j in range(n)]
        def after(k, pre, mode=None, idle=0.0, n=4):
            run(pre, 8)
            if idle: torch.cuda.synchronize(); time.sleep(idle)
            if mode: scrubs[mode]()
            return run(k, n)
        print(f"## rows {m}")
        for trial in range(a.trials):
            print(f"trial {trial}")
            print("  mma, 40 replays behind 8 of up :", after("mma", "up", n=40))
            print("  mma, 12 replays behind 8 of mma':", after("mma", "mma'", n=12))
            print("  up,  12 replays behind 8 of mma :", after("up", "mma", n=12))
            print("  up,  12 replays behind 8 of up'  :", after("up", "up'", n=12))
            print("  mma behind up, 20 ms idle between:", after("mma", "up", idle=0.02, n=8))
            for mode in ("read", "write"):
                print(f"  sweep={mode}: mma behind up {after('mma', 'up', mode)} | mma behind mma' {after('mma', chr(109)+chr(109)+chr(97)+chr(39), mode)} | up behind mma {after('up', 'mma', mode)} | up behind up' {after('up', 'up'+chr(39), mode)}", flush=True)
    break
