File size: 13,161 Bytes
4de12e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""HandleAtlas benchmark eval harness.

Strap any NER model into one of the adapters below and run:

    python run_eval.py --adapter gliner --model LumeData/HandleAtlas-166m

Reads ``eval.yaml`` (sitting next to this file) for the dataset id, label list,
thresholds and scoring protocol, then loads the dataset from the Hugging Face
Hub and reports span-only F1, span+label F1, and CPU latency.

Add your own model by writing a new ``Adapter`` subclass and registering it
in ``ADAPTERS`` at the bottom of the file. Adapters MUST return a list of
``{"start": int, "end": int, "label": str}`` dicts where ``start``/``end`` are
Python character offsets into the input ``text`` (end exclusive).
"""
from __future__ import annotations

import argparse
import json
import statistics
import time
from collections import defaultdict
from pathlib import Path
from typing import Callable, Iterable

import yaml
from datasets import load_dataset

HERE = Path(__file__).resolve().parent


# ---------------------------------------------------------------------------
# Scoring  (identical to the reference impl in data/benchmark.py)
# ---------------------------------------------------------------------------
def iou(a: dict, b: dict) -> float:
    inter = max(0, min(a["end"], b["end"]) - max(a["start"], b["start"]))
    if inter == 0:
        return 0.0
    union = max(a["end"], b["end"]) - min(a["start"], b["start"])
    return inter / union if union else 0.0


def score_span_only(pred_per_rec, gold_per_rec, iou_thresh: float = 0.5) -> dict:
    tp = fp = fn = 0
    for preds, gold in zip(pred_per_rec, gold_per_rec):
        matched = set()
        for p in preds:
            best_i, best_v = -1, 0.0
            for gi, g in enumerate(gold):
                if gi in matched:
                    continue
                v = iou(p, g)
                if v > best_v:
                    best_v, best_i = v, gi
            if best_v >= iou_thresh and best_i != -1:
                tp += 1
                matched.add(best_i)
            else:
                fp += 1
        fn += len(gold) - len(matched)
    p = tp / (tp + fp) if (tp + fp) else 0.0
    r = tp / (tp + fn) if (tp + fn) else 0.0
    f = 2 * p * r / (p + r) if (p + r) else 0.0
    return {"tp": tp, "fp": fp, "fn": fn, "precision": p, "recall": r, "f1": f}


def score_span_label(pred_per_rec, gold_per_rec) -> dict:
    tp = fp = fn = 0
    per_tp: dict[str, int] = defaultdict(int)
    per_fp: dict[str, int] = defaultdict(int)
    per_fn: dict[str, int] = defaultdict(int)
    for preds, gold in zip(pred_per_rec, gold_per_rec):
        gs = {(g["start"], g["end"], g["label"]) for g in gold}
        ps = {(p["start"], p["end"], p["label"]) for p in preds}
        for t in gs & ps:
            tp += 1; per_tp[t[2]] += 1
        for t in ps - gs:
            fp += 1; per_fp[t[2]] += 1
        for t in gs - ps:
            fn += 1; per_fn[t[2]] += 1
    p = tp / (tp + fp) if (tp + fp) else 0.0
    r = tp / (tp + fn) if (tp + fn) else 0.0
    f = 2 * p * r / (p + r) if (p + r) else 0.0
    return {
        "tp": tp, "fp": fp, "fn": fn, "precision": p, "recall": r, "f1": f,
        "per_label_tp": dict(per_tp),
        "per_label_fp": dict(per_fp),
        "per_label_fn": dict(per_fn),
    }


def fmt_latency(times: list[float]) -> dict:
    if not times:
        return {}
    s = sorted(times)
    return {
        "mean": statistics.mean(s),
        "p50": s[len(s) // 2],
        "p95": s[int(len(s) * 0.95)],
    }


# ---------------------------------------------------------------------------
# Adapter protocol
# ---------------------------------------------------------------------------
class Adapter:
    """Subclass + register to plug a new NER model into the harness.

    The harness will instantiate exactly one Adapter per run, then call
    ``predict(text)`` once per record. Do all your model loading in
    ``__init__`` so the per-call path is hot.
    """
    name: str = ""

    def __init__(self, model: str, labels: list[str], threshold: float,
                 per_label_thresholds: dict[str, float], **kwargs):
        self.model_id = model
        self.labels = labels
        self.threshold = threshold
        self.per_label_thresholds = per_label_thresholds

    def predict(self, text: str) -> list[dict]:
        raise NotImplementedError

    def _apply_thresholds(self, ents: Iterable[dict]) -> list[dict]:
        out = []
        for e in ents:
            t = self.per_label_thresholds.get(e["label"], self.threshold)
            if e.get("score", 1.0) >= t:
                out.append({"start": int(e["start"]),
                            "end":   int(e["end"]),
                            "label": e["label"]})
        return out


class GLiNERAdapter(Adapter):
    """Works for any GLiNER-format model (Hub id or local path)."""
    name = "gliner"

    def __init__(self, model, labels, threshold, per_label_thresholds,
                 onnx: bool = False, onnx_file: str = "model_quantized.onnx",
                 threads: int = 8, **_):
        super().__init__(model, labels, threshold, per_label_thresholds)
        import os
        os.environ.setdefault("OMP_NUM_THREADS", str(threads))
        import torch
        torch.set_num_threads(threads)
        from gliner import GLiNER
        kw = {}
        if onnx:
            kw.update(load_onnx_model=True, onnx_model_file=onnx_file)
        if Path(model).exists():
            kw["local_files_only"] = True
        self.m = GLiNER.from_pretrained(model, **kw)
        self.m.eval()
        self._floor = min(threshold, *per_label_thresholds.values()) \
            if per_label_thresholds else threshold

    def predict(self, text):
        ents = self.m.predict_entities(text, self.labels, threshold=self._floor)
        return self._apply_thresholds(ents)


class HFPipelineAdapter(Adapter):
    """Token-classification pipeline (BERT/DeBERTa-style PII / NER models).

    Maps the model's entity_group strings to your label list via
    ``--label-map key1=value1,key2=value2``.
    """
    name = "hf-pipeline"

    def __init__(self, model, labels, threshold, per_label_thresholds,
                 label_map: dict[str, str] | None = None, device: int = -1, **_):
        super().__init__(model, labels, threshold, per_label_thresholds)
        from transformers import pipeline
        self.pipe = pipeline("token-classification", model=model,
                             aggregation_strategy="simple", device=device)
        self.label_map = label_map or {}
        self.label_set = set(labels)

    def predict(self, text):
        out = []
        for ent in self.pipe(text):
            raw = (ent.get("entity_group") or ent.get("entity") or "").lower()
            mapped = self.label_map.get(raw, raw)
            if mapped not in self.label_set:
                continue
            out.append({"start": int(ent["start"]),
                        "end":   int(ent["end"]),
                        "label": mapped,
                        "score": float(ent.get("score", 1.0))})
        return self._apply_thresholds(out)


ADAPTERS: dict[str, type[Adapter]] = {
    GLiNERAdapter.name:    GLiNERAdapter,
    HFPipelineAdapter.name: HFPipelineAdapter,
}


# ---------------------------------------------------------------------------
# Harness
# ---------------------------------------------------------------------------
def parse_kv(s: str) -> dict[str, str]:
    if not s:
        return {}
    out = {}
    for pair in s.split(","):
        if "=" not in pair:
            continue
        k, v = pair.split("=", 1)
        out[k.strip()] = v.strip()
    return out


def run(adapter: Adapter, ds, primary_iou: float) -> dict:
    preds_all = []
    gold_all = []
    times = []
    for rec in ds:
        text = rec["text"]
        gold_all.append(rec["entities"])
        t0 = time.perf_counter()
        preds = adapter.predict(text)
        times.append((time.perf_counter() - t0) * 1000)
        preds_all.append(preds)

    span_only = score_span_only(preds_all, gold_all, iou_thresh=primary_iou)
    span_label = score_span_label(preds_all, gold_all)
    return {
        "span_only_f1": span_only,
        "span_label_f1": span_label,
        "latency_ms": fmt_latency(times),
        "n_records": len(gold_all),
        "n_gold_spans": sum(len(g) for g in gold_all),
        "predictions": preds_all,
    }


def report(name: str, results: dict) -> None:
    so = results["span_only_f1"]
    sl = results["span_label_f1"]
    lat = results["latency_ms"]
    print(f"\n=== {name} ===")
    print(f"  records: {results['n_records']}   "
          f"gold spans: {results['n_gold_spans']}")
    print(f"  span-only F1   P={so['precision']:.3f}  R={so['recall']:.3f}  "
          f"F1={so['f1']:.3f}   (TP={so['tp']} FP={so['fp']} FN={so['fn']})")
    print(f"  span+label F1  P={sl['precision']:.3f}  R={sl['recall']:.3f}  "
          f"F1={sl['f1']:.3f}   (TP={sl['tp']} FP={sl['fp']} FN={sl['fn']})")
    if lat:
        print(f"  latency        mean={lat['mean']:6.1f} ms   "
              f"p50={lat['p50']:6.1f} ms   p95={lat['p95']:6.1f} ms")

    labels_seen = (set(sl["per_label_tp"]) | set(sl["per_label_fp"])
                   | set(sl["per_label_fn"]))
    if labels_seen:
        print("\n  per-label (span+label):")
        for l in sorted(labels_seen):
            tp = sl["per_label_tp"].get(l, 0)
            fp = sl["per_label_fp"].get(l, 0)
            fn = sl["per_label_fn"].get(l, 0)
            p = tp / (tp + fp) if (tp + fp) else 0.0
            r = tp / (tp + fn) if (tp + fn) else 0.0
            f = 2*p*r/(p+r) if (p+r) else 0.0
            print(f"    {l:<22} P={p:.2f} R={r:.2f} F1={f:.2f}   "
                  f"TP={tp} FP={fp} FN={fn}")


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--adapter", required=True, choices=sorted(ADAPTERS),
                    help="Which built-in adapter to use.")
    ap.add_argument("--model", required=True,
                    help="HF Hub id or local path passed verbatim to the adapter.")
    ap.add_argument("--spec", default=str(HERE / "eval.yaml"),
                    help="Path to eval.yaml (default: next to this file).")
    ap.add_argument("--threshold", type=float, default=None,
                    help="Override default decoding threshold from the spec.")
    ap.add_argument("--label-map", default="",
                    help="model_label=target_label,... (hf-pipeline only).")
    ap.add_argument("--onnx", action="store_true",
                    help="GLiNER: load the ONNX file instead of PyTorch.")
    ap.add_argument("--onnx-file", default="model_quantized.onnx")
    ap.add_argument("--threads", type=int, default=8)
    ap.add_argument("--device", type=int, default=-1,
                    help="hf-pipeline: -1 = CPU, 0 = first GPU.")
    ap.add_argument("--limit", type=int, default=None,
                    help="Only score the first N records (smoke test).")
    ap.add_argument("--save-predictions", default=None,
                    help="Write per-record predictions as JSONL to this path.")
    ap.add_argument("--json", action="store_true",
                    help="Also dump the final metrics JSON to stdout.")
    args = ap.parse_args()

    spec = yaml.safe_load(open(args.spec))

    repo = spec["dataset"]["repo_id"]
    split = spec["dataset"]["split"]
    print(f"Loading {repo}:{split} ...")
    ds = load_dataset(repo, split=split)
    if args.limit:
        ds = ds.select(range(min(args.limit, len(ds))))

    labels = spec["labels"]
    proto = spec["inference_protocol"]
    threshold = args.threshold if args.threshold is not None else proto["threshold"]
    overrides = dict(proto.get("per_label_threshold_overrides") or {})

    primary_metric = next(m for m in spec["metrics"] if m.get("primary"))
    primary_iou = primary_metric.get("iou_threshold", 0.5)

    print(f"Building adapter '{args.adapter}' over {args.model} ...")
    cls = ADAPTERS[args.adapter]
    adapter = cls(
        model=args.model,
        labels=labels,
        threshold=threshold,
        per_label_thresholds=overrides,
        label_map=parse_kv(args.label_map),
        onnx=args.onnx,
        onnx_file=args.onnx_file,
        threads=args.threads,
        device=args.device,
    )

    print(f"Running over {len(ds)} records ...")
    results = run(adapter, ds, primary_iou=primary_iou)

    if args.save_predictions:
        with open(args.save_predictions, "w") as f:
            for rec, preds in zip(ds, results["predictions"]):
                f.write(json.dumps({"id": rec.get("id"),
                                    "text": rec["text"],
                                    "predictions": preds}) + "\n")
        print(f"Wrote per-record predictions -> {args.save_predictions}")

    report(args.model, results)

    if args.json:
        slim = {k: v for k, v in results.items() if k != "predictions"}
        print("\n" + json.dumps(slim, indent=2))


if __name__ == "__main__":
    main()