"""Qwen3.8-27B gate|up group: one 5120-deep slice (the plan on 48/64/80-SM cards) against five slices of 1024 (the
cut the plan rule makes there, and the cut a 128-SM card already takes), on the pack's real weights. Kernel-level:
(1) each member's error against a float64 reference, per sampled layer; (2) the last layer's MLP output (down in float64
on each cut's gate|up) added to the residual, final norm, the served head -> logits: argmax flips and KL/TVD under the
served sampler (T 1.0, top-k 20, top-p 0.95). Activations: the pack's own embedding rows (LM-shaped), and Gaussian rows."""
import argparse, hashlib, json, pathlib, sys, os
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=1024)
ap.add_argument("--layers", type=int, nargs="*", default=[0, 21, 42, 63])
ap.add_argument("--json-out", required=True)
a = ap.parse_args()
dev = "cuda:0"; ag = arbi_gemv_ext(); load_ext()
P = "model.language_model"
cells = census(a.model)
gate_cell = next(c for c in cells if c.example.endswith("mlp.gate_proj"))
shard = gate_cell.shard
def tensors(names):
    out = {}
    for p in sorted(a.model.glob("*.safetensors")):
        with safe_open(str(p), framework="pt", device=dev) as f:
            for n in names:
                if n in f.keys(): out[n] = f.get_tensor(n)
    return out
def shard_of(example):
    idx = json.load(open(a.model / "model.safetensors.index.json"))["weight_map"]
    return a.model / idx[example + ".trellis"]
def lin(example):
    sh = shard_of(example); b = load_one(sh, example, dev)
    K, N = b["suh"].numel(), b["svh"].numel()
    inner = Exl3Weight.bind(in_features=K, out_features=N, trellis=b["trellis"], suh=b["suh"], svh=b["svh"], **load_seeds(sh, example, dev))
    return b, K, N, inner
H = None
def had(x):
    global H
    if H is None:
        h = torch.ones(1, 1, dtype=torch.float64, device=dev)
        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_fn(b, inner):
    W = upstream_linear(inner).get_inner_weight_tensor().double()
    return lambda x: had(had(x.double() * b["suh"].double()) @ W) * b["svh"].double()
bits, cb = gate_cell.bits, gate_cell.cb
def group(x, mem, widths, K, splits, dt):
    ys = []
    for s in range(0, x.shape[0], 64):
        xb = x[s:s + 64].contiguous()
        ys.append(ag.gemv_exl3_mma_group(xb, [m["trellis"] for m in mem], [m["suh"] for m in mem], [m["svh"] for m in mem], widths, bits, cb, K, xb.shape[0], dt, splits, 1, True))
    return [torch.cat([y[i] for y in ys]) for i in range(len(widths))]
g = torch.Generator(device=dev).manual_seed(20261112)
t = tensors([f"{P}.embed_tokens.weight", f"{P}.norm.weight"] + [f"{P}.layers.{L}.post_attention_layernorm.weight" for L in a.layers])
emb = t[f"{P}.embed_tokens.weight"]
idx = torch.randperm(emb.shape[0], generator=g, device=dev)[: a.rows]
e = emb[idx].float(); del emb
def rmsn(x, w): x = x.float(); return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6) * (1.0 + w.float())
res = []
KN = None
for L in a.layers:
    ex = f"{P}.layers.{L}.mlp"
    (bg, K, Ng, ig), (bu, _, Nu, iu) = lin(f"{ex}.gate_proj"), lin(f"{ex}.up_proj")
    KN = (K, Ng + Nu)
    assert ag.gemv_exl3_mma_plan(K, Ng + Nu, 1) == (K, 1) and ag.gemv_exl3_mma_plan(K, Ng + Nu, 5) == (1024, 5)
    x_emb = rmsn(e, t[f"{P}.layers.{L}.post_attention_layernorm.weight"]).half()
    x_gau = (torch.randn(a.rows, K, generator=g, device=dev) * x_emb.float().std()).half()
    rg, ru = ref_fn(bg, ig), ref_fn(bu, iu)
    for name, x in (("embedding rows through the layer's post-attention norm", x_emb), ("gaussian", x_gau)):
        for dt in (torch.float16, torch.float32):
            y1 = group(x, [bg, bu], [Ng, Nu], K, 1, dt); y5 = group(x, [bg, bu], [Ng, Nu], K, 5, dt)
            rec = {"layer": L, "activations": name, "out_dtype": str(dt).split(".")[-1], "rows": a.rows}
            for i, (role, rf) in enumerate((("gate", rg), ("up", ru))):
                se1 = se5 = sr = 0.0; differ = n = 0; maxd = 0.0
                for s in range(0, a.rows, 128):
                    r = rf(x[s:s + 128]); a1 = y1[i][s:s + 128].double(); a5 = y5[i][s:s + 128].double()
                    se1 += float((a1 - r).pow(2).sum()); se5 += float((a5 - r).pow(2).sum()); sr += float(r.pow(2).sum())
                    d = (a1 - a5).abs(); differ += int((d > 0).sum()); n += d.numel(); maxd = max(maxd, float(d.max()))
                rec[role] = {"rel_rms_err_one_slice": (se1 / sr) ** 0.5, "rel_rms_err_five_slices": (se5 / sr) ** 0.5,
                             "frac_outputs_differing": differ / n, "max_abs_diff": maxd}
            res.append(rec); print(json.dumps(rec), flush=True)
    if L != a.layers[-1]:
        del rg, ru; torch.cuda.empty_cache(); continue
    # the last layer's MLP through the head
    bd, Kd, Nd, idn = lin(f"{ex}.down_proj"); rd = ref_fn(bd, idn)
    hb, hK, hN, _ = lin("lm_head")
    fnorm = t[f"{P}.norm.weight"]
    def logits_of(mlp):
        h = rmsn(e + mlp.float(), fnorm).half()
        out = []
        for s in range(0, a.rows, 64):
            xb = h[s:s + 64].contiguous()
            out.append(ag.gemv_exl3_mma(xb, hb["trellis"], hb["suh"], hb["svh"], head_bits, head_cb, hK, hN, xb.shape[0], torch.float32, 0, 1))
        return torch.cat(out)
    head_cell = max(cells, key=lambda c: c.out_f); head_bits, head_cb = head_cell.bits, head_cell.cb
    x = x_emb
    mlps = {}
    for tag, splits in (("one", 1), ("five", 5)):
        yg, yu = group(x, [bg, bu], [Ng, Nu], K, splits, torch.float16)
        act = torch.nn.functional.silu(yg.double()) * yu.double()
        mlps[tag] = torch.cat([rd(act[s:s + 128].half().double()) for s in range(0, a.rows, 128)])
    act = torch.cat([torch.nn.functional.silu(rg(x[s:s + 128])) * ru(x[s:s + 128]) for s in range(0, a.rows, 128)])
    mlps["fp64"] = torch.cat([rd(act[s:s + 128]) for s in range(0, a.rows, 128)])
    del act
    lg = {k: logits_of(v) for k, v in mlps.items()}
    def sampler(l):
        p = torch.softmax(l.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 kl(lp, lq):
        i, p = sampler(lp); q = torch.softmax(lq.double(), -1).gather(-1, i) * (p > 0); q = q / q.sum(-1, keepdim=True); m = p > 0
        return float((p[m] * (p[m] / q[m]).log()).sum()) / a.rows, float(0.5 * (p - q).abs().sum()) / a.rows
    am = {k: v.argmax(-1) for k, v in lg.items()}
    kl15, tvd15 = kl(lg["one"], lg["five"]); kl1r, _ = kl(lg["fp64"], lg["one"]); kl5r, _ = kl(lg["fp64"], lg["five"])
    rec = {"last_layer_through_head": L, "rows": a.rows, "head": f"{hK}x{hN}",
           "mlp_rel_rms_err_one_slice": float((mlps["one"] - mlps["fp64"]).pow(2).sum() / mlps["fp64"].pow(2).sum()) ** 0.5,
           "mlp_rel_rms_err_five_slices": float((mlps["five"] - mlps["fp64"]).pow(2).sum() / mlps["fp64"].pow(2).sum()) ** 0.5,
           "argmax_flips_one_vs_five": int((am["one"] != am["five"]).sum()), "argmax_flips_one_vs_fp64_mlp": int((am["one"] != am["fp64"]).sum()),
           "argmax_flips_five_vs_fp64_mlp": int((am["five"] != am["fp64"]).sum()),
           "kl_served_sampler_one_to_five_mean": kl15, "tvd_served_sampler_one_to_five_mean": tvd15,
           "kl_served_sampler_fp64mlp_to_one_mean": kl1r, "kl_served_sampler_fp64mlp_to_five_mean": kl5r}
    res.append(rec); print(json.dumps(rec), flush=True)
# the forced five-slice launch is the cut the rule makes: its hash under sr_bits' input must equal the built branch's on 48/64/80 SMs
gg = torch.Generator(device=dev).manual_seed(KN[0] * 7 + KN[1])
xs = torch.randn(64, KN[0], 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_group_hash_M1": {sp: "|".join(sha(y) for y in ag.gemv_exl3_mma_group(xs[:1].contiguous(), [bg["trellis"], bu["trellis"]], [bg["suh"], bu["suh"]], [bg["svh"], bu["svh"]], [Ng, Nu], bits, cb, KN[0], 1, torch.float16, sp, 1, True)) for sp in (1, 5)}})
print(json.dumps(res[-1]))
with open(a.json_out, "w") as f:
    for r in res: f.write(json.dumps(r) + "\n")
