"""The route race tool with one change: per-replay times are also grouped by the arm replayed
just before, and printed for each arm. Args pass to the race."""
import argparse, collections, os, random, statistics, sys
sys.path.insert(0, os.getcwd())
os.environ["I8_SERVED_BUILD"] = "1"
import arbi_serve._prebake_loader  # noqa
from arbi_serve.weight_quant.exl3 import int8_kernel as ik
from arbi_serve.weight_quant.exl3 import int8_served_set as ss
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))
import torch
from tools import exl3_gemv_mma_race as R
orig = R._graph_timer
def timer(reps):
    inner = orig(1)
    cap = inner.__closure__  # reuse capture through a one-rep race is awkward; re-implement
    def capture(fn):
        s = torch.cuda.Stream(); s.wait_stream(torch.cuda.current_stream())
        with torch.cuda.stream(s): fn(); fn()
        torch.cuda.current_stream().wait_stream(s); torch.cuda.synchronize()
        g = torch.cuda.CUDAGraph()
        with torch.cuda.graph(g): fn()
        g.replay(); torch.cuda.synchronize(); return g
    def race(fns, calls):
        graphs, refused = {}, {}
        for k, fn in fns.items():
            try: graphs[k] = capture(fn)
            except Exception as exc:  # noqa
                torch.cuda.synchronize(); refused[k] = str(exc).splitlines()[0][:160]
        ts = {k: [] for k in graphs}; by = collections.defaultdict(list); prev = None
        for _ in range(reps):
            order = list(graphs); random.shuffle(order)
            for k in order:
                a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
                a.record(); graphs[k].replay(); b.record(); b.synchronize()
                t = a.elapsed_time(b) * 1e3 / calls; ts[k].append(t)
                if prev: by[(k, prev)].append(t)
                prev = k
        for k in graphs:
            if k in os.environ.get("SR_SHOW", "mma,up_gemv,i8,served").split(","):
                print(f"   {k:8s} " + " ".join(f"<{p}:{statistics.median(by[(k, p)]):.1f}" for p in graphs if by.get((k, p))), flush=True)
        return {k: statistics.median(v) for k, v in ts.items()}, refused
    return race
R._graph_timer = timer
R.main()
