File size: 12,857 Bytes
80554db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Unified apples-to-apples evaluation suite for Tamarillo zeroshot-policy-guard and 5 legacy/8K baselines.

Evaluates:
  - Strictly Zero-Shot OOD Multilingual NLI: facebook/xnli (15 languages, macro F1 & ROC-AUC, non-EN breakdown)
  - Strictly Zero-Shot OOD Topic Classification: fancyzhx/ag_news (4-way macro F1 / accuracy)
  - Strictly Zero-Shot OOD Financial Intent: PolyAI/banking77 (10-way candidate accuracy / macro F1)
  - Strictly Zero-Shot OOD Real Long-Document Legal NLI: kiddothe2b/contract-nli (macro F1 & ROC-AUC)
  - Unconfounded Long-Context Late-Policy Needle Recall (exact same 60 needles at ~250 / 800 / 1,600 / 3,200 tok)
  - L4 GPU p50/p95 latency (n=30) at 64 and 2,048 tokens
"""

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 accuracy_score, f1_score, roc_auc_score
from transformers import AutoModelForSequenceClassification, AutoTokenizer

BENIGN_FILLER = (
    "Enterprise operational log summary: all regional clusters passed routine health probes with "
    "99.98% availability, normal memory pressure, and zero unresolved infrastructure incidents. "
)


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)


class NLIAdapter:
    """Supports both 2-class (entailment/not_entailment) and 3-class (entailment/neutral/contradiction) NLI models."""

    def __init__(self, name: str, path_or_id: str, max_length_override: int | None = None) -> None:
        self.name = name
        self.path_or_id = path_or_id
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        self.tokenizer = AutoTokenizer.from_pretrained(path_or_id, use_fast=True)
        self.model = AutoModelForSequenceClassification.from_pretrained(path_or_id)
        if hasattr(self.model.config, "reference_compile"):
            self.model.config.reference_compile = False
        self.model.to(self.device).eval()

        cfg = self.model.config
        self.id2label = {int(k): str(v).lower() for k, v in (cfg.id2label or {}).items()}
        self.ent_idx = next((k for k, v in self.id2label.items() if v == "entailment"), 0)
        self.con_idx = next((k for k, v in self.id2label.items() if "contradict" in v or "not_entail" in v), 1)
        self.num_labels = int(cfg.num_labels)
        mpe = int(getattr(cfg, "max_position_embeddings", 512) or 512)
        if mpe in (512, 514):
            self.native_max_len = 512
        else:
            self.native_max_len = min(max_length_override or 4096, mpe)
        self.param_count = sum(p.numel() for p in self.model.parameters())
        self.is_deberta = "deberta" in str(getattr(cfg, "model_type", "")).lower()

    def entailment_probs(self, premises: list[str], hypotheses: list[str], batch_size: int = 32, max_length: int | None = None) -> np.ndarray:
        ml = min(max_length or self.native_max_len, 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
        out = []
        for i in range(0, len(premises), batch_size):
            enc = self.tokenizer(
                premises[i : i + batch_size],
                hypotheses[i : i + batch_size],
                padding=True,
                truncation="only_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():
                if use_amp:
                    with torch.amp.autocast("cuda", dtype=dtype):
                        logits = self.model(**enc).logits.float().cpu().numpy()
                else:
                    logits = self.model(**enc).logits.float().cpu().numpy()
            if self.num_labels == 2:
                p_ent = _softmax(logits)[:, self.ent_idx]
            else:
                # Standard HF zero-shot-classification convention for 3-class NLI: softmax over [entailment, contradiction]
                # For binary NLI (entailment vs neutral+contradiction), full 3-way softmax[:, ent_idx] is exact!
                p_ent = _softmax(logits)[:, self.ent_idx]
            out.append(p_ent)
        return np.concatenate(out, axis=0) if out else np.zeros((0,), dtype=np.float32)

    def zero_shot_score_candidates(self, text: str, candidates: list[str], template: str = "This example is {}.") -> np.ndarray:
        prems = [text] * len(candidates)
        hyps = [template.format(c) for c in candidates]
        return self.entailment_probs(prems, hyps, batch_size=len(candidates))

    def bench_gpu_latency(self, seq_len: int, n_runs: int = 30) -> dict[str, Any] | None:
        if self.device != "cuda":
            return None
        eff = min(seq_len, self.native_max_len)
        txt = (BENIGN_FILLER * 90) if eff >= 512 else (BENIGN_FILLER * 4)
        enc = self.tokenizer(txt, "This example is infrastructure monitoring.", truncation="only_first", padding="max_length", max_length=eff, return_token_type_ids=False, return_tensors="pt")
        enc = {k: v.to(self.device) for k, v in enc.items()}
        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(8):
                if use_amp:
                    with torch.amp.autocast("cuda", dtype=dtype):
                        _ = self.model(**enc)
                else:
                    _ = self.model(**enc)
            torch.cuda.synchronize()
            times = []
            for _ in range(n_runs):
                t0 = time.perf_counter()
                if use_amp:
                    with torch.amp.autocast("cuda", dtype=dtype):
                        _ = self.model(**enc)
                else:
                    _ = 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 eval_model(adapter: NLIAdapter, suites: dict[str, list[dict[str, Any]]]) -> dict[str, Any]:
    out: dict[str, Any] = {"params_m": round(adapter.param_count / 1e6, 2), "native_max_length": adapter.native_max_len, "suites": {}}

    # 1. Zero-shot OOD XNLI (15 languages)
    if suites.get("ood_xnli"):
        rows = suites["ood_xnli"]
        p_ent = adapter.entailment_probs([r["premise"] for r in rows], [r["hypothesis"] for r in rows], batch_size=32)
        y_ent = np.array([1 if int(r["label"]) == 0 else 0 for r in rows])
        by_lang = defaultdict(list)
        for i, r in enumerate(rows):
            by_lang[r["language"]].append(i)
        lang_aucs, lang_f1s, ne_aucs, ne_f1s = [], [], [], []
        per_lang = {}
        for l, idxs in sorted(by_lang.items()):
            ia = np.array(idxs)
            auc = float(roc_auc_score(y_ent[ia], p_ent[ia])) if len(np.unique(y_ent[ia])) == 2 else 0.0
            f1 = float(f1_score(y_ent[ia], (p_ent[ia] >= 0.5).astype(int), zero_division=0))
            per_lang[l] = {"roc_auc": round(auc, 4), "ent_f1": round(f1, 4), "n": len(idxs)}
            lang_aucs.append(auc)
            lang_f1s.append(f1)
            if l != "en":
                ne_aucs.append(auc)
                ne_f1s.append(f1)
        out["suites"]["ood_xnli"] = {
            "n": len(rows),
            "overall_roc_auc": round(float(roc_auc_score(y_ent, p_ent)), 4),
            "overall_ent_f1": round(float(f1_score(y_ent, (p_ent >= 0.5).astype(int), zero_division=0)), 4),
            "macro_lang_roc_auc": round(float(np.mean(lang_aucs)), 4),
            "non_en_macro_roc_auc": round(float(np.mean(ne_aucs)), 4) if ne_aucs else None,
            "non_en_macro_f1": round(float(np.mean(ne_f1s)), 4) if ne_f1s else None,
            "per_language": per_lang,
        }

    # 2. Zero-shot OOD AG News (4-class topic classification) & Banking77 (10-way intent)
    for sname in ("ood_ag_news", "ood_banking77"):
        if suites.get(sname):
            rows = suites[sname]
            prems, hyps, offsets = [], [], []
            for r in rows:
                cands = r["candidate_labels"]
                offsets.append((len(prems), len(prems) + len(cands)))
                for c in cands:
                    prems.append(r["text"])
                    hyps.append(f"This text is about {c}.")
            scores = adapter.entailment_probs(prems, hyps, batch_size=64)
            preds = [int(np.argmax(scores[a:b])) for a, b in offsets]
            golds = [int(r["gold_idx"]) for r in rows]
            out["suites"][sname] = {
                "n": len(rows),
                "accuracy": round(float(accuracy_score(golds, preds)), 4),
                "macro_f1": round(float(f1_score(golds, preds, average="macro", zero_division=0)), 4),
            }

    # 3. Zero-shot OOD ContractNLI (real long-document legal NDA entailment!)
    if suites.get("ood_contract_nli"):
        rows = suites["ood_contract_nli"]
        p_ent = adapter.entailment_probs([r["premise"] for r in rows], [r["hypothesis"] for r in rows], batch_size=8, max_length=4096)
        y_ent = np.array([1 if int(r["label"]) == 0 else 0 for r in rows])
        pred = (p_ent >= 0.5).astype(int)
        out["suites"]["ood_contract_nli"] = {
            "n": len(rows),
            "roc_auc": round(float(roc_auc_score(y_ent, p_ent)), 4) if len(np.unique(y_ent)) == 2 else None,
            "ent_f1": round(float(f1_score(y_ent, pred, zero_division=0)), 4),
            "macro_f1": round(float(f1_score(y_ent, pred, average="macro", zero_division=0)), 4),
        }

    # 4. Unconfounded Long-Context Late-Policy Needle Recall (exact same 60 needles at all 4 depths!)
    if suites.get("long_context_needle"):
        rows = suites["long_context_needle"]
        p_ent = adapter.entailment_probs([r["premise"] for r in rows], [r["hypothesis"] for r in rows], batch_size=16, max_length=4096)
        by_d = defaultdict(list)
        for i, r in enumerate(rows):
            by_d[int(r.get("approx_token_depth", 0))].append(i)
        out["suites"]["long_context_needle"] = {
            f"depth_{d}_tok": {"entailment_recall": round(float((p_ent[np.array(idxs)] >= 0.5).mean()), 4), "n": len(idxs)}
            for d, idxs in sorted(by_d.items())
        }

    out["gpu_latency_64"] = adapter.bench_gpu_latency(64, n_runs=30)
    out["gpu_latency_2048"] = adapter.bench_gpu_latency(2048, n_runs=30)
    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)
    suites = {s: load_jsonl(data_dir / f"test_{s}.jsonl") for s in ("ood_xnli", "ood_ag_news", "ood_banking77", "ood_contract_nli", "long_context_needle")}
    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 = NLIAdapter(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()