"""Flint head in the boot race's own race_cell with 1 instance (boot) and 2 instances (the offline tool's copies)."""
import os, sys, pathlib
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.gemv.kernel import load_gemv_kernel
from tools.exl3_pack_census import census
from tools.exl3_gemv_mma_race import _bind
ag = load_gemv_kernel(); ag.set_pipeline(True, True)
l2 = torch.cuda.get_device_properties(0).L2_cache_size
real = rr._instance_count
for c in census(pathlib.Path(sys.argv[1])):
    if c.out_f != int(sys.argv[2]): continue
    b, inner = _bind(c, "cuda:0", 16); ext = co._exllamav3_ext()
    job = rr.CellJob(c.bits, c.cb, c.in_f, c.out_f, [inner])
    s = rr.RaceSettings(chains=3, reps=12, cold_bytes=3 * l2)
    for rep in range(2):
        for n in (1, 2, 3):
            rr._instance_count = (lambda w, s_, n=n: n)
            ctx = SimpleNamespace(ag=ag, ext=ext, ours=True, up=True, mma=True, i8_call=None, i8_attr=lambda _i, _m: None, progress=None)
            times, refused = rr.race_cell(job, [4, 8, 16], ctx, s)
            print(f"instances={n}", {m: {a: round(min(v), 1) for a, v in t.items()} for m, t in times.items()}, flush=True)
