"""Does the MMA arm's time on a K-deep cell depend on WHERE its partial buffer sits? The base kernel behind the lab C ABI,
the same launch, the partials at different offsets inside one large allocation (and in fresh allocations).
usage: part_probe.py MODEL CELL ROWS"""
import ctypes, 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
import pathlib
model, cellname, m = pathlib.Path(sys.argv[1]), sys.argv[2], int(sys.argv[3])
ag = arbi_gemv_ext(); dev = "cuda:0"
L = ctypes.CDLL("/scripts/lab/lab_base.so")
L.lab_launch.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] + [ctypes.c_void_p] * 6 + [ctypes.c_int] * 6 + [ctypes.c_void_p]
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)]
kc, splits = ag.gemv_exl3_mma_plan(K, N, 0)
kst = max(1, min(32768 // 2048, kc // 128))
x = torch.randn(m, K, dtype=torch.float16, device=dev) * 0.5
need = splits * m * N * 4
big = torch.empty(need + (64 << 20), dtype=torch.uint8, device=dev)
base = big.data_ptr()
ctr = torch.zeros(N // 128 + 16, dtype=torch.int32, device=dev)
out = torch.empty(m, N, dtype=torch.float16, device=dev)
print(f"# {cellname} M={m} kc={kc} splits={splits} partial {need/2**20:.1f} MiB, big base % 2MiB = {base % (2<<20)}, L2 {l2>>20} MiB", flush=True)
def mk(ptr):
    def f():
        s = torch.cuda.current_stream().cuda_stream
        for tr in trs:
            rc = L.lab_launch(s, c.bits, c.cb, x.data_ptr(), tr.data_ptr(), ptr, out.data_ptr(), b["suh"].data_ptr(), b["svh"].data_ptr(), K, N, kc, splits, kst, m, ctr.data_ptr())
            assert rc == 0
    return f
al = (-base) % (2 << 20)   # offset that makes the partials 2 MiB aligned
fns = {"2MiB-aligned": mk(base + al), "+16B": mk(base + al + 16), "+64B": mk(base + al + 64), "+256B": mk(base + al + 256), "+4KiB": mk(base + al + 4096), "+64KiB": mk(base + al + 65536), "+1MiB": mk(base + al + (1 << 20)), "+31MiB": mk(base + al + (31 << 20))}
keep = []
for i in range(4):
    t = torch.empty(need // 4, dtype=torch.float32, device=dev); keep.append(t); keep.append(torch.empty(random.randrange(1, 9) << 18, dtype=torch.uint8, device=dev))
    fns[f"fresh{i}(%2MiB={t.data_ptr() % (2<<20)})"] = mk(t.data_ptr())
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(15):
    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)
for k, v in ts.items(): print(f"{k:28} {statistics.median(v):8.2f}  [{min(v):.2f} .. {max(v):.2f}]", flush=True)
