#!/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()