File size: 15,011 Bytes
ef7cbe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Unified apples-to-apples evaluation suite for Tamarillo/injection-span-guard (token-classification)
and 5 ungated sequence-classification prompt-injection incumbents.

Evaluates:
  - OOD BIPIA (CC-BY-SA-4.0, EVAL-ONLY): Doc ROC-AUC, F1, Recall@1%FPR, Clean FPR + Token F1, Char Span IoU, Clean-Char Retention %
  - OOD Hard-Splice Benign Stress Test (120 unseen NotInject prompts spliced in identical HTML/JSON/MD/email wrappers): Hard-Splice FPR@0.50
  - OOD NotInject (leolee99/NotInject, 339 trigger-word benign prompts): Over-Defense FPR@0.50 (overall + 1/2/3 trigger breakdown)
  - OOD deepset/prompt-injections (test): Doc ROC-AUC, F1@0.50, Benign FPR@0.50
  - OOD Multilingual (rikka-snow/prompt-injection-multilingual test, deduped vs deepset): Doc ROC-AUC, F1@0.50, Benign FPR@0.50
  - OOD 4-Depth Long-Context Needle (250/800/1600/3200 tok, pos + matched hard-spliced benign): Recall / Hard-Splice FPR / ROC-AUC + Token F1 & Clean-Char Retention %
  - L4 GPU latency (64 & 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 f1_score, roc_auc_score
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoTokenizer,
)

from schema import TOOL_FILLERS, merge_token_predictions, surgical_sanitize


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 _recall_at_fpr(y_true: np.ndarray, scores: np.ndarray, target_fpr: float = 0.01) -> float | None:
    neg = scores[y_true == 0]
    pos = scores[y_true == 1]
    if len(neg) == 0 or len(pos) == 0:
        return None
    thresh = float(np.quantile(neg, 1.0 - target_fpr))
    return round(float((pos > thresh).mean()), 4)


def _char_span_metrics(text: str, gold_spans: list[list[int]], pred_spans: list[tuple[int, int]]) -> tuple[float, float, float]:
    """Return (char_iou, char_f1, clean_char_retention) for a single document."""
    n = len(text)
    if n == 0:
        return 1.0, 1.0, 1.0
    g_mask = np.zeros(n, dtype=bool)
    for s, e in gold_spans:
        g_mask[max(0, s) : min(n, e)] = True
    p_mask = np.zeros(n, dtype=bool)
    for s, e in pred_spans:
        p_mask[max(0, s) : min(n, e)] = True

    inter = int((g_mask & p_mask).sum())
    union = int((g_mask | p_mask).sum())
    iou = (inter / union) if union > 0 else 1.0
    denom = int(g_mask.sum()) + int(p_mask.sum())
    cf1 = (2.0 * inter / denom) if denom > 0 else 1.0

    clean_mask = ~g_mask
    n_clean = int(clean_mask.sum())
    clean_kept = int((clean_mask & (~p_mask)).sum())
    retention = (clean_kept / n_clean) if n_clean > 0 else 1.0
    return iou, cf1, retention


class InjectionAdapter:
    """Unified adapter for both Token-Classification (Tamarillo) and Sequence-Classification baselines."""

    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"
        self.cfg = AutoConfig.from_pretrained(path_or_id)
        if hasattr(self.cfg, "reference_compile"):
            self.cfg.reference_compile = False
        self.tokenizer = AutoTokenizer.from_pretrained(path_or_id, use_fast=True)

        archs = [a.lower() for a in (getattr(self.cfg, "architectures", None) or [])]
        self.is_token_cls = any("tokenclassification" in a for a in archs) or (
            isinstance(self.cfg.id2label, dict) and any("b-injection" in str(v).lower() for v in self.cfg.id2label.values())
        )
        if self.is_token_cls:
            self.model = AutoModelForTokenClassification.from_pretrained(path_or_id, config=self.cfg)
        else:
            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.inj_idx = next((k for k, v in id2l.items() if any(t in v for t in ("inject", "jailbreak", "malicious", "unsafe", "1"))), 1)

        self.model.to(self.device).eval()
        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)
        self.param_count = sum(p.numel() for p in self.model.parameters())
        self.is_deberta = "deberta" in str(getattr(self.cfg, "model_type", "")).lower()

    def predict(self, texts: list[str], batch_size: int = 16, max_length: int = 4096) -> tuple[np.ndarray, list[list[tuple[int, int]]] | None]:
        """Return (doc_scores, pred_char_spans_or_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
        doc_scores: list[float] = []
        all_spans: list[list[tuple[int, int]]] = []

        for i in range(0, len(texts), batch_size):
            batch_txt = texts[i : i + batch_size]
            enc = self.tokenizer(
                batch_txt,
                padding=True,
                truncation=True,
                max_length=ml,
                return_offsets_mapping=self.is_token_cls,
                return_token_type_ids=False,
                return_tensors="pt",
            )
            offsets_batch = enc.pop("offset_mapping").tolist() if self.is_token_cls else None
            enc_dev = {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_dev).logits.float().cpu().numpy()
                else:
                    logits = self.model(**enc_dev).logits.float().cpu().numpy()

            if self.is_token_cls:
                probs = _softmax(logits)  # [B, T, 3]
                p_inj = 1.0 - probs[:, :, 0]  # [B, T]
                attn = enc["attention_mask"].numpy()
                for bi, txt in enumerate(batch_txt):
                    offs = [(int(s), int(e)) for s, e in offsets_batch[bi]]
                    valid_ps = [float(p_inj[bi, ti]) for ti, (s, e) in enumerate(offs) if attn[bi, ti] == 1 and e > s]
                    doc_scores.append(max(valid_ps) if valid_ps else 0.0)
                    tok_ps = [float(p_inj[bi, ti]) if attn[bi, ti] == 1 else 0.0 for ti in range(len(offs))]
                    spans = merge_token_predictions(txt, offs, tok_ps, threshold=0.50)
                    all_spans.append([(sp.start, sp.end) for sp in spans])
            else:
                probs = _softmax(logits)
                for bi in range(len(batch_txt)):
                    doc_scores.append(float(probs[bi, self.inj_idx]))

        return np.array(doc_scores, dtype=np.float32), (all_spans if self.is_token_cls else None)

    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 = (" ".join(TOOL_FILLERS) * 20) if eff >= 512 else TOOL_FILLERS[0]
        enc = self.tokenizer([txt], padding="max_length", truncation=True, 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_binary_and_span(rows: list[dict[str, Any]], scores: np.ndarray, spans: list[list[tuple[int, int]]] | None) -> dict[str, Any]:
    y = np.array([int(r["doc_label"]) for r in rows])
    preds = (scores >= 0.5).astype(int)
    pos_m = y == 1
    neg_m = y == 0
    res: dict[str, Any] = {
        "n": len(rows),
        "n_pos": int(pos_m.sum()),
        "n_neg": int(neg_m.sum()),
        "doc_f1": round(float(f1_score(y, preds, zero_division=0)), 4) if pos_m.any() else None,
        "doc_recall": round(float((preds[pos_m] == 1).mean()), 4) if pos_m.any() else None,
        "doc_fpr": round(float((preds[neg_m] == 1).mean()), 4) if neg_m.any() else None,
        "doc_roc_auc": round(float(roc_auc_score(y, scores)), 4) if (pos_m.any() and neg_m.any()) else None,
        "recall_at_1pct_fpr": _recall_at_fpr(y, scores, 0.01) if (pos_m.any() and neg_m.any()) else None,
    }
    if spans is not None and pos_m.any():
        ious, cf1s, rets = [], [], []
        for idx in np.where(pos_m)[0]:
            iou, cf1, ret = _char_span_metrics(rows[idx]["text"], rows[idx].get("spans") or [], spans[idx])
            ious.append(iou)
            cf1s.append(cf1)
            rets.append(ret)
        res["pos_char_span_iou"] = round(float(np.mean(ious)), 4)
        res["pos_char_span_f1"] = round(float(np.mean(cf1s)), 4)
        res["pos_clean_char_retention"] = round(float(np.mean(rets)), 4)
    elif spans is None and pos_m.any():
        # Binary document blockers discard 100% of benign context on flagged positive documents
        res["pos_clean_char_retention"] = round(float(1.0 - (preds[pos_m] == 1).mean()), 4)
    return res


def eval_model(ad: InjectionAdapter, 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,
        "is_token_cls": ad.is_token_cls,
        "suites": {},
    }

    for sname in ("ood_bipia", "ood_deepset", "ood_multilingual"):
        if suites.get(sname):
            rows = suites[sname]
            sc, sp = ad.predict([r["text"] for r in rows], batch_size=16)
            out["suites"][sname] = _eval_binary_and_span(rows, sc, sp)

    # OOD NotInject (over-defense trigger-word FPR overall + by trigger count)
    if suites.get("ood_notinject"):
        rows = suites["ood_notinject"]
        sc, _ = ad.predict([r["text"] for r in rows], batch_size=32)
        preds = (sc >= 0.5).astype(int)
        by_src = defaultdict(list)
        for i, r in enumerate(rows):
            by_src[r["source"]].append(int(preds[i]))
        out["suites"]["ood_notinject"] = {
            "n": len(rows),
            "overall_fpr": round(float(preds.mean()), 4),
            "by_split": {k: round(float(np.mean(v)), 4) for k, v in sorted(by_src.items())},
        }

    # OOD Hard-Splice Benign Stress Test (by depth!)
    if suites.get("ood_hard_splice_neg"):
        rows = suites["ood_hard_splice_neg"]
        sc, _ = ad.predict([r["text"] for r in rows], batch_size=16)
        preds = (sc >= 0.5).astype(int)
        by_d = defaultdict(list)
        for i, r in enumerate(rows):
            by_d[int(r.get("approx_token_depth", 0))].append(int(preds[i]))
        out["suites"]["ood_hard_splice_neg"] = {
            "n": len(rows),
            "overall_fpr": round(float(preds.mean()), 4),
            "by_depth": {f"depth_{d}_tok": round(float(np.mean(v)), 4) for d, v in sorted(by_d.items())},
        }

    # OOD 4-Depth Long-Context Indirect Tool-Output Needle (pos + matched hard-spliced benign!)
    if suites.get("ood_lc_needle"):
        rows = suites["ood_lc_needle"]
        sc, sp = ad.predict([r["text"] for r in rows], batch_size=12)
        by_d = defaultdict(list)
        for i, r in enumerate(rows):
            by_d[int(r.get("approx_token_depth", 0))].append(i)
        d_res = {}
        for d, idxs in sorted(by_d.items()):
            sub_rows = [rows[i] for i in idxs]
            sub_sc = sc[np.array(idxs)]
            sub_sp = [sp[i] for i in idxs] if sp is not None else None
            d_res[f"depth_{d}_tok"] = _eval_binary_and_span(sub_rows, sub_sc, sub_sp)
        out["suites"]["ood_lc_needle"] = d_res

    out["gpu_latency_64"] = ad.bench_gpu_latency(64, n_runs=30)
    out["gpu_latency_2048"] = ad.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)
    suite_names = ("ood_bipia", "ood_hard_splice_neg", "ood_notinject", "ood_deepset", "ood_multilingual", "ood_lc_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 = InjectionAdapter(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()