# ruff: noqa
"""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("--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)
    kst = max(1, min(32768 // 2048, kc // 128))
    occ = {t: L.lab_occ(c.bits, c.cb, kst, int(kst * 128 >= kc)) for t, L in libs.items()}
    print(f"# {key} K{c.bits} cb{c.cb} kc={kc} splits={splits} kst={kst} copies={copies} occ={occ}", 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 = {}, {}
        for t, L in libs.items():
            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):
                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 a.sweep:
            t0 = a.tags[0]; L0 = libs[t0]
            blocks = K // 128
            seen = {splits}
            for want in a.sweep:
                per = -(-blocks // max(1, min(want, blocks)))
                kc2 = per * 128; sp2 = -(-K // kc2)
                if sp2 in seen: continue
                seen.add(sp2)
                kst2 = max(1, min(32768 // 2048, kc2 // 128))
                out = torch.empty(m, N, dtype=torch.float16, device=dev)
                part = torch.empty(max(1, sp2 * m * N), dtype=torch.float32, device=dev)
                ctr = torch.zeros(N // 128 + 16, dtype=torch.int32, device=dev)
                def f(out=out, part=part, ctr=ctr, kc2=kc2, sp2=sp2, kst2=kst2):
                    s = torch.cuda.current_stream().cuda_stream
                    for tr in trs:
                        rc = L0.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, kc2, sp2, kst2, m, ctr.data_ptr())
                        assert rc == 0, rc
                f(); torch.cuda.synchronize()
                err = float((out.float() - ref.float()).abs().max() / ref.float().abs().max())
                assert err < 5e-3, (sp2, err)
                fns[f"s{sp2}"] = f
        if a.kst:
            L0 = libs[a.tags[0]]
            for kq in a.kst:
                if kq == kst or kq * 128 > kc: continue
                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(out=out, part=part, ctr=ctr, kq=kq):
                    s = torch.cuda.current_stream().cuda_stream
                    for tr in trs:
                        rc = L0.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, kq, m, ctr.data_ptr())
                        assert rc == 0, rc
                f(); torch.cuda.synchronize()
                assert torch.equal(out, ref), ("kst", kq)
                fns[f"kst{kq}"] = 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
        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)
                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()
