"""Per-launch time of the served GDN verify+fold launch at 1/2/4/8 rows for the mounted tree (one arm per process).
Graph replay of L launches, one cold slab each. `commit`: the launches alone. `chain`: each launch followed by two
DRAM-bound cold fp32 reductions of RD_MB each (stand-ins for the gate|up GEMMs). `readers`: the reductions alone.
Operand dtypes/views are the served ones, so every launch resolves a prebuilt binary (Triton cache is read-only)."""
import argparse, json, statistics
import torch
import arbi_serve.kernels.fused_sigmoid_gating as fsg

H, HV, K, V, T_BUF = 16, 48, 128, 128, 8
bf, dev = torch.bfloat16, "cuda"
ap = argparse.ArgumentParser()
ap.add_argument("--arm", required=True); ap.add_argument("--L", type=int, default=48); ap.add_argument("--reps", type=int, default=80)
ap.add_argument("--out", required=True); ap.add_argument("--rd-mb", type=int, default=45); ap.add_argument("--round", type=int, default=0)
ap.add_argument("--n-pre", type=int, default=2)
a = ap.parse_args()
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)


def build(B):
    n = B + 1
    return dict(A_log=r(HV, sc=0.5), dt_bias=r(HV, sc=0.5), slab=[r(n, HV, V, K, sc=0.3, d=torch.float32) for _ in range(a.L)],
        rk=[r(n, T_BUF, H, K) for _ in range(a.L)], rv=[r(n, T_BUF, HV, V) for _ in range(a.L)],
        rb=[r(n, T_BUF, HV) for _ in range(a.L)], ra=[r(n, T_BUF, HV) for _ in range(a.L)],
        ak=[r(n, T_BUF, H, K) for _ in range(a.L)], ab=[r(n, T_BUF, HV) for _ in range(a.L)], aa=[r(n, T_BUF, HV) for _ in range(a.L)],
        rows=torch.arange(1, B + 1, dtype=torch.int32, device=dev), has_init=torch.ones(B, dtype=torch.int8, device=dev),
        pending=torch.full((n,), a.n_pre, dtype=torch.int32, device=dev), parity=torch.zeros(n, dtype=torch.int32, device=dev))


def launch(st, x, i, T=8):
    q, k, v, b, a_ = x
    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"], 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, fold_n_steps=st["pending"], fold_parity=st["parity"],
        fold_alt_kba=(st["ak"][i], st["ab"][i], st["aa"][i]))[0]


def inputs(B, T=8):
    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:])


nf = (a.rd_mb << 20) // 4
W = [torch.ones(2 * nf, dtype=torch.float32, device=dev) for _ in range(a.L)]
sink = [torch.empty((), dtype=torch.float32, device=dev) for _ in range(2)]


def readers(i):
    torch.sum(W[i][:nf], dim=0, out=sink[0]); torch.sum(W[i][nf:], dim=0, out=sink[1])


def graph(fn):
    gr = torch.cuda.CUDAGraph()
    with torch.cuda.graph(gr):
        keep = [fn(i) for i in range(a.L)]
    return gr, keep


def tm(gr):
    for _ in range(5): gr.replay()
    ts = []
    for _ in range(a.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 / a.L)
    return round(statistics.median(ts), 2)


readers(0); torch.cuda.synchronize()
g_rd = graph(readers)
rec = open(a.out, "a")
for B in (1, 2, 4, 8):
    st = build(B); x = inputs(B)
    launch(st, x, 0); torch.cuda.synchronize()
    gc = graph(lambda i: launch(st, x, i)); gch = graph(lambda i: (launch(st, x, i), readers(i)))
    row = dict(arm=a.arm, round=a.round, B=B, n_pre=a.n_pre, commit_us=tm(gc[0]), readers_us=tm(g_rd[0]), chain_us=tm(gch[0]))
    row["hidden_us"] = round(row["chain_us"] - row["commit_us"] - row["readers_us"], 2)
    rec.write(json.dumps(row) + "\n"); rec.flush(); print(row, flush=True)
    del gc, gch, st; torch.cuda.empty_cache()
