# ruff: noqa
# Small-row analysis scratch, kept as run (docs/receipts/exl3-mma-reduce-loads-2026-11-11.md).
"""Output hashes of the MMA arm (single and grouped) on a pack's real weights, per (cell, rows).
Run once per tree; equal hashes across trees are bitwise-equal kernels."""
import argparse, hashlib, json, os, pathlib, sys
sys.path.insert(0, os.getcwd())
import torch
import arbi_serve._prebake_loader  # noqa
from arbi_serve.weight_quant.exl3.gemv_route import arbi_gemv_ext
from tools.exl3_pack_census import census, load_one
from tools.exl3_gemv_mma_race import GROUP_ROLES
ap = argparse.ArgumentParser()
ap.add_argument("--model", type=pathlib.Path, required=True)
ap.add_argument("--rows", type=int, nargs="+", default=[1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 16, 17, 24, 32, 33, 48, 64])
ap.add_argument("--json-out", required=True)
a = ap.parse_args()
ag = arbi_gemv_ext()
dev = "cuda:0"
def sha(t): return hashlib.sha256(t.detach().cpu().numpy().tobytes()).hexdigest()[:16]
out = {}
cells = census(a.model)
for c in cells:
    b = load_one(c.shard, c.example, dev)
    g = torch.Generator(device=dev).manual_seed(c.in_f * 31 + c.out_f)
    x = torch.randn(max(a.rows), c.in_f, generator=g, device=dev, dtype=torch.float16) * 0.5
    for m in a.rows:
        for prec in (1, 3):
            y = ag.gemv_exl3_mma(x[:m].contiguous(), b["trellis"], b["suh"], b["svh"], c.bits, c.cb, c.in_f, c.out_f, m, torch.float16, 0, prec)
            out[f"{c.in_f}x{c.out_f}/K{c.bits}cb{c.cb}/M{m}/p{prec}"] = sha(y)
    del b; torch.cuda.empty_cache()
seen = set()
for c in cells:
    if "." not in c.example: continue
    prefix, role = c.example.rsplit(".", 1)
    for roles in GROUP_ROLES:
        if role != roles[0] or "experts." in c.example: continue
        try: mem = [load_one(c.shard, f"{prefix}.{r}", dev) for r in roles]
        except Exception: continue
        widths = [int(m_["trellis"].shape[1]) * 16 for m_ in mem]
        key = (c.bits, c.cb, c.in_f, tuple(widths))
        if key in seen: continue
        seen.add(key)
        g = torch.Generator(device=dev).manual_seed(c.in_f * 7 + sum(widths))
        x = torch.randn(max(a.rows), c.in_f, generator=g, device=dev, dtype=torch.float16) * 0.5
        for m in a.rows:
            ys = ag.gemv_exl3_mma_group(x[:m].contiguous(), [m_["trellis"] for m_ in mem], [m_["suh"] for m_ in mem], [m_["svh"] for m_ in mem], widths, c.bits, c.cb, c.in_f, m, torch.float16, 0, 1, True)
            out[f"{c.in_f}x{'+'.join(map(str, widths))}/K{c.bits}cb{c.cb}/M{m}/group"] = "|".join(sha(y) for y in ys)
        del mem; torch.cuda.empty_cache()
json.dump(out, open(a.json_out, "w"), indent=0)
print(len(out), "hashes")
