"""Flint's logits head, one slice against two (the cut PR #5090's plan rule makes), on the pack's real
head weights: how the logits and the served-sampler distribution move, and each cut's error against a
float64 reference. Activations: the pack's own embedding rows through the final RMSNorm (LM-shaped
logits), and Gaussian rows. Kernel-level only: no engine, no context, one decode row per position."""
import argparse, hashlib, json, os, pathlib, sys
sys.path.insert(0, os.getcwd())
import torch
import arbi_serve._prebake_loader  # noqa
from safetensors import safe_open
from arbi_serve.weight_quant.exl3.gemv_route import arbi_gemv_ext
from arbi_serve.weight_quant.exl3.shim import load_ext
from arbi_serve.weight_quant.exl3.weight import Exl3Weight
from tests._exl3_upstream import upstream_linear
from tools.exl3_pack_census import census, load_one, load_seeds
ap = argparse.ArgumentParser()
ap.add_argument("--model", type=pathlib.Path, required=True)
ap.add_argument("--rows", type=int, default=2048)
ap.add_argument("--json-out", required=True)
a = ap.parse_args()
dev = "cuda:0"
ag = arbi_gemv_ext(); load_ext()
cell = max(census(a.model), key=lambda c: c.out_f)
K, N = cell.in_f, cell.out_f
b = load_one(cell.shard, cell.example, dev)
inner = Exl3Weight.bind(in_features=K, out_features=N, trellis=b["trellis"], suh=b["suh"], svh=b["svh"], **load_seeds(cell.shard, cell.example, dev))
W = upstream_linear(inner).get_inner_weight_tensor().double()
def had(x):
    h = torch.ones(1, 1, dtype=torch.float64, device=x.device)
    while h.shape[0] < 128: h = torch.cat([torch.cat([h, h], 1), torch.cat([h, -h], 1)], 0)
    h = h / 128**0.5
    sh = x.shape
    return (x.reshape(*sh[:-1], sh[-1] // 128, 128) @ h).reshape(sh)
def ref(x): return had(had(x.double() * b["suh"].double()) @ W) * b["svh"].double()
def run(x, splits, dt):
    return ag.gemv_exl3_mma(x, b["trellis"], b["suh"], b["svh"], cell.bits, cell.cb, K, N, x.shape[0], dt, splits, 1)
assert ag.gemv_exl3_mma_plan(K, N, 1) == (K, 1) and ag.gemv_exl3_mma_plan(K, N, 2) == (K // 2, 2)
# activations
g = torch.Generator(device=dev).manual_seed(20261112)
emb = norm = None
for p in sorted(a.model.glob("*.safetensors")):
    with safe_open(str(p), framework="pt", device=dev) as f:
        if "model.embed_tokens.weight" in f.keys(): emb = f.get_tensor("model.embed_tokens.weight")
        if "model.norm.weight" in f.keys(): norm = f.get_tensor("model.norm.weight")
idx = torch.randperm(emb.shape[0], generator=g, device=dev)[: a.rows]
e = emb[idx].float()
x_emb = (e * torch.rsqrt(e.pow(2).mean(-1, keepdim=True) + 1e-6) * norm.float()).half()
x_gau = (torch.randn(a.rows, K, generator=g, device=dev) * x_emb.float().std()).half()
del emb
def sampler(logits):  # served sampler support: T 1.0, top-k 20, top-p 0.95
    p = torch.softmax(logits.double(), -1)
    v, i = p.topk(20, -1)
    keep = (v.cumsum(-1) - v) < 0.95
    v = v * keep
    return i, v / v.sum(-1, keepdim=True)
def stats(name, x, dt):
    out = {"activations": name, "out_dtype": str(dt).split(".")[-1], "rows": int(x.shape[0])}
    tot = dict(n=0, differ=0, flips=0, kl=0.0, tvd=0.0, se1=0.0, se2=0.0, sr=0.0, maxd=0.0, flips1=0, flips2=0)
    for s in range(0, x.shape[0], 64):
        xb = x[s : s + 64].contiguous()
        y1, y2 = run(xb, 1, dt), run(xb, 2, dt)
        r = ref(xb)
        d = (y1.double() - y2.double()).abs()
        tot["n"] += d.numel(); tot["differ"] += int((d > 0).sum()); tot["maxd"] = max(tot["maxd"], float(d.max()))
        tot["se1"] += float((y1.double() - r).pow(2).sum()); tot["se2"] += float((y2.double() - r).pow(2).sum()); tot["sr"] += float(r.pow(2).sum())
        a1, a2, ar = y1.argmax(-1), y2.argmax(-1), r.argmax(-1)
        tot["flips"] += int((a1 != a2).sum()); tot["flips1"] += int((a1 != ar).sum()); tot["flips2"] += int((a2 != ar).sum())
        i1, p1 = sampler(y1)
        q = torch.softmax(y2.double(), -1).gather(-1, i1) * (p1 > 0)
        q = q / q.sum(-1, keepdim=True)
        m = p1 > 0
        tot["kl"] += float((p1[m] * (p1[m] / q[m]).log()).sum()); tot["tvd"] += float(0.5 * (p1 - q).abs().sum())
    R = x.shape[0]
    out.update(logits=tot["n"], logits_differing=tot["differ"], frac_differing=tot["differ"] / tot["n"], max_abs_logit_diff=tot["maxd"],
               rel_rms_err_one_slice=(tot["se1"] / tot["sr"]) ** 0.5, rel_rms_err_two_slices=(tot["se2"] / tot["sr"]) ** 0.5,
               argmax_flips_one_vs_two=tot["flips"], argmax_flips_one_vs_fp64=tot["flips1"], argmax_flips_two_vs_fp64=tot["flips2"],
               kl_served_sampler_mean=tot["kl"] / R, tvd_served_sampler_mean=tot["tvd"] / R)
    return out
res = [stats(n, x, dt) for n, x in (("embedding rows through the final norm", x_emb), ("gaussian", x_gau)) for dt in (torch.float16, torch.float32)]
# the forced two-slice launch is the cut the plan rule makes: its hash under sr_bits' input must equal the built branch's
gg = torch.Generator(device=dev).manual_seed(K * 31 + N)
xs = torch.randn(64, K, generator=gg, device=dev, dtype=torch.float16) * 0.5
sha = lambda t: hashlib.sha256(t.detach().cpu().numpy().tobytes()).hexdigest()[:16]
res.append({"sr_bits_hash_M1_p1": {"one_slice": sha(run(xs[:1].contiguous(), 1, torch.float16)), "two_slices": sha(run(xs[:1].contiguous(), 2, torch.float16))}})
with open(a.json_out, "w") as f:
    for r in res: f.write(json.dumps(r) + "\n")
for r in res: print(json.dumps(r))
