trust-calibration-benchmark / code /run_repeat_v03.py
carlostoxtli's picture
Upload Trust-Calibration Benchmark (TCB) v1.0.0
f8c91b8 verified
Raw History Blame Contribute Delete
5.06 kB
"""Repeated-sampling sub-study: quantify generation (run-to-run) stochasticity.
The headline panel uses one deterministic run per item (temperature 0). To characterize how
much a model's accuracy/calibration would move under nondeterministic decoding, we re-run every
item R times at temperature 0.7 with distinct seeds, and report, per model: the mean and SD of
accuracy and ECE-5 across repeats, and the per-item answer-flip rate (fraction of items whose
yes/no answer is not constant across the R repeats).
export VLLM_API_KEY=<your-endpoint-token> # and VLLM_BASE_URL if not the default
python run_repeat_v03.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"))
PROMPT = BENCH["prompt"]
OUT = HERE / ".." / "data" / "tcb_repeat_results.json"
OUT_TRIALS = HERE / ".." / "data" / "tcb_repeat_trials.json"
CACHE = HERE / ".." / "data" / "llm_cache"
LABEL_FIXES = {"g7": "Yes"}
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"]
R = 3
TEMP = 0.7
MAX_TOKENS = 512
def items():
out = []
for scen, its in BENCH["scenarios"].items():
for it in its:
truth = LABEL_FIXES.get(it["id"], it["truth"])
out.append((it["id"], it["q"], truth, it["tier"]))
return out
def ece(rows, nb=5):
b = defaultdict(list)
for r in rows:
p = r[1]/100; k = min(nb-1, int(p*nb)); b[k].append(r)
n = len(rows); e = 0.0
for rs in b.values():
cf = sum(x[1]/100 for x in rs)/len(rs); ac = sum(x[0] for x in rs)/len(rs); e += len(rs)/n*abs(cf-ac)
return e
def main():
cli = LLMClient(ClientConfig(cache_dir=CACHE))
ITS = items()
jobs = []
for m in MODELS:
for rep in range(R):
seed = 9000000 + rep*100003
for (iid, q, truth, tier) in ITS:
jobs.append((m, rep, iid, q, truth, seed)); seed += 10
print(f"[repeat] {len(MODELS)} models x {len(ITS)} items x {R} reps = {len(jobs)} calls (temp {TEMP})", flush=True)
res = defaultdict(lambda: defaultdict(dict)) # model -> rep -> id -> (correct,conf,ans)
done = 0
with ThreadPoolExecutor(max_workers=48) as ex:
fut = {}
for (m, rep, iid, q, truth, seed) in jobs:
fut[ex.submit(chat_parsed, cli, m, PROMPT, q, seed,
MAX_TOKENS, 4000, TEMP)] = (m, rep, iid, truth)
for f in as_completed(fut):
m, rep, iid, truth = fut[f]
try: ans, conf, _strict, _stated, _raw = f.result()
except Exception: ans, conf = None, 50
if ans is not None:
res[m][rep][iid] = (int(ans == truth), conf, ans)
done += 1
if done % 200 == 0: print(f"[repeat] {done}/{len(jobs)}", flush=True)
truth_of = {iid: truth for (iid, q, truth, tier) in ITS}
trials = [{"model": m, "rep": rep, "id": iid, "truth": truth_of[iid], "answer": a, "conf": cf, "correct": c}
for m in MODELS for rep in range(R) for iid, (c, cf, a) in sorted(res[m][rep].items())]
json.dump(trials, open(OUT_TRIALS, "w"), indent=1)
summary = {"R": R, "temperature": TEMP, "per_model": {}}
for m in MODELS:
accs, eces = [], []
for rep in range(R):
rows = [(c, cf) for (c, cf, a) in res[m][rep].values()]
if rows:
accs.append(sum(c for c, _ in rows)/len(rows)); eces.append(ece(rows))
# answer-flip rate across reps (items adherent in all reps)
common = set.intersection(*[set(res[m][rep].keys()) for rep in range(R)]) if all(res[m][rep] for rep in range(R)) else set()
flips = sum(1 for iid in common if len({res[m][rep][iid][2] for rep in range(R)}) > 1)
def msd(xs):
mu = sum(xs)/len(xs) if xs else float("nan")
sd = math.sqrt(sum((x-mu)**2 for x in xs)/len(xs)) if len(xs) > 1 else 0.0
return round(mu, 4), round(sd, 4)
am, asd = msd(accs); em, esd = msd(eces)
summary["per_model"][m] = {"acc_mean": am, "acc_sd": asd, "ece5_mean": em, "ece5_sd": esd,
"answer_flip_rate": round(flips/len(common), 4) if common else None,
"n_common": len(common), "per_rep_acc": [round(a, 4) for a in accs]}
print(f" {m:22s} acc {am:.3f} +/- {asd:.3f} ece5 {em:.3f} +/- {esd:.3f} flip {summary['per_model'][m]['answer_flip_rate']}", flush=True)
json.dump(summary, open(OUT, "w"), indent=2)
print(f"[repeat] wrote {OUT}")
if __name__ == "__main__":
main()