"""The MMA arm's two capture modes on a K-deep cell: capture the SAME ext call many times, two ways
(warm-up on a side stream as the route race does; warm-up on the default stream as the lab does), and time each capture.
usage: mode_probe.py MODEL CELL ROWS"""
import 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
from tools.exl3_pack_census import census, load_one
model, cellname, m = pathlib.Path(sys.argv[1]), sys.argv[2], int(sys.argv[3])
ag = arbi_gemv_ext(); dev = "cuda:0"
l2 = torch.cuda.get_device_properties(dev).L2_cache_size
c = next(c for c in census(model) if f"{c.in_f}x{c.out_f}" == cellname)
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)]
x = torch.randn(m, K, dtype=torch.float16, device=dev) * 0.5
outs = []
def fn():
    outs.clear()
    for tr in trs: outs.append(ag.gemv_exl3_mma(x, tr, b["suh"], b["svh"], c.bits, c.cb, K, N, m, torch.float16, 0, 1))
def cap_side():
    s = torch.cuda.Stream(); s.wait_stream(torch.cuda.current_stream())
    with torch.cuda.stream(s): fn(); fn()
    torch.cuda.current_stream().wait_stream(s); torch.cuda.synchronize()
    g = torch.cuda.CUDAGraph()
    with torch.cuda.graph(g): fn()
    g.replay(); torch.cuda.synchronize(); return g, [o.data_ptr() for o in outs]
def cap_default():
    fn(); fn(); torch.cuda.synchronize()
    g = torch.cuda.CUDAGraph()
    with torch.cuda.graph(g): fn()
    g.replay(); torch.cuda.synchronize(); return g, [o.data_ptr() for o in outs]
gs = {}
for i in range(6):
    gs[f"side{i}"] = cap_side(); gs[f"default{i}"] = cap_default()
ts = {k: [] for k in gs}
for _ in range(11):
    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][0].replay(); e0.record(); gs[k][0].replay(); e1.record(); e1.synchronize()
        ts[k].append(e0.elapsed_time(e1) * 1e3 / copies)
print(f"# {cellname} M={m} copies={copies}")
for k in sorted(ts): print(f"{k:10} {statistics.median(ts[k]):8.2f} [{min(ts[k]):.2f}..{max(ts[k]):.2f}]  out ptrs % 2MiB = {[p % (2<<20) for p in gs[k][1]]}  out gap = {abs(gs[k][1][1]-gs[k][1][0])}")
