""" Jev extended experiments — does Jev's weak zero-shot result survive a fair shot? =============================================================================== Follow-up to jev_benchmark.py (bare-label zero-shot on val: 34.4% / 0.132 macro F1). Two questions, both answered on the canonical val split, with every design choice made on training data only: 1. FEATURES — Jev's 113-way probabilities as features for a classifier trained on our labels ("turn judgments into reusable data"). Needs bare-label Jev answers for train (57,846) and test (21,432); val answers come from jev_benchmark.py. 2. CRITERIA — structured label definitions (TypeSafe's own recommended fix for confusable options), designed from Jev's errors on train, iterated on a train dev slice, then run on val once. Subcommands (from repo root, same uv invocation as jev_benchmark.py): python verification/jev_extended.py collect --split train python verification/jev_extended.py collect --split test python verification/jev_extended.py features # no API calls python verification/jev_extended.py confusions # no API calls; design view of train python verification/jev_extended.py criteria-dev --variant v1 # train dev slice python verification/jev_extended.py criteria-val --variant v1 # val, run once Every answer is appended to a per-split JSONL cache keyed by row index within the split, so reruns only request what is missing. """ import argparse import asyncio import json import os import sys from pathlib import Path import numpy as np from sklearn.metrics import f1_score sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from jev_benchmark import (MODEL, OUT_DIR, CACHE_PATH, SEED, build_questions, load_cache, run_jev, load_comparators, macro_f1, tier_f1, zero_f1_count, ece, paired_bootstrap) from utils.data_utils import load_course_data, LABEL_LIST, NUM_LABELS SPLITS = ("train", "test") def cache_path(split, variant="bare"): return OUT_DIR / f"{MODEL}_{variant}_{split}_responses.jsonl" def split_texts(split): train_ds, val_ds, test_ds = load_course_data() ds = {"train": train_ds, "val": val_ds, "test": test_ds}[split] return list(ds["text"]), np.array(ds["label"]) def jev_probs(split, variant="bare"): """(n, 113) Jev probabilities in LABEL_LIST order, plus Jev's own choice per row.""" if split == "val" and variant == "bare": cache = load_cache(CACHE_PATH, key_field="val_idx") else: cache = load_cache(cache_path(split, variant), key_field="idx") n = max(cache) + 1 assert sorted(cache) == list(range(n)), f"{split}/{variant}: cache has gaps" probs = np.array([cache[i]["probs"] for i in range(n)]) choice = np.array([LABEL_LIST.index(cache[i]["choice"]) for i in range(n)]) return probs, choice def report(title, rows, y, tiers, pairs): """rows: {name: (preds, probs)}; pairs: [(a, b)] → paired bootstrap Δ macro F1 (a − b).""" tier_labels = {t: sorted(set(y[tiers == t].tolist())) for t in ("head", "mid", "tail")} print("\n" + "=" * 104) print(f" {title}") print("=" * 104) print(f" {'Model':<46} {'Acc':>6} {'MacroF1':>8} {'Head':>6} {'Mid':>6} {'Tail':>6} " f"{'Zero-F1':>9} {'ECE':>6}") out = {"models": {}, "paired": {}} for name, (p, pr) in rows.items(): z, k = zero_f1_count(y, p) r = {"accuracy": float((p == y).mean()), "macro_f1": float(macro_f1(y, p)), **{f"{t}_f1": float(tier_f1(y, p, tiers, t, tier_labels)) for t in ("head", "mid", "tail")}, "zero_f1": z, "classes_present": k, "ece": float(ece(y, pr))} out["models"][name] = r print(f" {name:<46} {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 = A − B (1000 resamples, seed {SEED}):") for a, b in pairs: d, (lo, hi) = paired_bootstrap(y, rows[a][0], rows[b][0]) sig = "significant" if (lo > 0 or hi < 0) else "CI includes 0" out["paired"][f"{a} || {b}"] = {"delta": float(d), "ci95": [float(lo), float(hi)]} print(f" {a:<40} vs {b:<40} Δ={d:+.3f} [{lo:+.3f}, {hi:+.3f}] {sig}") return out def cmd_collect(args): texts, _ = split_texts(args.split) path = cache_path(args.split) cache = load_cache(path, key_field="idx") todo = [i for i in range(len(texts)) if i not in cache] print(f"{args.split}: {len(texts)} rows | cached {len(cache)} | to request {len(todo)}") if not todo: return if not os.environ.get("TYPESAFE_API_KEY"): sys.exit("ERROR: TYPESAFE_API_KEY not set") asyncio.run(run_jev(texts, todo, args.concurrency, questions=build_questions(), cache_path=path, key_field="idx", progress_every=2000)) # ========================================================================= # FEATURES — Jev probabilities as inputs to a classifier trained on our labels # ========================================================================= JEV_EPS = 0.005 # half of Jev's 0.01 rounding step; keeps log() finite for zeroed labels DEV_FRACTION = 0.1 def jev_feats(probs): return np.log(probs + JEV_EPS) def fit_lr(X, y, C, class_weight): from sklearn.linear_model import LogisticRegression return LogisticRegression(C=C, class_weight=class_weight, max_iter=2000, solver="lbfgs").fit(X, y) def cmd_features(args): from joblib import Parallel, delayed from scipy.sparse import csr_matrix, hstack from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler train_ds, val_ds, test_ds = load_course_data() fit_texts = list(train_ds["text"]) + list(test_ds["text"]) y_fit = np.concatenate([train_ds["label"], test_ds["label"]]) val_texts, y_val = list(val_ds["text"]), np.array(val_ds["label"]) p_fit = np.vstack([jev_probs("train")[0], jev_probs("test")[0]]) p_val, jev_choice_val = jev_probs("val") assert len(p_fit) == len(y_fit) and len(p_val) == len(y_val) print(f"Fit set: train+test, {len(y_fit):,} rows (the best models' training data). Eval: val.") # Model selection on a held-out slice of the fit set — val is touched once, at the end idx = np.arange(len(y_fit)) counts = np.bincount(y_fit) strat = y_fit if counts[counts > 0].min() >= 2 else None # full data: every class has >= 2 tr, dev = train_test_split(idx, test_size=DEV_FRACTION, stratify=strat, random_state=SEED) def build(kind, rows, fitted=None, w=None): """Feature matrix for rows of the fit set (fitted=None → fit transforms on rows).""" texts = [fit_texts[i] for i in rows] if rows is not None else val_texts P = p_fit[rows] if rows is not None else p_val fitted = dict(fitted or {}) parts = [] if kind in ("tfidf", "tfidf+jev"): if "tfidf" not in fitted: fitted["tfidf"] = TfidfVectorizer(max_features=50000, sublinear_tf=True, ngram_range=(1, 2)).fit(texts) parts.append(fitted["tfidf"].transform(texts)) if kind in ("jev", "tfidf+jev"): if "scaler" not in fitted: fitted["scaler"] = StandardScaler().fit(jev_feats(P)) J = fitted["scaler"].transform(jev_feats(P)) parts.append(csr_matrix(J * (w if w is not None else 1.0))) return hstack(parts).tocsr(), fitted # C=30/100 added after the first pass selected C=10 (the grid edge) for both TF-IDF sets. # w=0.01/0.03 added (pass 3) after the embedding control's selected w=0.1 sat at the grid edge; TF-IDF + Jev had # also selected w=0.1, so both feature sets get the same extended grid. Pass-2 outputs are kept as *_pass2.* grids = { "jev": [dict(C=C, class_weight=cw) for C in (0.01, 0.1, 1.0, 10.0) for cw in (None, "balanced")], "tfidf": [dict(C=C, class_weight=cw) for C in (1.0, 10.0, 30.0, 100.0) for cw in (None, "balanced")], "tfidf+jev": [dict(C=C, class_weight=cw, w=w) for C in (1.0, 10.0, 30.0, 100.0) for cw in (None, "balanced") for w in (0.01, 0.03, 0.1, 0.3)], } def dev_score(kind, cfg): Xtr, fitted = build(kind, tr, w=cfg.get("w")) Xdv, _ = build(kind, dev, fitted, w=cfg.get("w")) clf = fit_lr(Xtr, y_fit[tr], cfg["C"], cfg["class_weight"]) return kind, cfg, macro_f1(y_fit[dev], clf.predict(Xdv)) # Dev scores are cached per (feature set, config): same split and seed, so reruns only fit # configs not scored before sel_cache_path = OUT_DIR / f"{MODEL}_features_selection_cache.json" sel_cache = json.loads(sel_cache_path.read_text()) if sel_cache_path.exists() else {} key = lambda k, c: f"{k} {json.dumps(c, sort_keys=True)}" jobs = [(k, c) for k, cfgs in grids.items() for c in cfgs if key(k, c) not in sel_cache] print(f"Model selection: {len(jobs)} new fits on {len(tr):,} rows " f"({len(sel_cache)} cached), scored on {len(dev):,} dev rows...") for k, c, f1 in Parallel(n_jobs=max(1, min(len(jobs), 12)))(delayed(dev_score)(k, c) for k, c in jobs): sel_cache[key(k, c)] = f1 sel_cache_path.write_text(json.dumps(sel_cache, indent=1)) scores = [(k, c, sel_cache[key(k, c)]) for k, cfgs in grids.items() for c in cfgs] best, selection = {}, [] for kind, cfg, f1 in scores: selection.append({"kind": kind, **{k: v for k, v in cfg.items()}, "dev_macro_f1": float(f1)}) print(f" {kind:<10} {json.dumps(cfg):<55} dev macro F1 {f1:.4f}") if kind not in best or f1 > best[kind][1]: best[kind] = (cfg, f1) def final(kind): cfg = best[kind][0] Xfit, fitted = build(kind, idx, w=cfg.get("w")) Xv, _ = build(kind, None, fitted, w=cfg.get("w")) clf = fit_lr(Xfit, y_fit, cfg["C"], cfg["class_weight"]) pr = clf.predict_proba(Xv) full = np.zeros((len(y_val), NUM_LABELS)); full[:, clf.classes_] = pr return kind, full print(f"\nRefitting the selected config per feature set on all {len(y_fit):,} rows...") finals = dict(Parallel(n_jobs=3)(delayed(final)(k) for k in grids)) comps, tiers = load_comparators(y_val) names = {"jev": "LR on Jev probs (train+test)", "tfidf": "TF-IDF + LR (train+test)", "tfidf+jev": "TF-IDF + Jev probs + LR (train+test)"} rows = {"Jev zero-shot (bare labels)": (jev_choice_val, p_val)} for k in grids: rows[names[k]] = (finals[k].argmax(-1), finals[k]) for c in comps: rows[c["name"]] = (c["preds"], c["probs"]) pairs = [(names["jev"], "Jev zero-shot (bare labels)"), (names["jev"], names["tfidf"]), (names["tfidf+jev"], names["tfidf"]), (names["tfidf+jev"], comps[0]["name"]), (names["tfidf+jev"], comps[1]["name"]), (names["tfidf+jev"], comps[2]["name"]), (names["tfidf+jev"], comps[3]["name"]), (names["jev"], comps[1]["name"])] res = report("FEATURES — canonical val (6,430), all classifiers fit on train+test", rows, y_val, tiers, pairs) res["selection"] = selection res["selected"] = {k: {**best[k][0], "dev_macro_f1": float(best[k][1])} for k in best} (OUT_DIR / f"{MODEL}_features_results.json").write_text(json.dumps(res, indent=2)) np.savez_compressed(OUT_DIR / f"{MODEL}_features_val_probs.npz", labels=y_val, tiers=tiers, **{k.replace("+", "_"): finals[k] for k in finals}) print(f"\n Saved {MODEL}_features_results.json and {MODEL}_features_val_probs.npz") # ========================================================================= # CRITERIA — structured label definitions, designed and iterated on train only # ========================================================================= CRITERIA_DIR = Path(__file__).resolve().parent / "jev_criteria" DEV_IDX_PATH = CRITERIA_DIR / "train_dev_idx.json" DEV_N = 1000 def train_dev_idx(): """Fixed 1,000-row train slice for scoring criteria variants. Never used for design.""" if DEV_IDX_PATH.exists(): return json.loads(DEV_IDX_PATH.read_text()) n = len(load_course_data()[0]) idx = sorted(np.random.default_rng(20260918).choice(n, size=DEV_N, replace=False).tolist()) CRITERIA_DIR.mkdir(exist_ok=True) DEV_IDX_PATH.write_text(json.dumps(idx)) return idx def latest_year_mentioned(text): """Latest 4-digit year (1990-2019) written in the complaint, or None. Dollar amounts like {$2016.00} are not years. Date logic lives in code: Jev reads dates as text.""" import re years = [int(m) for m in re.findall(r"(?.json → (instructions, criteria over all 113 labels, state fields).""" spec = json.loads((CRITERIA_DIR / f"{variant}.json").read_text()) defs = spec["criteria"] unknown = set(defs) - set(LABEL_LIST) assert not unknown, f"{variant}: not canonical labels: {sorted(unknown)}" criteria = {label: defs.get(label) for label in LABEL_LIST} extras = spec.get("state_fields", []) assert set(extras) <= set(STATE_FIELDS), f"unknown state fields: {extras}" return spec.get("instructions", build_questions()["issue"].instructions), criteria, extras def cmd_confusions(args): """Where bare-label Jev goes wrong on train (dev slice excluded), with example texts.""" from collections import Counter texts, y = split_texts("train") cache = load_cache(cache_path("train"), key_field="idx") dev = set(train_dev_idx()) rows = [i for i in sorted(cache) if i not in dev] pred = {i: LABEL_LIST.index(cache[i]["choice"]) for i in rows} print(f"Design view: {len(rows):,} answered train rows (dev slice of {len(dev)} excluded)") true_c = Counter(y[i] for i in rows) pred_c = Counter(pred[i] for i in rows) hit = Counter(y[i] for i in rows if pred[i] == y[i]) print(f"\n{'label':<62} {'true':>6} {'pred':>6} {'recall':>7} {'prec':>6}") for l, _ in sorted(true_c.items(), key=lambda kv: -kv[1])[:args.top_labels]: print(f"{LABEL_LIST[l][:62]:<62} {true_c[l]:>6} {pred_c[l]:>6} " f"{hit[l] / true_c[l]:>7.2f} {hit[l] / max(pred_c[l], 1):>6.2f}") conf = Counter((y[i], pred[i]) for i in rows if pred[i] != y[i]) wrong = sum(conf.values()) print(f"\nTop confusions (true -> Jev), share of {wrong:,} errors:") for (t, p_), c in conf.most_common(args.top_pairs): print(f" {c:>5} {c / wrong:>5.1%} {LABEL_LIST[t][:55]:<55} -> {LABEL_LIST[p_][:55]}") rng = np.random.default_rng(0) for t, p_ in [pair for pair, _ in conf.most_common(args.examples_for)]: cand = [i for i in rows if y[i] == t and pred[i] == p_] print(f"\n--- true: {LABEL_LIST[t]} | Jev: {LABEL_LIST[p_]}") for i in rng.choice(cand, size=min(args.k, len(cand)), replace=False): print(f" [{i}] {texts[i][:args.chars]}") def run_variant(split, idx, variant, texts, concurrency): instructions, criteria, extras = load_variant(variant) questions = build_questions(criteria=criteria, instructions=instructions) def state_fn(i): return {"complaint": texts[i], **{f: STATE_FIELDS[f](texts[i]) for f in extras}} path = cache_path(split, variant) cache = load_cache(path, key_field="idx") todo = [i for i in idx if i not in cache] print(f"{variant} on {split}: {len(idx)} rows | cached {len(idx) - len(todo)} | to request {len(todo)}") if todo: if not os.environ.get("TYPESAFE_API_KEY"): sys.exit("ERROR: TYPESAFE_API_KEY not set") asyncio.run(run_jev(texts, todo, concurrency, questions=questions, cache_path=path, key_field="idx", progress_every=500, state_fn=state_fn)) cache = load_cache(path, key_field="idx") missing = [i for i in idx if i not in cache] assert not missing, f"{len(missing)} rows failed; rerun to retry" probs = np.array([cache[i]["probs"] for i in idx]) choice = np.array([LABEL_LIST.index(cache[i]["choice"]) for i in idx]) tokens = sum(cache[i]["input_tokens"] or 0 for i in idx) return choice, probs, tokens def cmd_criteria_dev(args): from collections import Counter texts, y_train = split_texts("train") idx = train_dev_idx() choice, probs, tokens = run_variant("train", idx, args.variant, texts, args.concurrency) bare = load_cache(cache_path("train"), key_field="idx") pending = [i for i in idx if i not in bare] if pending: print(f"{len(pending)} dev rows still lack bare-label answers; rerun after collection.") return b_choice = np.array([LABEL_LIST.index(bare[i]["choice"]) for i in idx]) b_probs = np.array([bare[i]["probs"] for i in idx]) y = y_train[idx] print(f"\nInput tokens: {tokens:,} ({tokens / len(idx):.0f}/request)") # tiers aren't meaningful on 1,000 rows; report overall + paired Δ vs bare on the same rows for name, p, pr in [("bare labels", b_choice, b_probs), (args.variant, choice, probs)]: print(f" {name:<12} acc {np.mean(p == y):.3f} macro F1 {macro_f1(y, p):.3f} ECE {ece(y, pr):.3f}") d, (lo, hi) = paired_bootstrap(y, choice, b_choice) acc_d = np.mean(choice == y) - np.mean(b_choice == y) print(f" Δ macro F1 {args.variant} − bare = {d:+.3f} [{lo:+.3f}, {hi:+.3f}] | Δ acc {acc_d:+.3f}") pc, bc, tc = Counter(choice), Counter(b_choice), Counter(y) moved = sorted(set(pc) | set(bc), key=lambda l: -abs(pc[l] - bc[l]))[:10] print(f"\n Biggest shifts in predicted-label counts (bare -> {args.variant}, true):") for l in moved: print(f" {LABEL_LIST[l][:60]:<60} {bc[l]:>4} -> {pc[l]:>4} (true {tc[l]})") def design_idx(n): """Seeded train rows outside the dev slice, for looking at a variant's errors.""" dev = set(train_dev_idx()) pool = [i for i in range(len(load_course_data()[0])) if i not in dev] return sorted(np.random.default_rng(7).choice(pool, size=n, replace=False).tolist()) def cmd_criteria_design(args): """Run a variant on design rows (never the dev slice) and show where it still errs.""" from collections import Counter texts, y_train = split_texts("train") idx = design_idx(args.n) choice, _, tokens = run_variant("train", idx, args.variant, texts, args.concurrency) y = y_train[idx] print(f"\n{args.variant} on {len(idx)} design rows: acc {np.mean(choice == y):.3f}, " f"macro F1 {macro_f1(y, choice):.3f}") pc, tc = Counter(choice), Counter(y) hit = Counter(y[choice == y]) print(f"\n{'label':<62} {'true':>5} {'pred':>5} {'recall':>7} {'prec':>6}") for l in sorted(set(tc) | set(pc), key=lambda l: -abs(pc[l] - tc[l]))[:args.top]: print(f"{LABEL_LIST[l][:62]:<62} {tc[l]:>5} {pc[l]:>5} {hit[l] / max(tc[l], 1):>7.2f} " f"{hit[l] / max(pc[l], 1):>6.2f}") conf = Counter((a, b) for a, b in zip(y, choice) if a != b) print(f"\nTop confusions (true -> {args.variant}) of {sum(conf.values())} errors:") for (t, p_), c in conf.most_common(args.top): print(f" {c:>4} {LABEL_LIST[t][:55]:<55} -> {LABEL_LIST[p_][:55]}") def cmd_criteria_val(args): texts, y_val = split_texts("val") choice, probs, tokens = run_variant("val", list(range(len(y_val))), args.variant, texts, args.concurrency) comps, tiers = load_comparators(y_val) b_probs, b_choice = jev_probs("val") name = f"Jev + structured criteria ({args.variant})" rows = {"Jev zero-shot (bare labels)": (b_choice, b_probs), name: (choice, probs)} for c in comps[:2]: rows[c["name"]] = (c["preds"], c["probs"]) pairs = [(name, "Jev zero-shot (bare labels)")] + [(name, c["name"]) for c in comps[:2]] res = report(f"CRITERIA {args.variant} — canonical val (6,430)", rows, y_val, tiers, pairs) res["input_tokens"] = int(tokens) (OUT_DIR / f"{MODEL}_criteria_{args.variant}_val_results.json").write_text(json.dumps(res, indent=2)) print(f"\n Input tokens {tokens:,}. Saved results JSON.") def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) c = sub.add_parser("collect", help="bare-label Jev answers for a whole split") c.add_argument("--split", choices=SPLITS, required=True) c.add_argument("--concurrency", type=int, default=12) sub.add_parser("features", help="LR on Jev probs vs TF-IDF (no API calls)") c = sub.add_parser("confusions", help="bare-label Jev errors on train, dev slice excluded") c.add_argument("--top-labels", type=int, default=30) c.add_argument("--top-pairs", type=int, default=30) c.add_argument("--examples-for", type=int, default=0, help="show texts for top-N pairs") c.add_argument("--k", type=int, default=4) c.add_argument("--chars", type=int, default=400) c = sub.add_parser("criteria-design") c.add_argument("--variant", required=True) c.add_argument("--n", type=int, default=1500) c.add_argument("--top", type=int, default=25) c.add_argument("--concurrency", type=int, default=6) for name in ("criteria-dev", "criteria-val"): c = sub.add_parser(name) c.add_argument("--variant", required=True) c.add_argument("--concurrency", type=int, default=12) args = ap.parse_args() {"collect": cmd_collect, "features": cmd_features, "confusions": cmd_confusions, "criteria-dev": cmd_criteria_dev, "criteria-design": cmd_criteria_design, "criteria-val": cmd_criteria_val}[args.cmd](args) if __name__ == "__main__": main()