dleemiller commited on
Commit
c2d2e87
·
verified ·
1 Parent(s): e294207

Add the calibration config (11,018 validation/dev rows, 32 benchmarks); evaluate.py: Skill Index = Brier skill at a temperature fitted on it

Browse files
Files changed (3) hide show
  1. README.md +13 -0
  2. calibration/validation.parquet +3 -0
  3. evaluate.py +91 -8
README.md CHANGED
@@ -184,6 +184,10 @@ configs:
184
  data_files:
185
  - split: test
186
  path: crossingguard/test.parquet
 
 
 
 
187
  ---
188
 
189
  # OpenNLI eval sets
@@ -207,6 +211,8 @@ Labels are mapped from the model's `id2label`, or use `--label-order` (e.g. `ent
207
  - accuracy per dataset
208
  - category score = mean over datasets
209
  - overall = mean of the 4 category scores.
 
 
210
 
211
  >[!Note]
212
  > For license information, refer to the original dataset's license.
@@ -215,6 +221,13 @@ Labels are mapped from the model's `id2label`, or use `--label-order` (e.g. `ent
215
  > DocNLI (1,000) and VitaminC (10,000) are fixed random samples of their test splits.
216
 
217
 
 
 
 
 
 
 
 
218
  | Config | Dataset | Category | Rows | Labels |
219
  | --- | --- | --- | ---: | --- |
220
  | `mnli` | MNLI-m | NLI | 9,815 | 3way |
 
184
  data_files:
185
  - split: test
186
  path: crossingguard/test.parquet
187
+ - config_name: calibration
188
+ data_files:
189
+ - split: validation
190
+ path: calibration/validation.parquet
191
  ---
192
 
193
  # OpenNLI eval sets
 
211
  - accuracy per dataset
212
  - category score = mean over datasets
213
  - overall = mean of the 4 category scores.
214
+ - Skill Index (the leaderboard headline) = Brier skill vs a uniform guess, per dataset (floored at −100), averaged the same
215
+ way, at each model's fitted temperature (see Calibration).
216
 
217
  >[!Note]
218
  > For license information, refer to the original dataset's license.
 
221
  > DocNLI (1,000) and VitaminC (10,000) are fixed random samples of their test splits.
222
 
223
 
224
+ ## Calibration
225
+
226
+ The `calibration` config (split `validation`, 11,018 rows) is used only to fit each model's temperature: one number that
227
+ rescales the model's confidence before the Skill Index is computed. It's drawn from the validation / dev splits of 32
228
+ benchmarks (never a test split), up to 400 rows each, labelled like the test sets, with no text overlapping any test set.
229
+ Models may calibrate on it however they like; it never scores anything.
230
+
231
  | Config | Dataset | Category | Rows | Labels |
232
  | --- | --- | --- | ---: | --- |
233
  | `mnli` | MNLI-m | NLI | 9,815 | 3way |
calibration/validation.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55d02d454c4205438b93ea280737a0b77a0efc1fa277e9be2ea29f000832a724
3
+ size 9678332
evaluate.py CHANGED
@@ -10,8 +10,22 @@ Scoring (same as the leaderboard):
10
  - a row with label 0/1/2 is correct when the prediction matches; a 2-way row (label 3 = not_entailment) is correct when
11
  the prediction is neutral or contradiction;
12
  - dataset score = accuracy; category score = mean over its datasets; overall = mean of the category scores (macro);
13
- - skill (the leaderboard's default view) = max(0, (accuracy - chance) / (1 - chance)) per dataset, chance = 1/3 for 3-way
14
- and 1/2 for 2-way datasets (mixed sets: weighted by their share of 2-way rows), aggregated the same way.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  Calibration (on by default): per-row probabilities are saved (--preds-dir) and expected calibration error is reported
16
  per dataset (15 equal-width confidence bins), averaged the same way as accuracy. 3-way rows: confidence = the top class
17
  probability; 2-way rows: the binary decision P(entailment) vs 1 - P(entailment).
@@ -49,6 +63,54 @@ def chance_level(df: pd.DataFrame) -> float:
49
  return share / 2 + (1 - share) / 3
50
 
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  def calibration(p: np.ndarray, label: np.ndarray) -> dict:
53
  """ECE over rows: 3-way rows use the top-class confidence, 2-way rows (label 3) the entailment-vs-not decision."""
54
  two = label == NOT_ENT
@@ -119,6 +181,7 @@ def main():
119
  ap.add_argument("--max-batch", type=int, default=512, help="max pairs per batch (lower it on a shared GPU)")
120
  ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
121
  ap.add_argument("--limit", type=int, default=0, help="first N rows per set (smoke test; not leaderboard numbers)")
 
122
  ap.add_argument("--out", default="results.json")
123
  ap.add_argument("--preds-dir", help="per-set predictions (id, label, pred, probabilities); default preds/<model>")
124
  ap.add_argument("--no-preds", action="store_true", help="do not save per-row predictions")
@@ -133,7 +196,22 @@ def main():
133
  cols = label_columns(cfg, a.label_order)
134
  print(f"{a.model}: context {model.max_length}, logit columns (ent, neu, con) = {cols}, device {a.device}", flush=True)
135
 
136
- sets = a.sets or get_dataset_config_names(a.dataset)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  results, cats, n_total, t_total = {}, {}, 0, 0.0
138
  for name in sets:
139
  df = load_dataset(a.dataset, name, split="test").to_pandas()
@@ -152,12 +230,14 @@ def main():
152
  prob = torch.softmax(torch.from_numpy(lg), -1).numpy()
153
  cal = calibration(prob, label)
154
  ch = chance_level(df)
155
- results[name] = {"category": cat, "n": len(df), "accuracy": float(ok.mean()), "chance": ch, "skill": max(0.0, (float(ok.mean()) - ch) / (1 - ch)),
156
- "ece": cal["ece"], "mean_conf": cal["mean_conf"],
 
157
  "calibration_bins": cal["bins"], "seconds": round(dt, 2)} # fmt: skip
158
  cats.setdefault(cat, []).append(float(ok.mean()))
159
  n_total, t_total = n_total + len(df), t_total + dt
160
- print(f"{name:18s} {cat:10s} n={len(df):6d} acc={ok.mean():.4f} ece={cal['ece']:.4f} ({len(df) / dt:.0f} pairs/s)", flush=True)
 
161
  if not a.no_preds:
162
  pdir = Path(a.preds_dir or Path("preds") / a.model.replace("/", "__"))
163
  pdir.mkdir(parents=True, exist_ok=True)
@@ -166,16 +246,19 @@ def main():
166
 
167
  cat_scores = {c: float(np.mean(v)) for c, v in cats.items()}
168
  cat_ece = {c: float(np.mean([r["ece"] for r in results.values() if r["category"] == c])) for c in cats}
169
- cat_skill = {c: float(np.mean([r["skill"] for r in results.values() if r["category"] == c])) for c in cats}
 
170
  summary = {"model": a.model, "dataset": a.dataset, "context": model.max_length, "device": a.device, "limit": a.limit or None,
171
  "overall": float(np.mean(list(cat_scores.values()))), "categories": cat_scores,
172
  "skill_overall": float(np.mean(list(cat_skill.values()))), "skill_categories": cat_skill,
 
 
173
  "ece_overall": float(np.mean(list(cat_ece.values()))), "ece_categories": cat_ece,
174
  "dataset_mean": float(np.mean([r["accuracy"] for r in results.values()])),
175
  "throughput_pairs_per_s": round(n_total / t_total, 1) if t_total else None, "sets": results} # fmt: skip
176
  Path(a.out).write_text(json.dumps(summary, indent=1))
177
  print("\n" + " ".join(f"{c}={v * 100:.1f}" for c, v in cat_scores.items()) + f" overall={summary['overall'] * 100:.1f}"
178
- + f" skill={summary['skill_overall'] * 100:.1f} ECE={summary['ece_overall'] * 100:.1f} -> {a.out}")
179
 
180
 
181
  if __name__ == "__main__":
 
10
  - a row with label 0/1/2 is correct when the prediction matches; a 2-way row (label 3 = not_entailment) is correct when
11
  the prediction is neutral or contradiction;
12
  - dataset score = accuracy; category score = mean over its datasets; overall = mean of the category scores (macro);
13
+ - Skill Index (the leaderboard's headline, 2026-10-30) = Brier skill score per dataset, aggregated the same way:
14
+ skill = 1 - sum(Brier) / sum(Brier of a uniform guess), from the model's probabilities. 3-way rows: Brier summed over
15
+ 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
16
+ entailment decision, Brier = 2 (P(entailment) - y)^2, uniform guess 1/2 (Brier 1/2). 0 = no better than guessing,
17
+ 100 = always right with full confidence; negative = confidently wrong often enough to do worse than guessing,
18
+ floored at -100 per dataset (twice the guess's error), so one pathological dataset cannot swamp a category.
19
+ Brier is a proper scoring rule: it is the expected cost of acting on the probabilities over all cost trade-offs, so
20
+ it rewards both being right and being calibrated, and cannot be improved by misreporting confidence.
21
+ A model that only returns labels can be scored with one-hot probabilities.
22
+ Scored at a fitted temperature (2026-10-30): the logits are divided by one temperature per model, fitted to
23
+ maximise the Brier skill on the `calibration` config (11k rows from the validation / dev splits of 32 benchmarks,
24
+ never a test split), then applied to every test set. So the index measures the model once its confidence is
25
+ calibrated on held-out data, as a production user would; `temperature` reports how far off it was (1 = already
26
+ calibrated, > 1 = overconfident) and `skill_raw` is the score as shipped (T = 1).
27
+ - acc_skill = max(0, (accuracy - chance) / (1 - chance)) per dataset (chance 1/3 for 3-way, 1/2 for 2-way; mixed sets
28
+ weighted by their share of 2-way rows); auroc = AUROC of P(entailment) for entailment vs not; both aggregated the same way.
29
  Calibration (on by default): per-row probabilities are saved (--preds-dir) and expected calibration error is reported
30
  per dataset (15 equal-width confidence bins), averaged the same way as accuracy. 3-way rows: confidence = the top class
31
  probability; 2-way rows: the binary decision P(entailment) vs 1 - P(entailment).
 
63
  return share / 2 + (1 - share) / 3
64
 
65
 
66
+ def brier_skill(p: np.ndarray, label: np.ndarray, label_space: str, floor: float = -1.0) -> float:
67
+ """Brier skill vs a uniform guess (see the module docstring). p: (n, 3) probabilities in entailment/neutral/contradiction order."""
68
+ p = p / p.sum(1, keepdims=True)
69
+ y = np.asarray(label)
70
+ two = np.full(len(y), label_space == "2way") | (y == NOT_ENT)
71
+ ye = (y == 0).astype(float)
72
+ b3 = ((p - np.eye(4)[y][:, :3]) ** 2).sum(1)
73
+ b2 = 2 * (p[:, 0] - ye) ** 2
74
+ return float(max(floor, 1 - np.where(two, b2, b3).sum() / np.where(two, 0.5, 2 / 3).sum()))
75
+
76
+
77
+ def softmax_t(lg: np.ndarray, t: float) -> np.ndarray:
78
+ z = lg / t
79
+ z = np.exp(z - z.max(1, keepdims=True))
80
+ return z / z.sum(1, keepdims=True)
81
+
82
+
83
+ def fit_temperature(items: list[tuple[str, np.ndarray, np.ndarray, str]]) -> float:
84
+ """The single temperature (logits / T) that maximises the macro-average Brier skill over the given (category, logits,
85
+ label, label_space) sets (unfloored, categories weighted equally); T in [0.25, 20], searched on log T."""
86
+ from scipy.optimize import minimize_scalar
87
+
88
+ def neg(logt: float) -> float:
89
+ cat: dict[str, list[float]] = {}
90
+ for c, lg, y, sp in items:
91
+ cat.setdefault(c, []).append(brier_skill(softmax_t(lg, np.exp(logt)), y, sp, floor=-np.inf))
92
+ return -float(np.mean([np.mean(v) for v in cat.values()]))
93
+
94
+ return float(np.exp(minimize_scalar(neg, bounds=(np.log(0.25), np.log(20)), method="bounded", options={"xatol": 1e-3}).x))
95
+
96
+
97
+ def calibration_items(df: pd.DataFrame, lg: np.ndarray) -> list[tuple[str, np.ndarray, np.ndarray, str]]:
98
+ """The calibration config's rows grouped by source dataset, as fit_temperature input."""
99
+ 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")]
100
+
101
+
102
+ def auroc(p: np.ndarray, label: np.ndarray) -> float:
103
+ """AUROC of P(entailment), entailment vs not (ties count half)."""
104
+ from scipy.stats import rankdata
105
+
106
+ pos = np.asarray(label) == 0
107
+ n1, n0 = int(pos.sum()), int((~pos).sum())
108
+ if not n1 or not n0:
109
+ return float("nan")
110
+ r = rankdata(p[:, 0])
111
+ return float((r[pos].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))
112
+
113
+
114
  def calibration(p: np.ndarray, label: np.ndarray) -> dict:
115
  """ECE over rows: 3-way rows use the top-class confidence, 2-way rows (label 3) the entailment-vs-not decision."""
116
  two = label == NOT_ENT
 
181
  ap.add_argument("--max-batch", type=int, default=512, help="max pairs per batch (lower it on a shared GPU)")
182
  ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
183
  ap.add_argument("--limit", type=int, default=0, help="first N rows per set (smoke test; not leaderboard numbers)")
184
+ ap.add_argument("--calibration-only", action="store_true", help="score only the calibration config (temperature + its predictions)")
185
  ap.add_argument("--out", default="results.json")
186
  ap.add_argument("--preds-dir", help="per-set predictions (id, label, pred, probabilities); default preds/<model>")
187
  ap.add_argument("--no-preds", action="store_true", help="do not save per-row predictions")
 
196
  cols = label_columns(cfg, a.label_order)
197
  print(f"{a.model}: context {model.max_length}, logit columns (ent, neu, con) = {cols}, device {a.device}", flush=True)
198
 
199
+ sets = [s for s in (a.sets or get_dataset_config_names(a.dataset)) if s != "calibration"]
200
+ # temperature first: fitted on the calibration config only
201
+ cdf = load_dataset(a.dataset, "calibration", split="validation").to_pandas()
202
+ if a.limit:
203
+ cdf = cdf.groupby("dataset", group_keys=False).head(a.limit).reset_index(drop=True)
204
+ clg = logits(model, cdf.premise.tolist(), cdf.hypothesis.tolist(), cols, a.batch_tokens, a.max_batch)
205
+ temp = fit_temperature(calibration_items(cdf, clg))
206
+ print(f"temperature {temp:.3f} (fitted on the calibration config, {len(cdf):,} rows)", flush=True)
207
+ if not a.no_preds:
208
+ pdir = Path(a.preds_dir or Path("preds") / a.model.replace("/", "__"))
209
+ pdir.mkdir(parents=True, exist_ok=True)
210
+ pd.DataFrame({"id": cdf.id, "dataset": cdf.dataset, "label": cdf.label, "logit_ent": clg[:, 0], "logit_neu": clg[:, 1],
211
+ "logit_con": clg[:, 2]}).to_parquet(pdir / "calibration.parquet", index=False) # fmt: skip
212
+ if a.calibration_only:
213
+ Path(a.out).write_text(json.dumps({"model": a.model, "dataset": a.dataset, "temperature": temp, "calibration_rows": len(cdf)}, indent=1))
214
+ return
215
  results, cats, n_total, t_total = {}, {}, 0, 0.0
216
  for name in sets:
217
  df = load_dataset(a.dataset, name, split="test").to_pandas()
 
230
  prob = torch.softmax(torch.from_numpy(lg), -1).numpy()
231
  cal = calibration(prob, label)
232
  ch = chance_level(df)
233
+ results[name] = {"category": cat, "n": len(df), "accuracy": float(ok.mean()), "chance": ch,
234
+ "skill_raw": brier_skill(prob, label, df.label_space.iat[0]), "acc_skill": max(0.0, (float(ok.mean()) - ch) / (1 - ch)),
235
+ "auroc": auroc(prob, label), "ece": cal["ece"], "mean_conf": cal["mean_conf"],
236
  "calibration_bins": cal["bins"], "seconds": round(dt, 2)} # fmt: skip
237
  cats.setdefault(cat, []).append(float(ok.mean()))
238
  n_total, t_total = n_total + len(df), t_total + dt
239
+ 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)
240
+ results[name]["skill"] = brier_skill(softmax_t(lg, temp), label, df.label_space.iat[0])
241
  if not a.no_preds:
242
  pdir = Path(a.preds_dir or Path("preds") / a.model.replace("/", "__"))
243
  pdir.mkdir(parents=True, exist_ok=True)
 
246
 
247
  cat_scores = {c: float(np.mean(v)) for c, v in cats.items()}
248
  cat_ece = {c: float(np.mean([r["ece"] for r in results.values() if r["category"] == c])) for c in cats}
249
+ 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
250
+ cat_skill, cat_skill_raw, cat_acc_skill, cat_auroc = cat_mean("skill"), cat_mean("skill_raw"), cat_mean("acc_skill"), cat_mean("auroc")
251
  summary = {"model": a.model, "dataset": a.dataset, "context": model.max_length, "device": a.device, "limit": a.limit or None,
252
  "overall": float(np.mean(list(cat_scores.values()))), "categories": cat_scores,
253
  "skill_overall": float(np.mean(list(cat_skill.values()))), "skill_categories": cat_skill,
254
+ "temperature": temp, "skill_raw_overall": float(np.mean(list(cat_skill_raw.values()))),
255
+ "acc_skill_overall": float(np.mean(list(cat_acc_skill.values()))), "auroc_overall": float(np.mean(list(cat_auroc.values()))),
256
  "ece_overall": float(np.mean(list(cat_ece.values()))), "ece_categories": cat_ece,
257
  "dataset_mean": float(np.mean([r["accuracy"] for r in results.values()])),
258
  "throughput_pairs_per_s": round(n_total / t_total, 1) if t_total else None, "sets": results} # fmt: skip
259
  Path(a.out).write_text(json.dumps(summary, indent=1))
260
  print("\n" + " ".join(f"{c}={v * 100:.1f}" for c, v in cat_scores.items()) + f" overall={summary['overall'] * 100:.1f}"
261
+ + 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}")
262
 
263
 
264
  if __name__ == "__main__":