"""Tail probe: the race tool's cells with the int8 leg's 1..16-row verify band plan replaced by a stream-K plan
(the verify table's own non-data-parallel window, int8_verify_table._window_plan) on the band's own tile, so the
136-tile wave tail is spread over every resident slot. TAIL=dp keeps the shipped data-parallel plan (control).
Served int8 build selected as in sr_race.py. Args pass to the race tool."""
import argparse, os, 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))
from tools import exl3_gemv_mma_race as R
mode = os.environ.get("TAIL", "dp")
_orig = R._bind
def bind(cell, dev, rows_max):
    b, inner = _orig(cell, dev, rows_max)
    if mode == "dp":
        return b, inner
    import torch
    from arbi_serve.weight_quant.exl3 import custom_op as co
    from arbi_serve.weight_quant.exl3 import int8_verify_table as vt
    co._ensure_int8_band_tables()
    attr = co._INT8_VERIFY_BAND_SELECT[0][1]
    old = getattr(inner, attr)
    sms = torch.cuda.get_device_properties(dev).multi_processor_count
    module = ik.int8_kernel_module()
    plan, why = vt._window_plan(module, old, vt.VerifyWindow(1, co._INT8_VERIFY_BAND_SELECT[0][0], old.shape_id, False, 0),
                                sm_count=sms, bits=cell.bits, dims=(cell.in_f, cell.out_f))
    print(f"# tail probe {cell.in_f}x{cell.out_f}: band<= {co._INT8_VERIFY_BAND_SELECT[0][0]} shape {old.shape_id} split {old.split_k} -> stream-K",
          "REFUSED " + str(why) if plan is None else f"blocks/SM {plan.sk_blocks_per_sm}", flush=True)
    if plan is not None:
        setattr(inner, attr, plan)
        co.reserve_int8_scratch(dev)
    return b, inner
R._bind = bind
print("build:", ik._extension_name(), "TAIL", mode, flush=True)
R.main()
