#!/usr/bin/env python3 """Evaluate one span-extraction arm on the frozen val split. Identical code path for a zero-shot base model and for a fine-tuned checkpoint. Emits a JSON with the full threshold sweep so the bakeoff never has to guess a threshold, plus the selected operating point chosen by the Golden Rule (highest exact_match among thresholds meeting over-deletion < 1.0%). Usage: venv/bin/python eval_span.py --model --tag --out [--cpu-latency] [--export-onnx] """ import argparse import json import os import sys import time import numpy as np import torch from transformers import AutoModelForTokenClassification, AutoTokenizer sys.path.insert(0, "/opt/vox/sandbox/scripts") from span_common import ( # noqa: E402 LABELS, MAX_LEN, decode_bio, load_jsonl, split_words, sweep_thresholds, ) THRESHOLDS = [0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.97, 0.99, 0.995] @torch.no_grad() def predict(rows, tok, model, device, max_len=MAX_LEN, batch_size=32): """Returns {threshold: [char spans per row]} in one forward pass per row.""" probs = [] order = sorted(range(len(rows)), key=lambda i: len(rows[i]["raw_text"])) out = [None] * len(rows) for b in range(0, len(order), batch_size): chunk = order[b:b + batch_size] encs, wids_all = [], [] for i in chunk: words, _, _ = split_words(rows[i]["raw_text"]) e = tok(words, is_split_into_words=True, truncation=True, max_length=max_len) encs.append(e) wids_all.append(e.word_ids()) pad = tok.pad(encs, return_tensors="pt") pad = {k: v.to(device) for k, v in pad.items()} logits = model(**pad).logits.float() p = torch.softmax(logits, dim=-1).cpu().numpy() for j, i in enumerate(chunk): wids = wids_all[j] if wids is None: out[i] = ([], []) continue p_inspan = np.zeros(len(wids)) p_begin = np.zeros(len(wids)) for t, w in enumerate(wids): if w is None or t >= p.shape[1]: continue pr = p[j][t] p_inspan[w] = max(0.0, 1.0 - pr[0]) tot = pr[1] + pr[2] p_begin[w] = (pr[1] / tot) if tot > 1e-9 else 0.5 out[i] = (p_inspan, p_begin) for t in THRESHOLDS: preds = [decode_bio(rows[i]["raw_text"], out[i][0], out[i][1], t) for i in range(len(rows))] probs.append((t, preds)) return dict(probs) def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--tag", required=True) ap.add_argument("--out", required=True) ap.add_argument("--val", default="/opt/vox/sandbox/corpus/pilot_v2_val.jsonl") ap.add_argument("--max-len", type=int, default=MAX_LEN) ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") ap.add_argument("--cpu-latency", action="store_true") ap.add_argument("--export-onnx", action="store_true") ap.add_argument("--onnx-int8", action="store_true") ap.add_argument("--latency-threads", type=int, default=16) args = ap.parse_args() rows = load_jsonl(args.val) tok = AutoTokenizer.from_pretrained(args.model) model = AutoModelForTokenClassification.from_pretrained(args.model, dtype=torch.float32).to(args.device).eval() t0 = time.time() preds_by_thr = predict(rows, tok, model, args.device, args.max_len) gpu_s = time.time() - t0 res = sweep_thresholds(rows, preds_by_thr, THRESHOLDS) n_par = sum(p.numel() for p in model.parameters()) / 1e6 out = { "tag": args.tag, "model": args.model, "params_m": round(n_par, 2), "n_val": len(rows), "eval_device": args.device, "eval_wall_s": round(gpu_s, 2), "best": res["best"], "sweep": res["sweep"], } # ONNX is a Layer 5 shipping concern, not an accuracy gate (user-directed # 2026-10-03). It must never be able to kill an accuracy measurement. if args.export_onnx: try: out["onnx"] = export_and_check(model, tok, rows, args) except Exception as e: out["onnx"] = {"error": f"{type(e).__name__}: {str(e)[:200]}"} print(f"[{args.tag}] onnx export FAILED (non-fatal): {type(e).__name__}: {str(e)[:120]}", flush=True) if args.cpu_latency: try: out["cpu_latency"] = measure_cpu(model, tok, rows, args) except Exception as e: out["cpu_latency"] = {"error": f"{type(e).__name__}: {str(e)[:200]}"} print(f"[{args.tag}] cpu latency FAILED (non-fatal): {type(e).__name__}", flush=True) os.makedirs(os.path.dirname(args.out), exist_ok=True) with open(args.out, "w") as f: json.dump(out, f, indent=2) b = out["best"] print(f"[{args.tag}] P={b['span_word']['precision']} R={b['span_word']['recall']} " f"EM={b['exact_match']} overdel={b['over_deletion_rate']}% " f"harmful={b['harmful_span_rate']}% thr={b['threshold']} passes={b['passes_gate']}", flush=True) def export_and_check(model, tok, rows, args): """ONNX export -> optional int8 dynamic quant -> char-level parity vs PyTorch. Parity is the gate, not F1: a silent divergence here becomes a word corruption bug in the Rust runtime. """ import onnx import onnxruntime as ort from onnxruntime.quantization import QuantType, quantize_dynamic res = {} onnx_dir = os.path.join(os.path.dirname(args.out), f"onnx_{args.tag}") os.makedirs(onnx_dir, exist_ok=True) fp32_path = os.path.join(onnx_dir, "model.onnx") # Export must run on CPU: the live model may be on CUDA while the tracer's # dummy inputs are not, which silently produced a device-mismatch RuntimeError # for all six arms until this was found. was_device = next(model.parameters()).device model = model.cpu() dummy = tok(["We need to upgrade the database."], return_tensors="pt", padding=True) torch.onnx.export( model, (dummy["input_ids"], dummy["attention_mask"]), fp32_path, input_names=["input_ids", "attention_mask"], output_names=["logits"], dynamic_axes={k: {0: "b", 1: "s"} for k in ("input_ids", "attention_mask")} | {"logits": {0: "b", 1: "s"}}, opset_version=17, do_constant_folding=True, dynamo=False, ) onnx.checker.check_model(fp32_path) res["fp32_bytes"] = os.path.getsize(fp32_path) res["opset"] = 17 cand = fp32_path if args.onnx_int8: int8_path = os.path.join(onnx_dir, "model_int8.onnx") quantize_dynamic(fp32_path, int8_path, weight_type=QuantType.QInt8) onnx.checker.check_model(int8_path) res["int8_bytes"] = os.path.getsize(int8_path) res["int8_compression"] = round(res["fp32_bytes"] / res["int8_bytes"], 2) cand = int8_path res["checked_path"] = cand # char-level parity: does the exported model decode to the same spans? sess = ort.InferenceSession(cand, providers=["CPUExecutionProvider"]) sub = rows[:200] mism = 0 for r in sub: words, _, _ = split_words(r["raw_text"]) e = tok(words, is_split_into_words=True, truncation=True, max_length=args.max_len, return_tensors="np") ort_out = sess.run(None, {"input_ids": e["input_ids"], "attention_mask": e["attention_mask"]})[0] probs = torch.softmax(torch.tensor(ort_out), dim=-1).numpy()[0] wids = tok(words, is_split_into_words=True, truncation=True, max_length=args.max_len).word_ids() pi = np.zeros(len(wids)); pb = np.zeros(len(wids)) for t, w in enumerate(wids): if w is None or t >= probs.shape[0]: continue pi[w] = max(0.0, 1.0 - probs[t][0]) tot = probs[t][1] + probs[t][2] pb[w] = (probs[t][1] / tot) if tot > 1e-9 else 0.5 ort_spans = decode_bio(r["raw_text"], pi, pb, 0.5) with torch.no_grad(): pt = model(input_ids=e["input_ids"].to(args.device), attention_mask=e["attention_mask"].to(args.device)).logits.float().cpu().numpy()[0] pp = torch.softmax(torch.tensor(pt), dim=-1).numpy() pi2 = np.zeros(len(wids)); pb2 = np.zeros(len(wids)) for t, w in enumerate(wids): if w is None or t >= pp.shape[0]: continue pi2[w] = max(0.0, 1.0 - pp[t][0]) tot = pp[t][1] + pp[t][2] pb2[w] = (pp[t][1] / tot) if tot > 1e-9 else 0.5 if decode_bio(r["raw_text"], pi2, pb2, 0.5) != ort_spans: mism += 1 res["parity_rows"] = len(sub) res["parity_mismatch"] = mism res["parity_rate"] = round(100.0 * (len(sub) - mism) / len(sub), 2) res["parity_pass"] = res["parity_rate"] >= 99.0 model = model.to(was_device) return res def measure_cpu(model, tok, rows, args): """CPU p50/p95 at production thread count. Invariant 9: client HW is >=2x slower.""" import shutil m = AutoModelForTokenClassification.from_pretrained(args.model, dtype=torch.float32) t = AutoTokenizer.from_pretrained(args.model) torch.set_num_threads(args.latency_threads) try: torch.set_num_interop_threads(1) except RuntimeError: pass m.eval() texts = [r["raw_text"] for r in rows[:200]] with torch.no_grad(): for s in texts[:20]: w, _, _ = split_words(s) e = t(w, is_split_into_words=True, truncation=True, max_length=args.max_len, return_tensors="pt", padding=True) m(input_ids=e["input_ids"], attention_mask=e["attention_mask"]) lat = [] for s in texts: w, _, _ = split_words(s) t0 = time.perf_counter() e = t(w, is_split_into_words=True, truncation=True, max_length=args.max_len, return_tensors="pt", padding=True) m(input_ids=e["input_ids"], attention_mask=e["attention_mask"]) lat.append((time.perf_counter() - t0) * 1000.0) lat = np.array(lat) return { "threads": args.latency_threads, "n": len(lat), "p50_ms": round(float(np.percentile(lat, 50)), 2), "p95_ms": round(float(np.percentile(lat, 95)), 2), "mean_ms": round(float(lat.mean()), 2), "client_2x_p95_ms": round(float(np.percentile(lat, 95)) * 2, 2), "note": "2x multiplier per AGENTS.md invariant 9", } if __name__ == "__main__": main()