File size: 6,876 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
"""Evaluate exact Character-Level Span Hallucination F1, Precision, Recall & IoU for all
TokenClassification models (`tamarillo-tiny-en`, `tamarillo-small`, `tamarillo-base`, and
`KRLabsOrg/lettucedect-v2-mmbert-base`) on `s-nlp/PsiloQA` test (EN & 13-Lang Non-EN)!
"""

from __future__ import annotations

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

import numpy as np
import torch
from transformers import AutoConfig, AutoModelForTokenClassification, AutoTokenizer


def _hash_bucket(s: str, mod: int = 997) -> int:
    import hashlib
    return int(hashlib.md5(s.encode("utf-8", errors="ignore")).hexdigest()[:8], 16) % mod


def _char_mask(length: int, spans: list[list[int]]) -> np.ndarray:
    m = np.zeros(length, dtype=bool)
    for pair in spans:
        if isinstance(pair, (list, tuple)) and len(pair) == 2:
            s, e = max(0, int(pair[0])), min(length, int(pair[1]))
            if e > s:
                m[s:e] = True
    return m


def _eval_model_spans(name: str, path_or_id: str, rows: list[dict[str, Any]], threshold: float = 0.5) -> dict[str, Any]:
    device = "cuda" if torch.cuda.is_available() else "cpu"
    dtype = torch.bfloat16 if (device == "cuda" and torch.cuda.is_bf16_supported()) else torch.float16
    cfg = AutoConfig.from_pretrained(path_or_id)
    if hasattr(cfg, "reference_compile"):
        cfg.reference_compile = False
    tok = AutoTokenizer.from_pretrained(path_or_id, use_fast=True)
    model = AutoModelForTokenClassification.from_pretrained(path_or_id, config=cfg).to(device).eval()

    id2l = {int(k): str(v).lower() for k, v in (cfg.id2label or {}).items()}
    hal_idx = 1
    for k, v in id2l.items():
        if v in ("hallucinated", "unsupported", "contradiction"):
            hal_idx = k
            break

    stats = {
        "overall": {"tp": 0, "fp": 0, "fn": 0, "n": 0, "n_hal": 0},
        "en": {"tp": 0, "fp": 0, "fn": 0, "n": 0, "n_hal": 0},
        "non_en": {"tp": 0, "fp": 0, "fn": 0, "n": 0, "n_hal": 0},
    }

    bs = 12
    for i in range(0, len(rows), bs):
        ch = rows[i : i + bs]
        enc = tok(
            [r["premise"] for r in ch],
            [r["hypothesis"] for r in ch],
            padding=True,
            truncation="only_first",
            max_length=4096,
            return_offsets_mapping=True,
            return_tensors="pt",
        )
        offsets_b = enc.pop("offset_mapping").tolist()
        sids_b = [enc.sequence_ids(j) for j in range(len(ch))]
        t_in = {k: v.to(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 device == "cuda" else torch.no_grad():
                logits = model(**t_in).logits.float()
        probs = torch.softmax(logits, dim=-1)[:, :, hal_idx].cpu().numpy()

        for j, r in enumerate(ch):
            hyp = r["hypothesis"]
            L = len(hyp)
            gold = _char_mask(L, r["spans"])
            pred = np.zeros(L, dtype=bool)
            for t, (sid, (cs, ce)) in enumerate(zip(sids_b[j], offsets_b[j])):
                if sid == 1 and ce > cs and probs[j, t] >= threshold:
                    pred[max(0, cs) : min(L, ce)] = True
            tp = int(np.logical_and(gold, pred).sum())
            fp = int(np.logical_and(~gold, pred).sum())
            fn = int(np.logical_and(gold, ~pred).sum())
            buckets = ["overall", "en" if r["language"] == "en" else "non_en"]
            for bk in buckets:
                stats[bk]["tp"] += tp
                stats[bk]["fp"] += fp
                stats[bk]["fn"] += fn
                stats[bk]["n"] += 1
                if r["spans"]:
                    stats[bk]["n_hal"] += 1

    del model
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()

    out: dict[str, Any] = {}
    for bk, s in stats.items():
        tp, fp, fn = s["tp"], s["fp"], s["fn"]
        prec = tp / max(1, tp + fp)
        rec = tp / max(1, tp + fn)
        f1 = (2 * prec * rec) / max(1e-12, prec + rec)
        iou = tp / max(1, tp + fp + fn)
        out[bk] = {
            "n": s["n"],
            "n_with_hal_spans": s["n_hal"],
            "char_precision": round(prec, 4),
            "char_recall": round(rec, 4),
            "char_f1": round(f1, 4),
            "char_iou": round(iou, 4),
        }
    return out


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--models", nargs="+", required=True)
    parser.add_argument("--out-json", type=str, required=True)
    parser.add_argument("--seed", type=int, default=42)
    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

    from datasets import load_dataset

    # Reconstruct the exact same deterministic PsiloQA test split used in eval_suite.py (up to 200/lang)
    by_lg: dict[str, list[dict[str, Any]]] = defaultdict(list)
    en_cons_cnt = 0
    en_hal_cnt = 0
    for row in load_dataset("s-nlp/PsiloQA", split="test"):
        ctx = str(row.get("wiki_passage") or "").strip()
        ans = str(row.get("llm_answer") or "").strip()
        lg = str(row.get("lang") or "en").strip().lower()
        spans = row.get("labels")
        if len(ctx) < 15 or len(ans) < 5 or spans is None:
            continue
        by_lg[lg].append({"premise": ctx, "hypothesis": ans, "spans": spans, "language": lg})
        if lg == "en":
            if len(spans) == 0:
                en_cons_cnt += 1
            else:
                en_hal_cnt += 1

    sampled = []
    for lg, items in sorted(by_lg.items()):
        rlg = random.Random(args.seed + _hash_bucket(lg, 997))
        rlg.shuffle(items)
        sampled.extend(items[:200])

    print(f"[span_eval] PsiloQA test rows={len(sampled):,} (all EN split has cons={en_cons_cnt}, hal={en_hal_cnt})")
    res: dict[str, Any] = {
        "benchmark": "s-nlp/PsiloQA (test split, up to 200/lang, gold char spans)",
        "lc_needle_seed_provenance": {
            "psiloqa_en_consistent_available": min(60, en_cons_cnt),
            "ragtruth_supplement_consistent": max(0, 60 - en_cons_cnt),
            "psiloqa_en_hallucinated": min(60, en_hal_cnt),
        },
        "models": {},
    }
    for spec in args.models:
        name, path_or_id = spec.split("=", 1)
        print(f"[span_eval] Evaluating {name} ({path_or_id}) ...")
        res["models"][name] = _eval_model_spans(name, path_or_id, sampled)
        print(f"  -> {json.dumps(res['models'][name])}")

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


if __name__ == "__main__":
    main()