"""GPU cost of the int8 grid-fidelity check at bind, as the pin runs it: every linear shape of a pack (from the sweep),
a random trellis of that shape (decode cost does not depend on the words), all resident, then ONE call of
int8_grid_fidelity_refusals over them (one host sync). Prints one JSON line: seconds, linears, card."""
import json, sys, time, torch
from types import SimpleNamespace
from arbi_serve.weight_quant.exl3.gemv_route import arbi_gemv_ext
from arbi_serve.weight_quant.exl3.int8_grid_fidelity import int8_grid_fidelity_refusals
recs = [json.loads(l) for l in open(sys.argv[1]) if sys.argv[2] in l]
recs = [r for r in recs if r["pack"] == sys.argv[2] and "int8_round_rel_rms" in r]
arbi_gemv_ext(); dev = torch.device("cuda")
items = []
for r in recs:
    k, n = r["shape"]; b = r["bits"]
    tr = torch.randint(-32768, 32767, (k // 16, n // 16, 16 * b), dtype=torch.int16, device=dev)
    items.append((SimpleNamespace(trellis=tr, mcg=r["cb"] == 1, mul1=r["cb"] == 2), b, 0.02707))
int8_grid_fidelity_refusals(items[:1]); torch.cuda.synchronize()
t = time.perf_counter(); int8_grid_fidelity_refusals(items); torch.cuda.synchronize(); dt = time.perf_counter() - t
print(json.dumps({"pack": sys.argv[2], "linears": len(recs), "seconds": round(dt, 3), "path": "fused+one-sync", "card": torch.cuda.get_device_name()}))
