Techpro864 commited on
Commit
4de12e0
·
verified ·
1 Parent(s): a1e8c95

Initial benchmark dataset upload

Browse files
Files changed (3) hide show
  1. EVAL.md +172 -0
  2. eval.yaml +119 -0
  3. run_eval.py +348 -0
EVAL.md ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluating on HandleAtlas-benchmark
2
+
3
+ A self-contained eval harness for the
4
+ [`LumeData/HandleAtlas-benchmark`](https://huggingface.co/datasets/LumeData/HandleAtlas-benchmark)
5
+ dataset. The whole protocol — splits, labels, thresholds, scoring — lives in
6
+ [`eval.yaml`](./eval.yaml); the runner in [`run_eval.py`](./run_eval.py) reads
7
+ that file, loads the dataset from the Hub, and reports the same numbers used
8
+ on the model cards.
9
+
10
+ ---
11
+
12
+ ## What gets measured
13
+
14
+ | metric | definition |
15
+ |---|---|
16
+ | **span-only F1** *(primary)* | label-agnostic; a prediction matches a gold span when their character-offset IoU ≥ 0.5 |
17
+ | **span+label F1** | exact match on `(start, end, label)` — only fair when models share this taxonomy |
18
+ | **latency** | wall-clock ms per record, batch=1, CPU |
19
+
20
+ Per-label P/R/F1 is also printed for diagnostic use.
21
+
22
+ ---
23
+
24
+ ## Setup
25
+
26
+ You only need the deps for the adapter you plan to use.
27
+
28
+ ```bash
29
+ # core (always needed)
30
+ pip install datasets pyyaml
31
+
32
+ # adapter: gliner (GLiNER models, including HandleAtlas)
33
+ pip install gliner "transformers<5" torch
34
+ # + ONNX (only if you pass --onnx):
35
+ pip install onnx onnxruntime optimum "accelerate>=0.26"
36
+
37
+ # adapter: hf-pipeline (BERT/DeBERTa token-classification models)
38
+ pip install "transformers<5" torch
39
+ # Some PII models (e.g. openai/privacy-filter) require a newer transformers:
40
+ pip install "git+https://github.com/huggingface/transformers.git"
41
+ ```
42
+
43
+ Recommended: use `uv` so each run gets an isolated env.
44
+
45
+ ```bash
46
+ uv run --with gliner --with 'transformers<5' --with torch \
47
+ --with datasets --with pyyaml \
48
+ python run_eval.py --adapter gliner --model LumeData/HandleAtlas-166m
49
+ ```
50
+
51
+ ---
52
+
53
+ ## Quickstart
54
+
55
+ ### Evaluate HandleAtlas (PyTorch float)
56
+
57
+ ```bash
58
+ python run_eval.py --adapter gliner --model LumeData/HandleAtlas-166m
59
+ ```
60
+
61
+ ### Evaluate the CPU (INT8 ONNX) variant
62
+
63
+ ```bash
64
+ python run_eval.py \
65
+ --adapter gliner \
66
+ --model LumeData/HandleAtlas-166m-CPU \
67
+ --onnx
68
+ ```
69
+
70
+ ### Evaluate base GLiNER zero-shot
71
+
72
+ ```bash
73
+ python run_eval.py --adapter gliner --model urchade/gliner_small-v2.1
74
+ ```
75
+
76
+ ### Evaluate a different-taxonomy PII model (label-agnostic only)
77
+
78
+ The span-only F1 is fair across taxonomies; the span+label F1 will read low —
79
+ that's expected.
80
+
81
+ ```bash
82
+ python run_eval.py \
83
+ --adapter hf-pipeline \
84
+ --model openai/privacy-filter
85
+ ```
86
+
87
+ If you want span+label to be meaningful, pass `--label-map` to translate the
88
+ model's classes into the HandleAtlas label set:
89
+
90
+ ```bash
91
+ python run_eval.py \
92
+ --adapter hf-pipeline \
93
+ --model some/pii-model \
94
+ --label-map "USERNAME=generic_username,SOCIAL=instagram_username"
95
+ ```
96
+
97
+ ---
98
+
99
+ ## CLI flags
100
+
101
+ | flag | what it does |
102
+ |---|---|
103
+ | `--adapter` | `gliner` or `hf-pipeline` (required) |
104
+ | `--model` | HF Hub id or local path; passed straight to the adapter (required) |
105
+ | `--spec` | path to `eval.yaml` (defaults to the one next to `run_eval.py`) |
106
+ | `--threshold` | override the decoding threshold from the spec |
107
+ | `--label-map` | `model_label=target_label,...` for `hf-pipeline` |
108
+ | `--onnx`, `--onnx-file` | load the ONNX file instead of the PyTorch weights (GLiNER) |
109
+ | `--threads` | CPU threads (default 8) |
110
+ | `--device` | hf-pipeline: `-1`=CPU, `0`=first GPU |
111
+ | `--limit N` | only score the first N records (smoke test) |
112
+ | `--save-predictions PATH` | write per-record predictions to JSONL |
113
+ | `--json` | also dump the metrics JSON at the end |
114
+
115
+ ---
116
+
117
+ ## Adding your own model
118
+
119
+ If neither built-in adapter fits, subclass `Adapter` in `run_eval.py` and
120
+ register it. The contract is one method:
121
+
122
+ ```python
123
+ class MyAdapter(Adapter):
124
+ name = "mymodel"
125
+
126
+ def __init__(self, model, labels, threshold, per_label_thresholds, **_):
127
+ super().__init__(model, labels, threshold, per_label_thresholds)
128
+ # load once
129
+ self.m = my_lib.load(model)
130
+
131
+ def predict(self, text: str) -> list[dict]:
132
+ # MUST return [{"start": int, "end": int, "label": str}, ...]
133
+ # `start`/`end` are Python character offsets, end exclusive.
134
+ return [{"start": s, "end": e, "label": l}
135
+ for s, e, l in self.m.extract(text, self.labels)]
136
+
137
+ ADAPTERS["mymodel"] = MyAdapter
138
+ ```
139
+
140
+ Then:
141
+
142
+ ```bash
143
+ python run_eval.py --adapter mymodel --model path/or/id
144
+ ```
145
+
146
+ That's it — scoring and reporting are reused.
147
+
148
+ ---
149
+
150
+ ## Reproducing the published numbers
151
+
152
+ The values printed by this harness on `--model LumeData/HandleAtlas-166m`
153
+ should match the baselines table in `eval.yaml`. If they don't, check:
154
+
155
+ 1. **Threshold** — the spec sets `0.5` with a `0.65` override on
156
+ `generic_username`. Don't override unless you mean to.
157
+ 2. **Split** — the harness only uses the `test` split; the published numbers
158
+ are on this same split with `seed=123`.
159
+ 3. **Hardware** — latency was measured on a MacBook Pro M5 Pro at 8 threads.
160
+ Different hardware will give different ms numbers; F1 should not move.
161
+
162
+ ---
163
+
164
+ ## Files
165
+
166
+ | file | purpose |
167
+ |---|---|
168
+ | `eval.yaml` | declarative protocol — dataset, labels, thresholds, metrics, baselines |
169
+ | `run_eval.py` | runner — loads dataset, calls the adapter, scores, reports |
170
+ | `EVAL.md` | this file |
171
+ | `test.jsonl` | the actual eval data, also mirrored on the Hub |
172
+ | `README.md` | dataset card |
eval.yaml ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## HandleAtlas Benchmark — evaluation spec
2
+ ##
3
+ ## Self-contained recipe for reproducing the numbers on the dataset card.
4
+ ## Spans are character offsets into `text` (Python code points, end exclusive).
5
+ ## Scoring is label-agnostic span F1 at IoU >= 0.5, plus exact span+label F1.
6
+
7
+ name: handleatlas-benchmark
8
+ version: 1
9
+ dataset:
10
+ repo_id: LumeData/HandleAtlas-benchmark
11
+ config: default
12
+ split: test
13
+ loader: |
14
+ from datasets import load_dataset
15
+ ds = load_dataset("LumeData/HandleAtlas-benchmark", split="test")
16
+
17
+ task:
18
+ type: token-classification
19
+ subtype: span-extraction
20
+ input_field: text
21
+ target_field: entities # list[{start, end, label}]
22
+ offsets: python-char # not UTF-16, not BPE tokens
23
+ end_exclusive: true
24
+ multi_label_spans: true # identical (start,end) with different labels are allowed
25
+
26
+ labels:
27
+ - instagram_username
28
+ - snapchat_username
29
+ - youtube_username
30
+ - twitch_username
31
+ - tiktok_username
32
+ - discord_username
33
+ - x_username
34
+ - cashapp_username
35
+ - onlyfans_username
36
+ - tumblr_username
37
+ - github_username
38
+ - kofi_username
39
+ - patreon_username
40
+ - roblox_username
41
+ - generic_username
42
+
43
+ metrics:
44
+ - id: span_only_f1
45
+ description: Label-agnostic span detection. A prediction matches a gold span
46
+ when their character-offset IoU >= iou_threshold. Each gold span is matched
47
+ at most once (greedy by best IoU).
48
+ iou_threshold: 0.5
49
+ primary: true
50
+ aggregate: micro
51
+ reports: [precision, recall, f1, tp, fp, fn]
52
+
53
+ - id: span_label_f1
54
+ description: Exact match on (start, end, label). Stricter than span_only_f1
55
+ and only fair to compare across models that share this label taxonomy.
56
+ aggregate: micro
57
+ reports: [precision, recall, f1, tp, fp, fn]
58
+
59
+ - id: latency_ms
60
+ description: Wall-clock ms per record, single batch=1 inference. CPU only.
61
+ reports: [mean, p50, p95]
62
+ hardware: MacBook Pro M5 Pro
63
+ threads: 8
64
+
65
+ reference_implementation:
66
+ language: python
67
+ file: data/benchmark.py
68
+ scoring_fns:
69
+ - score_span_only
70
+ - score_span_label
71
+
72
+ inference_protocol:
73
+ threshold: 0.5
74
+ per_label_threshold_overrides:
75
+ generic_username: 0.65
76
+ drop_predictions_with_label:
77
+ - discord_invite # excluded from this taxonomy
78
+ decoding: greedy
79
+ batch_size: 1
80
+
81
+ baselines:
82
+ - model: LumeData/HandleAtlas-166m
83
+ span_only_f1: 0.955
84
+ span_label_f1: 0.887
85
+ precision: 0.914
86
+ recall: 1.000
87
+ latency_ms_mean: 37.1
88
+ latency_ms_p95: 52.2
89
+ runtime: pytorch-float
90
+ - model: LumeData/HandleAtlas-166m-CPU
91
+ span_only_f1: 0.955
92
+ span_label_f1: 0.887
93
+ latency_ms_mean: 13.3
94
+ latency_ms_p95: 22.3
95
+ runtime: onnx-int8
96
+ - model: urchade/gliner_small-v2.1
97
+ span_only_f1: 0.061
98
+ span_label_f1: 0.031
99
+ precision: 1.000
100
+ recall: 0.031
101
+ latency_ms_mean: 35.0
102
+ latency_ms_p95: 49.9
103
+ runtime: pytorch-float
104
+ note: zero-shot, same label list at threshold 0.5
105
+ - model: openai/privacy-filter
106
+ span_only_f1: 0.402
107
+ precision: 0.305
108
+ recall: 0.591
109
+ latency_ms_mean: 113.6
110
+ latency_ms_p95: 288.1
111
+ runtime: pytorch-float
112
+ note: different label taxonomy — span+label F1 not comparable
113
+
114
+ splits:
115
+ test:
116
+ n_records: 100
117
+ n_spans: 127
118
+ seed: 123
119
+ notes: shuffle(annotations) -> take first 100; reproducible with SEED=123
run_eval.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """HandleAtlas benchmark eval harness.
3
+
4
+ Strap any NER model into one of the adapters below and run:
5
+
6
+ python run_eval.py --adapter gliner --model LumeData/HandleAtlas-166m
7
+
8
+ Reads ``eval.yaml`` (sitting next to this file) for the dataset id, label list,
9
+ thresholds and scoring protocol, then loads the dataset from the Hugging Face
10
+ Hub and reports span-only F1, span+label F1, and CPU latency.
11
+
12
+ Add your own model by writing a new ``Adapter`` subclass and registering it
13
+ in ``ADAPTERS`` at the bottom of the file. Adapters MUST return a list of
14
+ ``{"start": int, "end": int, "label": str}`` dicts where ``start``/``end`` are
15
+ Python character offsets into the input ``text`` (end exclusive).
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import statistics
22
+ import time
23
+ from collections import defaultdict
24
+ from pathlib import Path
25
+ from typing import Callable, Iterable
26
+
27
+ import yaml
28
+ from datasets import load_dataset
29
+
30
+ HERE = Path(__file__).resolve().parent
31
+
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Scoring (identical to the reference impl in data/benchmark.py)
35
+ # ---------------------------------------------------------------------------
36
+ def iou(a: dict, b: dict) -> float:
37
+ inter = max(0, min(a["end"], b["end"]) - max(a["start"], b["start"]))
38
+ if inter == 0:
39
+ return 0.0
40
+ union = max(a["end"], b["end"]) - min(a["start"], b["start"])
41
+ return inter / union if union else 0.0
42
+
43
+
44
+ def score_span_only(pred_per_rec, gold_per_rec, iou_thresh: float = 0.5) -> dict:
45
+ tp = fp = fn = 0
46
+ for preds, gold in zip(pred_per_rec, gold_per_rec):
47
+ matched = set()
48
+ for p in preds:
49
+ best_i, best_v = -1, 0.0
50
+ for gi, g in enumerate(gold):
51
+ if gi in matched:
52
+ continue
53
+ v = iou(p, g)
54
+ if v > best_v:
55
+ best_v, best_i = v, gi
56
+ if best_v >= iou_thresh and best_i != -1:
57
+ tp += 1
58
+ matched.add(best_i)
59
+ else:
60
+ fp += 1
61
+ fn += len(gold) - len(matched)
62
+ p = tp / (tp + fp) if (tp + fp) else 0.0
63
+ r = tp / (tp + fn) if (tp + fn) else 0.0
64
+ f = 2 * p * r / (p + r) if (p + r) else 0.0
65
+ return {"tp": tp, "fp": fp, "fn": fn, "precision": p, "recall": r, "f1": f}
66
+
67
+
68
+ def score_span_label(pred_per_rec, gold_per_rec) -> dict:
69
+ tp = fp = fn = 0
70
+ per_tp: dict[str, int] = defaultdict(int)
71
+ per_fp: dict[str, int] = defaultdict(int)
72
+ per_fn: dict[str, int] = defaultdict(int)
73
+ for preds, gold in zip(pred_per_rec, gold_per_rec):
74
+ gs = {(g["start"], g["end"], g["label"]) for g in gold}
75
+ ps = {(p["start"], p["end"], p["label"]) for p in preds}
76
+ for t in gs & ps:
77
+ tp += 1; per_tp[t[2]] += 1
78
+ for t in ps - gs:
79
+ fp += 1; per_fp[t[2]] += 1
80
+ for t in gs - ps:
81
+ fn += 1; per_fn[t[2]] += 1
82
+ p = tp / (tp + fp) if (tp + fp) else 0.0
83
+ r = tp / (tp + fn) if (tp + fn) else 0.0
84
+ f = 2 * p * r / (p + r) if (p + r) else 0.0
85
+ return {
86
+ "tp": tp, "fp": fp, "fn": fn, "precision": p, "recall": r, "f1": f,
87
+ "per_label_tp": dict(per_tp),
88
+ "per_label_fp": dict(per_fp),
89
+ "per_label_fn": dict(per_fn),
90
+ }
91
+
92
+
93
+ def fmt_latency(times: list[float]) -> dict:
94
+ if not times:
95
+ return {}
96
+ s = sorted(times)
97
+ return {
98
+ "mean": statistics.mean(s),
99
+ "p50": s[len(s) // 2],
100
+ "p95": s[int(len(s) * 0.95)],
101
+ }
102
+
103
+
104
+ # ---------------------------------------------------------------------------
105
+ # Adapter protocol
106
+ # ---------------------------------------------------------------------------
107
+ class Adapter:
108
+ """Subclass + register to plug a new NER model into the harness.
109
+
110
+ The harness will instantiate exactly one Adapter per run, then call
111
+ ``predict(text)`` once per record. Do all your model loading in
112
+ ``__init__`` so the per-call path is hot.
113
+ """
114
+ name: str = ""
115
+
116
+ def __init__(self, model: str, labels: list[str], threshold: float,
117
+ per_label_thresholds: dict[str, float], **kwargs):
118
+ self.model_id = model
119
+ self.labels = labels
120
+ self.threshold = threshold
121
+ self.per_label_thresholds = per_label_thresholds
122
+
123
+ def predict(self, text: str) -> list[dict]:
124
+ raise NotImplementedError
125
+
126
+ def _apply_thresholds(self, ents: Iterable[dict]) -> list[dict]:
127
+ out = []
128
+ for e in ents:
129
+ t = self.per_label_thresholds.get(e["label"], self.threshold)
130
+ if e.get("score", 1.0) >= t:
131
+ out.append({"start": int(e["start"]),
132
+ "end": int(e["end"]),
133
+ "label": e["label"]})
134
+ return out
135
+
136
+
137
+ class GLiNERAdapter(Adapter):
138
+ """Works for any GLiNER-format model (Hub id or local path)."""
139
+ name = "gliner"
140
+
141
+ def __init__(self, model, labels, threshold, per_label_thresholds,
142
+ onnx: bool = False, onnx_file: str = "model_quantized.onnx",
143
+ threads: int = 8, **_):
144
+ super().__init__(model, labels, threshold, per_label_thresholds)
145
+ import os
146
+ os.environ.setdefault("OMP_NUM_THREADS", str(threads))
147
+ import torch
148
+ torch.set_num_threads(threads)
149
+ from gliner import GLiNER
150
+ kw = {}
151
+ if onnx:
152
+ kw.update(load_onnx_model=True, onnx_model_file=onnx_file)
153
+ if Path(model).exists():
154
+ kw["local_files_only"] = True
155
+ self.m = GLiNER.from_pretrained(model, **kw)
156
+ self.m.eval()
157
+ self._floor = min(threshold, *per_label_thresholds.values()) \
158
+ if per_label_thresholds else threshold
159
+
160
+ def predict(self, text):
161
+ ents = self.m.predict_entities(text, self.labels, threshold=self._floor)
162
+ return self._apply_thresholds(ents)
163
+
164
+
165
+ class HFPipelineAdapter(Adapter):
166
+ """Token-classification pipeline (BERT/DeBERTa-style PII / NER models).
167
+
168
+ Maps the model's entity_group strings to your label list via
169
+ ``--label-map key1=value1,key2=value2``.
170
+ """
171
+ name = "hf-pipeline"
172
+
173
+ def __init__(self, model, labels, threshold, per_label_thresholds,
174
+ label_map: dict[str, str] | None = None, device: int = -1, **_):
175
+ super().__init__(model, labels, threshold, per_label_thresholds)
176
+ from transformers import pipeline
177
+ self.pipe = pipeline("token-classification", model=model,
178
+ aggregation_strategy="simple", device=device)
179
+ self.label_map = label_map or {}
180
+ self.label_set = set(labels)
181
+
182
+ def predict(self, text):
183
+ out = []
184
+ for ent in self.pipe(text):
185
+ raw = (ent.get("entity_group") or ent.get("entity") or "").lower()
186
+ mapped = self.label_map.get(raw, raw)
187
+ if mapped not in self.label_set:
188
+ continue
189
+ out.append({"start": int(ent["start"]),
190
+ "end": int(ent["end"]),
191
+ "label": mapped,
192
+ "score": float(ent.get("score", 1.0))})
193
+ return self._apply_thresholds(out)
194
+
195
+
196
+ ADAPTERS: dict[str, type[Adapter]] = {
197
+ GLiNERAdapter.name: GLiNERAdapter,
198
+ HFPipelineAdapter.name: HFPipelineAdapter,
199
+ }
200
+
201
+
202
+ # ---------------------------------------------------------------------------
203
+ # Harness
204
+ # ---------------------------------------------------------------------------
205
+ def parse_kv(s: str) -> dict[str, str]:
206
+ if not s:
207
+ return {}
208
+ out = {}
209
+ for pair in s.split(","):
210
+ if "=" not in pair:
211
+ continue
212
+ k, v = pair.split("=", 1)
213
+ out[k.strip()] = v.strip()
214
+ return out
215
+
216
+
217
+ def run(adapter: Adapter, ds, primary_iou: float) -> dict:
218
+ preds_all = []
219
+ gold_all = []
220
+ times = []
221
+ for rec in ds:
222
+ text = rec["text"]
223
+ gold_all.append(rec["entities"])
224
+ t0 = time.perf_counter()
225
+ preds = adapter.predict(text)
226
+ times.append((time.perf_counter() - t0) * 1000)
227
+ preds_all.append(preds)
228
+
229
+ span_only = score_span_only(preds_all, gold_all, iou_thresh=primary_iou)
230
+ span_label = score_span_label(preds_all, gold_all)
231
+ return {
232
+ "span_only_f1": span_only,
233
+ "span_label_f1": span_label,
234
+ "latency_ms": fmt_latency(times),
235
+ "n_records": len(gold_all),
236
+ "n_gold_spans": sum(len(g) for g in gold_all),
237
+ "predictions": preds_all,
238
+ }
239
+
240
+
241
+ def report(name: str, results: dict) -> None:
242
+ so = results["span_only_f1"]
243
+ sl = results["span_label_f1"]
244
+ lat = results["latency_ms"]
245
+ print(f"\n=== {name} ===")
246
+ print(f" records: {results['n_records']} "
247
+ f"gold spans: {results['n_gold_spans']}")
248
+ print(f" span-only F1 P={so['precision']:.3f} R={so['recall']:.3f} "
249
+ f"F1={so['f1']:.3f} (TP={so['tp']} FP={so['fp']} FN={so['fn']})")
250
+ print(f" span+label F1 P={sl['precision']:.3f} R={sl['recall']:.3f} "
251
+ f"F1={sl['f1']:.3f} (TP={sl['tp']} FP={sl['fp']} FN={sl['fn']})")
252
+ if lat:
253
+ print(f" latency mean={lat['mean']:6.1f} ms "
254
+ f"p50={lat['p50']:6.1f} ms p95={lat['p95']:6.1f} ms")
255
+
256
+ labels_seen = (set(sl["per_label_tp"]) | set(sl["per_label_fp"])
257
+ | set(sl["per_label_fn"]))
258
+ if labels_seen:
259
+ print("\n per-label (span+label):")
260
+ for l in sorted(labels_seen):
261
+ tp = sl["per_label_tp"].get(l, 0)
262
+ fp = sl["per_label_fp"].get(l, 0)
263
+ fn = sl["per_label_fn"].get(l, 0)
264
+ p = tp / (tp + fp) if (tp + fp) else 0.0
265
+ r = tp / (tp + fn) if (tp + fn) else 0.0
266
+ f = 2*p*r/(p+r) if (p+r) else 0.0
267
+ print(f" {l:<22} P={p:.2f} R={r:.2f} F1={f:.2f} "
268
+ f"TP={tp} FP={fp} FN={fn}")
269
+
270
+
271
+ def main():
272
+ ap = argparse.ArgumentParser(description=__doc__,
273
+ formatter_class=argparse.RawDescriptionHelpFormatter)
274
+ ap.add_argument("--adapter", required=True, choices=sorted(ADAPTERS),
275
+ help="Which built-in adapter to use.")
276
+ ap.add_argument("--model", required=True,
277
+ help="HF Hub id or local path passed verbatim to the adapter.")
278
+ ap.add_argument("--spec", default=str(HERE / "eval.yaml"),
279
+ help="Path to eval.yaml (default: next to this file).")
280
+ ap.add_argument("--threshold", type=float, default=None,
281
+ help="Override default decoding threshold from the spec.")
282
+ ap.add_argument("--label-map", default="",
283
+ help="model_label=target_label,... (hf-pipeline only).")
284
+ ap.add_argument("--onnx", action="store_true",
285
+ help="GLiNER: load the ONNX file instead of PyTorch.")
286
+ ap.add_argument("--onnx-file", default="model_quantized.onnx")
287
+ ap.add_argument("--threads", type=int, default=8)
288
+ ap.add_argument("--device", type=int, default=-1,
289
+ help="hf-pipeline: -1 = CPU, 0 = first GPU.")
290
+ ap.add_argument("--limit", type=int, default=None,
291
+ help="Only score the first N records (smoke test).")
292
+ ap.add_argument("--save-predictions", default=None,
293
+ help="Write per-record predictions as JSONL to this path.")
294
+ ap.add_argument("--json", action="store_true",
295
+ help="Also dump the final metrics JSON to stdout.")
296
+ args = ap.parse_args()
297
+
298
+ spec = yaml.safe_load(open(args.spec))
299
+
300
+ repo = spec["dataset"]["repo_id"]
301
+ split = spec["dataset"]["split"]
302
+ print(f"Loading {repo}:{split} ...")
303
+ ds = load_dataset(repo, split=split)
304
+ if args.limit:
305
+ ds = ds.select(range(min(args.limit, len(ds))))
306
+
307
+ labels = spec["labels"]
308
+ proto = spec["inference_protocol"]
309
+ threshold = args.threshold if args.threshold is not None else proto["threshold"]
310
+ overrides = dict(proto.get("per_label_threshold_overrides") or {})
311
+
312
+ primary_metric = next(m for m in spec["metrics"] if m.get("primary"))
313
+ primary_iou = primary_metric.get("iou_threshold", 0.5)
314
+
315
+ print(f"Building adapter '{args.adapter}' over {args.model} ...")
316
+ cls = ADAPTERS[args.adapter]
317
+ adapter = cls(
318
+ model=args.model,
319
+ labels=labels,
320
+ threshold=threshold,
321
+ per_label_thresholds=overrides,
322
+ label_map=parse_kv(args.label_map),
323
+ onnx=args.onnx,
324
+ onnx_file=args.onnx_file,
325
+ threads=args.threads,
326
+ device=args.device,
327
+ )
328
+
329
+ print(f"Running over {len(ds)} records ...")
330
+ results = run(adapter, ds, primary_iou=primary_iou)
331
+
332
+ if args.save_predictions:
333
+ with open(args.save_predictions, "w") as f:
334
+ for rec, preds in zip(ds, results["predictions"]):
335
+ f.write(json.dumps({"id": rec.get("id"),
336
+ "text": rec["text"],
337
+ "predictions": preds}) + "\n")
338
+ print(f"Wrote per-record predictions -> {args.save_predictions}")
339
+
340
+ report(args.model, results)
341
+
342
+ if args.json:
343
+ slim = {k: v for k, v in results.items() if k != "predictions"}
344
+ print("\n" + json.dumps(slim, indent=2))
345
+
346
+
347
+ if __name__ == "__main__":
348
+ main()