#!/usr/bin/env python3 """Perplexity, KL divergence and top-1 agreement of an arm vs the BF16 reference (T1-T4). uv run --with numpy python kld.py --ref bf16.npz --test arm.npz [--vocab 248320] [--json out.json] KLD(P_ref || Q_arm) per position over the ref's top-k ids + one tail bucket: P: ref top-k probs, tail = 1 - sum. Q: the arm's prob for each of those ids if it is in the arm's top-k, else the arm's tail mass spread evenly over the vocab ids outside its top-k; Q tail = 1 - sum(Q over ref top-k). This is exact for the top-k part; the tail bucket coarse-grains the rest. The ref's top-k mass is reported so readers can see how much of the distribution sits in the tail. top-1 agreement compares the argmax ids exactly (both files are sorted by logprob). """ import argparse, json, math import numpy as np ap = argparse.ArgumentParser() ap.add_argument("--ref", required=True); ap.add_argument("--test", required=True) ap.add_argument("--vocab", type=int, default=248320); ap.add_argument("--json") a = ap.parse_args() R, T = np.load(a.ref), np.load(a.test) rm, tm = json.loads(str(R["meta"])), json.loads(str(T["meta"])) assert rm["eval_set_sha256"] == tm["eval_set_sha256"], "arms were scored on different eval sets" res = {"ref": rm["model"], "test": tm["model"], "eval_set_sha256": rm["eval_set_sha256"]} for s in ("ppl-wiki", "ppl-code", "kld"): if f"{s}.target" not in R or f"{s}.target" not in T: continue pr, pt = math.exp(-R[f"{s}.target"].mean()), math.exp(-T[f"{s}.target"].mean()) res[s] = {"ppl_ref": pr, "ppl_test": pt, "ppl_delta_pct": 100 * (pt / pr - 1)} if "kld.ids" in R: rid, rlp = R["kld.ids"].astype(np.int64), R["kld.lp"].astype(np.float64) tid, tlp = T["kld.ids"].astype(np.int64), T["kld.lp"].astype(np.float64) W, P, K = rid.shape rid, rlp, tid, tlp = (x.reshape(W * P, K) for x in (rid, rlp, tid, tlp)) p = np.exp(rlp); p_tail = np.clip(1 - p.sum(1), 1e-12, None) tq = np.exp(tlp); t_tail_each = np.clip(1 - tq.sum(1), 1e-12, None) / (a.vocab - K) # Q for each ref id: look it up in the arm's top-k row q = np.empty_like(p) for j in range(K): hit = tid == rid[:, j:j + 1] found = hit.any(1) q[:, j] = np.where(found, (tq * hit).sum(1), t_tail_each) q = np.clip(q, 1e-12, None); q_tail = np.clip(1 - q.sum(1), 1e-12, None) kl = (p * (np.log(np.clip(p, 1e-12, None)) - np.log(q))).sum(1) + p_tail * (np.log(p_tail) - np.log(q_tail)) kl = np.clip(kl, 0, None) res["kld"].update({"kld_mean": float(kl.mean()), "kld_median": float(np.median(kl)), "kld_p99": float(np.quantile(kl, 0.99)), "kld_max": float(kl.max()), "top1_agree_pct": float(100 * (rid[:, 0] == tid[:, 0]).mean()), "ref_topk_mass_mean": float(p.sum(1).mean()), "positions": int(W * P)}) # Distribution for the report: a histogram over positions on log-spaced edges, 1e-5 .. 100 nats, # 8 bins a decade (values below 1e-5, mostly exact agreement, land in the first bin), and the mean # KLD in 32 position bins, binned like the report's loss-by-position. edges = np.logspace(-5, 2, 57) counts, _ = np.histogram(np.clip(kl, edges[0], edges[-1] * (1 - 1e-12)), bins=edges) klw, pe = kl.reshape(W, P), np.linspace(0, P, 33).astype(int) res["kld"]["hist"] = {"edges": [float(e) for e in edges], "counts": [int(c) for c in counts]} res["kld"]["by_pos"] = [[int(pe[i]), int(pe[i + 1]), float(klw[:, pe[i]:pe[i + 1]].mean())] for i in range(32)] print(json.dumps({k: ({kk: vv for kk, vv in v.items() if kk not in ("hist", "by_pos")} if isinstance(v, dict) else v) for k, v in res.items()}, indent=1)) if a.json: json.dump(res, open(a.json, "w"), indent=1)