"""Per-linear int8-grid fidelity sweep: every EXL3 linear (``*.trellis`` + suh/svh) of the packs given, decoded by the
exllamav3 / our reconstruct in its rotated basis, reporting decoded std, kurtosis, and the relative rms of rounding the
decoded weights to the int8 leg's fixed per-codebook grid (``w_scale``), one JSON record per linear."""
import argparse, json, os, struct, 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=["4:mul1+6:mcg+6:mul1"], exl3_checkpoint=None, gguf=["Q8_KS:none"], gguf_manifest=None))
import pathlib, torch
from arbi_serve.weight_quant.exl3 import custom_op as co, shim
from arbi_serve.weight_quant.exl3 import int8_kernel as ik
from arbi_serve.weight_quant.exl3.int8_kernel import codebook_for
from arbi_serve.weight_quant.exl3.gemv_route import arbi_gemv_ext
from tools.exl3_pack_census import load_one
dev = "cuda:0"; shim.load_ext(); ext = co._exllamav3_ext(); ag = arbi_gemv_ext()
mod = ik.load_int8_kernel()
out = open(sys.argv[1], "w")
for pack in sys.argv[2:]:
    root = pathlib.Path(pack); t0 = time.time(); n = 0
    for shard in sorted(root.glob("*.safetensors")):
        with open(shard, "rb") as f:
            hdr = json.loads(f.read(struct.unpack("<Q", f.read(8))[0]))
        for key in sorted(k for k in hdr if k.endswith(".trellis")):
            prefix = key[: -len(".trellis")]
            try:
                b = load_one(shard, prefix, dev)
                tr = b["trellis"]; k, nn, bits = tr.shape[0] * 16, tr.shape[1] * 16, tr.shape[2] // 16
                w = torch.empty(k, nn, dtype=torch.float16, device=dev)
                if hasattr(ag, "exl3_reconstruct"): ag.exl3_reconstruct(w, tr, float(bits), bool(b["mcg"]), bool(b["mul1"]), 0)
                else: ext.reconstruct(w, tr, int(bits), bool(b["mcg"]), bool(b["mul1"]))
                wf = w.float(); cb = codebook_for(mcg=bool(b["mcg"]), mul1=bool(b["mul1"])); sc = float(mod.w_scale(cb))
                q = torch.clamp(torch.round(wf / sc), -127, 127) * sc
                rel = float((q - wf).pow(2).mean().sqrt() / wf.pow(2).mean().sqrt())
                z = (wf - wf.mean()) / wf.std()
                rec = {"pack": root.name, "linear": prefix, "shape": [k, nn], "bits": bits, "cb": cb, "std": round(float(wf.std()), 4),
                       "kurtosis": round(float((z ** 4).mean()), 2), "max_abs": round(float(wf.abs().max()), 3), "int8_round_rel_rms": float(f"{rel:.3e}")}
            except Exception as e:  # noqa: BLE001
                rec = {"pack": root.name, "linear": prefix, "error": f"{type(e).__name__}: {str(e)[:120]}"}
            out.write(json.dumps(rec) + "\n"); n += 1
            del w
    out.flush(); print(f"{root.name}: {n} linears in {time.time()-t0:.0f} s", flush=True)
