"""Decompose the served GDN verify+fold launch on one card (existing kernel, no source change).

A CUDA graph of L launches, one per layer slab (L x B x 3.15 MB > L2, so every launch meets its
state cold and the write-back of its stores is paid inside the replay). Per-launch time =
replay time / L. Cells vary rows B, verify tokens T, pending replay steps n_pre (0 = no store),
and the launch shape (BV, warps) through the module constants.
"""
import argparse, json, statistics, sys, time
import torch
import arbi_serve.kernels.fused_sigmoid_gating as fsg

H, HV, K, V = 16, 48, 128, 128
T_BUF = 8
dev, bf = "cuda", torch.bfloat16


def build(L, B):
    n_rows = B + 1
    g = torch.Generator(device=dev).manual_seed(7)
    r = lambda *s, sc=1.0, d=bf: (torch.randn(*s, generator=g, device=dev) * sc).to(d)
    st = dict(
        A_log=r(HV, sc=0.5, d=torch.float32), dt_bias=r(HV, sc=0.5, d=torch.float32),
        slab=[r(n_rows, HV, V, K, sc=0.3, d=torch.float32) for _ in range(L)],
        rk=[r(n_rows, T_BUF, H, K) for _ in range(L)], rv=[r(n_rows, T_BUF, HV, V) for _ in range(L)],
        rb=[r(n_rows, T_BUF, HV) for _ in range(L)], ra=[r(n_rows, T_BUF, HV) for _ in range(L)],
        ak=[r(n_rows, T_BUF, H, K) for _ in range(L)], ab=[r(n_rows, T_BUF, HV) for _ in range(L)],
        aa=[r(n_rows, T_BUF, HV) for _ in range(L)],
        rows=torch.arange(1, B + 1, dtype=torch.int32, device=dev),
        has_init=torch.ones(B, dtype=torch.float32, device=dev),
        pending=torch.zeros(n_rows, dtype=torch.int32, device=dev),
        parity=torch.zeros(n_rows, dtype=torch.int32, device=dev),
    )
    return st


def inputs(B, T):
    g = torch.Generator(device=dev).manual_seed(11)
    r = lambda *s: (torch.randn(*s, generator=g, device=dev)).to(bf)
    qkv = r(B * T, 2 * H * K + HV * V)
    ba = r(B * T, 2 * HV)
    return (qkv[:, : H * K].view(B * T, H, K), qkv[:, H * K : 2 * H * K].view(B * T, H, K),
            qkv[:, 2 * H * K :].view(B * T, HV, V), ba[:, :HV], ba[:, HV:])


def launch(st, x, T, i, fold=True):
    q, k, v, b, a = x
    kw = dict(fold_n_steps=st["pending"], fold_parity=st["parity"],
              fold_alt_kba=(st["ak"][i], st["ab"][i], st["aa"][i])) if fold else {}
    return fsg.fused_sigmoid_gating_delta_rule_update(
        A_log=st["A_log"], a=a, b=b, dt_bias=st["dt_bias"],
        q=q.unflatten(0, (-1, T)), k=k.unflatten(0, (-1, T)), v=v.unflatten(0, (-1, T)),
        initial_state=st["slab"][i], ssm_state_indices=st["rows"], final_state_out=None,
        init_state_mask=st["has_init"],
        save_inputs_kvba=(st["rk"][i], st["rv"][i], st["rb"][i], st["ra"][i]),
        commit_final_state=False, use_qk_l2norm_in_kernel=True, **kw)[0]


def time_graph(st, x, T, L, reps, fold=True):
    for i in range(min(L, 2)):
        launch(st, x, T, i, fold)  # compile outside capture
    torch.cuda.synchronize()
    gr = torch.cuda.CUDAGraph()
    with torch.cuda.graph(gr):
        outs = [launch(st, x, T, i, fold) for i in range(L)]
    for _ in range(5):
        gr.replay()
    torch.cuda.synchronize()
    ts = []
    for _ in range(reps):
        s, e = torch.cuda.Event(True), torch.cuda.Event(True)
        s.record(); gr.replay(); e.record(); e.synchronize()
        ts.append(s.elapsed_time(e) * 1000.0 / L)
    del outs
    return statistics.median(ts), min(ts)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--L", type=int, default=48)
    ap.add_argument("--reps", type=int, default=60)
    ap.add_argument("--out", default="/out/decomp.jsonl")
    ap.add_argument("--mode", default="all")
    a = ap.parse_args()
    print(torch.cuda.get_device_name(0), torch.__version__, "triton", __import__("triton").__version__, flush=True)
    rec = open(a.out, "a")

    def emit(**kw):
        rec.write(json.dumps(kw) + "\n"); rec.flush()
        print(" ".join(f"{k}={v}" for k, v in kw.items()), flush=True)

    if a.mode in ("all", "decomp"):
        for B in (1, 2, 4, 8):
            st = build(a.L, B)
            for T in (1, 2, 4, 8):
                x = inputs(B, T)
                for n_pre in (0, 1, 2, 4, 8):
                    st["pending"].fill_(n_pre)
                    med, mn = time_graph(st, x, T, a.L, a.reps)
                    emit(cell="decomp", B=B, T=T, n_pre=n_pre, bv=fsg.GDN_BV, warps=fsg.GDN_NUM_WARPS,
                         us_med=round(med, 2), us_min=round(mn, 2))
            # no-fold build (plain replay-save verify) at T=8: the fold's constexpr cost
            med, mn = time_graph(st, inputs(B, 8), 8, a.L, a.reps, fold=False)
            emit(cell="nofold", B=B, T=8, n_pre=-1, bv=fsg.GDN_BV, warps=fsg.GDN_NUM_WARPS, us_med=round(med, 2), us_min=round(mn, 2))
            del st; torch.cuda.empty_cache()
    if a.mode in ("all", "shape"):
        for bv, w in ((8, 1), (16, 1), (32, 1), (8, 2), (16, 2), (32, 2), (32, 4), (64, 4), (128, 4), (128, 8)):
            fsg.GDN_BV, fsg.GDN_NUM_WARPS = bv, w
            for B in (1, 2, 4, 8):
                st = build(a.L, B); x = inputs(B, 8)
                for n_pre in (0, 4):
                    st["pending"].fill_(n_pre)
                    try:
                        med, mn = time_graph(st, x, 8, a.L, a.reps)
                    except Exception as ex:  # noqa: BLE001
                        emit(cell="shape", B=B, T=8, n_pre=n_pre, bv=bv, warps=w, error=str(ex)[:200]); continue
                    emit(cell="shape", B=B, T=8, n_pre=n_pre, bv=bv, warps=w, us_med=round(med, 2), us_min=round(mn, 2))
                del st; torch.cuda.empty_cache()
        fsg.GDN_BV, fsg.GDN_NUM_WARPS = 8, 1
    if a.mode == "ncu":
        # eager launches for ncu: served cell, cold slabs by rotation
        for B in (1, 4, 8):
            st = build(a.L, B); x = inputs(B, 8); st["pending"].fill_(4)
            for i in range(a.L):
                launch(st, x, 8, i)
            torch.cuda.synchronize()
            del st; torch.cuda.empty_cache()


main()
