"""cont 6-B: forced int8 tile x split timing in the 33-48-row band, stock alongside.

The race tool (served int8 build, as sr_race.py) with, for every band job the boot's split race
sees, one extra arm per (tile, split) candidate -- incumbent tile's counts, 94's, 363's -- each
captured with its arm frozen on the band plan, so all arms are timed in the same shuffled replay
loop as `served` / `auto` / `i8` (the boot's pick). The card is held at NVML P0 first and pstate +
clocks are printed per cell. Args pass to the race tool.
"""
import argparse
import os
import sys
import time

sys.path.insert(0, os.getcwd())
os.environ["I8_SERVED_BUILD"] = "1"
import arbi_serve._prebake_loader  # noqa: E402,F401
from arbi_serve.weight_quant.exl3 import int8_kernel as ik  # noqa: E402
from arbi_serve.weight_quant.exl3 import int8_served_set as ss  # noqa: E402

ik._SERVED_PLAN = ss.build_plan(argparse.Namespace(exl3=[os.environ.get("SR_PACK", "4:mul1+6:mcg+6:mul1")],
                                                   exl3_checkpoint=None, gguf=["Q8_KS:none"], gguf_manifest=None))
print("build:", ik._extension_name(), flush=True)
import pynvml  # noqa: E402
import torch  # noqa: E402

from arbi_serve.weight_quant.exl3 import int8_split_k_race as skr  # noqa: E402
from tools import exl3_gemv_mma_race as R  # noqa: E402

pynvml.nvmlInit()
_H = pynvml.nvmlDeviceGetHandleByIndex(0)


def pstate():
    return (f"P{pynvml.nvmlDeviceGetPerformanceState(_H)} sm={pynvml.nvmlDeviceGetClockInfo(_H, pynvml.NVML_CLOCK_SM)}"
            f" mem={pynvml.nvmlDeviceGetClockInfo(_H, pynvml.NVML_CLOCK_MEM)} T={pynvml.nvmlDeviceGetTemperature(_H, 0)}"
            f" cap={pynvml.nvmlDeviceGetEnforcedPowerLimit(_H) // 1000}W")


def warm_p0(min_s=6.0, timeout_s=20.0):
    # Memory-bound load: a power-capped GEMM load holds the card in P2 (seen on the A5500).
    a = torch.empty(64 << 20, device="cuda", dtype=torch.float32)
    b = torch.empty_like(a)
    t0 = time.perf_counter()
    while True:
        for _ in range(20):
            b.copy_(a)
        torch.cuda.synchronize()
        dt = time.perf_counter() - t0
        if dt >= min_s and pynvml.nvmlDeviceGetPerformanceState(_H) == 0:
            break
        if dt > timeout_s:
            # Pool cards hold P2 under sustained CUDA load (6-A's warm_to_pstate times out too); every arm
            # of a cell is timed in one shuffled replay loop, so the A/B is same-clock; pstate is logged.
            print(f"# warm: NO P0 after {dt:.0f}s", flush=True)
            break
    print(f"# warm: {dt:.1f}s {pstate()}", flush=True)


BAND = set(range(33, 49))
JOBS = []  # (inner, attr, ceiling, cands)
_orig_race = skr.race_split_k


def race_wrap(entries, **kw):
    entries = list(entries)
    JOBS.clear()  # one cell per call; the previous cell's weights are freed
    for j in skr.split_jobs(entries).values():
        if j.ceiling == 48:
            for inner, attr in j.sites:
                JOBS.append((inner, attr, j.ceiling, j.cands, j.shape))
            print(f"# t48 job {j.tag}", flush=True)
    return _orig_race(entries, **kw)


skr.race_split_k = race_wrap
_orig_arms = R._cell_arms


def arms(ag, ext, w):
    fns = _orig_arms(ag, ext, w)
    if w.m not in BAND or w.i8_call is None:
        return fns
    x = torch.randn(w.m, w.k, dtype=torch.float16, device=w.dev) * 0.5
    y = torch.empty(w.m, w.n, dtype=torch.float16, device=w.dev)
    for inner, attr, ceil, cands, own in JOBS:
        plan = getattr(inner, attr)
        pick = (int(plan.shape_id), int(plan.split_k[0]))
        # every tile also at S=1 (data-parallel), so a tile is compared at equal split too
        extra = tuple((sid, 1) for sid in sorted({c[0] for c in cands}) if (sid, 1) not in cands)
        for c in cands + extra:
            def f(w=w, c=c, plan=plan, pick=pick, ceil=ceil):
                skr._set_arm(plan, c, ceil)
                for t in w.trs:
                    w.i8_call(x, t, y, w.suh, w.svh, plan, w.mcg, w.mul1, w.n)
                skr._set_arm(plan, pick, ceil)
            fns[f"f_t{c[0]}s{c[1]}"] = f
        # bit identity between arms on the same input (eager, outside the timing)
        outs = {}
        for c in cands + extra:
            skr._set_arm(plan, c, ceil)
            yo = torch.empty_like(y)
            w.i8_call(x, w.trs[0], yo, w.suh, w.svh, plan, w.mcg, w.mul1, w.n)
            outs[c] = yo
        skr._set_arm(plan, pick, ceil)
        ref = outs[cands[0]].float()
        mod = ik.int8_kernel_module()
        res = {}
        for sid in sorted({c[0] for c in cands}):
            for sk in (0, 1):
                try:
                    res[f"t{sid}{'sk' if sk else 'dp'}"] = list(mod.shape_probe(int(sid), int(w.bits), 2, int(plan.cb), sk=sk))
                except Exception as exc:  # noqa: BLE001
                    res[f"t{sid}{'sk' if sk else 'dp'}"] = str(exc)[:60]
        print(f"#   probe {w.k}x{w.n} K{w.bits} cb{plan.cb}: {res}", flush=True)
        firsts = {}
        for c, o in outs.items():
            firsts.setdefault(c[1], (c, o))
        print(f"#   same-S {w.k}x{w.n} M={w.m}: " + " ".join(
            f"t{c[0]}s{c[1]}{'==' if torch.equal(o, firsts[c[1]][1]) else '!='}t{firsts[c[1]][0][0]}s{c[1]}"
            for c, o in outs.items() if firsts[c[1]][0] != c), flush=True)
        print(f"#   bits {w.k}x{w.n} M={w.m}: " + " ".join(
            f"t{c[0]}s{c[1]}:{'=' if torch.equal(o, outs[cands[0]]) else ''}"
            f"{(o.float() - ref).abs().max().item():.1e}" for c, o in outs.items()), flush=True)
    return fns


R._cell_arms = arms
_orig_cells = R.race_cells


def cells(args, ag, ext, race):
    _orig_print = R._print

    def pr(geom, bits, m, w_bytes, t):
        _orig_print(geom, bits, m, w_bytes, t)
        if m in BAND:
            print(f"#   pstate {geom} M={m}: {pstate()}", flush=True)

    R._print = pr
    return _orig_cells(args, ag, ext, race)


R.race_cells = cells
warm_p0()
R.main()
print(f"# end {pstate()}", flush=True)
