"""The boot route race (race_cell + decide) on a pack's cells with the upstream arms timed (main) and not timed at the
listed rows (EXL3_NO_UPSTREAM_CELL_ROWS), alternated, several races each: picks per row under each, and one race's wall time.
No int8 arm (it needs a boot's plans): GEMV arms, and on the main side the pinned GEMM and upstream's GEMV."""
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 import gemv_route_decide as rd
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("--rows", type=int, nargs="+", default=[1, 2, 4, 8, 16])
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)
listed = rd.EXL3_NO_UPSTREAM_CELL_ROWS; real = rr.upstream_raced
print(f"# {props.name} ({props.multi_processor_count} SMs) chains={co._PIN_MIN_RACES} reps={co._PIN_TIMING_REPS} cold=3 L2s")
out = []; tot = {"main": 0.0, "listed": 0.0}
for c in census(a.model):
    key = (c.bits, c.cb, c.in_f, c.out_f)
    if "experts." in c.example: continue
    try: b, inner = _bind(c, dev, max(a.rows))
    except Exception as e: print("skip", key, str(e)[:80]); continue
    ext = co._exllamav3_ext()
    job = rr.CellJob(*key, [inner])
    s = rr.RaceSettings(chains=int(co._PIN_MIN_RACES), reps=int(co._PIN_TIMING_REPS), cold_bytes=3 * l2)
    res = {"main": [], "listed": []}; wall = {"main": [], "listed": []}
    for i in range(a.races):
        for mode in ("main", "listed"):
            rr.upstream_raced = (lambda k, m: True) if mode == "main" else real
            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 = rd.decide(times, {}, no_upstream_rows=frozenset() if mode == "main" else listed.get(key, frozenset()))
            res[mode].append((by_row, receipt))
    for k in tot: tot[k] += statistics.median(wall[k])
    print(f"## {c.in_f}x{c.out_f} K{c.bits} cb{c.cb} listed={key in listed}: one race main {statistics.median(wall['main']):.2f} s, listed {statistics.median(wall['listed']):.2f} s", flush=True)
    for m in a.rows:
        rec = {"cell": f"{c.in_f}x{c.out_f}", "bits": c.bits, "rows": m}; line = f"  M={m}"
        for mode in ("main", "listed"):
            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": dict(med)}
            line += f" | {mode}: {picks} " + " ".join(f"{k}={min(v):.1f}-{max(v):.1f}" for k, v in sorted(med.items()))
        rec["wall_s"] = {k: round(statistics.median(v), 3) for k, v in wall.items()}
        out.append(rec); print(line, flush=True)
    del b, inner, job; torch.cuda.empty_cache()
print(f"# pack total, one race per cell: main {tot['main']:.2f} s, listed {tot['listed']:.2f} s")
if a.json_out:
    with open(a.json_out, "w") as f:
        for r in out: f.write(json.dumps(r) + "\n")
