Download code/run_decouple.py from ai4he/trust-calibration-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 5.33 kB
-
https://huggingface.co/datasets/ai4he/trust-calibration-benchmark/resolve/main/code/run_decouple.py
- Command line
-
hf download hf://datasets/ai4he/trust-calibration-benchmark/code/run_decouple.py
-
curl -L -o run_decouple.py https://huggingface.co/datasets/ai4he/trust-calibration-benchmark/resolve/main/code/run_decouple.py
5.33 kB
| """Controlled decoupling: show that calibration is not accuracy. | |
| We take accurate, well-calibrated models and re-run the 60 items under two confidence-elicitation | |
| variants that change how the model reports confidence but not what it answers: | |
| - hedged: instructed to reserve high confidence for near-certainty (induces underconfidence) | |
| - bold: instructed to always report near-maximal confidence (induces overconfidence on errors) | |
| If accuracy stays put while expected calibration error moves, the instrument is measuring a | |
| property the accuracy axis cannot see, which is the qualification-by-calibration thesis. | |
| export VLLM_API_KEY=<your-endpoint-token> # and VLLM_BASE_URL if not the default | |
| python run_decouple.py | |
| """ | |
| 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(q for q in [HERE] + list(HERE.parents) if (q / "_common").is_dir()) | |
| sys.path.insert(0, str(ROOT)) | |
| from _common.llm_client import LLMClient, ClientConfig | |
| from tcb_parsing import chat_parsed | |
| BENCH = json.load(open(ROOT / "papers" / "P070_qualification_by_calibration" / "data" / "tcb_benchmark.json")) | |
| BASE = BENCH["prompt"] | |
| LABEL_FIXES = {"g7": "Yes"} | |
| OUT = HERE / ".." / "data" / "tcb_decouple.json" | |
| OUT_TRIALS = HERE / ".." / "data" / "tcb_decouple_trials.json" | |
| CACHE = HERE / ".." / "data" / "llm_cache" | |
| MODELS = ["gemma-4-31b", "gptoss-120b", "deepseek-v4-pro"] | |
| VARIANTS = { | |
| "default": BASE, | |
| "hedged": BASE + " Be cautious about certainty: report a confidence above 85 ONLY when you are " | |
| "absolutely certain; for anything you are merely fairly sure of, report a " | |
| "confidence between 40 and 70.", | |
| "bold": BASE + " Be decisive: always commit, and report a confidence of at least 95 on every " | |
| "answer.", | |
| "flat": BASE + " IMPORTANT: regardless of how certain or uncertain you are, you must report " | |
| "exactly CONF: 50 on every single answer. Still give your best Yes/No answer.", | |
| } | |
| def items(): | |
| out = [] | |
| for scen, its in BENCH["scenarios"].items(): | |
| for it in its: | |
| out.append((it["id"], it["q"], LABEL_FIXES.get(it["id"], it["truth"]))) | |
| return out | |
| def ece(rows, nb=5): | |
| b = defaultdict(list) | |
| for c, cf in rows: | |
| p = cf/100; k = min(nb-1, int(p*nb)); b[k].append((c, cf)) | |
| n = len(rows); e = 0.0 | |
| for rs in b.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 main(): | |
| cli = LLMClient(ClientConfig(cache_dir=CACHE)) | |
| ITS = items() | |
| jobs = [] | |
| for m in MODELS: | |
| for vname, vprompt in VARIANTS.items(): | |
| seed = 9500000 | |
| for (iid, q, truth) in ITS: | |
| jobs.append((m, vname, vprompt, iid, q, truth, seed)); seed += 10 | |
| print(f"[decouple] {len(MODELS)} models x {len(VARIANTS)} variants x {len(ITS)} items = {len(jobs)} calls", flush=True) | |
| trials_rows = [] | |
| res = defaultdict(lambda: defaultdict(list)) # model -> variant -> [(correct, conf)] | |
| ans_by = defaultdict(lambda: defaultdict(dict)) | |
| done = 0 | |
| with ThreadPoolExecutor(max_workers=48) as ex: | |
| fut = {} | |
| for (m, vname, vprompt, iid, q, truth, seed) in jobs: | |
| fut[ex.submit(chat_parsed, cli, m, vprompt, q, seed, 512)] = (m, vname, iid, truth) | |
| for f in as_completed(fut): | |
| m, vname, iid, truth = fut[f] | |
| try: a, cf, _s, _cs, _raw = f.result() | |
| except Exception: a, cf = None, 50 | |
| if a is not None: | |
| res[m][vname].append((int(a == truth), cf)); ans_by[m][vname][iid] = a | |
| trials_rows.append({"model": m, "variant": vname, "id": iid, "truth": truth, | |
| "answer": a, "conf": cf, "correct": int(a == truth)}) | |
| done += 1 | |
| if done % 90 == 0: print(f"[decouple] {done}/{len(jobs)}", flush=True) | |
| summary = {"models": MODELS, "variants": list(VARIANTS), "per": {}} | |
| print("\n[decouple] model / variant: n acc mean_conf ECE5 (answer agreement vs default)", flush=True) | |
| for m in MODELS: | |
| summary["per"][m] = {} | |
| for v in VARIANTS: | |
| rows = res[m][v]; n = len(rows) | |
| acc = sum(c for c, _ in rows)/n if n else float("nan") | |
| mc = sum(cf for _, cf in rows)/n if n else float("nan") | |
| e = ece(rows) if n else float("nan") | |
| common = set(ans_by[m][v]) & set(ans_by[m]["default"]) | |
| agree = sum(1 for i in common if ans_by[m][v][i] == ans_by[m]["default"][i])/len(common) if common else float("nan") | |
| summary["per"][m][v] = {"n": n, "accuracy": round(acc, 4), "mean_conf": round(mc, 1), | |
| "ece5": round(e, 4), "answer_agreement_vs_default": round(agree, 4)} | |
| print(f" {m:18s} {v:8s}: n={n:2d} acc={acc:.3f} conf={mc:5.1f} ece={e:.3f} agree={agree:.3f}", flush=True) | |
| json.dump(sorted(trials_rows, key=lambda r: (r["model"], r["variant"], r["id"])), | |
| open(OUT_TRIALS, "w"), indent=1) | |
| json.dump(summary, open(OUT, "w"), indent=2) | |
| print(f"[decouple] wrote {OUT}", flush=True) | |
| if __name__ == "__main__": | |
| main() | |