azharmo commited on
Commit
42558dd
·
verified ·
1 Parent(s): 9762a25

Upload jev_toy/eval.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. jev_toy/eval.py +137 -0
jev_toy/eval.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ jev_toy/eval.py
3
+
4
+ Measure what matters for a System One decision model:
5
+ - accuracy (does the argmax/label match)
6
+ - expected calibration error (ECE) and reliability
7
+ - Brier score (proper scoring rule)
8
+ Applied to noul and choice heads. Also does post-hoc temperature scaling
9
+ (our implementation of the "calibrated" property; tuning T on a held-out set).
10
+
11
+ Usage:
12
+ python -m jev_toy.eval --ckpt checkpoints/model.pt
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import math
19
+
20
+ import torch
21
+ import torch.nn.functional as F
22
+
23
+ from jev_toy.data import build_examples, tokenize
24
+ from jev_toy.model import SystemOneConfig, SystemOneModel
25
+ from jev_toy.train import featurize
26
+
27
+
28
+ @torch.no_grad()
29
+ def predict(model, eval_examples, vocab, cfg, device):
30
+ """Return per-row predictions for noul and choice rows."""
31
+ model.eval()
32
+ model = model.to(device)
33
+ n_rows, c_rows = [], []
34
+ for bidx in range(0, len(eval_examples), 64):
35
+ idx = list(range(bidx, min(bidx + 64, len(eval_examples))))
36
+ (ids_s, mask_s, ids_q, mask_q, types, targets) = featurize(idx, eval_examples, vocab, cfg, device)
37
+ h = model.encode_state(ids_s, mask_s)
38
+ logits, _ = model.answer(h, ids_q, mask_q, types)
39
+ for k, t in enumerate(types):
40
+ if t == "noul":
41
+ n_rows.append({"p": torch.sigmoid(logits["noul"][k]).item(), "y": int(targets[k])})
42
+ elif t == "choice":
43
+ probs = F.softmax(logits["choice"][k], dim=-1).cpu()
44
+ c_rows.append({"p": probs, "y": int(targets[k])})
45
+ return n_rows, c_rows
46
+
47
+
48
+ def brier(p, y):
49
+ return (p - y) ** 2
50
+
51
+
52
+ def ece(probs, ys, n_bins=10):
53
+ """Expected Calibration Error over probability bins."""
54
+ bins = [0.0] * n_bins
55
+ conf = [0.0] * n_bins
56
+ cnt = [0] * n_bins
57
+ for p, y in zip(probs, ys):
58
+ b = min(int(p * n_bins), n_bins - 1)
59
+ cnt[b] += 1
60
+ conf[b] += p
61
+ bins[b] += 1.0 if p >= 0.5 and y == 1 or p < 0.5 and y == 0 else 0.0
62
+ tot = sum(cnt)
63
+ if tot == 0:
64
+ return 0.0
65
+ e = 0.0
66
+ for i in range(n_bins):
67
+ if cnt[i]:
68
+ acc = bins[i] / cnt[i]
69
+ e += cnt[i] / tot * abs(acc - conf[i] / cnt[i])
70
+ return e
71
+
72
+
73
+ def noul_metrics(n_rows, temp=1.0):
74
+ probs = [r["p"] for r in n_rows]
75
+ ys = [r["y"] for r in n_rows]
76
+ if temp != 1.0:
77
+ probs = [1.0 / (1.0 + math.exp(-(math.log(p / (1 - p + 1e-9))) / temp)) for p in probs]
78
+ acc = sum(1 for p, y in zip(probs, ys) if (p >= 0.5) == (y == 1)) / len(n_rows)
79
+ brier = sum((p - y) ** 2 for p, y in zip(probs, ys)) / len(n_rows)
80
+ return {"n": len(n_rows), "acc": acc, "brier": brier, "ece": ece(probs, ys)}
81
+
82
+
83
+ def choice_metrics(c_rows, temp=1.0):
84
+ acc = 0
85
+ brier_total = 0.0
86
+ for r in c_rows:
87
+ logit = torch.log(r["p"] + 1e-9) / temp
88
+ probs = F.softmax(logit, dim=-1)
89
+ pred = int(probs.argmax())
90
+ acc += (pred == r["y"])
91
+ y1h = torch.zeros_like(probs)
92
+ y1h[r["y"]] = 1.0
93
+ brier_total += ((probs - y1h) ** 2).sum().item()
94
+ n = len(c_rows)
95
+ return {"n": n, "acc": acc / n, "brier": brier_total / n}
96
+
97
+
98
+ def temperature_scan(n_rows, c_rows):
99
+ """Pick the temperature that minimises ECE on a held-out split."""
100
+ half_n = len(n_rows) // 2
101
+ half_c = len(c_rows) // 2
102
+ best = {"nce": (1.0, 9e9), "cce": (1.0, 9e9)}
103
+ for t in [0.4, 0.6, 0.8, 1.0, 1.2, 1.5, 2.0, 3.0]:
104
+ mn = noul_metrics(n_rows[:half_n], t)
105
+ if mn["ece"] < best["nce"][1]:
106
+ best["nce"] = (t, mn["ece"])
107
+ return best
108
+
109
+
110
+ def main():
111
+ ap = argparse.ArgumentParser()
112
+ ap.add_argument("--ckpt", default="checkpoints/model.pt")
113
+ args = ap.parse_args()
114
+
115
+ device = "cuda" if torch.cuda.is_available() else "cpu"
116
+ ck = torch.load(args.ckpt, map_location=device)
117
+ cfg = SystemOneConfig(**ck["config"])
118
+ vocab = type("V", (), {"stoi": ck["vocab"], "oov": ck["vocab"].get("__oov__", 1)})()
119
+ model = SystemOneModel(cfg).to(device)
120
+ model.load_state_dict(ck["state_dict"])
121
+
122
+ from datasets import load_dataset
123
+ ag = load_dataset("fancyzhx/ag_news")
124
+ bq = load_dataset("google/boolq")
125
+ st = load_dataset("stanfordnlp/sst2")
126
+ # small eval splits
127
+ subsample = {"agnews": 600, "boolq": 600, "sst2": 600}
128
+ eval_examples, _ = build_examples({"agnews": ag, "boolq": bq, "sst2": st}, subsample)
129
+ n_rows, c_rows = predict(model, eval_examples, vocab, cfg, device)
130
+ print("--- noul (BoolQ+SST2) ---", noul_metrics(n_rows))
131
+ print("--- choice (AG News) ---", choice_metrics(c_rows))
132
+ ts = temperature_scan(n_rows, c_rows)
133
+ print("best noul temperature:", ts["nce"][0], "ECE", round(ts["nce"][1], 4))
134
+
135
+
136
+ if __name__ == "__main__":
137
+ main()