"""The boot race's own race_cell + decide (gemv_route_race / gemv_route_decide, the engine's settings) on a
pack's real weights, per cell at rows 1-8, MMA seeded as incumbent, int8 not armed: which rows the decision
gives ``mma_pre``, and the race's wall time with the arm and without it (PRESTAGE_MIN_BYTES raised past
every cell); the arm races at its probe row first and leaves a cell where it is slower there. Also bitwise: the forced-prestage launch against the default one, per (cell, rows, precision)."""
import json, os, pathlib, sys, time
sys.path.insert(0, os.getcwd())
from types import SimpleNamespace
import torch
import arbi_serve._prebake_loader  # noqa
from arbi_serve.weight_quant.exl3 import gemv_route_race as R
from arbi_serve.weight_quant.exl3.gemv_route_decide import ARM_MMA, decide
from arbi_serve.weight_quant.exl3.gemv_route import arbi_gemv_ext
from arbi_serve.weight_quant.exl3.custom_op import _exllamav3_ext, _PIN_MIN_RACES, _PIN_TIMING_REPS
from arbi_serve.weight_quant.exl3.shim import load_ext
from arbi_serve.weight_quant.exl3.weight import Exl3Weight
from tools.exl3_pack_census import census, load_one, load_seeds
model = pathlib.Path(sys.argv[1]); out_path = sys.argv[2]
dev = "cuda:0"; load_ext(); ag = arbi_gemv_ext(); ag.set_pipeline(True, True); ext = _exllamav3_ext()
props = torch.cuda.get_device_properties(dev)
s = R.RaceSettings(chains=int(_PIN_MIN_RACES), reps=int(_PIN_TIMING_REPS), cold_bytes=3 * props.L2_cache_size)
rows = list(range(1, 9))
recs = []
for c in census(model):
    if "experts." in c.example: continue
    # bound and pin-resolved exactly as the race tool binds a cell (kernel-shape and int8 pins), so the
    # pinned-GEMM arm times the served launch at every row
    from tools.exl3_gemv_mma_race import _bind
    b, inner = _bind(c, dev, max(rows))
    job = R.CellJob(c.bits, c.cb, c.in_f, c.out_f, [inner])
    ctx = SimpleNamespace(ag=ag, ext=ext, ours=True, up=True, mma=True, i8_call=None, i8_attr=lambda _i, _m: None, progress=None)
    # bitwise: forced prologue against the default schedule, both precisions, rows 1-8
    g = torch.Generator(device=dev).manual_seed(c.in_f * 31 + c.out_f)
    x = torch.randn(8, c.in_f, generator=g, device=dev, dtype=torch.float16) * 0.5
    same = all(torch.equal(ag.gemv_exl3_mma(x[:m].contiguous(), b["trellis"], b["suh"], b["svh"], c.bits, c.cb, c.in_f, c.out_f, m, torch.float16, 0, p),
                           ag.gemv_exl3_mma(x[:m].contiguous(), b["trellis"], b["suh"], b["svh"], c.bits, c.cb, c.in_f, c.out_f, m, torch.float16, 0, p, prestage=1))
               for m in rows for p in (1, 3))
    t0 = time.perf_counter(); times, refused = R.race_cell(job, rows, ctx, s); t_with = time.perf_counter() - t0
    keep = R.PRESTAGE_MIN_BYTES; R.PRESTAGE_MIN_BYTES = 1 << 62
    t0 = time.perf_counter(); R.race_cell(job, rows, ctx, s); t_without = time.perf_counter() - t0
    R.PRESTAGE_MIN_BYTES = keep
    by_row, receipt = decide(times, dict.fromkeys(rows, ARM_MMA))
    pre = [m for m in rows if by_row.get(m) == "mma_pre"]
    raced_pre = any("mma_pre" in times.get(m, {}) for m in rows)
    rec = {"card": props.name, "sms": props.multi_processor_count, "cell": f"{c.in_f}x{c.out_f}", "bits": c.bits, "w_bytes": int(b["trellis"].numel()) * 2,
           "prestage_raced": raced_pre, "decision": {m: by_row.get(m) for m in rows}, "mma_pre_rows": pre, "bitwise_forced_vs_default": same,
           "race_s_with": round(t_with, 2), "race_s_without": round(t_without, 2), "refused": refused,
           "median_us": {m: receipt[m]["median_us"] for m in rows if m in receipt}}
    recs.append(rec)
    print(f'{rec["cell"]:12s} K{c.bits} raced={raced_pre!s:5s} bitwise={same} pre_rows={pre} decision={"".join(str(by_row.get(m))[:1] if by_row.get(m)!="mma_pre" else "p" for m in rows)} race {t_without:.2f}s -> {t_with:.2f}s', flush=True)
    del b, inner, job; torch.cuda.empty_cache()
open(out_path, "w").write("\n".join(json.dumps(r) for r in recs) + "\n")
