"""Criterion validity: do TCB verdicts predict downstream task behavior? Pre-committed design (declared before seeing results): run the full nine-model panel on two downstream tasks disjoint from the benchmark, with the same final-line answer+confidence elicitation, and test whether TCB accuracy and TCB calibration error predict downstream accuracy and calibration error (Spearman rank correlation over the nine models), and whether the models passing a TCB admission gate (accuracy >= 0.90 and ECE-5 <= 0.05) outperform the models failing it downstream. Downstream task A (annotation): SST-2 sentiment, the canonical crowdsourcing annotation task family; the first 100 validation sentences, asked as "Is the sentiment positive?" (gold = label). Downstream task B (computable QA): the 54-item computable-gold battery released with the companion reporting-standard paper (six domains; every gold label re-derivable by execution). Outputs: data/tcb_criterion_trials.json (per-trial) and data/tcb_criterion.json (summary). Requires the model endpoint (VLLM_API_KEY); analysis of the shipped outputs is offline. """ import json, re, sys, pathlib, math from concurrent.futures import ThreadPoolExecutor, as_completed from collections import defaultdict HERE = pathlib.Path(__file__).resolve().parent ROOT = next(p for p in [HERE] + list(HERE.parents) if (p / "_common").is_dir()) sys.path.insert(0, str(ROOT)) from _common.llm_client import LLMClient, ClientConfig from tcb_parsing import parse, chat_parsed CACHE = HERE / ".." / "data" / "llm_cache" OUT_TRIALS = HERE / ".." / "data" / "tcb_criterion_trials.json" OUT_SUMMARY = HERE / ".." / "data" / "tcb_criterion.json" PANEL_RESULTS = ROOT / "papers" / "P070_qualification_by_calibration" / "data" / "tcb_v03_results.json" BATTERY = ROOT / "papers" / "P065_wisdom_of_the_model_crowd" / "data" / "complementary_battery.json" MODELS = ["glm-5.1-fp8", "deepseek-v4-pro", "gemma-4-31b", "gptoss-120b", "leanstral-2603", "qwen3-omni-30b-a3b", "qwen3.6-35b-a3b-fp8", "qwen3.6-27b-fp8", "qwen3.5-9b"] PROMPT = "Answer Yes/No and confidence 0-100. ON THE LAST LINE ONLY: ANSWER: Yes|No | CONF: <0-100>" MAX_TOKENS = 512 GATE_ACC, GATE_ECE = 0.90, 0.05 def sst2_items(n=100): from datasets import load_dataset ds = load_dataset("stanfordnlp/sst2", split="validation") out = [] for i in range(n): ex = ds[i] q = ("Is the sentiment of the following movie review positive?\n\n" f"Review: {ex['sentence'].strip()}") out.append((f"sst{i}", q, "Yes" if ex["label"] == 1 else "No")) return out def battery_items(): bench = json.load(open(BATTERY)) return [(it["id"], it["q"], it["truth"]) for it in bench["items"]] def ece(rows, nb=5): bins = defaultdict(list) for c, cf in rows: p = cf / 100; k = min(nb - 1, int(p * nb)); bins[k].append((c, cf)) n = len(rows); e = 0.0 for rs in bins.values(): mc = sum(cf / 100 for _, cf in rs) / len(rs); ma = sum(c for c, _ in rs) / len(rs) e += len(rs) / n * abs(mc - ma) return e def spearman(xs, ys): def rank(v): order = sorted(range(len(v)), key=lambda i: v[i]) r = [0.0] * len(v); i = 0 while i < len(order): j = i while j + 1 < len(order) and v[order[j + 1]] == v[order[i]]: j += 1 avg = (i + j) / 2 + 1 for k in range(i, j + 1): r[order[k]] = avg i = j + 1 return r rx, ry = rank(xs), rank(ys) mx, my = sum(rx) / len(rx), sum(ry) / len(ry) num = sum((a - mx) * (b - my) for a, b in zip(rx, ry)) den = math.sqrt(sum((a - mx) ** 2 for a in rx) * sum((b - my) ** 2 for b in ry)) return num / den if den else float("nan") def main(): cli = LLMClient(ClientConfig(cache_dir=CACHE)) tasks = {"sst2": sst2_items(), "battery": battery_items()} jobs = [] for task, items in tasks.items(): for m in MODELS: seed = 10000000 if task == "sst2" else 8000000 for (iid, q, truth) in items: jobs.append((task, m, iid, q, truth, seed)); seed += 10 print(f"[criterion] {len(jobs)} calls " f"({len(MODELS)} models x ({len(tasks['sst2'])} sst2 + {len(tasks['battery'])} battery))", flush=True) trials = [] done = 0 with ThreadPoolExecutor(max_workers=64) as ex: fut = {} for (task, m, iid, q, truth, seed) in jobs: fut[ex.submit(chat_parsed, cli, m, PROMPT, q, seed, MAX_TOKENS)] = (task, m, iid, truth) for f in as_completed(fut): task, m, iid, truth = fut[f] try: ans, conf, _s, conf_stated_v, _raw = f.result() conf = conf if (conf_stated_v or conf is None) else None except Exception: ans, conf = None, None trials.append({"task": task, "model": m, "id": iid, "truth": truth, "answer": ans, "conf": conf, "conf_stated": int(conf is not None), "correct": (int(ans == truth) if ans is not None else None)}) done += 1 if done % 200 == 0: print(f"[criterion] {done}/{len(jobs)}", flush=True) json.dump(trials, open(OUT_TRIALS, "w"), indent=1) panel = json.load(open(PANEL_RESULTS))["per_model"] tcb_acc = {m: panel[m]["accuracy"] for m in MODELS} tcb_ece = {m: panel[m]["ece5"] for m in MODELS} passes = [m for m in MODELS if tcb_acc[m] >= GATE_ACC and tcb_ece[m] <= GATE_ECE] fails = [m for m in MODELS if m not in passes] summary = {"gate": {"accuracy_min": GATE_ACC, "ece5_max": GATE_ECE, "pass": passes, "fail": fails}, "per_task": {}} for task in tasks: rows_by = defaultdict(list) for r in trials: if r["task"] == task and r["answer"] is not None: rows_by[r["model"]].append((r["correct"], r["conf"] if r["conf"] is not None else 50)) accs = {m: sum(c for c, _ in rows_by[m]) / len(rows_by[m]) for m in MODELS} eces = {m: ece(rows_by[m]) for m in MODELS} rho_acc = spearman([tcb_acc[m] for m in MODELS], [accs[m] for m in MODELS]) rho_ece = spearman([tcb_ece[m] for m in MODELS], [eces[m] for m in MODELS]) gp = sum(accs[m] for m in passes) / len(passes) gf = sum(accs[m] for m in fails) / len(fails) gpe = sum(eces[m] for m in passes) / len(passes) gfe = sum(eces[m] for m in fails) / len(fails) summary["per_task"][task] = { "n_items": len(tasks[task]), "per_model": {m: {"n": len(rows_by[m]), "accuracy": round(accs[m], 4), "ece5": round(eces[m], 4)} for m in MODELS}, "spearman_tcbacc_vs_acc": round(rho_acc, 3), "spearman_tcbece_vs_ece": round(rho_ece, 3), "gate_pass_mean_acc": round(gp, 4), "gate_fail_mean_acc": round(gf, 4), "gate_pass_mean_ece": round(gpe, 4), "gate_fail_mean_ece": round(gfe, 4), "pass_min_acc": round(min(accs[m] for m in passes), 4), "fail_max_acc": round(max(accs[m] for m in fails), 4), } print(f"\n[{task}] rho(acc)={rho_acc:.3f} rho(ece)={rho_ece:.3f} " f"pass acc {gp:.3f} vs fail acc {gf:.3f} | pass ece {gpe:.3f} vs fail ece {gfe:.3f}", flush=True) for m in MODELS: print(f" {m:22s} n={len(rows_by[m]):3d} acc={accs[m]:.3f} ece={eces[m]:.3f}", flush=True) json.dump(summary, open(OUT_SUMMARY, "w"), indent=2) print(f"\n[criterion] wrote {OUT_TRIALS} and {OUT_SUMMARY}", flush=True) if __name__ == "__main__": main()