OpenNLI-Leaderboard / evaluate.py
dleemiller's picture
evaluate.py: premise-only truncation (the hypothesis is never cut; longest-first only if the hypothesis alone cannot fit)
bd78ad9 verified
Raw History Blame Contribute Delete
18.2 kB
"""OpenNLI leaderboard: score an NLI cross-encoder on the public OpenNLI test sets.
pip install "sentence-transformers>=5" datasets pandas
python evaluate.py --model cross-encoder/nli-deberta-v3-base --out results.json
python evaluate.py --model dleemiller/finecat-nli-ultra-m --trust-remote-code # predictions -> preds/<model>/
Scoring (same as the leaderboard):
- every dataset is a config of dleemiller/OpenNLI-Leaderboard (split `test`);
- the model predicts entailment / neutral / contradiction (argmax of its 3 logits, mapped by the model's id2label);
- a row with label 0/1/2 is correct when the prediction matches; a 2-way row (label 3 = not_entailment) is correct when
the prediction is neutral or contradiction;
- dataset score = accuracy; category score = mean over its datasets; overall = mean of the category scores (macro);
- Skill Index (the leaderboard's headline, 2026-10-30) = Brier skill score per dataset, aggregated the same way:
skill = 1 - sum(Brier) / sum(Brier of a uniform guess), from the model's probabilities. 3-way rows: Brier summed over
the 3 classes, uniform guess 1/3 each (Brier 2/3). Rows of a 2-way dataset (and label-3 rows of a mixed one): the
entailment decision, Brier = 2 (P(entailment) - y)^2, uniform guess 1/2 (Brier 1/2). 0 = no better than guessing,
100 = always right with full confidence; negative = confidently wrong often enough to do worse than guessing,
floored at -100 per dataset (twice the guess's error), so one pathological dataset cannot swamp a category.
Brier is a proper scoring rule: it is the expected cost of acting on the probabilities over all cost trade-offs, so
it rewards both being right and being calibrated, and cannot be improved by misreporting confidence.
A model that only returns labels can be scored with one-hot probabilities.
Scored at a fitted temperature (2026-10-30): the logits are divided by one temperature per model, fitted to
maximise the Brier skill on the `calibration` config (11k rows from the validation / dev splits of 32 benchmarks,
never a test split), then applied to every test set. So the index measures the model once its confidence is
calibrated on held-out data, as a production user would; `temperature` reports how far off it was (1 = already
calibrated, > 1 = overconfident) and `skill_raw` is the score as shipped (T = 1).
- acc_skill = max(0, (accuracy - chance) / (1 - chance)) per dataset (chance 1/3 for 3-way, 1/2 for 2-way; mixed sets
weighted by their share of 2-way rows); auroc = AUROC of P(entailment) for entailment vs not; both aggregated the same way.
Calibration (on by default): per-row probabilities are saved (--preds-dir) and expected calibration error is reported
per dataset (15 equal-width confidence bins), averaged the same way as accuracy. 3-way rows: confidence = the top class
probability; 2-way rows: the binary decision P(entailment) vs 1 - P(entailment).
Truncation (2026-11-03): when a pair exceeds the context, only the PREMISE is cut (the hypothesis is the claim being
judged and is never truncated); a pair whose hypothesis alone cannot fit falls back to longest-first.
Inputs are scored whole up to the model's own context length (max_position_embeddings; RoBERTa 512 usable; models
without the field, e.g. RoPE-only configs, need --context), capped by --max-length. On GPU the model runs in bfloat16.
"""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from datasets import get_dataset_config_names, load_dataset
from sentence_transformers.cross_encoder import CrossEncoder
DATASET = "dleemiller/OpenNLI-Leaderboard"
NOT_ENT = 3
ECE_BINS = 15
def chance_level(df: pd.DataFrame) -> float:
"""Random choice among the task's labels: 1/3 (3-way), 1/2 (2-way); mixed sets weighted by their 2-way row share."""
sp = df.label_space.iat[0]
if sp == "3way":
return 1 / 3
if sp == "2way":
return 1 / 2
n3, n12 = int((df.label == NOT_ENT).sum()), int(df.label.isin([1, 2]).sum())
share = n3 / max(1, n3 + n12)
return share / 2 + (1 - share) / 3
def brier_skill(p: np.ndarray, label: np.ndarray, label_space: str, floor: float = -1.0) -> float:
"""Brier skill vs a uniform guess (see the module docstring). p: (n, 3) probabilities in entailment/neutral/contradiction order."""
p = p / p.sum(1, keepdims=True)
y = np.asarray(label)
two = np.full(len(y), label_space == "2way") | (y == NOT_ENT)
ye = (y == 0).astype(float)
b3 = ((p - np.eye(4)[y][:, :3]) ** 2).sum(1)
b2 = 2 * (p[:, 0] - ye) ** 2
return float(max(floor, 1 - np.where(two, b2, b3).sum() / np.where(two, 0.5, 2 / 3).sum()))
def softmax_t(lg: np.ndarray, t: float) -> np.ndarray:
z = lg / t
z = np.exp(z - z.max(1, keepdims=True))
return z / z.sum(1, keepdims=True)
def fit_temperature(items: list[tuple[str, np.ndarray, np.ndarray, str]]) -> float:
"""The single temperature (logits / T) that maximises the macro-average Brier skill over the given (category, logits,
label, label_space) sets (unfloored, categories weighted equally); T in [0.25, 20], searched on log T."""
from scipy.optimize import minimize_scalar
def neg(logt: float) -> float:
cat: dict[str, list[float]] = {}
for c, lg, y, sp in items:
cat.setdefault(c, []).append(brier_skill(softmax_t(lg, np.exp(logt)), y, sp, floor=-np.inf))
return -float(np.mean([np.mean(v) for v in cat.values()]))
return float(np.exp(minimize_scalar(neg, bounds=(np.log(0.25), np.log(20)), method="bounded", options={"xatol": 1e-3}).x))
def calibration_items(df: pd.DataFrame, lg: np.ndarray) -> list[tuple[str, np.ndarray, np.ndarray, str]]:
"""The calibration config's rows grouped by source dataset, as fit_temperature input."""
return [(g.category.iat[0], lg[g.index.to_numpy()], g.label.to_numpy(), g.label_space.iat[0]) for _, g in df.groupby("dataset")]
def auroc(p: np.ndarray, label: np.ndarray) -> float:
"""AUROC of P(entailment), entailment vs not (ties count half)."""
from scipy.stats import rankdata
pos = np.asarray(label) == 0
n1, n0 = int(pos.sum()), int((~pos).sum())
if not n1 or not n0:
return float("nan")
r = rankdata(p[:, 0])
return float((r[pos].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))
def calibration(p: np.ndarray, label: np.ndarray) -> dict:
"""ECE over rows: 3-way rows use the top-class confidence, 2-way rows (label 3) the entailment-vs-not decision."""
two = label == NOT_ENT
pe = p[:, 0]
conf = p.max(1)
correct = p.argmax(1) == label
# 2-way rows: decide entailment if P(ent) >= 0.5; confidence of that decision
conf = np.where(two, np.maximum(pe, 1 - pe), conf)
correct = np.where(two, pe < 0.5, correct)
bins = np.minimum((conf * ECE_BINS).astype(int), ECE_BINS - 1)
ece = sum(abs(correct[bins == b].mean() - conf[bins == b].mean()) * (bins == b).mean() for b in range(ECE_BINS) if (bins == b).any())
hist = [{"bin": b, "n": int((bins == b).sum()), "conf": float(conf[bins == b].mean()), "acc": float(correct[bins == b].mean())}
for b in range(ECE_BINS) if (bins == b).any()] # fmt: skip
return {"ece": float(ece), "mean_conf": float(conf.mean()), "acc_decision": float(correct.mean()), "bins": hist}
def model_context(cfg, override: int | None) -> int:
if override:
return override
ctx = getattr(cfg, "max_position_embeddings", None) or getattr(getattr(cfg, "encoder", None), "max_position_embeddings", None)
if not ctx and getattr(cfg, "model_type", "") == "neobert":
ctx = getattr(cfg, "max_length", None)
if not ctx and getattr(cfg, "model_type", "") == "ultrabert":
ctx = 32768 # RoPE-only config; native 32k context
if getattr(cfg, "model_type", "") in ("roberta", "xlm-roberta", "camembert") and ctx:
ctx -= 2 # positions start at padding_idx + 1: 514 slots = 512 usable tokens
return int(ctx or 512)
def label_columns(cfg, order: str | None) -> list[int]:
"""Logit columns for (entailment, neutral, contradiction)."""
if order: # e.g. "con,ent,neu" = the model's logit 0 is contradiction
names = [x.strip()[:3] for x in order.split(",")]
return [names.index(k) for k in ("ent", "neu", "con")]
i2l = {int(k): str(v).lower() for k, v in cfg.id2label.items()}
if any(v.startswith("entail") for v in i2l.values()):
return [next(k for k, v in i2l.items() if v.startswith(p)) for p in ("entail", "neutral", "contra")]
print(f"WARNING: generic labels {i2l}; assuming entailment, neutral, contradiction (pass --label-order otherwise)")
return [0, 1, 2]
def _premise_only(model: CrossEncoder, prem: list[str], hyp: list[str]) -> tuple[list[str], list[bool]]:
"""Per pair: does the hypothesis fit in the context with room for the premise? For sentence-transformers < 6 (no
per-call truncation setting) the premise is also pre-cut to its token budget here."""
tok, ml = model.tokenizer, model.max_length
special = tok.num_special_tokens_to_add(pair=True)
hl = [len(x) for x in tok(list(hyp), add_special_tokens=False)["input_ids"]]
fits = [h + special + 1 <= ml for h in hl]
if _ST_TRUNCATION_KW:
return list(prem), fits
out = []
for p, h, f in zip(prem, hl, fits):
ids = tok(p, add_special_tokens=False)["input_ids"]
out.append(tok.decode(ids[: ml - h - special]) if f and len(ids) > ml - h - special else p)
return out, fits
_ST_TRUNCATION_KW = "processing_kwargs" in __import__("inspect").signature(CrossEncoder.predict).parameters or \
int(__import__("sentence_transformers").__version__.split(".")[0]) >= 6
@torch.no_grad()
def logits(model: CrossEncoder, prem: list[str], hyp: list[str], cols: list[int], batch_tokens: int, max_batch: int = 512) -> np.ndarray:
"""Length-sorted batches under an approximate token budget (characters / 3); premise-only truncation."""
prem, fits = _premise_only(model, prem, hyp)
est = np.array([min(model.max_length, (len(p) + len(h)) // 3 + 8) for p, h in zip(prem, hyp)])
order = np.argsort(-est)
out = np.zeros((len(prem), 3), dtype=np.float32)
i = 0
while i < len(order):
b = order[i : i + max(1, min(max_batch, batch_tokens // int(est[order[i]])))]
for grp, mode in (([j for j in b if fits[j]], "only_first"), ([j for j in b if not fits[j]], "longest_first")):
if not grp:
continue
kw = {"processing_kwargs": {"text": {"truncation": mode}}} if _ST_TRUNCATION_KW else {}
lg = model.predict([(prem[j], hyp[j]) for j in grp], batch_size=len(grp), activation_fn=torch.nn.Identity(),
convert_to_numpy=True, show_progress_bar=False, **kw) # fmt: skip
out[grp] = np.asarray(lg, dtype=np.float32)[:, cols]
i += len(b)
return out
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--model", required=True, help="Hugging Face model id or local path (sentence-transformers CrossEncoder)")
ap.add_argument("--dataset", default=DATASET)
ap.add_argument("--sets", nargs="*", help="subset of dataset configs (default: all)")
ap.add_argument("--trust-remote-code", action="store_true", help="needed for models with custom code (e.g. UltraBERT)")
ap.add_argument("--label-order", help='logit order if the model has generic labels, e.g. "ent,neu,con"')
ap.add_argument("--context", type=int, help="override the model's context length (tokens)")
ap.add_argument("--max-length", type=int, default=32768, help="cap on input length (tokens)")
ap.add_argument("--batch-tokens", type=int, default=65536, help="approximate tokens per batch")
ap.add_argument("--max-batch", type=int, default=512, help="max pairs per batch (lower it on a shared GPU)")
ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
ap.add_argument("--limit", type=int, default=0, help="first N rows per set (smoke test; not leaderboard numbers)")
ap.add_argument("--calibration-only", action="store_true", help="score only the calibration config (temperature + its predictions)")
ap.add_argument("--out", default="results.json")
ap.add_argument("--preds-dir", help="per-set predictions (id, label, pred, probabilities); default preds/<model>")
ap.add_argument("--no-preds", action="store_true", help="do not save per-row predictions")
a = ap.parse_args()
model = CrossEncoder(a.model, device=a.device, trust_remote_code=a.trust_remote_code)
cfg = model.model.config
model.max_length = min(model_context(cfg, a.context), a.max_length)
if a.device.startswith("cuda"):
model.model.to(torch.bfloat16)
model.model.eval()
cols = label_columns(cfg, a.label_order)
print(f"{a.model}: context {model.max_length}, logit columns (ent, neu, con) = {cols}, device {a.device}", flush=True)
sets = [s for s in (a.sets or get_dataset_config_names(a.dataset)) if s != "calibration"]
# temperature first: fitted on the calibration config only
cdf = load_dataset(a.dataset, "calibration", split="validation").to_pandas()
if a.limit:
cdf = cdf.groupby("dataset", group_keys=False).head(a.limit).reset_index(drop=True)
clg = logits(model, cdf.premise.tolist(), cdf.hypothesis.tolist(), cols, a.batch_tokens, a.max_batch)
temp = fit_temperature(calibration_items(cdf, clg))
print(f"temperature {temp:.3f} (fitted on the calibration config, {len(cdf):,} rows)", flush=True)
if not a.no_preds:
pdir = Path(a.preds_dir or Path("preds") / a.model.replace("/", "__"))
pdir.mkdir(parents=True, exist_ok=True)
pd.DataFrame({"id": cdf.id, "dataset": cdf.dataset, "label": cdf.label, "logit_ent": clg[:, 0], "logit_neu": clg[:, 1],
"logit_con": clg[:, 2]}).to_parquet(pdir / "calibration.parquet", index=False) # fmt: skip
if a.calibration_only:
Path(a.out).write_text(json.dumps({"model": a.model, "dataset": a.dataset, "temperature": temp, "calibration_rows": len(cdf)}, indent=1))
return
results, cats, n_total, t_total = {}, {}, 0, 0.0
for name in sets:
df = load_dataset(a.dataset, name, split="test").to_pandas()
if a.limit:
df = df.head(a.limit)
if a.device.startswith("cuda"):
torch.cuda.synchronize()
t0 = time.perf_counter()
lg = logits(model, df.premise.tolist(), df.hypothesis.tolist(), cols, a.batch_tokens, a.max_batch)
if a.device.startswith("cuda"):
torch.cuda.synchronize()
dt = time.perf_counter() - t0
pred, label = lg.argmax(1), df.label.to_numpy()
ok = np.where(label == NOT_ENT, pred != 0, pred == label)
cat = df.category.iat[0]
prob = torch.softmax(torch.from_numpy(lg), -1).numpy()
cal = calibration(prob, label)
ch = chance_level(df)
results[name] = {"category": cat, "n": len(df), "accuracy": float(ok.mean()), "chance": ch,
"skill_raw": brier_skill(prob, label, df.label_space.iat[0]), "acc_skill": max(0.0, (float(ok.mean()) - ch) / (1 - ch)),
"auroc": auroc(prob, label), "ece": cal["ece"], "mean_conf": cal["mean_conf"],
"calibration_bins": cal["bins"], "seconds": round(dt, 2)} # fmt: skip
cats.setdefault(cat, []).append(float(ok.mean()))
n_total, t_total = n_total + len(df), t_total + dt
print(f"{name:18s} {cat:10s} n={len(df):6d} acc={ok.mean():.4f} skill(T=1)={results[name]['skill_raw']:+.4f} ece={cal['ece']:.4f} ({len(df) / dt:.0f} pairs/s)", flush=True)
results[name]["skill"] = brier_skill(softmax_t(lg, temp), label, df.label_space.iat[0])
if not a.no_preds:
pdir = Path(a.preds_dir or Path("preds") / a.model.replace("/", "__"))
pdir.mkdir(parents=True, exist_ok=True)
pd.DataFrame({"id": df.id, "label": label, "pred": pred, "logit_ent": lg[:, 0], "logit_neu": lg[:, 1], "logit_con": lg[:, 2],
"p_ent": prob[:, 0], "p_neu": prob[:, 1], "p_con": prob[:, 2]}).to_parquet(pdir / f"{name}.parquet", index=False) # fmt: skip
cat_scores = {c: float(np.mean(v)) for c, v in cats.items()}
cat_ece = {c: float(np.mean([r["ece"] for r in results.values() if r["category"] == c])) for c in cats}
cat_mean = lambda key: {c: float(np.nanmean([r[key] for r in results.values() if r["category"] == c])) for c in cats} # noqa: E731
cat_skill, cat_skill_raw, cat_acc_skill, cat_auroc = cat_mean("skill"), cat_mean("skill_raw"), cat_mean("acc_skill"), cat_mean("auroc")
summary = {"model": a.model, "dataset": a.dataset, "context": model.max_length, "device": a.device, "limit": a.limit or None,
"overall": float(np.mean(list(cat_scores.values()))), "categories": cat_scores,
"skill_overall": float(np.mean(list(cat_skill.values()))), "skill_categories": cat_skill,
"temperature": temp, "skill_raw_overall": float(np.mean(list(cat_skill_raw.values()))),
"acc_skill_overall": float(np.mean(list(cat_acc_skill.values()))), "auroc_overall": float(np.mean(list(cat_auroc.values()))),
"ece_overall": float(np.mean(list(cat_ece.values()))), "ece_categories": cat_ece,
"dataset_mean": float(np.mean([r["accuracy"] for r in results.values()])),
"throughput_pairs_per_s": round(n_total / t_total, 1) if t_total else None, "sets": results} # fmt: skip
Path(a.out).write_text(json.dumps(summary, indent=1))
print("\n" + " ".join(f"{c}={v * 100:.1f}" for c, v in cat_scores.items()) + f" overall={summary['overall'] * 100:.1f}"
+ f" skill={summary['skill_overall'] * 100:.1f} (T={temp:.2f}; as shipped {summary['skill_raw_overall'] * 100:.1f}) ECE={summary['ece_overall'] * 100:.1f} -> {a.out}")
if __name__ == "__main__":
main()