"""Small-row analysis: is the 3-4 us/call bimodality a property of the captured graph?
Capture the SAME arm N times (fresh activation/output allocations each time, pads in between)
and time every capture. Prints us/call per capture and the pointers' low bits."""
import argparse, importlib, os, pathlib, statistics, sys
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, EXL3_GEMV_PLAN_ROWS
from tools.exl3_pack_census import census, load_one
ap = argparse.ArgumentParser()
ap.add_argument("--model", type=pathlib.Path, required=True)
ap.add_argument("--cells", nargs="+", required=True)
ap.add_argument("--rows", type=int, nargs="+", default=[4])
ap.add_argument("--caps", type=int, default=8)
ap.add_argument("--reps", type=int, default=15)
ap.add_argument("--copies", type=int, default=0)
a = ap.parse_args()
ext = importlib.import_module("exllamav3.ext").exllamav3_ext
ag = arbi_gemv_ext()
ag.set_pipeline(True, True)
dev = "cuda:0"
l2 = torch.cuda.get_device_properties(dev).L2_cache_size
def capture(fn):
    fn(); fn(); torch.cuda.synchronize()
    g = torch.cuda.CUDAGraph()
    with torch.cuda.graph(g):
        fn()
    g.replay(); torch.cuda.synchronize()
    return g
def t(g, calls):
    ts = []
    for _ in range(a.reps):
        e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
        e0.record(); g.replay(); e1.record(); e1.synchronize()
        ts.append(e0.elapsed_time(e1) * 1e3 / calls)
    return statistics.median(ts), min(ts), max(ts)
pads = []
for cell in census(a.model):
    key = f"{cell.in_f}x{cell.out_f}"
    if key not in a.cells: continue
    b = load_one(cell.shard, cell.example, dev)
    copies = a.copies or max(2, min(64, -(-3 * l2 // cell.w_bytes)))
    trs = [b["trellis"].clone() for _ in range(copies)]
    k, n = cell.in_f, cell.out_f
    for m in a.rows:
        for cap in range(a.caps):
            pads.append(torch.empty(1024 * (1 + 37 * cap % 61), device=dev, dtype=torch.uint8))
            x = torch.randn(m, k, dtype=torch.float16, device=dev) * 0.5
            xh = torch.empty_like(x); y = torch.empty(m, n, dtype=torch.float16, device=dev)
            def mma():
                for tr in trs: ag.gemv_exl3_mma(x, tr, b["suh"], b["svh"], cell.bits, cell.cb, k, n, m, torch.float16, 0, 1)
            def simt():
                for tr in trs: ag.gemv_exl3(x, tr, b["suh"], b["svh"], cell.bits, cell.cb, k, n, False, torch.float16, 0, m, EXL3_GEMV_PLAN_ROWS)
            def up():
                for tr in trs: ext.exl3_gemv(x, tr, y, b["suh"], xh, b["svh"], b["mcg"], b["mul1"])
            arms = {"mma": mma, "simt": simt}
            if cell.bits <= 4: arms["up_gemv"] = up
            gs = {nm: capture(f) for nm, f in arms.items()}
            # two timing rounds per capture: is the state stable for one graph?
            r1 = {nm: t(g, copies) for nm, g in gs.items()}
            r2 = {nm: t(g, copies) for nm, g in gs.items()}
            print(f"{key} M={m} cap={cap} x%4096={x.data_ptr() % 4096:4d} y%4096={y.data_ptr() % 4096:4d} "
                  + " ".join(f"{nm}={r1[nm][0]:.2f}/{r2[nm][0]:.2f}[{r1[nm][1]:.1f}-{r1[nm][2]:.1f}]" for nm in gs), flush=True)
            del gs
    del trs, b
    torch.cuda.empty_cache()
