Upload alea/eval.py with huggingface_hub
Browse files- alea/eval.py +248 -245
alea/eval.py
CHANGED
|
@@ -1,245 +1,248 @@
|
|
| 1 |
-
"""Evaluation: accuracy, ECE, known-q L2, permutation invariance, isolation."""
|
| 2 |
-
import argparse
|
| 3 |
-
import json
|
| 4 |
-
import random
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
|
| 8 |
-
from .dataset import row_to_specs
|
| 9 |
-
from .model import AleaModel, collate
|
| 10 |
-
from .packing import QuestionSpec, pack_request
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
ans[r["qid"]] = {"type": "
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
out
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
#
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
d = max(abs(a - b) for a, b in
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
ap
|
| 218 |
-
ap.add_argument("--
|
| 219 |
-
ap.add_argument("--
|
| 220 |
-
ap.add_argument("--
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
print("
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluation: accuracy, ECE, known-q L2, permutation invariance, isolation."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import random
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from .dataset import row_to_specs
|
| 9 |
+
from .model import AleaModel, collate
|
| 10 |
+
from .packing import QuestionSpec, pack_request
|
| 11 |
+
from .train import load_into
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_model(ckpt_path, model_name, device):
|
| 15 |
+
ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 16 |
+
args = ck.get("args", {})
|
| 17 |
+
del ck
|
| 18 |
+
model = AleaModel(
|
| 19 |
+
model_name, attn_impl=args.get("attn", "sdpa"),
|
| 20 |
+
use_aux_embed=args.get("use_aux_embed", False),
|
| 21 |
+
use_ngram=args.get("use_ngram", False),
|
| 22 |
+
use_ngram2=args.get("use_ngram2", False),
|
| 23 |
+
use_ngram3=args.get("use_ngram3", False),
|
| 24 |
+
).to(device)
|
| 25 |
+
load_into(model, ckpt_path)
|
| 26 |
+
model.eval()
|
| 27 |
+
return model
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@torch.no_grad()
|
| 31 |
+
def predict_all(model, tok, rows, device, max_len=4096):
|
| 32 |
+
"""Return {row_id: {qid: {type, probs[list], keys}}}."""
|
| 33 |
+
res = {}
|
| 34 |
+
for row in rows:
|
| 35 |
+
state, qs, targets = row_to_specs(row)
|
| 36 |
+
pk = pack_request(tok, state, qs, max_len=max_len)
|
| 37 |
+
ids, mask, pos = collate([pk], tok.pad_token_id or tok.eos_token_id)
|
| 38 |
+
out = model(ids.to(device), mask.to(device).to(torch.bfloat16),
|
| 39 |
+
pos.to(device), [pk])[0]
|
| 40 |
+
ans = {}
|
| 41 |
+
for r in out:
|
| 42 |
+
if r["qtype"] in ("choice", "score"):
|
| 43 |
+
p = torch.softmax(r["logits"], -1).tolist()
|
| 44 |
+
ans[r["qid"]] = {"type": r["qtype"], "probs": p}
|
| 45 |
+
elif r["qtype"] == "regress":
|
| 46 |
+
ans[r["qid"]] = {"type": "regress",
|
| 47 |
+
"quantiles": r["quantiles"].tolist()}
|
| 48 |
+
else:
|
| 49 |
+
ans[r["qid"]] = {"type": "noul", "p": r["p_yes"].item()}
|
| 50 |
+
res[row["id"]] = ans
|
| 51 |
+
return res
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def metrics(rows, preds):
|
| 55 |
+
"""acc, ECE(10-bin on top-prob), known-q L2, noul Brier."""
|
| 56 |
+
import math
|
| 57 |
+
n_ch = correct = 0
|
| 58 |
+
ece_bins = [[] for _ in range(10)]
|
| 59 |
+
l2_sum, l2_n = 0.0, 0
|
| 60 |
+
noul_err, noul_n = 0.0, 0
|
| 61 |
+
regr_err, regr_n, regr_scale = 0.0, 0, 0.0
|
| 62 |
+
fam_err, fam_scale = {}, {}
|
| 63 |
+
fam_cor, fam_n = {}, {}
|
| 64 |
+
fam_brier, fam_bn = {}, {}
|
| 65 |
+
for row in rows:
|
| 66 |
+
_, qs, targets = row_to_specs(row)
|
| 67 |
+
ans = preds[row["id"]]
|
| 68 |
+
fam = row.get("family", "?")
|
| 69 |
+
for q in qs:
|
| 70 |
+
t = targets[q.qid]
|
| 71 |
+
a = ans[q.qid]
|
| 72 |
+
if q.qtype in ("choice", "score"):
|
| 73 |
+
p = a["probs"]
|
| 74 |
+
k = max(range(len(t)), key=lambda i: t[i])
|
| 75 |
+
ok = int(max(range(len(p)), key=lambda i: p[i]) == k)
|
| 76 |
+
correct += ok
|
| 77 |
+
n_ch += 1
|
| 78 |
+
fam_cor[fam] = fam_cor.get(fam, 0) + ok
|
| 79 |
+
fam_n[fam] = fam_n.get(fam, 0) + 1
|
| 80 |
+
pm = max(p)
|
| 81 |
+
ece_bins[min(9, int(pm * 10))].append((pm, k == p.index(pm)))
|
| 82 |
+
l2_sum += sum((pi - qi) ** 2 for pi, qi in zip(p, t))
|
| 83 |
+
l2_n += 1
|
| 84 |
+
elif q.qtype == "regress":
|
| 85 |
+
pq = a["quantiles"]
|
| 86 |
+
e = sum((x - y) ** 2 for x, y in zip(pq, t)) / len(t)
|
| 87 |
+
s = sum(y * y for y in t) / len(t)
|
| 88 |
+
regr_err += e
|
| 89 |
+
regr_scale += s
|
| 90 |
+
regr_n += 1
|
| 91 |
+
fam_err[fam] = fam_err.get(fam, 0.0) + e
|
| 92 |
+
fam_scale[fam] = fam_scale.get(fam, 0.0) + s
|
| 93 |
+
else:
|
| 94 |
+
noul_err += (a["p"] - t) ** 2
|
| 95 |
+
noul_n += 1
|
| 96 |
+
fam_brier[fam] = fam_brier.get(fam, 0.0) + (a["p"] - t) ** 2
|
| 97 |
+
fam_bn[fam] = fam_bn.get(fam, 0) + 1
|
| 98 |
+
ece = 0.0
|
| 99 |
+
for b in ece_bins:
|
| 100 |
+
if not b:
|
| 101 |
+
continue
|
| 102 |
+
conf = sum(x[0] for x in b) / len(b)
|
| 103 |
+
acc = sum(x[1] for x in b) / len(b)
|
| 104 |
+
ece += len(b) / n_ch * abs(conf - acc)
|
| 105 |
+
out = {"n_choice": n_ch, "acc": correct / max(1, n_ch),
|
| 106 |
+
"ece10": ece, "known_q_l2": l2_sum / max(1, l2_n),
|
| 107 |
+
"noul_brier": noul_err / max(1, noul_n)}
|
| 108 |
+
out["acc_byfam"] = {f: round(fam_cor[f] / fam_n[f], 3)
|
| 109 |
+
for f in sorted(fam_cor) if fam_n[f] >= 8}
|
| 110 |
+
out["brier_byfam"] = {f: round(fam_brier[f] / fam_bn[f], 4)
|
| 111 |
+
for f in sorted(fam_brier) if fam_bn[f] >= 8}
|
| 112 |
+
if regr_n:
|
| 113 |
+
# R^2-style: fraction of target variance explained by quantile preds
|
| 114 |
+
out["regress_r2"] = 1 - regr_err / max(1e-9, regr_scale)
|
| 115 |
+
out["n_regress"] = regr_n
|
| 116 |
+
# per-family normalized error: mean over families of err/scale —
|
| 117 |
+
# keeps large-scale targets from dominating the aggregate
|
| 118 |
+
fr = {f: round(1 - fam_err[f] / max(1e-9, fam_scale[f]), 4)
|
| 119 |
+
for f in sorted(fam_err)}
|
| 120 |
+
out["regress_r2_byfam"] = fr
|
| 121 |
+
out["regress_r2_fam_mean"] = round(sum(fr.values())
|
| 122 |
+
/ max(1, len(fr)), 4)
|
| 123 |
+
return out
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def permutation_test(model, tok, rows, device, n_perm=8, max_len=4096):
|
| 127 |
+
"""Shuffle each choice question's options; measure argmax flips + |dp|."""
|
| 128 |
+
flips, tot = 0, 0
|
| 129 |
+
dp_sum, dp_n = 0.0, 0
|
| 130 |
+
for row in rows:
|
| 131 |
+
state, qs, _ = row_to_specs(row)
|
| 132 |
+
ch = [q for q in qs if q.qtype == "choice"]
|
| 133 |
+
if not ch:
|
| 134 |
+
continue
|
| 135 |
+
base_pk = pack_request(tok, state, qs, max_len=max_len)
|
| 136 |
+
ids, mask, pos = collate([base_pk], tok.pad_token_id or tok.eos_token_id)
|
| 137 |
+
base_out = model(ids.to(device), mask.to(device).to(torch.bfloat16),
|
| 138 |
+
pos.to(device), [base_pk])[0]
|
| 139 |
+
base = {r["qid"]: torch.softmax(r["logits"], -1).tolist()
|
| 140 |
+
for r in base_out if r["qtype"] == "choice"}
|
| 141 |
+
for _ in range(n_perm):
|
| 142 |
+
qs2 = []
|
| 143 |
+
perm_map = {}
|
| 144 |
+
for q in qs:
|
| 145 |
+
q2 = QuestionSpec(q.qid, q.qtype, q.instructions,
|
| 146 |
+
list(q.options), list(q.option_keys or []))
|
| 147 |
+
if q.qtype == "choice":
|
| 148 |
+
order = list(range(len(q.options)))
|
| 149 |
+
random.shuffle(order)
|
| 150 |
+
q2.options = [q.options[j] for j in order]
|
| 151 |
+
q2.option_keys = [q.option_keys[j] for j in order]
|
| 152 |
+
perm_map[q.qid] = order
|
| 153 |
+
qs2.append(q2)
|
| 154 |
+
pk2 = pack_request(tok, state, qs2, max_len=max_len)
|
| 155 |
+
ids, mask, pos = collate([pk2], tok.pad_token_id or tok.eos_token_id)
|
| 156 |
+
out2 = model(ids.to(device), mask.to(device).to(torch.bfloat16),
|
| 157 |
+
pos.to(device), [pk2])[0]
|
| 158 |
+
for r in out2:
|
| 159 |
+
if r["qtype"] != "choice":
|
| 160 |
+
continue
|
| 161 |
+
order = perm_map[r["qid"]]
|
| 162 |
+
p2 = torch.softmax(r["logits"], -1).tolist()
|
| 163 |
+
# map permuted probs back to canonical order
|
| 164 |
+
canon = [0.0] * len(p2)
|
| 165 |
+
for new_i, orig_i in enumerate(order):
|
| 166 |
+
canon[orig_i] = p2[new_i]
|
| 167 |
+
p1 = base[r["qid"]]
|
| 168 |
+
if max(range(len(canon)), key=lambda i: canon[i]) != \
|
| 169 |
+
max(range(len(p1)), key=lambda i: p1[i]):
|
| 170 |
+
flips += 1
|
| 171 |
+
tot += 1
|
| 172 |
+
dp_sum += max(abs(a - b) for a, b in zip(canon, p1))
|
| 173 |
+
dp_n += 1
|
| 174 |
+
return {"argmax_flip_rate": flips / max(1, tot),
|
| 175 |
+
"mean_max_dp": dp_sum / max(1, dp_n), "n": tot}
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def isolation_test(model, tok, rows, device, max_len=4096):
|
| 179 |
+
"""Mutating question B's token ids in place (same length -> same kernel
|
| 180 |
+
shapes) must leave question A's output bitwise unchanged."""
|
| 181 |
+
n_test = n_same = 0
|
| 182 |
+
max_dp = 0.0
|
| 183 |
+
fill_id = tok.encode("zzzzz", add_special_tokens=False)[0]
|
| 184 |
+
for row in rows:
|
| 185 |
+
state, qs, _ = row_to_specs(row)
|
| 186 |
+
if len(qs) < 2:
|
| 187 |
+
continue
|
| 188 |
+
pk1 = pack_request(tok, state, qs, max_len=max_len)
|
| 189 |
+
ids, mask, pos = collate([pk1], tok.pad_token_id or tok.eos_token_id)
|
| 190 |
+
out1 = model(ids.to(device), mask.to(device).to(torch.bfloat16),
|
| 191 |
+
pos.to(device), [pk1])[0]
|
| 192 |
+
ids2 = ids.clone()
|
| 193 |
+
qctx_lo, qctx_hi = pk1.qctx_spans[1]
|
| 194 |
+
ids2[0, qctx_lo:qctx_hi + 1] = fill_id
|
| 195 |
+
out2 = model(ids2.to(device), mask.to(device).to(torch.bfloat16),
|
| 196 |
+
pos.to(device), [pk1])[0]
|
| 197 |
+
for r1, r2 in zip(out1, out2):
|
| 198 |
+
if r1["qid"] == qs[1].qid:
|
| 199 |
+
continue
|
| 200 |
+
if r1["qtype"] == "noul":
|
| 201 |
+
d = abs(r1["p_yes"].item() - r2["p_yes"].item())
|
| 202 |
+
elif r1["qtype"] == "regress":
|
| 203 |
+
d = max(abs(a - b) for a, b in
|
| 204 |
+
zip(r1["quantiles"].tolist(), r2["quantiles"].tolist()))
|
| 205 |
+
else:
|
| 206 |
+
d = max(abs(a - b) for a, b in zip(
|
| 207 |
+
torch.softmax(r1["logits"], -1).tolist(),
|
| 208 |
+
torch.softmax(r2["logits"], -1).tolist()))
|
| 209 |
+
max_dp = max(max_dp, d)
|
| 210 |
+
n_same += int(d < 1e-4)
|
| 211 |
+
n_test += 1
|
| 212 |
+
return {"unchanged_rate": n_same / max(1, n_test),
|
| 213 |
+
"max_dp": max_dp, "n": n_test}
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def main():
|
| 217 |
+
ap = argparse.ArgumentParser()
|
| 218 |
+
ap.add_argument("--ckpt", required=True)
|
| 219 |
+
ap.add_argument("--data", default="data/test.jsonl")
|
| 220 |
+
ap.add_argument("--model", default="Qwen/Qwen3-0.6B")
|
| 221 |
+
ap.add_argument("--max-items", type=int, default=0)
|
| 222 |
+
ap.add_argument("--perm", type=int, default=8)
|
| 223 |
+
ap.add_argument("--skip-structural", action="store_true")
|
| 224 |
+
args = ap.parse_args()
|
| 225 |
+
|
| 226 |
+
from transformers import AutoTokenizer
|
| 227 |
+
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 228 |
+
tok = AutoTokenizer.from_pretrained(args.model)
|
| 229 |
+
model = load_model(args.ckpt, args.model, dev)
|
| 230 |
+
rows = [json.loads(l) for l in open(args.data, encoding="utf-8")]
|
| 231 |
+
if args.max_items:
|
| 232 |
+
rows = rows[: args.max_items]
|
| 233 |
+
|
| 234 |
+
preds = predict_all(model, tok, rows, dev)
|
| 235 |
+
print(json.dumps(metrics(rows, preds), indent=2))
|
| 236 |
+
|
| 237 |
+
if not args.skip_structural:
|
| 238 |
+
perm_rows = [r for r in rows if any(
|
| 239 |
+
s["type"] == "choice" for s in r["questions"].values())][:64]
|
| 240 |
+
print("permutation:", json.dumps(
|
| 241 |
+
permutation_test(model, tok, perm_rows, dev, n_perm=args.perm),
|
| 242 |
+
indent=2))
|
| 243 |
+
print("isolation:", json.dumps(
|
| 244 |
+
isolation_test(model, tok, rows[:64], dev), indent=2))
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
if __name__ == "__main__":
|
| 248 |
+
main()
|