Luni's picture
initial commit
d75081b verified
Raw History Blame Contribute Delete
4.35 kB
"""Score a Laya checkpoint on the LocalLLaMA/typed-decisions test split.
Metrics match the notebook's so the number is comparable to its published
0.766, and to the Jev 1.13.0 reference row it quotes (0.727).
"""
import json, time, argparse
import numpy as np
from datasets import load_dataset
import laya
from laya.common import ece_score
ap = argparse.ArgumentParser()
ap.add_argument("model", nargs="?", default="out/laya-typed-decisions")
ap.add_argument("--dataset", default="LocalLLaMA/typed-decisions")
ap.add_argument("--config", default="all")
ap.add_argument("--split", default="test")
ap.add_argument("--device", default="cuda")
ap.add_argument("--by-workflow", action="store_true")
args = ap.parse_args()
ds = load_dataset(args.dataset, args.config, split=args.split)
agent = laya.Agent(args.model, device=args.device)
rows, lat = [], []
for row in ds:
state, questions, gold = (json.loads(row[k]) for k in ("state", "questions", "gold"))
t = time.perf_counter()
res = agent.predict(state, questions)
lat.append((time.perf_counter() - t) * 1000)
rows.append((row.get("workflow", "?"), questions, gold, res["answers"]))
def score(subset):
acc, soft, brier, kl, tv, mae, w1, confs, corrects = ([] for _ in range(9))
for _, questions, gold, pred in subset:
for qid, qdef in questions.items():
p, g, t = pred[qid], gold[qid], qdef["type"]
if t == "choice":
keys = list(qdef["criteria"].keys())
is_corr = float(p["choice"] == str(g["label"]))
pp = np.array([p["probabilities"].get(k, 1e-6) for k in keys])
gp = np.array([g["probabilities"].get(k, 1e-6) for k in keys])
elif t == "noul":
pv = p["noul"]
gv = g.get("noul", g.get("probabilities", {}).get("true", 0.5))
is_corr = float(("true" if pv >= 0.5 else "false") == str(g["label"]).lower())
pp, gp = np.array([1 - pv, pv]), np.array([1 - gv, gv])
else: # score
n = len(qdef.get("criteria", []))
pp = np.array([p["probabilities"].get(str(i), 0.0) for i in range(n)])
gp = None
mae.append(abs(p["score"] - g.get("score", 0.0)))
w1.append(float(abs(p["score"] - g.get("score", 0.0)) <= 1.0))
if pp.sum() > 0:
pp = pp / pp.sum()
p_lvl, conf = int(np.argmax(pp)), float(pp.max())
else:
p_lvl, conf = int(round(p["score"])), 0.5
is_corr = float(p_lvl == int(g.get("label", round(g.get("score", 0.0)))))
acc.append(is_corr); corrects.append(is_corr); confs.append(conf)
continue
pp = pp / pp.sum(); gp = gp / gp.sum()
acc.append(is_corr); corrects.append(is_corr); confs.append(float(pp.max()))
soft.append(float((pp * gp).sum()))
brier.append(float(((pp - gp) ** 2).sum()))
tv.append(float(0.5 * np.abs(pp - gp).sum()))
kl.append(float((gp * np.log(np.clip(gp / pp, 1e-12, 1e4))).sum()))
return dict(n=len(acc), acc=np.mean(acc), soft=np.mean(soft), brier=np.mean(brier),
kl=np.mean(kl), tv=np.mean(tv),
ece=ece_score(np.array(confs), np.array(corrects)),
mae=np.mean(mae) if mae else 0.0, within1=np.mean(w1) if w1 else 0.0)
m = score(rows)
print(f"\nmodel {args.model}")
print(f"cases {len(rows)} decisions {m['n']}")
print(f"accuracy {m['acc']:.3f} soft acc {m['soft']:.3f}")
print(f"ECE {m['ece']:.3f} Brier {m['brier']:.3f} KL {m['kl']:.3f} TV {m['tv']:.3f}")
print(f"score MAE {m['mae']:.3f} within-1 {m['within1']:.3f}")
print(f"latency p50 {np.percentile(lat,50):.1f} ms p95 {np.percentile(lat,95):.1f} ms per case")
print("\nreference (from the notebook, same test split):")
print(" TypeSafe Jev 1.13.0 accuracy 0.727 ECE 0.144 710 ms/case")
print(" notebook's 2xT4 finetune accuracy 0.766")
print(" teacher self-agreement accuracy 0.735 <- ceiling")
if args.by_workflow:
print()
for wf in sorted({r[0] for r in rows}):
s = score([r for r in rows if r[0] == wf])
print(f" {wf:28s} acc {s['acc']:.3f} ECE {s['ece']:.3f} (n={s['n']})")