"""The boot route race (gemv_route_race.race_cell + gemv_route_decide.decide) on a pack's real cells, with and without
the L2 sweep before each sample, alternated, several races each: the decision per row count under each protocol, how
often it repeats, and what one race costs. No int8 arm (it needs a boot's plans): GEMV arms against the pinned GEMM."""
import argparse, collections, json, os, pathlib, statistics, sys, time
from types import SimpleNamespace
sys.path.insert(0, os.getcwd())
import torch
import arbi_serve._prebake_loader  # noqa
from arbi_serve.weight_quant.exl3 import custom_op as co
from arbi_serve.weight_quant.exl3 import gemv_route_race as rr
from arbi_serve.weight_quant.exl3.gemv_route_decide import decide
from arbi_serve.weight_quant.gemv.kernel import load_gemv_kernel
from tools.exl3_pack_census import census
from tools.exl3_gemv_mma_race import _bind
ap = argparse.ArgumentParser()
ap.add_argument("--model", type=pathlib.Path, required=True)
ap.add_argument("--cells", nargs="*", default=None)
ap.add_argument("--rows", type=int, nargs="+", default=[1, 2, 4, 8])
ap.add_argument("--races", type=int, default=3)
ap.add_argument("--json-out")
a = ap.parse_args()
dev = "cuda:0"; props = torch.cuda.get_device_properties(dev); l2 = props.L2_cache_size
ag = load_gemv_kernel(); ag.set_pipeline(True, True)
real_sweep = rr._l2_sweep
print(f"# {props.name} ({props.multi_processor_count} SMs) chains={co._PIN_MIN_RACES} reps={co._PIN_TIMING_REPS} cold=3 L2s sweep={rr.SWEEP_BYTES >> 20} MiB")
out = []
for c in census(a.model):
    key = f"{c.in_f}x{c.out_f}"
    if a.cells and key not in a.cells: continue
    b, inner = _bind(c, dev, max(a.rows))
    ext = co._exllamav3_ext()
    job = rr.CellJob(c.bits, c.cb, c.in_f, c.out_f, [inner])
    s = rr.RaceSettings(chains=int(co._PIN_MIN_RACES), reps=int(co._PIN_TIMING_REPS), cold_bytes=3 * l2)
    res = {"old": [], "swept": []}; wall = {"old": [], "swept": []}
    for i in range(a.races):
        for mode in ("old", "swept"):
            rr._l2_sweep = real_sweep if mode == "swept" else (lambda: (lambda: None))
            ctx = SimpleNamespace(ag=ag, ext=ext, ours=True, up=True, mma=True, i8_call=None, i8_attr=lambda _i, _m: None, progress=None)
            torch.cuda.synchronize(); t0 = time.perf_counter()
            times, refused = rr.race_cell(job, list(a.rows), ctx, s)
            torch.cuda.synchronize(); wall[mode].append(time.perf_counter() - t0)
            by_row, receipt = decide(times, {})
            res[mode].append((by_row, receipt))
    print(f"## {key} K{c.bits} cb{c.cb}: one race old {statistics.median(wall['old']):.2f} s, swept {statistics.median(wall['swept']):.2f} s", flush=True)
    for m in a.rows:
        line = f"  M={m}"
        rec = {"cell": key, "bits": c.bits, "rows": m, "wall_s": {k: round(statistics.median(v), 3) for k, v in wall.items()}}
        for mode in ("old", "swept"):
            picks = [r[0][m] for r in res[mode]]
            med = collections.defaultdict(list)
            for r in res[mode]:
                for arm, us in r[1][m]["median_us"].items(): med[arm].append(us)
            rec[mode] = {"picks": picks, "us": {k: v for k, v in med.items()}}
            line += f" | {mode}: picks {picks} " + " ".join(f"{k}={min(v):.1f}-{max(v):.1f}" for k, v in sorted(med.items()))
        out.append(rec); print(line, flush=True)
    del b, inner, job; torch.cuda.empty_cache()
if a.json_out:
    with open(a.json_out, "w") as f:
        for r in out: f.write(json.dumps(r) + "\n")
