File size: 17,384 Bytes
ce6548c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""Unified evaluation suite for Tamarillo/groundedness-guard (Token-Span MIL & SeqCls)
and public groundedness / NLI baselines:
  - vectara/hallucination_evaluation_model (HHEM-2.1-Open, trust_remote_code=True, Flan-T5-base)
  - Horizon-Labs/hallucination-guard-base (ModernBERT-base, 0=UNSUPPORTED, 1=SUPPORTED)
  - MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli (DeBERTa-v3-base 3-class NLI)
  - KRLabsOrg/lettucedect-v2-mmbert-base (mmBERT-base token-span hallucination detector)
  - Tamarillo/zeroshot-policy-guard-base (Family #3 general NLI model, 0=entailment)

For TokenClassification models (Tamarillo groundedness-guard AND LettuceDetect v2), computes BOTH:
  - `suites` (default single-pass `1 - max_t P(hal_t)`, exact LettuceDetect formula)
  - `suites_topk_lme` (`1 - sigmoid(Top-6 Log-Mean-Exp(beta=2.0))`, smooth multi-token pooling)
in a SINGLE forward pass, plus per-split `ood_ragtruth` breakdown (`qa / summarization / data2txt`)!
"""

from __future__ import annotations

import argparse
import gc
import json
import os
import statistics
import time
from collections import defaultdict
from pathlib import Path
from typing import Any

import numpy as np
import torch
from sklearn.metrics import f1_score, roc_auc_score
from transformers import AutoConfig, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoTokenizer

from schema import DISTRACTOR_CHUNKS


def load_jsonl(path: Path) -> list[dict[str, Any]]:
    if not path.exists():
        return []
    with path.open("r", encoding="utf-8") as f:
        return [json.loads(ln) for ln in f if ln.strip()]


def _softmax(x: np.ndarray) -> np.ndarray:
    x32 = x.astype(np.float32)
    e = np.exp(x32 - np.max(x32, axis=-1, keepdims=True))
    return e / np.sum(e, axis=-1, keepdims=True)


def _sigmoid(x: float) -> float:
    x = max(-40.0, min(40.0, x))
    return float(1.0 / (1.0 + np.exp(-x)))


class GroundednessAdapter:
    """Returns P(consistent) in [0, 1] for every (premise, hypothesis) pair."""

    def __init__(self, name: str, path_or_id: str) -> None:
        self.name = name
        self.path_or_id = path_or_id
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        low = path_or_id.lower()

        if "vectara/hallucination_evaluation_model" in low:
            self.mode = "vectara_hhem"
            self.model = AutoModelForSequenceClassification.from_pretrained(path_or_id, trust_remote_code=True)
            self.tokenizer = None
            self.native_max_len = 4096
            self.is_deberta = False
        else:
            self.cfg = AutoConfig.from_pretrained(path_or_id)
            if hasattr(self.cfg, "reference_compile"):
                self.cfg.reference_compile = False
            archs = [str(a) for a in (getattr(self.cfg, "architectures", None) or [])]
            is_tok = ("lettucedect" in low) or any("TokenClassification" in a for a in archs)
            self.tokenizer = AutoTokenizer.from_pretrained(path_or_id, use_fast=True)
            mtype = str(getattr(self.cfg, "model_type", "")).lower()
            self.is_deberta = "deberta" in mtype
            mpe = int(getattr(self.cfg, "max_position_embeddings", 512) or 512)
            self.native_max_len = 512 if mpe in (512, 514) else min(4096, mpe)

            if is_tok:
                self.mode = "token_span"
                self.model = AutoModelForTokenClassification.from_pretrained(path_or_id, config=self.cfg)
                id2l = {int(k): str(v).lower() for k, v in (self.cfg.id2label or {}).items()}
                self.hal_idx = 1
                for k, v in id2l.items():
                    if v in ("hallucinated", "unsupported", "contradiction"):
                        self.hal_idx = k
                        break
                self.sup_idx = 1 - self.hal_idx
                print(f"[eval] {name}: mode=token_span, id2label={id2l}, hal_idx={self.hal_idx}, max_len={self.native_max_len}")
            else:
                self.mode = "seq_cls"
                self.model = AutoModelForSequenceClassification.from_pretrained(path_or_id, config=self.cfg)
                id2l = {int(k): str(v).lower() for k, v in (self.cfg.id2label or {}).items()}
                self.cons_idx = None
                for k, v in id2l.items():
                    if v in ("consistent", "supported", "entailment", "faithful"):
                        self.cons_idx = k
                        break
                if self.cons_idx is None:
                    self.cons_idx = 1 if len(id2l) == 2 else 0
                print(f"[eval] {name}: mode=seq_cls, id2label={id2l}, cons_idx={self.cons_idx}, max_len={self.native_max_len}")

        self.model.to(self.device).eval()
        self.param_count = sum(p.numel() for p in self.model.parameters())

    def predict_both(self, premises: list[str], hypotheses: list[str], batch_size: int = 16, max_length: int = 4096) -> tuple[np.ndarray, np.ndarray | None]:
        """Returns (p_primary, p_topk_lme_or_None)."""
        n = len(premises)
        out = np.zeros(n, dtype=np.float32)
        out_lme = np.zeros(n, dtype=np.float32) if self.mode == "token_span" else None
        ml = min(max_length, self.native_max_len)
        use_amp = self.device == "cuda" and not self.is_deberta
        dtype = torch.bfloat16 if (self.device == "cuda" and torch.cuda.is_bf16_supported()) else torch.float16

        if self.mode == "vectara_hhem":
            bs = 8
            for i in range(0, n, bs):
                pairs = [(p[:16000], h[:4000]) for p, h in zip(premises[i : i + bs], hypotheses[i : i + bs])]
                with torch.no_grad():
                    scores = self.model.predict(pairs)
                arr = scores.float().cpu().numpy() if hasattr(scores, "cpu") else np.asarray(scores, dtype=np.float32)
                out[i : i + bs] = np.clip(arr.reshape(-1), 0.0, 1.0)
        elif self.mode == "token_span":
            bs = 12
            for i in range(0, n, bs):
                batch_p = premises[i : i + bs]
                batch_h = hypotheses[i : i + bs]
                try:
                    enc = self.tokenizer(
                        batch_p, batch_h, padding=True, truncation="only_first", max_length=ml, return_tensors="pt"
                    )
                except Exception:
                    enc = self.tokenizer(
                        batch_p, batch_h, padding=True, truncation="longest_first", max_length=ml, return_tensors="pt"
                    )
                seq_ids_list = [enc.sequence_ids(b_i) for b_i in range(len(batch_p))]
                t_in = {k: v.to(self.device) for k, v in enc.items() if k in ("input_ids", "attention_mask")}
                with torch.no_grad():
                    with torch.amp.autocast("cuda", dtype=dtype) if use_amp else torch.no_grad():
                        logits = self.model(**t_in).logits.float().cpu().numpy()
                probs_hal = _softmax(logits)[:, :, self.hal_idx]
                z_hal = logits[:, :, self.hal_idx] - logits[:, :, self.sup_idx]
                for j, sids in enumerate(seq_ids_list):
                    ans_idxs = [t for t, sid in enumerate(sids) if sid == 1]
                    if not ans_idxs:
                        out[i + j] = 1.0
                        assert out_lme is not None
                        out_lme[i + j] = 1.0
                        continue
                    max_hal = float(np.max(probs_hal[j, ans_idxs]))
                    out[i + j] = 1.0 - max_hal
                    zv = np.sort(z_hal[j, ans_idxs])[::-1][:6]
                    beta = 2.0
                    mx = float(np.max(beta * zv))
                    lme = (mx + float(np.log(np.mean(np.exp(beta * zv - mx))))) / beta
                    assert out_lme is not None
                    out_lme[i + j] = 1.0 - _sigmoid(lme)
        else:
            for i in range(0, n, batch_size):
                bp = premises[i : i + batch_size]
                bh = hypotheses[i : i + batch_size]
                try:
                    enc = self.tokenizer(
                        bp, bh, padding=True, truncation="only_first", max_length=ml,
                        return_token_type_ids=False, return_tensors="pt",
                    )
                except Exception:
                    enc = self.tokenizer(
                        bp, bh, padding=True, truncation="longest_first", max_length=ml,
                        return_token_type_ids=False, return_tensors="pt",
                    )
                enc = {k: v.to(self.device) for k, v in enc.items()}
                with torch.no_grad():
                    with torch.amp.autocast("cuda", dtype=dtype) if use_amp else torch.no_grad():
                        logits = self.model(**enc).logits.float().cpu().numpy()
                out[i : i + batch_size] = _softmax(logits)[:, self.cons_idx]
        return out, out_lme

    def predict(self, premises: list[str], hypotheses: list[str], batch_size: int = 16, max_length: int = 4096) -> np.ndarray:
        p, _ = self.predict_both(premises, hypotheses, batch_size=batch_size, max_length=max_length)
        return p

    def bench_gpu_latency(self, seq_len: int, n_runs: int = 20) -> dict[str, Any] | None:
        if self.device != "cuda":
            return None
        eff = min(seq_len, self.native_max_len)
        pre = ("\n\n".join(DISTRACTOR_CHUNKS) * 10) if eff >= 512 else DISTRACTOR_CHUNKS[0]
        hyp = "Automated health checks verify HTTP 200 every fifteen seconds."
        if self.mode == "vectara_hhem":
            pair = [(pre[: eff * 4], hyp)]
            with torch.no_grad():
                for _ in range(4):
                    _ = self.model.predict(pair)
                torch.cuda.synchronize()
                times = []
                for _ in range(min(15, n_runs)):
                    t0 = time.perf_counter()
                    _ = self.model.predict(pair)
                    torch.cuda.synchronize()
                    times.append((time.perf_counter() - t0) * 1000.0)
        else:
            try:
                enc = self.tokenizer([pre], [hyp], padding="max_length", truncation="only_first", max_length=eff, return_token_type_ids=False, return_tensors="pt")
            except Exception:
                enc = self.tokenizer([pre], [hyp], padding="max_length", truncation="longest_first", max_length=eff, return_token_type_ids=False, return_tensors="pt")
            enc = {k: v.to(self.device) for k, v in enc.items() if k in ("input_ids", "attention_mask")}
            use_amp = not self.is_deberta
            dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
            with torch.no_grad():
                for _ in range(6):
                    with torch.amp.autocast("cuda", dtype=dtype) if use_amp else torch.no_grad():
                        _ = self.model(**enc)
                torch.cuda.synchronize()
                times = []
                for _ in range(n_runs):
                    t0 = time.perf_counter()
                    with torch.amp.autocast("cuda", dtype=dtype) if use_amp else torch.no_grad():
                        _ = self.model(**enc)
                    torch.cuda.synchronize()
                    times.append((time.perf_counter() - t0) * 1000.0)
        times.sort()
        return {
            "requested_seq_len": seq_len,
            "effective_seq_len": eff,
            "p50_ms": round(statistics.median(times), 2),
            "p95_ms": round(times[int(0.95 * (len(times) - 1))], 2),
            "gpu_name": torch.cuda.get_device_name(0),
        }

    def close(self) -> None:
        del self.model
        gc.collect()
        if torch.cuda.is_available():
            torch.cuda.empty_cache()


def _score_binary(y: np.ndarray, p_cons: np.ndarray) -> dict[str, Any]:
    yi = y.astype(int)
    pred = (p_cons >= 0.5).astype(int)
    pos_m, neg_m = (yi == 1), (yi == 0)
    hal_f1 = float(f1_score(1 - yi, 1 - pred, zero_division=0)) if neg_m.any() else None
    cons_f1 = float(f1_score(yi, pred, zero_division=0)) if pos_m.any() else None
    auc = float(roc_auc_score(yi, p_cons)) if (pos_m.any() and neg_m.any()) else None
    hal_recall = float((pred[neg_m] == 0).mean()) if neg_m.any() else None
    false_alarm = float((pred[pos_m] == 0).mean()) if pos_m.any() else None
    return {
        "n": int(len(yi)),
        "roc_auc": round(auc, 4) if auc is not None else None,
        "hal_f1": round(hal_f1, 4) if hal_f1 is not None else None,
        "cons_f1": round(cons_f1, 4) if cons_f1 is not None else None,
        "hal_recall": round(hal_recall, 4) if hal_recall is not None else None,
        "false_alarm_fpr": round(false_alarm, 4) if false_alarm is not None else None,
    }


def eval_model(ad: GroundednessAdapter, suites: dict[str, list[dict[str, Any]]]) -> dict[str, Any]:
    out: dict[str, Any] = {"params_m": round(ad.param_count / 1e6, 2), "native_max_length": ad.native_max_len, "mode": ad.mode, "suites": {}}
    lme_suites: dict[str, Any] = {}

    for sname in ("ood_ragtruth", "ood_summeval", "ood_frank", "ood_finqa"):
        if suites.get(sname):
            rows = suites[sname]
            p, pl = ad.predict_both([r["premise"] for r in rows], [r["hypothesis"] for r in rows], batch_size=16)
            y = np.array([r["label"] for r in rows], dtype=np.int32)
            out["suites"][sname] = _score_binary(y, p)
            if pl is not None:
                lme_suites[sname] = _score_binary(y, pl)
            if sname == "ood_ragtruth":
                by_sp = defaultdict(list)
                for idx, r in enumerate(rows):
                    by_sp[r.get("source", "unknown")].append(idx)
                out["suites"]["ood_ragtruth_by_split"] = {sp: _score_binary(y[idxs], p[idxs]) for sp, idxs in sorted(by_sp.items())}
                if pl is not None:
                    lme_suites["ood_ragtruth_by_split"] = {sp: _score_binary(y[idxs], pl[idxs]) for sp, idxs in sorted(by_sp.items())}

    if suites.get("psiloqa_test"):
        rows = suites["psiloqa_test"]
        p, pl = ad.predict_both([r["premise"] for r in rows], [r["hypothesis"] for r in rows], batch_size=16)
        y = np.array([r["label"] for r in rows], dtype=np.int32)
        en_m = np.array([r.get("language", "").lower() == "en" for r in rows])
        out["suites"]["psiloqa_test"] = {
            "overall": _score_binary(y, p),
            "en": _score_binary(y[en_m], p[en_m]) if en_m.any() else {},
            "non_en": _score_binary(y[~en_m], p[~en_m]) if (~en_m).any() else {},
        }
        if pl is not None:
            lme_suites["psiloqa_test"] = {
                "overall": _score_binary(y, pl),
                "en": _score_binary(y[en_m], pl[en_m]) if en_m.any() else {},
                "non_en": _score_binary(y[~en_m], pl[~en_m]) if (~en_m).any() else {},
            }

    if suites.get("lc_rag_needle"):
        rows = suites["lc_rag_needle"]
        p, pl = ad.predict_both([r["premise"] for r in rows], [r["hypothesis"] for r in rows], batch_size=12, max_length=4096)
        y = np.array([r["label"] for r in rows], dtype=np.int32)
        by_d = defaultdict(list)
        for i, r in enumerate(rows):
            by_d[int(r.get("approx_token_depth", 0))].append(i)
        out["suites"]["lc_rag_needle"] = {f"depth_{d}_tok": _score_binary(y[np.array(idxs)], p[np.array(idxs)]) for d, idxs in sorted(by_d.items())}
        if pl is not None:
            lme_suites["lc_rag_needle"] = {f"depth_{d}_tok": _score_binary(y[np.array(idxs)], pl[np.array(idxs)]) for d, idxs in sorted(by_d.items())}

    if lme_suites:
        out["suites_topk_lme"] = lme_suites

    out["gpu_latency_64"] = ad.bench_gpu_latency(64, n_runs=20)
    out["gpu_latency_512"] = ad.bench_gpu_latency(512, n_runs=20)
    out["gpu_latency_2048"] = ad.bench_gpu_latency(2048, n_runs=20)
    return out


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data-dir", type=str, required=True)
    parser.add_argument("--models", nargs="+", required=True)
    parser.add_argument("--out-json", type=str, required=True)
    args = parser.parse_args()

    os.environ.setdefault("HF_HOME", "/tmp/hf")
    os.environ["TORCH_COMPILE_DISABLE"] = "1"
    if hasattr(torch, "_dynamo"):
        torch._dynamo.config.disable = True

    data_dir = Path(args.data_dir)
    suite_names = ("ood_ragtruth", "ood_summeval", "ood_frank", "ood_finqa", "psiloqa_test", "lc_rag_needle")
    suites = {s: load_jsonl(data_dir / f"test_{s}.jsonl") for s in suite_names}

    results: dict[str, Any] = {"models": {}}
    for spec in args.models:
        name, path_or_id = spec.split("=", 1)
        print(f"\n[eval] === Evaluating {name} ({path_or_id}) ===")
        t0 = time.time()
        try:
            ad = GroundednessAdapter(name, path_or_id)
            results["models"][name] = eval_model(ad, suites)
            results["models"][name]["source"] = path_or_id
            results["models"][name]["eval_sec"] = round(time.time() - t0, 1)
            ad.close()
        except Exception as e:
            print(f"[eval][ERROR] {name}: {e}")
            results["models"][name] = {"error": repr(e), "source": path_or_id}

    Path(args.out_json).write_text(json.dumps(results, indent=2), encoding="utf-8")
    print(f"[eval] Saved report -> {args.out_json}")


if __name__ == "__main__":
    main()