stable / dataset_upload /metrics /bcs_bes.py
LucasLoading's picture
Upload 30 files
6f2ed01 verified
Raw
History Blame Contribute Delete
7.14 kB
#!/usr/bin/env python
"""BCS and BES from the judge's semantic clusters. (protocol 4, 5, 6)
python src/bcs_bes.py --model Llama-3.2-1B
Family-balanced, per protocol 4.1: the distribution over answer clusters is
computed WITHIN each condition family first, then the families are averaged with
equal weight. Counting raw queries instead would let paraphrase (10,053) and
multilingual (12,010) drown out anchor (2,592), and the headline number would
mostly measure how many variants we happened to write.
p(a) = mean over families of (share of that family's queries in cluster a)
BCS = max_a p(a)
BES = 1 - H(p)/log A (1 when only one cluster was observed)
BCS deliberately does not consult correctness: a model that answers "Sydney" for
every phrasing of Australia's capital scores BCS = 1. That is the point --
protocol 6 then splits stable behaviour into Stable Correct and Stable Wrong
using the judge's reference-aware pass.
"""
import os, sys, math, argparse, collections
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mcommon as mc
def bcs_bes(assignments, families):
"""assignments: [(condition_family, cluster_id)] for one fact."""
counts = collections.defaultdict(collections.Counter)
for fam, cid in assignments:
counts[fam][cid] += 1
valid = [t for t in families if counts[t]]
if not valid:
return None
clusters = {c for t in valid for c in counts[t]}
p = {c: sum(counts[t][c] / sum(counts[t].values()) for t in valid) / len(valid)
for c in clusters}
modal = max(p, key=p.get)
pos = [v for v in p.values() if v > 0]
if len(pos) == 1:
bes = 1.0
else:
H = -sum(v * math.log(v) for v in pos)
bes = 1.0 - H / math.log(len(pos))
return {"bcs": p[modal], "bes": bes, "modal_cluster": modal,
"cluster_distribution": p, "valid_families": valid}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True)
ap.add_argument("--coverage", choices=["complete_family", "full_set"], default=None)
ap.add_argument("--sample", type=int, default=0,
help="score only the same fixed subset judge_run.py sampled")
ap.add_argument("--sample-seed", type=int, default=20260101)
args = ap.parse_args()
C = mc.cfg()
mode = args.coverage or C["headline_coverage"]
fams = C["main_families"]
tau = C["behavior"]["tau_b"]
keep = set(mc.eval_fact_set(mode))
if args.sample:
# Reproduce judge_run.py's draw exactly. A judge file can hold extra
# facts -- a debug run, or a --resume over an earlier partial pass --
# and scoring whatever happens to be in the file would give different
# models different fact sets, which protocol 1.3 forbids.
allf = sorted(mc.facts())
rng = np.random.default_rng(args.sample_seed)
pick = set(np.array(allf)[rng.choice(len(allf), size=args.sample,
replace=False)].tolist())
keep &= pick
rel_of = mc.fact_relation()
jpath = mc.out("metrics", "judge", f"{args.model}.jsonl")
if not os.path.exists(jpath):
raise SystemExit(f"no judge output for {args.model}; run src/judge_run.py")
per_fact, groups = [], collections.Counter()
for rec in mc.read_jsonl(jpath):
fid = rec["fact_id"]
if fid not in keep:
continue
label = {c["cluster_id"]: c for c in rec["clusters"]}
res = bcs_bes([(a["condition_family"], a["cluster_id"])
for a in rec["assignments"]], fams)
if res is None:
continue
modal = label.get(res["modal_cluster"], {})
correctness = modal.get("correctness", "REVIEW_REQUIRED")
status = modal.get("status", "ANSWER")
# Protocol 6: the four behaviour groups partition the fact set, so every
# fact lands in exactly one and the four rates sum to 1.
if res["bcs"] < tau:
grp = "Unstable"
elif status == "ABSTAIN" or correctness == "ABSTAIN":
grp = "Stable Abstention"
elif correctness == "CORRECT":
grp = "Stable Correct"
elif correctness == "INCORRECT":
grp = "Stable Wrong"
else:
grp = "Stable Unresolved"
groups[grp] += 1
per_fact.append({"model": args.model, "fact_id": fid, "relation": rel_of[fid],
"bcs": res["bcs"], "bes": res["bes"],
"modal_cluster": res["modal_cluster"],
"modal_correctness": correctness, "behavior_group": grp,
"valid_families": res["valid_families"]})
if not per_fact:
raise SystemExit(f"{args.model}: no facts scored")
mc.write_jsonl(mc.out("metrics", "behavioral", f"{args.model}.{mode}.per_fact.jsonl"),
per_fact)
n = len(per_fact)
bs = C["bootstrap"]
boot_bcs = mc.relation_clustered_bootstrap(
{r["fact_id"]: r["bcs"] for r in per_fact}, rel_of,
bs["n_resamples"], bs["seed"], bs["ci"])
boot_bes = mc.relation_clustered_bootstrap(
{r["fact_id"]: r["bes"] for r in per_fact}, rel_of,
bs["n_resamples"], bs["seed"], bs["ci"])
# Protocol 6: threshold sensitivity, because tau_b = 0.8 is a choice.
sens = {}
for t in C["behavior"]["tau_sensitivity"]:
sens[str(t)] = {"stable_rate": float(np.mean([r["bcs"] >= t for r in per_fact])),
"stable_correct": float(np.mean(
[r["bcs"] >= t and r["modal_correctness"] == "CORRECT"
for r in per_fact]))}
summary = {
"model": args.model, "coverage_mode": mode, "n_facts": n, "tau_b": tau,
"bcs": boot_bcs["mean"], "bcs_ci95": [boot_bcs["lo"], boot_bcs["hi"]],
"bes": boot_bes["mean"], "bes_ci95": [boot_bes["lo"], boot_bes["hi"]],
"stable_correct_rate": groups["Stable Correct"] / n,
"stable_wrong_rate": groups["Stable Wrong"] / n,
"stable_abstention_rate": groups["Stable Abstention"] / n,
"stable_unresolved_rate": groups["Stable Unresolved"] / n,
"unstable_rate": groups["Unstable"] / n,
"behavior_counts": dict(groups),
"tau_sensitivity": sens,
}
tot = sum(summary[k] for k in ("stable_correct_rate", "stable_wrong_rate",
"stable_abstention_rate", "stable_unresolved_rate",
"unstable_rate"))
if abs(tot - 1.0) > 1e-6:
raise SystemExit(f"behaviour rates sum to {tot}, not 1 (protocol 6)")
mc.write_json(mc.out("metrics", "behavioral", f"{args.model}.{mode}.summary.json"),
summary)
print(f"[{args.model}] BCS={summary['bcs']:.4f} BES={summary['bes']:.4f} "
f"SC={summary['stable_correct_rate']:.3f} SW={summary['stable_wrong_rate']:.3f} "
f"SA={summary['stable_abstention_rate']:.3f} "
f"U={summary['unstable_rate']:.3f} n={n} BCSBES_DONE")
if __name__ == "__main__":
main()