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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""HaluEval + FEVER hallucination AUROC for SRT-Adapter v8a.
|
| 3 |
+
|
| 4 |
+
For each benchmark we score the mean r_hat (BEN reflexivity) over each candidate
|
| 5 |
+
text and compute an AUROC where the "positive" class is the hallucination /
|
| 6 |
+
refuted claim.
|
| 7 |
+
|
| 8 |
+
HaluEval QA (pminervini/HaluEval, 'qa'): paired (question + right_answer) vs
|
| 9 |
+
(question + hallucinated_answer). AUROC = does mean r_hat distinguish?
|
| 10 |
+
|
| 11 |
+
FEVER (copenlu/fever_gold_evidence, 'validation'): claim alone, label in
|
| 12 |
+
{SUPPORTS, REFUTES, NOT ENOUGH INFO}. AUROC computed on SUPPORTS vs REFUTES.
|
| 13 |
+
|
| 14 |
+
Usage:
|
| 15 |
+
python scripts/hallucination_auroc.py --bench halueval --max-samples 500
|
| 16 |
+
python scripts/hallucination_auroc.py --bench fever --max-samples 500
|
| 17 |
+
python scripts/hallucination_auroc.py --bench both --max-samples 500
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import json
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
from sklearn.metrics import roc_auc_score
|
| 30 |
+
from transformers import AutoTokenizer
|
| 31 |
+
|
| 32 |
+
HERE = Path(__file__).resolve().parent
|
| 33 |
+
ROOT = HERE.parent
|
| 34 |
+
sys.path.insert(0, str((ROOT / "src").resolve()))
|
| 35 |
+
|
| 36 |
+
from srt.adapter import SRTAdapter # noqa: E402
|
| 37 |
+
from srt.config import ( # noqa: E402
|
| 38 |
+
SRTConfig, MAHConfig, RRMConfig, BENConfig, CommunityConfig, LossConfig,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def build_config(p: Path) -> SRTConfig:
|
| 43 |
+
raw = json.loads(p.read_text())
|
| 44 |
+
return SRTConfig(
|
| 45 |
+
backbone_id=raw["backbone_id"],
|
| 46 |
+
backbone_dtype=raw["backbone_dtype"],
|
| 47 |
+
mah_layer_indices=list(raw["mah_layer_indices"]),
|
| 48 |
+
rrm_inject_indices=list(raw["rrm_inject_indices"]),
|
| 49 |
+
community_layer_idx=raw["community_layer_idx"],
|
| 50 |
+
num_mah_layers=raw["num_mah_layers"],
|
| 51 |
+
mah=MAHConfig(**raw["mah"]),
|
| 52 |
+
rrm=RRMConfig(**raw["rrm"]),
|
| 53 |
+
ben=BENConfig(**raw["ben"]),
|
| 54 |
+
community=CommunityConfig(**raw["community"]),
|
| 55 |
+
loss=LossConfig(**{k: v for k, v in raw["loss"].items() if k in LossConfig.__dataclass_fields__}),
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def load_model(config_path: Path, adapter_path: Path, device: str):
|
| 60 |
+
config = build_config(config_path)
|
| 61 |
+
model = SRTAdapter(config).to(device)
|
| 62 |
+
if adapter_path.suffix == ".safetensors":
|
| 63 |
+
from safetensors.torch import load_file
|
| 64 |
+
state = load_file(str(adapter_path), device=device)
|
| 65 |
+
else:
|
| 66 |
+
state = torch.load(str(adapter_path), map_location=device)
|
| 67 |
+
model.load_state_dict(state, strict=False)
|
| 68 |
+
model.eval()
|
| 69 |
+
tok = AutoTokenizer.from_pretrained(config.backbone_id)
|
| 70 |
+
return model, tok
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@torch.no_grad()
|
| 74 |
+
def score_text(model, tok, text: str, device: str, max_len: int = 256) -> dict:
|
| 75 |
+
"""Return all candidate hallucination signals for a text."""
|
| 76 |
+
enc = tok(text, return_tensors="pt", truncation=True, max_length=max_len).to(device)
|
| 77 |
+
out = model(input_ids=enc.input_ids, attention_mask=enc.attention_mask)
|
| 78 |
+
if out.ben_output is None:
|
| 79 |
+
return {"r_hat_mean": float("nan"), "p_super_mean": float("nan"),
|
| 80 |
+
"p_super_max": float("nan"), "div2_mean": float("nan")}
|
| 81 |
+
r_hat = out.ben_output.r_hat[0].float()
|
| 82 |
+
p_super = torch.softmax(out.ben_output.regime_logits[0].float(), dim=-1)[:, 1]
|
| 83 |
+
div2 = out.divergences[2][0].norm(dim=-1).float() if len(out.divergences) >= 3 else torch.tensor([0.0])
|
| 84 |
+
return {
|
| 85 |
+
"r_hat_mean": float(r_hat.mean().cpu()),
|
| 86 |
+
"p_super_mean": float(p_super.mean().cpu()),
|
| 87 |
+
"p_super_max": float(p_super.max().cpu()),
|
| 88 |
+
"div2_mean": float(div2.mean().cpu()),
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def auroc_for_signal(scores_pos, scores_neg, signal_key: str) -> float:
|
| 93 |
+
pos = [s[signal_key] for s in scores_pos]
|
| 94 |
+
neg = [s[signal_key] for s in scores_neg]
|
| 95 |
+
y = [1] * len(pos) + [0] * len(neg)
|
| 96 |
+
s = pos + neg
|
| 97 |
+
return float(roc_auc_score(y, s))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def run_halueval(model, tok, device, max_samples: int, max_len: int) -> dict:
|
| 101 |
+
from datasets import load_dataset
|
| 102 |
+
ds = load_dataset("pminervini/HaluEval", "qa", split="data")
|
| 103 |
+
n = min(len(ds), max_samples)
|
| 104 |
+
print(f"[halueval] {n} examples")
|
| 105 |
+
pos, neg = [], [] # pos = hallucinated, neg = right
|
| 106 |
+
t0 = time.time()
|
| 107 |
+
for i in range(n):
|
| 108 |
+
ex = ds[i]
|
| 109 |
+
q = ex["question"]
|
| 110 |
+
neg.append(score_text(model, tok, f"Q: {q}\nA: {ex['right_answer']}", device, max_len))
|
| 111 |
+
pos.append(score_text(model, tok, f"Q: {q}\nA: {ex['hallucinated_answer']}", device, max_len))
|
| 112 |
+
if (i + 1) % 100 == 0:
|
| 113 |
+
print(f" [{i+1}/{n}] elapsed={time.time()-t0:.1f}s")
|
| 114 |
+
aurocs = {k: auroc_for_signal(pos, neg, k)
|
| 115 |
+
for k in ("r_hat_mean", "p_super_mean", "p_super_max", "div2_mean")}
|
| 116 |
+
paired_acc = {k: float(sum(1 for p, n_ in zip(pos, neg) if p[k] > n_[k]) / len(pos))
|
| 117 |
+
for k in aurocs}
|
| 118 |
+
return {
|
| 119 |
+
"n_pairs": n,
|
| 120 |
+
"auroc_unpaired": aurocs,
|
| 121 |
+
"paired_accuracy_hall_gt_right": paired_acc,
|
| 122 |
+
"wall_time_sec": time.time() - t0,
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def run_fever(model, tok, device, max_samples: int, max_len: int) -> dict:
|
| 127 |
+
from datasets import load_dataset
|
| 128 |
+
ds = load_dataset("copenlu/fever_gold_evidence", split="validation")
|
| 129 |
+
keep = [ex for ex in ds if ex["label"] in ("SUPPORTS", "REFUTES")]
|
| 130 |
+
if max_samples > 0 and len(keep) > max_samples:
|
| 131 |
+
sup = [ex for ex in keep if ex["label"] == "SUPPORTS"][:max_samples // 2]
|
| 132 |
+
ref = [ex for ex in keep if ex["label"] == "REFUTES"][:max_samples // 2]
|
| 133 |
+
keep = sup + ref
|
| 134 |
+
print(f"[fever] {len(keep)} examples ({sum(1 for e in keep if e['label']=='REFUTES')} REFUTES)")
|
| 135 |
+
pos, neg = [], []
|
| 136 |
+
t0 = time.time()
|
| 137 |
+
for i, ex in enumerate(keep):
|
| 138 |
+
s = score_text(model, tok, ex["claim"], device, max_len)
|
| 139 |
+
(pos if ex["label"] == "REFUTES" else neg).append(s)
|
| 140 |
+
if (i + 1) % 100 == 0:
|
| 141 |
+
print(f" [{i+1}/{len(keep)}] elapsed={time.time()-t0:.1f}s")
|
| 142 |
+
aurocs = {k: auroc_for_signal(pos, neg, k)
|
| 143 |
+
for k in ("r_hat_mean", "p_super_mean", "p_super_max", "div2_mean")}
|
| 144 |
+
return {
|
| 145 |
+
"n_samples": len(keep),
|
| 146 |
+
"n_refutes": len(pos),
|
| 147 |
+
"auroc_refutes_vs_supports": aurocs,
|
| 148 |
+
"wall_time_sec": time.time() - t0,
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def main() -> None:
|
| 153 |
+
ap = argparse.ArgumentParser()
|
| 154 |
+
ap.add_argument("--config", default=str(ROOT / "config.json"))
|
| 155 |
+
ap.add_argument("--adapter", default=str(ROOT / "adapter.safetensors"))
|
| 156 |
+
ap.add_argument("--bench", choices=("halueval", "fever", "both"), default="both")
|
| 157 |
+
ap.add_argument("--max-samples", type=int, default=500)
|
| 158 |
+
ap.add_argument("--max-len", type=int, default=256)
|
| 159 |
+
args = ap.parse_args()
|
| 160 |
+
|
| 161 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 162 |
+
model, tok = load_model(Path(args.config), Path(args.adapter), device)
|
| 163 |
+
print(f"loaded adapter on {device}")
|
| 164 |
+
|
| 165 |
+
results: dict = {}
|
| 166 |
+
if args.bench in ("halueval", "both"):
|
| 167 |
+
results["halueval_qa"] = run_halueval(model, tok, device, args.max_samples, args.max_len)
|
| 168 |
+
a = results["halueval_qa"]["auroc_unpaired"]
|
| 169 |
+
print(f"[halueval] AUROC: r_hat={a['r_hat_mean']:.3f} "
|
| 170 |
+
f"p_super_mean={a['p_super_mean']:.3f} "
|
| 171 |
+
f"p_super_max={a['p_super_max']:.3f} "
|
| 172 |
+
f"div2={a['div2_mean']:.3f}")
|
| 173 |
+
if args.bench in ("fever", "both"):
|
| 174 |
+
results["fever"] = run_fever(model, tok, device, args.max_samples, args.max_len)
|
| 175 |
+
a = results["fever"]["auroc_refutes_vs_supports"]
|
| 176 |
+
print(f"[fever] AUROC: r_hat={a['r_hat_mean']:.3f} "
|
| 177 |
+
f"p_super_mean={a['p_super_mean']:.3f} "
|
| 178 |
+
f"p_super_max={a['p_super_max']:.3f} "
|
| 179 |
+
f"div2={a['div2_mean']:.3f}")
|
| 180 |
+
|
| 181 |
+
out = ROOT / "benchmarks" / "hallucination_auroc.json"
|
| 182 |
+
out.write_text(json.dumps(results, indent=2))
|
| 183 |
+
print(f"\nwrote {out}")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
main()
|