"""Forced k cuts (a forced cut moves bits: a probe, not a fix) on one card, timed as the L2-swept race times them:
graphs over cold weight copies, arms shuffled each rep, an L2 read sweep then one untimed replay before each timed one.
CUT_TARGET=gateup: the gate|up grouped MMA launch; head: the largest-N single cell (the logits head)."""
import os, random, statistics, sys, pathlib, json
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.gpu_measure import make_l2_scrub
ag = arbi_gemv_ext(); ag.set_pipeline(True, True)
dev = "cuda:0"; model = pathlib.Path(sys.argv[1]); target = os.environ.get("CUT_TARGET", "gateup")
props = torch.cuda.get_device_properties(dev); l2 = props.L2_cache_size
_buf, scrub = make_l2_scrub(dev, "read")
rows = [int(v) for v in os.environ.get("CUT_ROWS", "1,2,4,8,12,16").split(",")]
splits = [int(v) for v in os.environ.get("CUT_SPLITS", "0,2,3,4,5,8,10").split(",")]
reps = int(os.environ.get("CUT_REPS", "15"))
cells = census(model)
print("card", props.name, "SMs", props.multi_processor_count, "target", target, flush=True)
out = []
if target == "gateup":
    c = next(c for c in cells if c.example.rsplit(".", 1)[-1] == "gate_proj" and "experts." not in c.example)
    prefix = c.example.rsplit(".", 1)[0]
    mem = [load_one(c.shard, f"{prefix}.{r}", dev) for r in ("gate_proj", "up_proj")]
    widths = [int(b["trellis"].shape[1]) * 16 for b in mem]; K = c.in_f; N = sum(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)]
    def call(x, m, fs, t): 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)
else:
    want = target.split(":", 1)[1] if target.startswith("cell:") else None
    c = (next(c for c in cells if f"{c.in_f}x{c.out_f}" == want) if want
         else max((c for c in cells if "experts." not in c.example), key=lambda c: c.out_f))
    b = load_one(c.shard, c.example, dev); K, N = c.in_f, c.out_f
    w_bytes = b["trellis"].numel() * 2
    copies = max(2, min(64, -(-3 * l2 // w_bytes)))
    trs = [b["trellis"]] + [b["trellis"].clone() for _ in range(copies - 1)]
    def call(x, m, fs, t): ag.gemv_exl3_mma(x, t, b["suh"], b["svh"], c.bits, c.cb, K, N, m, torch.float16, fs, 1)
print(f"{c.example} K{c.bits} cb{c.cb} {K}x{N} plan {ag.gemv_exl3_mma_plan(K, N, 0)} copies {copies}", flush=True)
for m in rows:
    x = torch.randn(m, K, dtype=torch.float16, device=dev) * 0.5
    gs = {}
    for fs in splits:
        def f(fs=fs):
            for t in trs: call(x, m, fs, t)
        f(); f(); torch.cuda.synchronize()
        g = torch.cuda.CUDAGraph()
        with torch.cuda.graph(g): f()
        g.replay(); torch.cuda.synchronize(); gs[fs] = g
    ts = {k: [] for k in gs}
    for _ in range(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)
            scrub(); gs[k].replay(); e0.record(); gs[k].replay(); e1.record(); e1.synchronize()
            ts[k].append(e0.elapsed_time(e1) * 1e3 / copies)
    med = {k: statistics.median(v) for k, v in ts.items()}
    print(f"M={m} " + " ".join(f"{'plan' if k == 0 else f's{k}'}={v:.2f}" for k, v in med.items()), flush=True)
    out.append({"card": props.name, "sms": props.multi_processor_count, "target": target, "cell": f"{K}x{N}", "M": m, "us": {str(k): round(v, 3) for k, v in med.items()}})
    del gs; torch.cuda.empty_cache()
if len(sys.argv) > 2: open(sys.argv[2], "w").write("\n".join(json.dumps(r) for r in out) + "\n")
