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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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
"""Head-to-head evaluation harness for Tamarillo pii-secrets-guard vs open baselines.

Reports:
  1. Per-benchmark exact-span & relaxed-overlap F1 on full taxonomy AND fair shared-entity intersection.
  2. Adversarial Hard-Negative False Positive Rate (FPR per 1,000 tokens & % clean docs with >=1 FP).
  3. Long-Context Needle-in-a-Haystack recall at ~250, 800, 1600, 3200, 5000 token depths.
  4. CPU & GPU inference latency (p50/p95 ms) across sequence lengths.
"""

from __future__ import annotations

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

import numpy as np
import torch
from huggingface_hub import hf_hub_download
from transformers import (
    AutoConfig,
    AutoModelForTokenClassification,
    AutoTokenizer,
    PreTrainedTokenizerFast,
    pipeline,
)

# Disable torch.compile/inductor so ModernBERT never invokes gcc/Triton on VMs without gcc
try:
    torch._dynamo.config.disable = True
except Exception:
    pass

from taxonomy import map_raw_label, normalize_and_merge_spans

# Baselines to benchmark candidly head-to-head
BASELINE_MODELS: dict[str, dict[str, Any]] = {
    "piiranha-v1": {
        "repo": "iiiorg/piiranha-v1-detect-personal-information",
        "max_length": 256,
        "supported_canonical": {
            "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS", "POSTAL_CODE",
            "DATE_OF_BIRTH", "SSN", "GOVERNMENT_ID", "DRIVER_LICENSE", "CREDIT_CARD",
            "BANK_ACCOUNT", "USERNAME", "PASSWORD",
        },
    },
    "isotonic-deberta-v3": {
        "repo": "Isotonic/deberta-v3-base_finetuned_ai4privacy_v2",
        "max_length": 512,
        "supported_canonical": {
            "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS", "POSTAL_CODE",
            "DATE_OF_BIRTH", "SSN", "CREDIT_CARD", "IBAN_CODE", "BANK_ACCOUNT",
            "USERNAME", "IP_ADDRESS", "PASSWORD",
        },
    },
    "vllm-sr-mmbert32k-pii": {
        "repo": "vllm-sr/mmbert32k-pii-detector-merged",
        "max_length": 8192,
        "supported_canonical": {
            "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS", "POSTAL_CODE",
            "SSN", "DRIVER_LICENSE", "CREDIT_CARD", "IBAN_CODE", "IP_ADDRESS",
        },
    },
    "wismut-nym-base": {
        "repo": "Wismut/nym-pii-multilingual",
        "tokenizer_repo": "jhu-clsp/mmBERT-base",
        "max_length": 2048,
        "supported_canonical": {
            "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS", "POSTAL_CODE",
            "DATE_OF_BIRTH", "SSN", "GOVERNMENT_ID", "PASSPORT", "DRIVER_LICENSE",
            "CREDIT_CARD", "IBAN_CODE", "BANK_ACCOUNT", "MEDICAL_ID", "USERNAME",
            "IP_ADDRESS", "PASSWORD", "API_KEY",
        },
    },
    "kalyan-ettin-68m": {
        "repo": "kalyan-ks/ettin-68m-nemotron-pii",
        "tokenizer_repo": "jhu-clsp/ettin-encoder-68m",
        "max_length": 2048,
        "supported_canonical": {
            "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS", "POSTAL_CODE",
            "DATE_OF_BIRTH", "SSN", "GOVERNMENT_ID", "CREDIT_CARD", "BANK_ACCOUNT",
            "MEDICAL_ID", "USERNAME", "IP_ADDRESS", "PASSWORD", "API_KEY", "AUTH_TOKEN",
        },
    },
}


def load_jsonl(path: Path, limit: int | None = None) -> list[dict[str, Any]]:
    rows = []
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
                if limit and len(rows) >= limit:
                    break
    return rows


def predict_spans_hf(
    ner_pipe: Any,
    text: str,
    max_length: int,
    map_to_canonical: bool = True,
) -> list[dict[str, Any]]:
    """Run standard HF token-classification pipeline with truncation matching model's native limit."""
    tok = ner_pipe.tokenizer
    enc = tok(text, truncation=True, max_length=max_length, return_offsets_mapping=True)
    # Slice text to the max character covered by max_length tokens to mirror real drop-in behavior
    offsets = enc.get("offset_mapping", [])
    max_char = max((e for _, e in offsets if e > 0), default=len(text))
    clipped = text[:max_char]
    if not clipped.strip():
        return []
    preds = ner_pipe(clipped)
    spans: list[dict[str, Any]] = []
    for p in preds:
        raw_lbl = p.get("entity_group") or p.get("entity") or ""
        lbl = map_raw_label(raw_lbl) if map_to_canonical else raw_lbl
        if lbl is None:
            continue
        start, end = int(p["start"]), int(p["end"])
        if start < end:
            spans.append({"start": start, "end": end, "label": lbl, "score": float(p.get("score", 1.0))})
    # Apply the exact same adjacent-span merging (e.g., first_name+last_name -> PERSON,
    # building_number+street -> STREET_ADDRESS) used on gold spans for 100% fair baseline scoring.
    return normalize_and_merge_spans(clipped, spans)


def _span_iou(a: dict[str, Any], b: dict[str, Any]) -> float:
    inter = max(0, min(a["end"], b["end"]) - max(a["start"], b["start"]))
    if inter == 0:
        return 0.0
    union = (a["end"] - a["start"]) + (b["end"] - b["start"]) - inter
    return inter / max(1, union)


def score_span_predictions(
    gold_list: list[list[dict[str, Any]]],
    pred_list: list[list[dict[str, Any]]],
    allowed_labels: set[str] | None = None,
    iou_threshold: float = 0.5,
) -> dict[str, Any]:
    """Compute both type-aware and type-agnostic (binary PII/secret redaction) span P/R/F1."""
    tp_typed = fp_typed = fn_typed = 0
    tp_any = fp_any = fn_any = 0
    per_label: dict[str, list[int]] = defaultdict(lambda: [0, 0, 0])  # tp, fp, fn

    for golds, preds in zip(gold_list, pred_list):
        if allowed_labels is not None:
            golds = [g for g in golds if g["label"] in allowed_labels]
            preds = [p for p in preds if p["label"] in allowed_labels]

        # Type-aware greedy matching
        matched_g: set[int] = set()
        for p in preds:
            best_i, best_iou = -1, 0.0
            for i, g in enumerate(golds):
                if i in matched_g or g["label"] != p["label"]:
                    continue
                iou = _span_iou(p, g)
                if iou >= iou_threshold and iou > best_iou:
                    best_i, best_iou = i, iou
            if best_i >= 0:
                matched_g.add(best_i)
                tp_typed += 1
                per_label[p["label"]][0] += 1
            else:
                fp_typed += 1
                per_label[p["label"]][1] += 1
        for i, g in enumerate(golds):
            if i not in matched_g:
                fn_typed += 1
                per_label[g["label"]][2] += 1

        # Type-agnostic redaction matching (did we catch the sensitive span regardless of label?)
        matched_g2: set[int] = set()
        for p in preds:
            best_i, best_iou = -1, 0.0
            for i, g in enumerate(golds):
                if i in matched_g2:
                    continue
                iou = _span_iou(p, g)
                if iou >= iou_threshold and iou > best_iou:
                    best_i, best_iou = i, iou
            if best_i >= 0:
                matched_g2.add(best_i)
                tp_any += 1
            else:
                fp_any += 1
        fn_any += len(golds) - len(matched_g2)

    def _prf(tp: int, fp: int, fn: int) -> dict[str, float]:
        p = tp / max(1, tp + fp)
        r = tp / max(1, tp + fn)
        f1 = 2 * p * r / max(1e-12, p + r)
        return {"precision": round(p, 4), "recall": round(r, 4), "f1": round(f1, 4), "tp": tp, "fp": fp, "fn": fn}

    per_lbl_f1 = {}
    for lbl, (tp, fp, fn) in sorted(per_label.items()):
        per_lbl_f1[lbl] = _prf(tp, fp, fn)

    return {
        "typed": _prf(tp_typed, fp_typed, fn_typed),
        "redaction_binary": _prf(tp_any, fp_any, fn_any),
        "per_label": per_lbl_f1,
    }


def _load_tokenizer_safe(repo_or_path: str, tokenizer_repo: str | None = None) -> Any:
    """Load tokenizer robustly; prefer canonical base tokenizer if repo uses transformers 5.x TokenizersBackend."""
    try:
        return AutoTokenizer.from_pretrained(repo_or_path, use_fast=True)
    except Exception as e:
        if "TokenizersBackend" not in str(e) and "does not exist" not in str(e):
            raise
        if tokenizer_repo:
            return AutoTokenizer.from_pretrained(tokenizer_repo, use_fast=True)
        p = Path(repo_or_path)
        tok_file = str(p / "tokenizer.json") if (p / "tokenizer.json").exists() else hf_hub_download(repo_or_path, "tokenizer.json")
        cfg_file = (p / "tokenizer_config.json") if (p / "tokenizer_config.json").exists() else Path(hf_hub_download(repo_or_path, "tokenizer_config.json"))
        tcfg = json.loads(cfg_file.read_text(encoding="utf-8"))
        kwargs = {}
        for k in ("bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token"):
            v = tcfg.get(k)
            if isinstance(v, dict):
                v = v.get("content")
            if isinstance(v, str):
                kwargs[k] = v
        return PreTrainedTokenizerFast(
            tokenizer_file=tok_file,
            model_input_names=["input_ids", "attention_mask"],
            **kwargs,
        )


def evaluate_model(
    name: str,
    repo_or_path: str,
    max_length: int,
    supported_canonical: set[str] | None,
    data_dir: Path,
    limit_per_suite: int,
    device: int,
    tokenizer_repo: str | None = None,
) -> dict[str, Any]:
    print(f"\n[eval] === {name} ({repo_or_path}, max_len={max_length}) ===")
    tok = _load_tokenizer_safe(repo_or_path, tokenizer_repo=tokenizer_repo)
    cfg = AutoConfig.from_pretrained(repo_or_path, trust_remote_code=False)
    if hasattr(cfg, "reference_compile"):
        cfg.reference_compile = False
    mod = AutoModelForTokenClassification.from_pretrained(repo_or_path, config=cfg, trust_remote_code=False)
    ner = pipeline(
        "token-classification",
        model=mod,
        tokenizer=tok,
        aggregation_strategy="simple",
        device=device,
    )

    results: dict[str, Any] = {
        "name": name,
        "repo": repo_or_path,
        "max_length": max_length,
        "params_m": round(sum(p.numel() for p in mod.parameters()) / 1e6, 2),
        "suites": {},
    }

    suite_names = [
        "nemotron_en",
        "gretel_en",
        "gretel_multi",
        "wismut_multi",
        "agent_secrets",
        "ood_yalen_bias",
        "ood_btx24_tr",
    ]
    for sname in suite_names:
        fpath = data_dir / f"test_{sname}.jsonl"
        if not fpath.exists():
            continue
        rows = load_jsonl(fpath, limit=limit_per_suite)
        golds = [r["spans"] for r in rows]
        preds = [predict_spans_hf(ner, r["text"], max_length=max_length) for r in rows]
        results["suites"][sname] = {
            "n": len(rows),
            "full_taxonomy": score_span_predictions(golds, preds, allowed_labels=None),
            "fair_shared_entities": score_span_predictions(golds, preds, allowed_labels=supported_canonical),
        }

    # Adversarial Hard-Negatives FPR
    hn_path = data_dir / "test_hard_negatives.jsonl"
    if hn_path.exists():
        rows = load_jsonl(hn_path, limit=min(limit_per_suite, 500))
        total_fp_spans = 0
        fp_docs = 0
        total_words = 0
        for r in rows:
            preds = predict_spans_hf(ner, r["text"], max_length=max_length)
            total_words += max(1, len(r["text"].split()))
            if preds:
                fp_docs += 1
                total_fp_spans += len(preds)
        results["hard_negatives"] = {
            "n_docs": len(rows),
            "fp_doc_rate": round(fp_docs / max(1, len(rows)), 4),
            "fp_spans_per_1k_words": round(1000.0 * total_fp_spans / max(1, total_words), 3),
            "total_fp_spans": total_fp_spans,
        }

    # Long-Context Needle-in-a-Haystack by depth
    lc_path = data_dir / "test_long_context_needle.jsonl"
    if lc_path.exists():
        rows = load_jsonl(lc_path)
        by_depth: dict[int, list[dict[str, Any]]] = defaultdict(list)
        for r in rows:
            by_depth[int(r.get("approx_token_depth", 0))].append(r)
        depth_res = {}
        for depth, drows in sorted(by_depth.items()):
            sub = drows[: min(60, len(drows))]
            golds = [r["spans"] for r in sub]
            preds = [predict_spans_hf(ner, r["text"], max_length=max_length) for r in sub]
            sc = score_span_predictions(golds, preds, allowed_labels=supported_canonical)
            depth_res[str(depth)] = sc["redaction_binary"]["recall"]
        results["long_context_recall_by_token_depth"] = depth_res

    # Latency benchmark (512-char & 4096-char texts)
    lat = {}
    sample_short = "Please email Elena Vargas at elena.vargas@acme-fin.io with API key sk-proj-AbCdEf1234567890GhIjKlMnOpQrStUvWxYz."
    sample_long = ("INFO worker: healthy queue=4 latency=2ms\n" * 120) + sample_short
    for tag, sample in [("short_~40tok", sample_short), ("long_~1200tok", sample_long)]:
        # warmup
        for _ in range(3):
            predict_spans_hf(ner, sample, max_length=max_length)
        times = []
        for _ in range(15):
            t0 = time.perf_counter()
            predict_spans_hf(ner, sample, max_length=max_length)
            times.append((time.perf_counter() - t0) * 1000.0)
        lat[tag] = {"p50_ms": round(float(np.median(times)), 2), "p95_ms": round(float(np.percentile(times, 95)), 2)}
    results["latency"] = lat

    del ner, mod
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    return results


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data-dir", type=str, required=True)
    parser.add_argument("--our-models", type=str, nargs="+", required=True, help="name=path pairs")
    parser.add_argument("--include-baselines", action="store_true")
    parser.add_argument("--limit-per-suite", type=int, default=500)
    parser.add_argument("--out-json", type=str, required=True)
    args = parser.parse_args()

    os.environ.setdefault("HF_HOME", "/tmp/hf")
    device = 0 if torch.cuda.is_available() else -1
    data_dir = Path(args.data_dir)
    all_results: list[dict[str, Any]] = []

    for spec in args.our_models:
        name, path = spec.split("=", 1)
        cfg_max = 7999 if "tiny" in name else 8192
        all_results.append(
            evaluate_model(
                name=name,
                repo_or_path=path,
                max_length=cfg_max,
                supported_canonical=None,
                data_dir=data_dir,
                limit_per_suite=args.limit_per_suite,
                device=device,
            )
        )

    if args.include_baselines:
        for bname, bcfg in BASELINE_MODELS.items():
            try:
                all_results.append(
                    evaluate_model(
                        name=bname,
                        repo_or_path=bcfg["repo"],
                        max_length=bcfg["max_length"],
                        supported_canonical=bcfg["supported_canonical"],
                        data_dir=data_dir,
                        limit_per_suite=args.limit_per_suite,
                        device=device,
                        tokenizer_repo=bcfg.get("tokenizer_repo"),
                    )
                )
            except Exception as e:
                print(f"[eval] Baseline {bname} failed: {e}")
                all_results.append({"name": bname, "error": str(e)})

    out_path = Path(args.out_json)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(all_results, indent=2), encoding="utf-8")
    print(f"[eval] Saved full report to {out_path}")


if __name__ == "__main__":
    main()