"""Lab race: MMA kernel variants (lab_<tag>.so, one per source/define set) on real weights.
Each variant is launched as ag_mma_launch launches the single-linear arm (grid bands x splits,
in-launch reduction), graph-replayed over cold weight copies, arms interleaved within a rep.
Every variant's output is compared BITWISE with the shipped extension's arm."""
import argparse, ctypes, glob, os, pathlib, random, 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=[1, 4, 8])
ap.add_argument("--tags", nargs="+", required=True)
ap.add_argument("--reps", type=int, default=15)
ap.add_argument("--libdir", default="/scripts/lab")
ap.add_argument("--extra", nargs="*", default=["shipped", "simt"])
ap.add_argument("--sweep", nargs="*", type=int, default=None, help="forced slice counts for the FIRST tag")
ap.add_argument("--res", nargs="*", type=float, default=[0, 4], help="CTAs an SM the slice-owning grid fills; 0 = one CTA a band")
ap.add_argument("--kst", nargs="*", type=int, default=None, help="forced staging depths (blocks a pass) for the FIRST tag")
a = ap.parse_args()
ag = arbi_gemv_ext(); ag.set_pipeline(True, True)
dev = "cuda:0"
l2 = torch.cuda.get_device_properties(dev).L2_cache_size
libs = {}
for t in a.tags:
    L = ctypes.CDLL(f"{a.libdir}/lab_{t}.so")
    L.lab_launch.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] + [ctypes.c_void_p] * 6 + [ctypes.c_int] * 6 + [ctypes.c_void_p]
    libs[t] = L
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
for c in census(a.model):
    key = f"{c.in_f}x{c.out_f}"
    if key not in a.cells: 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)]
    kc, splits = ag.gemv_exl3_mma_plan(K, N, 0)
    def sched(lanes):
        per = 2048 * lanes // 32
        kst = max(1, min(32768 // per, kc // 128))
        if (kc // 128) * per > 16384: kst = max(1, 8192 // per)
        return kst
    print(f"# {key} K{c.bits} cb{c.cb} kc={kc} splits={splits} copies={copies}", flush=True)
    for m in a.rows:
        x = torch.randn(m, K, dtype=torch.float16, device=dev) * 0.5
        ref = ag.gemv_exl3_mma(x, b["trellis"], b["suh"], b["svh"], c.bits, c.cb, K, N, m, torch.float16, 0, 1)
        fns, bits_ok = {}, {}
        arms = {}
        for t in libs:
            arms[t] = (t, 32)
        for t, (lt_, lanes) in arms.items():
            L = libs[lt_]
            kst = sched(lanes)
            out = torch.empty(m, N, dtype=torch.float16, device=dev)
            part = torch.empty(max(1, splits * m * N), dtype=torch.float32, device=dev)
            ctr = torch.zeros(N // 128 + 16, dtype=torch.int32, device=dev)
            def f(L=L, out=out, part=part, ctr=ctr, lanes=lanes, kst=kst):
                s = torch.cuda.current_stream().cuda_stream
                for tr in trs:
                    rc = L.lab_launch(s, c.bits, c.cb, x.data_ptr(), tr.data_ptr(), part.data_ptr(), out.data_ptr(),
                                      b["suh"].data_ptr(), b["svh"].data_ptr(), K, N, kc, splits, kst, m, ctr.data_ptr())
                    assert rc == 0, rc
            f(); torch.cuda.synchronize()
            bits_ok[t] = bool(torch.equal(out, ref))
            fns[t] = f
        if "shipped" in a.extra:
            def shipped():
                for tr in trs: ag.gemv_exl3_mma(x, tr, b["suh"], b["svh"], c.bits, c.cb, K, N, m, torch.float16, 0, 1)
            fns["shipped"] = shipped
        for fs in sorted({int(e[9:]) for e in a.extra if e.startswith("shipped_s")}):
            if True:
                def shipped_f(fs=fs):
                    for tr in trs: ag.gemv_exl3_mma(x, tr, b["suh"], b["svh"], c.bits, c.cb, K, N, m, torch.float16, fs, 1)
                fns[f"shipped_s{fs}"] = shipped_f
        if "up" in a.extra and m <= 8 and c.bits <= 4:
            import importlib
            ext = importlib.import_module("exllamav3.ext").exllamav3_ext
            xh = torch.empty_like(x); yu = torch.empty(m, N, dtype=torch.float16, device=dev)
            def up_gemv():
                for tr in trs: ext.exl3_gemv(x, tr, yu, b["suh"], xh, b["svh"], b["mcg"], b["mul1"])
            fns["up_gemv"] = up_gemv
        if "auto" in a.extra:
            import importlib
            ext = importlib.import_module("exllamav3.ext").exllamav3_ext
            xh2 = torch.empty_like(x); ya = torch.empty(m, N, dtype=torch.float16, device=dev)
            def auto():
                for tr in trs: ext.exl3_gemm(x, tr, ya, b["suh"], xh2, b["svh"], -1, b["mcg"], b["mul1"], 0, N)
            fns["auto"] = auto
        if "simt" in a.extra and m <= 8:
            def simt():
                for tr in trs: ag.gemv_exl3(x, tr, b["suh"], b["svh"], c.bits, c.cb, K, N, False, torch.float16, 0, m, EXL3_GEMV_PLAN_ROWS)
            fns["simt"] = simt
        gs = {k: capture(f) for k, f in fns.items()}
        ts = {k: [] for k in gs}
        for _ in range(a.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)
                gs[k].replay(); e0.record(); gs[k].replay(); e1.record(); e1.synchronize()
                ts[k].append(e0.elapsed_time(e1) * 1e3 / copies)
        bad = [t for t, ok in bits_ok.items() if not ok]
        print(f"{key} M={m} " + " ".join(f"{k}={statistics.median(v):.2f}" for k, v in ts.items()) + (f" BITS_DIFFER={bad}" if bad else " bits=ok"), flush=True)
        del gs
    del trs, b; torch.cuda.empty_cache()
