"""Flint's q|k|v group (2048 x 4096+512+512) on this card: the grouped MMA launch at the plan's cut and at forced
slice counts (a forced cut moves bits; it is here to show where the time goes), against the grouped SIMT launch.
Graph-replayed over cold weight copies, arms interleaved, as the route race times them."""
import os, 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
from tools.exl3_pack_census import census, load_one
from tools import exl3_gemv_mma_race as R
import argparse, types
ag = arbi_gemv_ext(); ag.set_pipeline(True, True)
dev = "cuda:0"; model = __import__("pathlib").Path(sys.argv[1])
props = torch.cuda.get_device_properties(dev); l2 = props.L2_cache_size
print("card", props.name, "SMs", props.multi_processor_count)
for c in census(model):
    if "." not in c.example: continue
    prefix, role = c.example.rsplit(".", 1)
    roles = {"q_proj": ("q_proj", "k_proj", "v_proj"), "gate_proj": ("gate_proj", "up_proj")}.get(role)
    if roles is None or roles[0] != os.environ.get("GRP_ROLE", "q_proj") or "experts." in c.example: continue
    mem = [load_one(c.shard, f"{prefix}.{r}", dev) for r in roles]
    widths = [int(b["trellis"].shape[1]) * 16 for b in mem]
    K = c.in_f; tot = sum(widths)
    kc, sp = ag.gemv_exl3_mma_plan(K, tot, 0)
    print("group", K, widths, "plan kc", kc, "splits", sp, "CTAs", tot // 128 * sp, "| member plans", [ag.gemv_exl3_mma_plan(K, w, 0) for w in widths])
    w_bytes = sum(b["trellis"].numel() * 2 for b in mem)
    copies = max(2, min(64, -(-3 * l2 // w_bytes)))
    trs = [[b["trellis"].clone() for b in mem] for _ in range(copies)]
    for m in [int(v) for v in os.environ.get("GRP_ROWS", "1,2,4,8").split(",")]:
        x = torch.randn(m, K, dtype=torch.float16, device=dev) * 0.5
        fns = {}
        for fs in [int(v) for v in os.environ.get("GRP_SPLITS", "0,2,3,4,5,6,8").split(",")]:
            def f(fs=fs):
                for t in trs: ag.gemv_exl3_mma_group(x, t, [b["suh"] for b in mem], [b["svh"] for b in mem], widths, c.bits, c.cb, K, m, torch.float16, fs, 1, True)
            fns[f"mma_s{fs}" if fs else "mma_plan"] = f
        gs = {}
        for k, f in fns.items():
            f(); f(); torch.cuda.synchronize()
            g = torch.cuda.CUDAGraph()
            with torch.cuda.graph(g): f()
            g.replay(); torch.cuda.synchronize(); gs[k] = g
        ts = {k: [] for k in gs}
        for _ in range(21):
            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)
        print(f"M={m} " + " ".join(f"{k}={statistics.median(v):.2f}" for k, v in ts.items()), flush=True)
    break
