File size: 21,855 Bytes
296ef60 07c63a7 296ef60 07c63a7 296ef60 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 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 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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | """
Jev (TypeSafe System One) zero-shot benchmark vs our fine-tuned models
=====================================================================
Asks Jev one flat 113-option Choice question per canonical val complaint and
compares it, example-for-example, against the fine-tuned models whose val
logits live on the HF Hub. Same 6,430 val examples, same label order, so every
comparison is a paired bootstrap on macro F1.
Val is the only clean split: the best models were trained on train+test.
Jev sees exactly what the fine-tuned models see — complaint text only. Criteria
are the bare canonical label names (no descriptions), so this is the zero-shot
analogue of the Opus 4.6 row in the reference table.
Usage (from repo root):
uv run --no-project --with datasets --with numpy --with scikit-learn \\
--with huggingface_hub --with typesafe-sdk \\
python verification/jev_benchmark.py --dry-run # no API calls
... python verification/jev_benchmark.py --n 200 # stratified pilot
... python verification/jev_benchmark.py # full val (6,430)
... python verification/jev_benchmark.py --n 200 --eval-only # re-score cache
Requires TYPESAFE_API_KEY (unless --dry-run / --eval-only).
Every response is appended to a JSONL cache keyed by val index, so a crash or
Ctrl-C never re-spends: rerunning skips examples already answered, and a
pilot's answers are reused by the full run.
"""
import argparse
import asyncio
import json
import os
import sys
import time
from functools import partial
from pathlib import Path
print = partial(print, flush=True)
import numpy as np
from sklearn.metrics import f1_score
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils.data_utils import load_course_data, LABEL_LIST, NUM_LABELS
# =========================================================================
# CONFIG
# =========================================================================
MODEL = "jev-1.13.0"
SEED = 42
N_BOOT = 1000
ECE_BINS = 15
DEFAULT_CONCURRENCY = 8 # 1,200 RPM account limit ≈ 20 req/s; 8 in flight stays under it
OUT_DIR = Path(__file__).resolve().parent / "jev_benchmark_artifacts"
CACHE_PATH = OUT_DIR / f"{MODEL}_val_responses.jsonl"
INSTRUCTIONS = (
"Which issue category best describes the consumer financial complaint in `complaint`?"
)
# (display name, CSV key, HF repo, file) — val predictions in canonical val order
COMPARATORS = [
("Qwen3-32B LoRA teacher (train+test)", "qwen32b",
"earino/ecbs5200-qwen3-32b-phase1-v4-teacher-canonical", "val_logits_canonical_final.npz"),
("ModernBERT-large control (train+test)", "mbert_large",
"earino/ecbs5200-modernbert-large-control-train-test", "val_logits_best.npz"),
("ModernBERT-base distilled (Wk 6)", "mbert_base_distilled",
"earino/ecbs5200-week6-distilled-student", "val_predictions.npz"),
("ModernBERT-base vanilla (Wk 6)", "mbert_base_vanilla",
"earino/ecbs5200-week6-vanilla-baseline", "val_predictions.npz"),
]
# Documented full-val macro F1 — asserted on load so a wrong file can't slip in
EXPECTED_FULL_VAL_F1 = [0.3223, 0.3085, 0.2789, 0.2638]
# =========================================================================
# Data
# =========================================================================
def load_comparators(val_labels):
from huggingface_hub import hf_hub_download
out = []
for (name, key, repo, fname), expected in zip(COMPARATORS, EXPECTED_FULL_VAL_F1):
path = hf_hub_download(repo_id=repo, filename=fname)
d = np.load(path, allow_pickle=True)
assert (d["labels"] == val_labels).all(), f"{name}: val label order mismatch"
logits = d["logits"].astype(np.float64)
probs = np.exp(logits - logits.max(-1, keepdims=True))
probs /= probs.sum(-1, keepdims=True)
preds = logits.argmax(-1)
f1 = f1_score(val_labels, preds, average="macro", zero_division=0)
assert abs(f1 - expected) < 5e-4, f"{name}: macro F1 {f1:.4f} != documented {expected}"
tiers = d["tiers"] if "tiers" in d.files else d["val_tiers"]
revision = Path(path).parent.name # hub cache layout: .../snapshots/<sha>/<file>
out.append({"name": name, "key": key, "repo": repo, "file": fname,
"revision": revision, "preds": preds, "probs": probs})
return out, np.asarray(tiers).astype(str)
def pick_subset(val_labels, n):
"""Stratified-by-proportion random subset (seeded); full val if n is None."""
if n is None or n >= len(val_labels):
return np.arange(len(val_labels))
from sklearn.model_selection import train_test_split
idx = np.arange(len(val_labels))
# Classes with 1 example can't be stratified; fall back to a plain seeded sample
try:
sub, _ = train_test_split(idx, train_size=n, stratify=val_labels, random_state=SEED)
except ValueError:
sub = np.random.default_rng(SEED).choice(idx, size=n, replace=False)
return np.sort(sub)
# =========================================================================
# Jev calls
# =========================================================================
def build_questions(criteria=None, instructions=INSTRUCTIONS):
"""Default: bare label names. `criteria` maps every label to a description (or None)."""
from typesafe_sdk import Choice
if criteria is None:
criteria = {label: None for label in LABEL_LIST}
assert list(criteria) == LABEL_LIST, "criteria must cover LABEL_LIST in order"
return {"issue": Choice(instructions=instructions, criteria=criteria)}
def load_cache(path=CACHE_PATH, key_field="val_idx"):
cache = {}
if path.exists():
for line in path.read_text().splitlines():
rec = json.loads(line)
cache[rec[key_field]] = rec
return cache
async def run_jev(texts, todo, concurrency, questions=None, cache_path=CACHE_PATH,
key_field="val_idx", progress_every=100, state_fn=None):
"""Ask Jev about texts[i] for i in todo, appending each answer to cache_path as it lands."""
from typesafe_sdk import (AsyncTypeSafeClient, RetryPolicy, TypeSafeError,
TypeSafeAuthenticationError, TypeSafePermissionDeniedError)
questions = questions or build_questions()
sem = asyncio.Semaphore(concurrency)
retry = RetryPolicy(max_retries=6, backoff_max=20.0, timeout=180.0)
failures = []
done = 0
t_start = time.time()
OUT_DIR.mkdir(exist_ok=True)
with open(cache_path, "a") as cache_f:
async with AsyncTypeSafeClient(model=MODEL, retry=retry) as client:
async def one(i):
nonlocal done
async with sem:
t0 = time.perf_counter()
try:
state = state_fn(i) if state_fn else {"complaint": texts[i]}
resp = await client.system_one(state, questions)
except (TypeSafeAuthenticationError, TypeSafePermissionDeniedError):
raise # bad key: abort instead of logging thousands of failures
except TypeSafeError as e:
failures.append((int(i), f"{type(e).__name__}: {str(e)[:200]}"))
return
latency = time.perf_counter() - t0
ans = resp.answers["issue"]
rec = {
key_field: int(i),
"choice": ans.choice,
"confidence": ans.confidence,
"probs": [ans.probabilities.get(l, 0.0) for l in LABEL_LIST],
"latency_s": latency,
"input_tokens": resp.usage.input_tokens,
"output_tokens": resp.usage.output_tokens,
"model": resp.model,
"request_id": resp.request_id,
}
cache_f.write(json.dumps(rec) + "\n")
cache_f.flush()
done += 1
if done == 1 or done % progress_every == 0 or done == len(todo):
el = time.time() - t_start
print(f" {done}/{len(todo)} | {el:.0f}s | {done / el:.1f} req/s | "
f"failures {len(failures)}")
await asyncio.gather(*(one(i) for i in todo))
if failures:
print(f"\n {len(failures)} requests failed (not cached; rerun to retry). First 5:")
for i, msg in failures[:5]:
print(f" {key_field} {i}: {msg}")
# =========================================================================
# Metrics
# =========================================================================
def macro_f1(y, p):
return f1_score(y, p, average="macro", zero_division=0)
def zero_f1_count(y, p):
per = f1_score(y, p, labels=np.unique(y), average=None, zero_division=0)
return int((per == 0).sum()), len(per)
def tier_f1(y, p, tiers, tier, tier_labels):
"""Macro F1 over the tier's own classes, on the tier's examples (distill_ab_v2.py convention)."""
m = tiers == tier
if not m.any():
return float("nan")
return f1_score(y[m], p[m], labels=tier_labels[tier], average="macro", zero_division=0)
def ece(y, probs):
conf = probs.max(-1)
correct = probs.argmax(-1) == y
edges = np.linspace(0, 1, ECE_BINS + 1)
total = 0.0
for lo, hi in zip(edges[:-1], edges[1:]):
m = (conf > lo) & (conf <= hi)
if m.any():
total += m.mean() * abs(correct[m].mean() - conf[m].mean())
return total
def paired_bootstrap(y, p_a, p_b):
"""Δ macro F1 (a − b) with 95% percentile CI, resampling examples jointly."""
rng = np.random.default_rng(SEED)
n = len(y)
deltas = np.empty(N_BOOT)
for b in range(N_BOOT):
idx = rng.integers(0, n, n)
deltas[b] = macro_f1(y[idx], p_a[idx]) - macro_f1(y[idx], p_b[idx])
return macro_f1(y, p_a) - macro_f1(y, p_b), np.percentile(deltas, [2.5, 97.5])
def evaluate(sub, y_all, tiers_all, comparators, cache, n_requested):
have = np.array([i for i in sub if i in cache])
if len(have) < len(sub):
print(f"\n NOTE: {len(sub) - len(have)} of {len(sub)} subset examples have no Jev "
f"answer yet; scoring the {len(have)} that do.")
if len(have) == 0:
return None
y = y_all[have]
tiers = tiers_all[have]
# Tier is a function of the label (train+test frequency rank); every class appears in val
tier_labels = {t: sorted(set(y_all[tiers_all == t].tolist())) for t in ("head", "mid", "tail")}
jev_probs = np.array([cache[i]["probs"] for i in have])
jev_preds = np.array([LABEL_LIST.index(cache[i]["choice"]) for i in have])
# Probabilities come back rounded to 0.01, so near-ties can show Jev's choice one rounding
# step below the displayed max. Jev's choice is the prediction; anything wider is a bug.
gap = jev_probs.max(-1) - jev_probs[np.arange(len(have)), jev_preds]
assert (gap <= 0.0101).all(), "choice is more than one rounding step below the max"
n_near_tie = int((gap > 1e-9).sum())
if n_near_tie:
print(f"\n NOTE: {n_near_tie} answers have Jev's choice 0.01 below the displayed max "
f"(rounded near-ties); scored by Jev's choice.")
rows = [("Jev 1.13 zero-shot (label names only)", jev_preds, jev_probs)]
rows += [(c["name"], c["preds"][have], c["probs"][have]) for c in comparators]
print("\n" + "=" * 100)
print(f" RESULTS — {len(have)} canonical val examples"
+ ("" if n_requested is None else f" (stratified pilot, requested n={n_requested})"))
print("=" * 100)
print(f" {'Model':<40} {'Acc':>6} {'MacroF1':>8} {'Head':>6} {'Mid':>6} {'Tail':>6} "
f"{'Zero-F1':>9} {'ECE':>6}")
results = {"n": int(len(have)), "jev_near_ties_scored_by_choice": n_near_tie, "models": {}}
for name, p, pr in rows:
z, k = zero_f1_count(y, p)
r = {
"accuracy": float((p == y).mean()),
"macro_f1": float(macro_f1(y, p)),
"head_f1": float(tier_f1(y, p, tiers, "head", tier_labels)),
"mid_f1": float(tier_f1(y, p, tiers, "mid", tier_labels)),
"tail_f1": float(tier_f1(y, p, tiers, "tail", tier_labels)),
"zero_f1": z, "classes_present": k,
"ece": float(ece(y, pr)),
}
results["models"][name] = r
print(f" {name:<40} {r['accuracy']:>6.3f} {r['macro_f1']:>8.3f} {r['head_f1']:>6.3f} "
f"{r['mid_f1']:>6.3f} {r['tail_f1']:>6.3f} {z:>4}/{k:<4} {r['ece']:>6.3f}")
print(f"\n Paired bootstrap, Δ macro F1 = Jev − model ({N_BOOT} resamples, seed {SEED}):")
results["paired"] = {}
for name, p, _ in rows[1:]:
d, (lo, hi) = paired_bootstrap(y, jev_preds, p)
sig = "significant" if (lo > 0 or hi < 0) else "CI includes 0"
results["paired"][name] = {"delta": float(d), "ci95": [float(lo), float(hi)]}
print(f" vs {name:<40} Δ={d:+.3f} 95% CI [{lo:+.3f}, {hi:+.3f}] {sig}")
lat = np.array([cache[i]["latency_s"] for i in have]) * 1000
tin = [cache[i]["input_tokens"] for i in have if cache[i]["input_tokens"] is not None]
tout = [cache[i]["output_tokens"] for i in have if cache[i]["output_tokens"] is not None]
conf = np.array([cache[i]["confidence"] for i in have])
correct = jev_preds == y
results["jev_ops"] = {
"latency_ms_p50": float(np.percentile(lat, 50)),
"latency_ms_p95": float(np.percentile(lat, 95)),
"input_tokens_total": int(sum(tin)), "output_tokens_total": int(sum(tout)),
"models_reported": sorted({cache[i]["model"] for i in have}),
}
print(f"\n Jev latency per request (client wall-clock, incl. network): "
f"p50 {results['jev_ops']['latency_ms_p50']:.0f} ms, "
f"p95 {results['jev_ops']['latency_ms_p95']:.0f} ms")
if tin:
print(f" Jev tokens: {sum(tin):,} in / {sum(tout):,} out "
f"({np.mean(tin):.0f} in per request)")
print(f" Jev model(s) reported: {results['jev_ops']['models_reported']}")
print("\n Jev accuracy by confidence:")
results["jev_by_confidence"] = {}
for lo, hi in [(0.9, 1.01), (0.5, 0.9), (0.0, 0.5)]:
m = (conf >= lo) & (conf < hi)
if m.any():
results["jev_by_confidence"][f"[{lo},{min(hi, 1.0)}]"] = {
"share": float(m.mean()), "accuracy": float(correct[m].mean())}
print(f" confidence [{lo:.1f}, {min(hi, 1.0):.1f}]: {m.mean():>5.1%} of examples, "
f"accuracy {correct[m].mean():.3f}")
return results
# =========================================================================
# Export (full run only) — everything the write-up needs, no re-querying
# =========================================================================
def export_full(texts, y_all, tiers_all, comparators, cache, results, args):
import csv
import datetime
import subprocess
import typesafe_sdk
n = len(y_all)
assert len(cache) >= n, "export needs every val example answered"
jev_probs = np.array([cache[i]["probs"] for i in range(n)])
jev_preds = np.array([LABEL_LIST.index(cache[i]["choice"]) for i in range(n)])
# Same layout as the comparator .npz files, so existing analysis scripts accept it
npz_path = OUT_DIR / f"{MODEL}_val_probs.npz"
np.savez_compressed(npz_path, probs=jev_probs, preds=jev_preds, labels=y_all, tiers=tiers_all,
confidence=np.array([cache[i]["confidence"] for i in range(n)]))
csv_path = OUT_DIR / f"{MODEL}_per_example_full.csv"
cols = ["val_idx", "tier", "true_label", "jev_choice", "jev_correct", "jev_confidence",
"jev_p_true", "jev_top2", "jev_top2_p", "jev_top3", "jev_top3_p",
"jev_latency_ms", "jev_input_tokens", "jev_output_tokens", "jev_request_id"]
for c in comparators:
cols += [f"{c['key']}_pred", f"{c['key']}_correct", f"{c['key']}_p_pred", f"{c['key']}_p_true"]
cols.append("text")
with open(csv_path, "w", newline="") as f:
w = csv.writer(f)
w.writerow(cols)
for i in range(n):
r, p, t = cache[i], jev_probs[i], y_all[i]
top = np.argsort(-p, kind="stable")
# rounded probs tie; Jev's own choice leads, then the next two by probability
rest = [j for j in top if j != jev_preds[i]][:2]
row = [i, tiers_all[i], LABEL_LIST[t], r["choice"], int(jev_preds[i] == t),
r["confidence"], p[t], LABEL_LIST[rest[0]], p[rest[0]],
LABEL_LIST[rest[1]], p[rest[1]], round(r["latency_s"] * 1000, 1),
r["input_tokens"], r["output_tokens"], r["request_id"]]
for c in comparators:
cp = c["preds"][i]
row += [LABEL_LIST[cp], int(cp == t), round(c["probs"][i][cp], 6),
round(c["probs"][i][t], 6)]
row.append(texts[i])
w.writerow(row)
q = build_questions()["issue"]
try:
commit = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True,
cwd=Path(__file__).resolve().parent).stdout.strip()
except OSError:
commit = None
in_tok = sum(cache[i]["input_tokens"] or 0 for i in range(n))
out_tok = sum(cache[i]["output_tokens"] or 0 for i in range(n))
manifest = {
"exported_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
"model_requested": MODEL,
"models_reported": sorted({cache[i]["model"] for i in range(n)}),
"typesafe_sdk_version": getattr(typesafe_sdk, "__version__", None),
"build_repo_commit": commit,
"eval_set": "canonical val (utils/data_utils.py), 6,430 examples, 113 classes",
"request": {
"state": {"complaint": "<val complaint text, untruncated>"},
"questions": {"issue": q.model_dump()},
},
"client": {"concurrency": args.concurrency, "retry": "RetryPolicy(max_retries=6, "
"backoff_max=20.0, timeout=180.0)"},
"comparators": [{k: c[k] for k in ("name", "key", "repo", "file", "revision")}
for c in comparators],
"usage": {"requests": n, "input_tokens": in_tok, "output_tokens": out_tok},
"files": {"responses_jsonl": CACHE_PATH.name, "per_example_csv": csv_path.name,
"probs_npz": npz_path.name, "results_json": f"{MODEL}_results_full.json"},
"results": results,
}
man_path = OUT_DIR / f"{MODEL}_manifest_full.json"
man_path.write_text(json.dumps(manifest, indent=2))
print(f" Exported {csv_path.name}, {npz_path.name}, {man_path.name}")
print(f" Usage: {in_tok:,} input tokens, {out_tok:,} output tokens")
# =========================================================================
# Main
# =========================================================================
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--n", type=int, default=None, help="stratified pilot size (default: full val)")
ap.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY)
ap.add_argument("--dry-run", action="store_true", help="build requests, estimate size, no API calls")
ap.add_argument("--eval-only", action="store_true", help="score cached answers, no API calls")
args = ap.parse_args()
print("Loading canonical val split...")
_, val_ds, _ = load_course_data()
texts = list(val_ds["text"])
y_all = np.array(val_ds["label"])
assert len(y_all) == 6430 and NUM_LABELS == 113
print("Loading comparator val predictions from HF Hub...")
comparators, tiers_all = load_comparators(y_all)
print(f" {len(comparators)} comparators loaded; full-val macro F1 matches documented numbers.")
sub = pick_subset(y_all, args.n)
cache = load_cache()
todo = [int(i) for i in sub if int(i) not in cache]
print(f"\nSubset: {len(sub)} examples | cached: {len(sub) - len(todo)} | to request: {len(todo)}")
if args.dry_run:
q = build_questions()["issue"]
payload = json.dumps({"instructions": q.instructions, "criteria": dict(q.criteria)})
chars = [len(texts[i]) for i in todo]
# ~4 chars/token is a rough English estimate; the real count comes back in usage
est_q = len(payload) / 4
est_total = sum(est_q + c / 4 for c in chars)
print(f"\n DRY RUN — no API calls made.")
print(f" Question payload: {len(payload):,} chars (~{est_q:,.0f} tokens), 113 criteria")
print(f" Complaint text: mean {np.mean(chars) if chars else 0:.0f} chars")
print(f" Estimated input tokens for {len(todo)} requests: ~{est_total / 1e6:.2f}M")
print(f" Example state: {json.dumps({'complaint': texts[int(sub[0])]})[:300]}...")
return
if todo and not args.eval_only:
if not os.environ.get("TYPESAFE_API_KEY"):
sys.exit("ERROR: TYPESAFE_API_KEY not set")
print(f"Calling {MODEL} (concurrency={args.concurrency})...")
asyncio.run(run_jev(texts, todo, args.concurrency))
cache = load_cache()
results = evaluate(sub, y_all, tiers_all, comparators, cache, args.n)
if results:
tag = "full" if args.n is None else f"pilot{args.n}"
out = OUT_DIR / f"{MODEL}_results_{tag}.json"
OUT_DIR.mkdir(exist_ok=True)
out.write_text(json.dumps(results, indent=2))
print(f"\n Saved {out.relative_to(Path.cwd()) if out.is_relative_to(Path.cwd()) else out}")
if args.n is None and results["n"] == len(y_all):
export_full(texts, y_all, tiers_all, comparators, cache, results, args)
if __name__ == "__main__":
main()
|