"""The split-K race's boot cost and decisions per pack: every dense census cell bound as the race tool binds it
(served int8 build), the boot's split race (int8_split_k_race.race_split_k, the engine's chains/reps/cold set)
over a DFlash K=7 / max_batch 8 deployment's rows (decode 1-8, verify slates 8..64). Nothing cached."""
import argparse, json, os, pathlib, sys, time
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 arbi_serve.engine.exl3_route_race import _i8_plans
from arbi_serve.weight_quant.exl3 import custom_op as co
from arbi_serve.weight_quant.exl3.custom_op import _PIN_MIN_RACES, _PIN_TIMING_REPS
from arbi_serve.weight_quant.exl3.gemv_route_race import RaceSettings
from arbi_serve.weight_quant.exl3 import int8_split_k_race as skr
from tools.exl3_gemv_mma_race import _bind
from tools.exl3_pack_census import census
model = pathlib.Path(sys.argv[1]); out = sys.argv[2]; dev = "cuda:0"
props = torch.cuda.get_device_properties(dev)
s = RaceSettings(chains=int(_PIN_MIN_RACES), reps=int(_PIN_TIMING_REPS), cold_bytes=3 * props.L2_cache_size)
slates = frozenset(b * 8 for b in (1, 2, 3, 4, 5, 6, 7, 8)); rows = sorted(set(range(1, 9)) | slates)
ext = co._exllamav3_ext()
recs, total = [], 0.0
for c in census(model):
    if "experts." in c.example: continue
    b, inner = _bind(c, dev, max(rows))
    call = co.int8_gemm_entry(ext)
    attr_for = _i8_plans(slates, decode_on=True)
    entries = [(inner, attr_for(inner, m), m) for m in rows]
    before = set(skr.DECISIONS)
    t0 = time.perf_counter()
    n = skr.race_split_k(entries, call=call, ext=ext, s=s, inputs={"probe": "splitk_boot"}, keep=False)
    dt = time.perf_counter() - t0; total += dt
    for tag in sorted(set(skr.DECISIONS) - before):
        d = skr.DECISIONS[tag]
        recs.append({"card": props.name, "sms": props.multi_processor_count, "cell": f"{c.in_f}x{c.out_f}", "bits": c.bits, "tag": tag, **d})
        print(f"{c.in_f}x{c.out_f} K{c.bits} {tag}: S={d['slices']} (inc {d.get('incumbent')}) totals={d.get('totals')} refused={d.get('refused')}", flush=True)
    print(f"{c.in_f}x{c.out_f} K{c.bits}: {n} plan(s) raced in {dt:.2f} s", flush=True)
    del b, inner; torch.cuda.empty_cache()
recs.append({"card": props.name, "sms": props.multi_processor_count, "pack": model.name, "split_race_s_total": round(total, 2)})
print(f"TOTAL split race {total:.2f} s for {model.name} on {props.name}", flush=True)
open(out, "w").write("\n".join(json.dumps(r) for r in recs) + "\n")
