evalsuite-python 0.6.0__cp39-abi3-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. evalsuite/__init__.py +268 -0
  2. evalsuite/__main__.py +5 -0
  3. evalsuite/_bench_metrics.py +2080 -0
  4. evalsuite/_core.pyd +0 -0
  5. evalsuite/_lazy.py +32 -0
  6. evalsuite/_native.py +60 -0
  7. evalsuite/api.py +275 -0
  8. evalsuite/benchmarks.py +946 -0
  9. evalsuite/calibration.py +392 -0
  10. evalsuite/classification/__init__.py +51 -0
  11. evalsuite/classification/_common.py +111 -0
  12. evalsuite/classification/metrics.py +945 -0
  13. evalsuite/cli/__init__.py +5 -0
  14. evalsuite/cli/main.py +606 -0
  15. evalsuite/clinical/__init__.py +18 -0
  16. evalsuite/clinical/metrics.py +342 -0
  17. evalsuite/clinical/report.py +366 -0
  18. evalsuite/core/__init__.py +1 -0
  19. evalsuite/core/context.py +199 -0
  20. evalsuite/core/exceptions.py +52 -0
  21. evalsuite/core/export.py +100 -0
  22. evalsuite/core/registry.py +90 -0
  23. evalsuite/core/result.py +379 -0
  24. evalsuite/core/types.py +23 -0
  25. evalsuite/core/validation.py +256 -0
  26. evalsuite/llmsys/__init__.py +189 -0
  27. evalsuite/llmsys/_common.py +215 -0
  28. evalsuite/llmsys/agents.py +384 -0
  29. evalsuite/llmsys/code.py +923 -0
  30. evalsuite/llmsys/efficiency.py +346 -0
  31. evalsuite/llmsys/longcontext.py +361 -0
  32. evalsuite/llmsys/multilingual.py +339 -0
  33. evalsuite/llmsys/robustness.py +504 -0
  34. evalsuite/llmsys/safety.py +509 -0
  35. evalsuite/llmsys/uncertainty.py +229 -0
  36. evalsuite/plot.py +651 -0
  37. evalsuite/py.typed +0 -0
  38. evalsuite/regression/__init__.py +41 -0
  39. evalsuite/regression/metrics.py +629 -0
  40. evalsuite/reporting.py +241 -0
  41. evalsuite/stats/__init__.py +46 -0
  42. evalsuite/stats/_resolve.py +229 -0
  43. evalsuite/stats/compare.py +420 -0
  44. evalsuite/stats/effect.py +159 -0
  45. evalsuite/stats/hypothesis.py +593 -0
  46. evalsuite/stats/intervals.py +338 -0
  47. evalsuite/stats/paired.py +214 -0
  48. evalsuite/stats/results.py +129 -0
  49. evalsuite/text/__init__.py +154 -0
  50. evalsuite/text/_common.py +97 -0
  51. evalsuite/text/factuality.py +469 -0
  52. evalsuite/text/generation.py +1346 -0
  53. evalsuite/text/judge.py +556 -0
  54. evalsuite/text/qa.py +108 -0
  55. evalsuite/text/rag.py +235 -0
  56. evalsuite/text/reasoning.py +215 -0
  57. evalsuite/text/report.py +158 -0
  58. evalsuite/text/retrieval.py +238 -0
  59. evalsuite/text/semantic.py +499 -0
  60. evalsuite/text/spice.py +162 -0
  61. evalsuite/text/structured.py +793 -0
  62. evalsuite/version.py +3 -0
  63. evalsuite/vision/__init__.py +47 -0
  64. evalsuite/vision/detection.py +696 -0
  65. evalsuite/vision/segmentation.py +1028 -0
  66. evalsuite_python-0.6.0.dist-info/METADATA +509 -0
  67. evalsuite_python-0.6.0.dist-info/RECORD +72 -0
  68. evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
  69. evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
  70. evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
  71. evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
  72. evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
@@ -0,0 +1,504 @@
1
+ """Robustness and reliability (v0.5.0): adversarial, paraphrase, noise, out-of-distribution and distribution
2
+ shift, counterfactual invariance, response stability, failures and recovery, prompt sensitivity and
3
+ long-context truncation.
4
+
5
+ Correctness verdicts come from your own scorer (exact match, a judge, unit tests); these functions compare
6
+ them across conditions. ``add_typos`` generates reproducible typographical noise for robustness tests.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import string
12
+ from collections import Counter
13
+ from collections.abc import Mapping, Sequence
14
+ from itertools import combinations
15
+ from typing import Any, Callable, Optional
16
+
17
+ import numpy as np
18
+
19
+ from ..core.exceptions import InputValidationError
20
+ from ..core.registry import register
21
+ from ..core.result import MetricResult
22
+ from ._common import bools, floats, lists_of, rate, same_length, seq
23
+
24
+ __all__ = [
25
+ "add_typos",
26
+ "adversarial_robustness",
27
+ "contradiction_rate",
28
+ "distribution_shift_drop",
29
+ "error_rate",
30
+ "invariance_violation_rate",
31
+ "noise_robustness",
32
+ "ood_accuracy",
33
+ "paraphrase_consistency",
34
+ "prompt_sensitivity",
35
+ "recovery_success_rate",
36
+ "response_stability",
37
+ "truncation_sensitivity",
38
+ ]
39
+
40
+ _C = "robustness"
41
+ _REF_ADVGLUE = (
42
+ "Wang B, Xu C, Wang S, et al. Adversarial GLUE: a multi-task benchmark for robustness evaluation of language "
43
+ "models. NeurIPS Datasets and Benchmarks. 2021."
44
+ )
45
+ _REF_CHECKLIST = (
46
+ "Ribeiro MT, Wu T, Guestrin C, Singh S. Beyond accuracy: behavioral testing of NLP models with CheckList. "
47
+ "ACL. 2020:4902-4912."
48
+ )
49
+ _REF_PROMPTBENCH = (
50
+ "Zhu K, Wang J, Zhou J, et al. PromptRobust: towards evaluating the robustness of large language models on "
51
+ "adversarial prompts. arXiv:2306.04528. 2023."
52
+ )
53
+ _REF_WILDS = (
54
+ "Koh PW, Sagawa S, Marklund H, et al. WILDS: a benchmark of in-the-wild distribution shifts. ICML. "
55
+ "2021:5637-5664."
56
+ )
57
+ _REF_HELM = "Liang P, Bommasani R, Lee T, et al. Holistic evaluation of language models. TMLR. 2023."
58
+ _REF_SCLAR = (
59
+ "Sclar M, Choi Y, Tsvetkov Y, Suhr A. Quantifying language models' sensitivity to spurious features in prompt "
60
+ "design. ICLR. 2024."
61
+ )
62
+ _REF_ELAZAR = (
63
+ "Elazar Y, Kassner N, Ravfogel S, et al. Measuring and improving consistency in pretrained language models. "
64
+ "TACL. 2021;9:1012-1031."
65
+ )
66
+ _REF_MANAKUL = (
67
+ "Manakul P, Liusie A, Gales MJF. SelfCheckGPT: zero-resource black-box hallucination detection for generative "
68
+ "large language models. EMNLP. 2023:9004-9017."
69
+ )
70
+ _REF_KAUSHIK = (
71
+ "Kaushik D, Hovy E, Lipton ZC. Learning the difference that makes a difference with counterfactually-"
72
+ "augmented data. ICLR. 2020."
73
+ )
74
+ _REF_BELINKOV = (
75
+ "Belinkov Y, Bisk Y. Synthetic and natural noise both break neural machine translation. ICLR. 2018."
76
+ )
77
+ _REF_HSIEH = (
78
+ "Hsieh CP, Sun S, Kriman S, et al. RULER: what's the real context size of your long-context language models? "
79
+ "COLM. 2024."
80
+ )
81
+
82
+
83
+ def _pair(clean: Any, perturbed: Any, a: str, b: str) -> tuple[np.ndarray, np.ndarray]:
84
+ c, p = bools(clean, a), bools(perturbed, b)
85
+ same_length((a, c), (b, p))
86
+ return c, p
87
+
88
+
89
+ def _drop_result(
90
+ metric: str, name: str, c: np.ndarray, p: np.ndarray, extra: Optional[dict[str, Any]] = None
91
+ ) -> MetricResult:
92
+ ca, pa = float(c.mean()), float(p.mean())
93
+ flipped = int((c & ~p).sum())
94
+ params = {
95
+ "clean_accuracy": ca,
96
+ "perturbed_accuracy": pa,
97
+ "absolute_drop": ca - pa,
98
+ "relative_drop": (ca - pa) / ca if ca > 0 else float("nan"),
99
+ "flip_rate": flipped / int(c.sum()) if c.any() else float("nan"),
100
+ "n": int(c.size),
101
+ **(extra or {}),
102
+ }
103
+ return MetricResult(metric, name, pa, params)
104
+
105
+
106
+ @register(
107
+ category=_C,
108
+ task="robustness",
109
+ name="Adversarial robustness",
110
+ definition="Accuracy under adversarial perturbation (robust accuracy), with the clean accuracy, the drop and "
111
+ "the attack success rate: the share of originally correct examples the attack flips.",
112
+ formula="robust acc = mean[correct_adv]; ASR = #(correct_clean ∧ ¬correct_adv) / #correct_clean",
113
+ range="[0, 1]",
114
+ input_requirements=("clean_correct", "adversarial_correct"),
115
+ references=(_REF_ADVGLUE, _REF_PROMPTBENCH),
116
+ )
117
+ def adversarial_robustness(clean_correct: Any, adversarial_correct: Any) -> MetricResult:
118
+ c, p = _pair(clean_correct, adversarial_correct, "clean_correct", "adversarial_correct")
119
+ r = _drop_result("adversarial_robustness", "Robust accuracy", c, p)
120
+ return MetricResult(r.metric, r.name, r.value, {**r.params, "attack_success_rate": r.params["flip_rate"]})
121
+
122
+
123
+ @register(
124
+ category=_C,
125
+ task="robustness",
126
+ name="Typographical-noise robustness",
127
+ definition="Accuracy on inputs with typos (character swaps, deletions, insertions, substitutions) relative to "
128
+ "clean inputs: perturbed accuracy, absolute and relative drop and flip rate. ``add_typos`` makes the noisy "
129
+ "inputs reproducibly.",
130
+ formula="acc_noisy; drop = acc_clean − acc_noisy",
131
+ range="[0, 1]",
132
+ input_requirements=("clean_correct", "noisy_correct"),
133
+ references=(_REF_BELINKOV, _REF_CHECKLIST),
134
+ )
135
+ def noise_robustness(clean_correct: Any, noisy_correct: Any) -> MetricResult:
136
+ c, p = _pair(clean_correct, noisy_correct, "clean_correct", "noisy_correct")
137
+ return _drop_result("noise_robustness", "Noisy-input accuracy", c, p)
138
+
139
+
140
+ def add_typos(texts: Any, *, rate: float = 0.05, random_state: Optional[int] = None) -> list[str]:
141
+ """Introduce character-level typos into each text: each letter is perturbed with probability ``rate`` by a
142
+ swap with its neighbour, deletion, insertion or substitution (equally likely). Reproducible with
143
+ ``random_state``."""
144
+ items = seq(texts, "texts")
145
+ if not 0 <= rate <= 1:
146
+ raise InputValidationError("rate must be in [0, 1].")
147
+ rng = np.random.default_rng(random_state)
148
+ letters = string.ascii_lowercase
149
+ out = []
150
+ for i, t in enumerate(items):
151
+ if not isinstance(t, str):
152
+ raise InputValidationError(f"texts[{i}] must be a string.")
153
+ chars = list(t)
154
+ j = 0
155
+ res: list[str] = []
156
+ while j < len(chars):
157
+ ch = chars[j]
158
+ if ch.isalpha() and rng.random() < rate:
159
+ op = int(rng.integers(4))
160
+ if op == 0 and j + 1 < len(chars):
161
+ res += [chars[j + 1], ch]
162
+ j += 2
163
+ continue
164
+ if op == 1:
165
+ j += 1
166
+ continue
167
+ if op == 2:
168
+ res += [ch, letters[int(rng.integers(26))]]
169
+ else:
170
+ res.append(letters[int(rng.integers(26))])
171
+ else:
172
+ res.append(ch)
173
+ j += 1
174
+ out.append("".join(res))
175
+ return out
176
+
177
+
178
+ def _norm(v: Any, normalize: Optional[Callable[[Any], Any]]) -> Any:
179
+ if normalize is not None:
180
+ return normalize(v)
181
+ return " ".join(v.lower().split()) if isinstance(v, str) else v
182
+
183
+
184
+ @register(
185
+ category=_C,
186
+ task="consistency",
187
+ name="Paraphrase consistency",
188
+ definition="Whether the model gives the same answer to paraphrases of the same question: the share of items "
189
+ "where all paraphrases agree, and the mean pairwise agreement (ParaRel consistency).",
190
+ formula="mean_items 1[all answers equal]; pairwise = mean over pairs 1[a_i = a_j]",
191
+ range="[0, 1]",
192
+ input_requirements=("answers",),
193
+ references=(_REF_ELAZAR, _REF_CHECKLIST),
194
+ )
195
+ def paraphrase_consistency(answers: Any, *, normalize: Optional[Callable[[Any], Any]] = None) -> MetricResult:
196
+ """``answers``: per item, the answers to each paraphrase (at least two). Strings are compared after
197
+ lower-casing and whitespace normalisation unless ``normalize`` is given."""
198
+ rows = lists_of(answers, "answers")
199
+ if any(len(r) < 2 for r in rows):
200
+ raise InputValidationError("Every item needs answers to at least two paraphrases.")
201
+ full, pair = [], []
202
+ for r in rows:
203
+ v = [_norm(a, normalize) for a in r]
204
+ full.append(all(x == v[0] for x in v))
205
+ pair.append(np.mean([x == y for x, y in combinations(v, 2)]))
206
+ return MetricResult(
207
+ "paraphrase_consistency",
208
+ "Paraphrase consistency",
209
+ float(np.mean(full)),
210
+ {"pairwise_agreement": float(np.mean(pair)), "n_items": len(rows)},
211
+ )
212
+
213
+
214
+ @register(
215
+ category=_C,
216
+ task="generalization",
217
+ name="Out-of-distribution accuracy",
218
+ definition="Accuracy on out-of-distribution examples, with in-distribution accuracy and the gap (WILDS "
219
+ "reports both; the gap is the generalisation cost).",
220
+ formula="acc_OOD = mean[correct | OOD]; gap = acc_ID − acc_OOD",
221
+ range="[0, 1]",
222
+ input_requirements=("correct", "is_ood"),
223
+ references=(_REF_WILDS,),
224
+ )
225
+ def ood_accuracy(correct: Any, is_ood: Any) -> MetricResult:
226
+ c, o = _pair(correct, is_ood, "correct", "is_ood")
227
+ if not o.any() or o.all():
228
+ raise InputValidationError("Need both in-distribution and out-of-distribution examples.")
229
+ ood, ind = float(c[o].mean()), float(c[~o].mean())
230
+ return MetricResult(
231
+ "ood_accuracy",
232
+ "Out-of-distribution accuracy",
233
+ ood,
234
+ {"id_accuracy": ind, "gap": ind - ood, "n_ood": int(o.sum()), "n_id": int((~o).sum())},
235
+ )
236
+
237
+
238
+ @register(
239
+ category=_C,
240
+ task="generalization",
241
+ name="Distribution-shift performance drop",
242
+ definition="Change in a per-example score from the source to the shifted (target) distribution: absolute and "
243
+ "relative drop with a 95% Welch interval for the absolute drop.",
244
+ formula="drop = mean(source) − mean(target); relative = drop / mean(source)",
245
+ range="(−∞, ∞) (0 = no drop)",
246
+ input_requirements=("source_scores", "target_scores"),
247
+ references=(_REF_WILDS, _REF_HELM),
248
+ higher_is_better=False,
249
+ )
250
+ def distribution_shift_drop(source_scores: Any, target_scores: Any) -> MetricResult:
251
+ s = floats(source_scores, "source_scores")
252
+ t = floats(target_scores, "target_scores")
253
+ from scipy import stats
254
+
255
+ drop = float(s.mean() - t.mean())
256
+ if s.size > 1 and t.size > 1:
257
+ vs, vt = s.var(ddof=1) / s.size, t.var(ddof=1) / t.size
258
+ se = float(np.sqrt(vs + vt))
259
+ dof = (vs + vt) ** 2 / (vs**2 / (s.size - 1) + vt**2 / (t.size - 1)) if vs + vt > 0 else np.inf
260
+ q = float(stats.t.ppf(0.975, dof)) if np.isfinite(dof) else 1.959963984540054
261
+ ci = (drop - q * se, drop + q * se)
262
+ else:
263
+ ci = (float("nan"), float("nan"))
264
+ return MetricResult(
265
+ "distribution_shift_drop",
266
+ "Distribution-shift performance drop",
267
+ drop,
268
+ {
269
+ "source_mean": float(s.mean()),
270
+ "target_mean": float(t.mean()),
271
+ "relative_drop": drop / float(s.mean()) if s.mean() != 0 else float("nan"),
272
+ "ci_low": ci[0],
273
+ "ci_high": ci[1],
274
+ },
275
+ )
276
+
277
+
278
+ @register(
279
+ category=_C,
280
+ task="consistency",
281
+ name="Counterfactual invariance violation rate",
282
+ definition="Share of examples whose prediction changes when only a protected or irrelevant attribute is "
283
+ "changed (names, gender terms, dialect): violations of an invariance test.",
284
+ formula="mean[pred(x) ≠ pred(x')]",
285
+ range="[0, 1]",
286
+ input_requirements=("original_predictions", "counterfactual_predictions"),
287
+ references=(_REF_CHECKLIST, _REF_KAUSHIK),
288
+ higher_is_better=False,
289
+ )
290
+ def invariance_violation_rate(
291
+ original_predictions: Any,
292
+ counterfactual_predictions: Any,
293
+ *,
294
+ normalize: Optional[Callable[[Any], Any]] = None,
295
+ groups: Optional[Sequence[Any]] = None,
296
+ ) -> MetricResult:
297
+ o = seq(original_predictions, "original_predictions")
298
+ c = seq(counterfactual_predictions, "counterfactual_predictions")
299
+ same_length(("original_predictions", o), ("counterfactual_predictions", c))
300
+ flags = np.array([_norm(a, normalize) != _norm(b, normalize) for a, b in zip(o, c)])
301
+ extra: dict[str, Any] = {"counterfactual_consistency": 1 - float(flags.mean())}
302
+ if groups is not None:
303
+ from ._common import by_group
304
+
305
+ extra["by_group"] = by_group(flags.astype(float), groups)
306
+ return rate("invariance_violation_rate", "Invariance violation rate", flags, extra)
307
+
308
+
309
+ @register(
310
+ category=_C,
311
+ task="consistency",
312
+ name="Response stability",
313
+ definition="Agreement among repeated samples for the same prompt: the mean pairwise agreement and the share "
314
+ "of prompts where every sample agrees, plus the mean share held by the most common answer.",
315
+ formula="mean_prompts mean_{i<j} 1[a_i = a_j]",
316
+ range="[0, 1]",
317
+ input_requirements=("samples",),
318
+ references=(_REF_MANAKUL, _REF_ELAZAR),
319
+ )
320
+ def response_stability(samples: Any, *, normalize: Optional[Callable[[Any], Any]] = None) -> MetricResult:
321
+ rows = lists_of(samples, "samples")
322
+ if any(len(r) < 2 for r in rows):
323
+ raise InputValidationError("Every prompt needs at least two samples.")
324
+ pair, unanimous, modal = [], [], []
325
+ for r in rows:
326
+ v = [_norm(a, normalize) for a in r]
327
+ pair.append(np.mean([x == y for x, y in combinations(v, 2)]))
328
+ unanimous.append(all(x == v[0] for x in v))
329
+ modal.append(Counter(map(repr, v)).most_common(1)[0][1] / len(v))
330
+ return MetricResult(
331
+ "response_stability",
332
+ "Response stability",
333
+ float(np.mean(pair)),
334
+ {
335
+ "unanimous_rate": float(np.mean(unanimous)),
336
+ "modal_share": float(np.mean(modal)),
337
+ "n_prompts": len(rows),
338
+ },
339
+ )
340
+
341
+
342
+ _NLI = {"contradiction", "entailment", "neutral"}
343
+
344
+
345
+ @register(
346
+ category=_C,
347
+ task="consistency",
348
+ name="Contradiction rate",
349
+ definition="Share of compared response pairs (repeated samples, or answers to related questions) that an NLI "
350
+ "model or judge labels as contradicting each other (SelfCheckGPT-NLI style).",
351
+ formula="#contradiction / #pairs",
352
+ range="[0, 1]",
353
+ input_requirements=("pair_labels",),
354
+ references=(_REF_MANAKUL,),
355
+ higher_is_better=False,
356
+ )
357
+ def contradiction_rate(pair_labels: Any) -> MetricResult:
358
+ """``pair_labels``: per compared pair, ``"contradiction"``, ``"entailment"`` or ``"neutral"`` (or a list of
359
+ such labels per prompt; all pairs are pooled)."""
360
+ items = seq(pair_labels, "pair_labels")
361
+ flat = []
362
+ for i, v in enumerate(items):
363
+ for lab in v if isinstance(v, (list, tuple)) else [v]:
364
+ if lab not in _NLI:
365
+ raise InputValidationError(f"pair_labels[{i}] must be one of {sorted(_NLI)}; got {lab!r}.")
366
+ flat.append(lab == "contradiction")
367
+ if not flat:
368
+ raise InputValidationError("pair_labels contains no pairs.")
369
+ return rate("contradiction_rate", "Contradiction rate", np.array(flat))
370
+
371
+
372
+ _STATUSES = ("ok", "error", "timeout")
373
+
374
+
375
+ @register(
376
+ category=_C,
377
+ task="reliability",
378
+ name="Failure / timeout / error rate",
379
+ definition="Share of requests that did not complete normally, split into errors and timeouts (any other "
380
+ "status label is counted as its own failure kind).",
381
+ formula="(#error + #timeout + …) / #requests",
382
+ range="[0, 1]",
383
+ input_requirements=("statuses",),
384
+ references=(_REF_HELM,),
385
+ higher_is_better=False,
386
+ )
387
+ def error_rate(statuses: Any, *, ok: Sequence[Any] = ("ok", "success", 200, True)) -> MetricResult:
388
+ """``statuses``: one status per request (``"ok"``, ``"error"``, ``"timeout"``, an HTTP code, ...). Values in
389
+ ``ok`` count as success."""
390
+ items = seq(statuses, "statuses")
391
+ oks = set(ok)
392
+ fail = np.array([s not in oks for s in items])
393
+ counts = Counter(str(s) for s in items if s not in oks)
394
+ n = len(items)
395
+ return rate(
396
+ "error_rate",
397
+ "Failure rate",
398
+ fail,
399
+ {"by_status": {k: v / n for k, v in sorted(counts.items())}, "timeout_rate": counts.get("timeout", 0) / n},
400
+ )
401
+
402
+
403
+ @register(
404
+ category=_C,
405
+ task="reliability",
406
+ name="Recovery success rate",
407
+ definition="Among episodes in which a failure occurred (an error, a failed tool call, a wrong intermediate "
408
+ "step), the share from which the system recovered and still completed the task.",
409
+ formula="#(failed ∧ recovered) / #failed",
410
+ range="[0, 1]",
411
+ input_requirements=("failed", "recovered"),
412
+ references=(_REF_HELM,),
413
+ )
414
+ def recovery_success_rate(failed: Any, recovered: Any) -> MetricResult:
415
+ f, r = _pair(failed, recovered, "failed", "recovered")
416
+ if (r & ~f).any():
417
+ raise InputValidationError("recovered is True for an episode where failed is False.")
418
+ if not f.any():
419
+ raise InputValidationError("No episode failed: the recovery rate is undefined.")
420
+ return rate("recovery_success_rate", "Recovery success rate", r[f], {"failure_rate": float(f.mean())})
421
+
422
+
423
+ @register(
424
+ category=_C,
425
+ task="robustness",
426
+ name="Prompt wording sensitivity",
427
+ definition="Spread of task performance across semantically equivalent prompt templates: the range (best − "
428
+ "worst accuracy), standard deviation and worst-case accuracy over templates (FormatSpread).",
429
+ formula="spread = max_t acc_t − min_t acc_t",
430
+ range="[0, 1]",
431
+ input_requirements=("correct_by_template",),
432
+ references=(_REF_SCLAR, _REF_PROMPTBENCH),
433
+ higher_is_better=False,
434
+ )
435
+ def prompt_sensitivity(correct_by_template: Any) -> MetricResult:
436
+ """``correct_by_template``: mapping template name -> per-example correctness (or scores), the same examples
437
+ under every template; or a 2-D array (templates × examples)."""
438
+ if isinstance(correct_by_template, Mapping):
439
+ names = [str(k) for k in correct_by_template]
440
+ mat = [
441
+ floats(np.asarray(v, dtype=float), f"correct_by_template[{k!r}]")
442
+ for k, v in correct_by_template.items()
443
+ ]
444
+ else:
445
+ arr = np.asarray(correct_by_template, dtype=float)
446
+ if arr.ndim != 2:
447
+ raise InputValidationError(
448
+ "correct_by_template must be a mapping or a 2-D array (templates × examples)."
449
+ )
450
+ names = [str(i) for i in range(arr.shape[0])]
451
+ mat = [floats(row, f"correct_by_template[{i}]") for i, row in enumerate(arr)]
452
+ if len(mat) < 2:
453
+ raise InputValidationError("Need at least two prompt templates.")
454
+ if len({m.size for m in mat}) != 1:
455
+ raise InputValidationError("Every template must be scored on the same examples.")
456
+ acc = np.array([m.mean() for m in mat])
457
+ per_example = np.vstack(mat)
458
+ flips = float(np.mean(per_example.max(0) != per_example.min(0)))
459
+ return MetricResult(
460
+ "prompt_sensitivity",
461
+ "Prompt sensitivity (spread)",
462
+ float(acc.max() - acc.min()),
463
+ {
464
+ "std": float(acc.std(ddof=1)),
465
+ "worst": float(acc.min()),
466
+ "best": float(acc.max()),
467
+ "mean": float(acc.mean()),
468
+ "by_template": dict(zip(names, acc.tolist())),
469
+ "example_disagreement_rate": flips,
470
+ },
471
+ )
472
+
473
+
474
+ @register(
475
+ category=_C,
476
+ task="long-context",
477
+ name="Long-context robustness / truncation sensitivity",
478
+ definition="How performance changes with context length or truncation: accuracy per length bucket and the "
479
+ "least-squares slope of accuracy against log2 length (negative = degrades as context grows).",
480
+ formula="slope of acc_b on log2(len_b)",
481
+ range="(−∞, ∞)",
482
+ input_requirements=("correct", "context_lengths"),
483
+ references=(_REF_HSIEH,),
484
+ higher_is_better=True,
485
+ )
486
+ def truncation_sensitivity(correct: Any, context_lengths: Any) -> MetricResult:
487
+ c = floats(np.asarray(seq(correct, "correct"), dtype=float), "correct")
488
+ lens = floats(context_lengths, "context_lengths", lo=1)
489
+ same_length(("correct", c), ("context_lengths", lens))
490
+ levels = np.unique(lens)
491
+ if levels.size < 2:
492
+ raise InputValidationError("Need at least two distinct context lengths.")
493
+ acc = np.array([c[lens == v].mean() for v in levels])
494
+ x = np.log2(levels)
495
+ slope = float(np.polyfit(x, acc, 1)[0])
496
+ return MetricResult(
497
+ "truncation_sensitivity",
498
+ "Accuracy slope per doubling of context",
499
+ slope,
500
+ {
501
+ "by_length": {str(int(v) if float(v).is_integer() else v): float(a) for v, a in zip(levels, acc)},
502
+ "drop_shortest_to_longest": float(acc[0] - acc[-1]),
503
+ },
504
+ )