evalsuite-python 0.6.0__cp39-abi3-win_amd64.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,556 @@
1
+ """LLM-as-a-judge and preference evaluation: rubric scores, win rates, Bradley–Terry and Elo ratings,
2
+ inter-rater agreement and judge bias checks.
3
+
4
+ The judge itself (a model, a panel or human raters) is yours; these functions turn its outputs into
5
+ reported numbers with the usual EvalSuite guarantees (validated inputs, documented conventions, intervals).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from collections.abc import Sequence
12
+ from typing import TYPE_CHECKING, Any, Optional
13
+
14
+ import numpy as np
15
+
16
+ if TYPE_CHECKING:
17
+ from scipy import stats
18
+ else:
19
+ from .._lazy import lazy_module
20
+
21
+ stats = lazy_module("scipy.stats")
22
+
23
+ from ..core.exceptions import InputValidationError
24
+ from ..core.registry import register
25
+ from ..core.result import MetricResult
26
+ from ._common import per_item
27
+
28
+ __all__ = [
29
+ "bradley_terry",
30
+ "elo_ratings",
31
+ "fleiss_kappa",
32
+ "judge_agreement",
33
+ "krippendorff_alpha",
34
+ "position_consistency",
35
+ "rubric_score",
36
+ "self_preference_bias",
37
+ "verbosity_bias",
38
+ "win_rate",
39
+ ]
40
+
41
+ _C = "text"
42
+ _REF_BT = "Bradley RA, Terry ME. Rank analysis of incomplete block designs. Biometrika. 1952;39(3/4):324-345."
43
+ _REF_HUNTER = "Hunter DR. MM algorithms for generalized Bradley-Terry models. Ann Stat. 2004;32(1):384-406."
44
+ _REF_ELO = "Elo AE. The Rating of Chessplayers, Past and Present. Arco; 1978."
45
+ _REF_ARENA = (
46
+ "Chiang WL, Zheng L, Sheng Y, et al. Chatbot Arena: an open platform for evaluating LLMs by human "
47
+ "preference. ICML. 2024."
48
+ )
49
+ _REF_KRIPP = "Krippendorff K. Content Analysis: An Introduction to Its Methodology. 4th ed. Sage; 2018."
50
+ _REF_FLEISS = "Fleiss JL. Measuring nominal scale agreement among many raters. Psychol Bull. 1971;76(5):378-382."
51
+ _REF_JUDGE = (
52
+ "Zheng L, Chiang WL, Sheng Y, et al. Judging LLM-as-a-judge with MT-Bench and Chatbot Arena. NeurIPS "
53
+ "Datasets and Benchmarks. 2023."
54
+ )
55
+ _REF_SELF = (
56
+ "Panickssery A, Bowman SR, Feng S. LLM evaluators recognize and favor their own generations. NeurIPS. 2024."
57
+ )
58
+ _REF_WILSON = (
59
+ "Wilson EB. Probable inference, the law of succession, and statistical inference. JASA. 1927;22:209-212."
60
+ )
61
+
62
+
63
+ def _outcome(v: Any) -> float:
64
+ if isinstance(v, str):
65
+ s = v.strip().lower()
66
+ if s in ("win", "w", "a", "1"):
67
+ return 1.0
68
+ if s in ("loss", "lose", "l", "b", "0"):
69
+ return 0.0
70
+ if s in ("tie", "draw", "t", "0.5"):
71
+ return 0.5
72
+ elif isinstance(v, (bool, np.bool_)) or (
73
+ isinstance(v, (int, float, np.integer, np.floating)) and float(v) in (0.0, 0.5, 1.0)
74
+ ):
75
+ return float(v)
76
+ raise InputValidationError(f"Outcome must be 'win', 'loss', 'tie' (or 1, 0, 0.5); got {v!r}.")
77
+
78
+
79
+ def _wilson(k: float, n: float, z: float = 1.959963984540054) -> tuple[float, float]:
80
+ if n == 0:
81
+ return float("nan"), float("nan")
82
+ p = k / n
83
+ centre = (p + z * z / (2 * n)) / (1 + z * z / n)
84
+ half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
85
+ return centre - half, centre + half
86
+
87
+
88
+ # ---------------------------------------------------------------- pairwise preferences
89
+ @register(
90
+ category=_C,
91
+ task="preference",
92
+ name="Pairwise win rate",
93
+ definition="Share of pairwise comparisons in which a system's response is preferred to the baseline; ties "
94
+ "count half (or are excluded). A Wilson interval is reported.",
95
+ formula="(wins + ½ ties) / comparisons",
96
+ range="[0, 1]",
97
+ input_requirements=("outcomes",),
98
+ references=(_REF_JUDGE, _REF_WILSON),
99
+ )
100
+ @per_item
101
+ def win_rate(outcomes: Any, *, ties: str = "half") -> MetricResult:
102
+ """Win rate from outcomes ``"win" / "loss" / "tie"`` (or 1 / 0 / 0.5) of the system against a baseline.
103
+ ``ties="half"`` counts a tie as half a win; ``"exclude"`` drops ties."""
104
+ vals = np.array([_outcome(v) for v in outcomes], dtype=float)
105
+ if vals.size == 0:
106
+ raise InputValidationError("outcomes is empty.")
107
+ if ties == "exclude":
108
+ vals = vals[vals != 0.5]
109
+ if vals.size == 0:
110
+ raise InputValidationError("Every comparison is a tie; the win rate excluding ties is undefined.")
111
+ elif ties != "half":
112
+ raise InputValidationError("ties must be 'half' or 'exclude'.")
113
+ wins = float(vals.sum())
114
+ low, high = _wilson(wins, vals.size)
115
+ return MetricResult(
116
+ "win_rate",
117
+ "Win rate",
118
+ wins / vals.size,
119
+ {"ties": ties, "n": int(vals.size), "n_ties": int(np.sum(vals == 0.5)), "ci_low": low, "ci_high": high},
120
+ )
121
+
122
+
123
+ def _comparisons(comparisons: Any) -> tuple[list[Any], list[tuple[int, int, float]]]:
124
+ rows = list(comparisons)
125
+ if not rows:
126
+ raise InputValidationError("comparisons is empty.")
127
+ names: dict[Any, int] = {}
128
+ out = []
129
+ for i, row in enumerate(rows):
130
+ if len(row) != 3:
131
+ raise InputValidationError(f"comparisons[{i}] must be (model_a, model_b, outcome for model_a).")
132
+ a, b, o = row
133
+ if a == b:
134
+ raise InputValidationError(f"comparisons[{i}] compares {a!r} with itself.")
135
+ ia, ib = names.setdefault(a, len(names)), names.setdefault(b, len(names))
136
+ out.append((ia, ib, _outcome(o)))
137
+ return list(names), out
138
+
139
+
140
+ @register(
141
+ category=_C,
142
+ task="preference",
143
+ name="Bradley–Terry scores",
144
+ definition="Maximum-likelihood strengths of a Bradley–Terry model fitted to pairwise preferences (ties as "
145
+ "half a win for each side), by Hunter's MM algorithm; reported as log-strengths centred at 0 or on the "
146
+ "Elo-like Chatbot Arena scale.",
147
+ formula="P(i beats j) = π_i / (π_i + π_j)",
148
+ range="(−∞, ∞)",
149
+ input_requirements=("comparisons",),
150
+ references=(_REF_BT, _REF_HUNTER, _REF_ARENA),
151
+ )
152
+ def bradley_terry(
153
+ comparisons: Any, *, scale: str = "log", max_iter: int = 10_000, tol: float = 1e-10
154
+ ) -> MetricResult:
155
+ """Bradley–Terry ratings from ``(model_a, model_b, outcome)`` rows, outcome for ``model_a`` being
156
+ ``"win" / "loss" / "tie"``. ``scale="log"`` returns natural-log strengths with mean 0 (as ``choix``);
157
+ ``"elo"`` maps them to ``1000 + 400·log10(π)``. The comparison graph must be connected and no model may win
158
+ or lose every comparison, otherwise the MLE does not exist."""
159
+ names, rows = _comparisons(comparisons)
160
+ m = len(names)
161
+ wins = np.zeros((m, m))
162
+ for a, b, o in rows:
163
+ wins[a, b] += o
164
+ wins[b, a] += 1 - o
165
+ games = wins + wins.T
166
+ total_w = wins.sum(axis=1)
167
+ if np.any(total_w == 0) or np.any(total_w == games.sum(axis=1)):
168
+ raise InputValidationError(
169
+ "The Bradley–Terry MLE does not exist: some model wins or loses every comparison. Add comparisons or "
170
+ "use a prior."
171
+ )
172
+ reach = (games > 0).astype(int)
173
+ seen, frontier = {0}, [0]
174
+ while frontier:
175
+ i = frontier.pop()
176
+ for j in np.flatnonzero(reach[i]):
177
+ if j not in seen:
178
+ seen.add(int(j))
179
+ frontier.append(int(j))
180
+ if len(seen) != m:
181
+ raise InputValidationError(
182
+ "The comparison graph is not connected; ratings are not comparable across parts."
183
+ )
184
+ p = np.ones(m)
185
+ for _ in range(max_iter):
186
+ denom = (games / (p[:, None] + p[None, :])).sum(axis=1)
187
+ new = total_w / denom
188
+ new /= np.exp(np.mean(np.log(new)))
189
+ if np.max(np.abs(np.log(new) - np.log(p))) < tol:
190
+ p = new
191
+ break
192
+ p = new
193
+ logp = np.log(p) - np.mean(np.log(p))
194
+ if scale == "log":
195
+ value = logp
196
+ elif scale == "elo":
197
+ value = 1000 + 400 * logp / math.log(10)
198
+ else:
199
+ raise InputValidationError("scale must be 'log' or 'elo'.")
200
+ return MetricResult(
201
+ "bradley_terry",
202
+ "Bradley–Terry score",
203
+ np.asarray(value),
204
+ {"scale": scale, "n_comparisons": len(rows)},
205
+ labels=tuple(names),
206
+ )
207
+
208
+
209
+ @register(
210
+ category=_C,
211
+ task="preference",
212
+ name="Elo ratings",
213
+ definition="Sequential Elo ratings from pairwise outcomes in the given order (expected score "
214
+ "1/(1 + 10^((R_b − R_a)/400)), update K·(outcome − expected)); order-dependent, unlike Bradley–Terry.",
215
+ formula="R_a ← R_a + K (S_a − E_a)",
216
+ range="(−∞, ∞), starting at the initial rating",
217
+ input_requirements=("comparisons",),
218
+ references=(_REF_ELO, _REF_ARENA),
219
+ )
220
+ def elo_ratings(
221
+ comparisons: Any, *, k: float = 4.0, initial: float = 1000.0, scale: float = 400.0, base: float = 10.0
222
+ ) -> MetricResult:
223
+ """Online Elo with Chatbot Arena's defaults (K = 4, initial 1000). Shuffle and average over several
224
+ orders, or prefer ``bradley_terry``, when the order of comparisons is arbitrary."""
225
+ names, rows = _comparisons(comparisons)
226
+ if k <= 0 or scale <= 0 or base <= 1:
227
+ raise InputValidationError("k and scale must be positive and base > 1.")
228
+ r = np.full(len(names), float(initial))
229
+ for a, b, o in rows:
230
+ ea = 1 / (1 + base ** ((r[b] - r[a]) / scale))
231
+ r[a] += k * (o - ea)
232
+ r[b] += k * ((1 - o) - (1 - ea))
233
+ return MetricResult(
234
+ "elo_ratings",
235
+ "Elo rating",
236
+ r,
237
+ {"k": k, "initial": initial, "n_comparisons": len(rows)},
238
+ labels=tuple(names),
239
+ )
240
+
241
+
242
+ # ---------------------------------------------------------------- agreement
243
+ def _reliability_matrix(ratings: Any) -> np.ndarray:
244
+ a = np.array(ratings, dtype=float)
245
+ if a.ndim != 2 or a.shape[0] < 2 or a.shape[1] < 1:
246
+ raise InputValidationError(
247
+ "ratings must be a 2-D array: one row per rater, one column per item (NaN = missing)."
248
+ )
249
+ return a
250
+
251
+
252
+ @register(
253
+ category=_C,
254
+ task="agreement",
255
+ name="Krippendorff's alpha",
256
+ definition="Chance-corrected agreement among any number of raters with missing ratings, for nominal, "
257
+ "ordinal, interval or ratio data.",
258
+ formula="α = 1 − D_observed / D_expected",
259
+ range="(−∞, 1]",
260
+ input_requirements=("ratings",),
261
+ references=(_REF_KRIPP,),
262
+ )
263
+ def krippendorff_alpha(ratings: Any, *, level: str = "nominal") -> MetricResult:
264
+ """Krippendorff's alpha from a raters × items matrix (``np.nan`` for missing), identical to the
265
+ ``krippendorff`` package. ``level`` is ``"nominal"``, ``"ordinal"``, ``"interval"`` or ``"ratio"``."""
266
+ a = _reliability_matrix(ratings)
267
+ if level not in ("nominal", "ordinal", "interval", "ratio"):
268
+ raise InputValidationError("level must be 'nominal', 'ordinal', 'interval' or 'ratio'.")
269
+ mask = ~np.isnan(a)
270
+ values, codes = np.unique(a[mask], return_inverse=True) # sorted values and each rating's code, one pass
271
+ if values.size < 2:
272
+ raise InputValidationError("Krippendorff's alpha needs at least two distinct rating values.")
273
+ v = values.size
274
+ # counts[u, c]: how many raters gave item u the value c (vectorised coincidence matrix)
275
+ items = np.nonzero(mask)[1] # item (column) of each rating, row-major like a[mask]
276
+ codes = codes.ravel()
277
+ counts = np.bincount(items * v + codes, minlength=a.shape[1] * v).reshape(a.shape[1], v).astype(np.float64)
278
+ m_u = counts.sum(axis=1)
279
+ pairable = m_u >= 2
280
+ paired = counts[pairable]
281
+ scaled = paired / (m_u[pairable] - 1)[:, None]
282
+ coinc = scaled.T @ paired - np.diag(scaled.sum(axis=0))
283
+ n_c = coinc.sum(axis=1)
284
+ n = n_c.sum()
285
+ if n == 0:
286
+ raise InputValidationError("No item has ratings from two or more raters.")
287
+ if level == "nominal":
288
+ delta = 1.0 - np.eye(v)
289
+ elif level == "interval":
290
+ delta = (values[:, None] - values[None, :]) ** 2
291
+ elif level == "ratio":
292
+ s = values[:, None] + values[None, :]
293
+ delta = np.where(s == 0, 0.0, ((values[:, None] - values[None, :]) / np.where(s == 0, 1, s)) ** 2)
294
+ else:
295
+ cum = np.cumsum(n_c)
296
+ delta = np.zeros((v, v))
297
+ for c in range(v):
298
+ for k_ in range(v):
299
+ lo, hi = min(c, k_), max(c, k_)
300
+ delta[c, k_] = (cum[hi] - (cum[lo - 1] if lo > 0 else 0) - (n_c[c] + n_c[k_]) / 2) ** 2
301
+ d_o = float((coinc * delta).sum() / n)
302
+ d_e = float((np.outer(n_c, n_c) * delta).sum() / (n * (n - 1)))
303
+ if d_e == 0:
304
+ raise InputValidationError("Expected disagreement is zero; alpha is undefined.")
305
+ return MetricResult(
306
+ "krippendorff_alpha",
307
+ "Krippendorff's alpha",
308
+ 1 - d_o / d_e,
309
+ {"level": level, "n_raters": int(a.shape[0]), "n_items": int(a.shape[1])},
310
+ )
311
+
312
+
313
+ @register(
314
+ category=_C,
315
+ task="agreement",
316
+ name="Fleiss' kappa",
317
+ definition="Chance-corrected agreement of a fixed number of raters assigning items to nominal categories.",
318
+ formula="κ = (P̄ − P̄_e) / (1 − P̄_e)",
319
+ range="(−∞, 1]",
320
+ input_requirements=("ratings",),
321
+ references=(_REF_FLEISS,),
322
+ )
323
+ def fleiss_kappa(ratings: Any) -> MetricResult:
324
+ """Fleiss' kappa from an items × raters matrix of category labels (every item rated by the same number of
325
+ raters), identical to ``statsmodels``' ``fleiss_kappa`` on the aggregated table."""
326
+ raw = np.asarray(ratings)
327
+ a = raw if raw.dtype.kind in "iuU" else np.asarray(ratings, dtype=object)
328
+ if a.ndim != 2 or a.shape[0] < 1 or a.shape[1] < 2:
329
+ raise InputValidationError("ratings must be a 2-D array: one row per item, one column per rater (>= 2).")
330
+ # Categories are compared by their string form; integer and string arrays are grouped with one vectorised
331
+ # pass (their string forms are distinct exactly when the values are), other inputs element by element.
332
+ if a.dtype.kind in "iuU":
333
+ uniq, inv = np.unique(a, return_inverse=True)
334
+ keys = [str(v) for v in uniq.tolist()]
335
+ else:
336
+ index: dict[str, int] = {}
337
+ keys = []
338
+ codes = []
339
+ for x in a.ravel():
340
+ sx = str(x)
341
+ if sx not in index:
342
+ index[sx] = len(keys)
343
+ keys.append(sx)
344
+ codes.append(index[sx])
345
+ inv = np.asarray(codes, dtype=np.intp)
346
+ k = len(keys)
347
+ rows = np.repeat(np.arange(a.shape[0]), a.shape[1])
348
+ table = np.bincount(rows * k + inv.ravel(), minlength=a.shape[0] * k).reshape(a.shape[0], k).astype(float)
349
+ cats = sorted(keys)
350
+ n_raters = a.shape[1]
351
+ p_j = table.sum(axis=0) / table.sum()
352
+ p_i = ((table * table).sum(axis=1) - n_raters) / (n_raters * (n_raters - 1))
353
+ p_bar, p_e = p_i.mean(), float((p_j**2).sum())
354
+ if p_e == 1:
355
+ raise InputValidationError("All ratings fall in one category; Fleiss' kappa is undefined.")
356
+ return MetricResult(
357
+ "fleiss_kappa",
358
+ "Fleiss' kappa",
359
+ (p_bar - p_e) / (1 - p_e),
360
+ {"n_items": int(a.shape[0]), "n_raters": int(n_raters), "categories": cats},
361
+ )
362
+
363
+
364
+ @register(
365
+ category=_C,
366
+ task="agreement",
367
+ name="Judge–human agreement",
368
+ definition="Agreement between an automatic judge and human ratings: Cohen's kappa for categories, "
369
+ "quadratic-weighted kappa for ordinal scores (with Spearman's ρ), Pearson / Spearman correlation for "
370
+ "continuous scores; raw agreement is reported alongside.",
371
+ formula="kappa or correlation, by data type",
372
+ range="[-1, 1]",
373
+ input_requirements=("judge", "human"),
374
+ references=(_REF_JUDGE,),
375
+ )
376
+ def judge_agreement(judge: Any, human: Any, *, kind: str = "categorical") -> MetricResult:
377
+ """Agreement between judge and human labels or scores. ``kind`` is ``"categorical"``, ``"ordinal"`` or
378
+ ``"continuous"``."""
379
+ j, h = list(judge), list(human)
380
+ if not j or len(j) != len(h):
381
+ raise InputValidationError("judge and human must be non-empty and the same length.")
382
+ from ..classification.metrics import cohen_kappa
383
+
384
+ if kind == "categorical":
385
+ k = float(cohen_kappa(h, j))
386
+ return MetricResult(
387
+ "judge_agreement",
388
+ "Judge–human Cohen's kappa",
389
+ k,
390
+ {"kind": kind, "raw_agreement": float(np.mean([a == b for a, b in zip(j, h)])), "n": len(j)},
391
+ )
392
+ ja, ha = np.asarray(j, dtype=float), np.asarray(h, dtype=float)
393
+ if kind == "ordinal":
394
+ k = float(cohen_kappa(ha, ja, weights="quadratic"))
395
+ rho = float(stats.spearmanr(ja, ha).statistic)
396
+ return MetricResult(
397
+ "judge_agreement",
398
+ "Judge–human weighted kappa",
399
+ k,
400
+ {"kind": kind, "spearman": rho, "raw_agreement": float(np.mean(ja == ha)), "n": len(j)},
401
+ )
402
+ if kind == "continuous":
403
+ r = float(stats.pearsonr(ja, ha).statistic)
404
+ return MetricResult(
405
+ "judge_agreement",
406
+ "Judge–human Pearson r",
407
+ r,
408
+ {"kind": kind, "spearman": float(stats.spearmanr(ja, ha).statistic), "n": len(j)},
409
+ )
410
+ raise InputValidationError("kind must be 'categorical', 'ordinal' or 'continuous'.")
411
+
412
+
413
+ # ---------------------------------------------------------------- judge reliability and bias
414
+ def _ab(v: Any) -> str:
415
+ s = str(v).strip().lower()
416
+ if s in ("a", "1", "first"):
417
+ return "a"
418
+ if s in ("b", "2", "second"):
419
+ return "b"
420
+ if s in ("tie", "draw", "t", "0.5"):
421
+ return "tie"
422
+ raise InputValidationError(f"Verdict must be 'A', 'B' or 'tie'; got {v!r}.")
423
+
424
+
425
+ @register(
426
+ category=_C,
427
+ task="judge-reliability",
428
+ name="Position consistency",
429
+ definition="Share of pairwise judgements that stay the same when the two responses are presented in swapped "
430
+ "order; the inconsistent cases that favour whichever response was shown first measure position bias.",
431
+ formula="mean[verdict(A, B) = verdict(B, A)]",
432
+ range="[0, 1]",
433
+ input_requirements=("verdicts_original", "verdicts_swapped"),
434
+ references=(_REF_JUDGE,),
435
+ )
436
+ def position_consistency(verdicts_original: Any, verdicts_swapped: Any) -> MetricResult:
437
+ """Both verdict lists name the winner by identity (``"A"`` is always the same response, whether it was
438
+ shown first or second). ``params["first_position_rate"]`` is the share of inconsistent pairs where the judge
439
+ chose the response shown first both times."""
440
+ o = [_ab(v) for v in verdicts_original]
441
+ s = [_ab(v) for v in verdicts_swapped]
442
+ if not o or len(o) != len(s):
443
+ raise InputValidationError("verdicts_original and verdicts_swapped must be non-empty and the same length.")
444
+ same = [a == b for a, b in zip(o, s)]
445
+ inconsistent = [(a, b) for a, b in zip(o, s) if a != b]
446
+ first = sum(a == "a" and b == "b" for a, b in inconsistent)
447
+ second = sum(a == "b" and b == "a" for a, b in inconsistent)
448
+ return MetricResult(
449
+ "position_consistency",
450
+ "Position consistency",
451
+ float(np.mean(same)),
452
+ {
453
+ "n": len(o),
454
+ "n_inconsistent": len(inconsistent),
455
+ "first_position_rate": first / len(inconsistent) if inconsistent else float("nan"),
456
+ "second_position_rate": second / len(inconsistent) if inconsistent else float("nan"),
457
+ },
458
+ )
459
+
460
+
461
+ @register(
462
+ category=_C,
463
+ task="judge-reliability",
464
+ name="Verbosity bias",
465
+ definition="Share of decisive judgements (no ties, different lengths) won by the longer response, with a "
466
+ "two-sided binomial test against 0.5; well above 0.5 suggests a preference for length.",
467
+ formula="wins of longer response / decisive comparisons",
468
+ range="[0, 1]",
469
+ input_requirements=("winners", "length_a", "length_b"),
470
+ references=(_REF_JUDGE,),
471
+ )
472
+ def verbosity_bias(winners: Any, length_a: Any, length_b: Any) -> MetricResult:
473
+ """``winners`` holds ``"A" / "B" / "tie"`` per comparison; lengths in tokens or characters. Pair it with
474
+ human labels on the same comparisons before calling a length preference a bias."""
475
+ w = [_ab(v) for v in winners]
476
+ la, lb = np.asarray(length_a, float).ravel(), np.asarray(length_b, float).ravel()
477
+ if not w or la.size != len(w) or lb.size != len(w):
478
+ raise InputValidationError("winners, length_a and length_b must be non-empty and the same length.")
479
+ longer_wins = [(x == "a") == (a > b) for x, a, b in zip(w, la, lb) if x != "tie" and a != b]
480
+ if not longer_wins:
481
+ raise InputValidationError("No decisive comparison between responses of different length.")
482
+ k, n = int(sum(longer_wins)), len(longer_wins)
483
+ p = float(stats.binomtest(k, n, 0.5).pvalue)
484
+ return MetricResult("verbosity_bias", "Longer-response win rate", k / n, {"n_decisive": n, "p_value": p})
485
+
486
+
487
+ @register(
488
+ category=_C,
489
+ task="judge-reliability",
490
+ name="Self-preference bias",
491
+ definition="How much more often a judge prefers its own model's outputs than human raters do on the same "
492
+ "comparisons.",
493
+ formula="judge win rate of own outputs − human win rate of own outputs",
494
+ range="[-1, 1]",
495
+ input_requirements=("judge_prefers_own", "human_prefers_own"),
496
+ references=(_REF_SELF,),
497
+ higher_is_better=None,
498
+ )
499
+ def self_preference_bias(judge_prefers_own: Any, human_prefers_own: Any) -> MetricResult:
500
+ """Difference in win rate of the judge's own model, judge versus humans; McNemar's exact p-value on the
501
+ paired verdicts is reported in ``params``."""
502
+ j = np.asarray(judge_prefers_own, dtype=bool).ravel()
503
+ h = np.asarray(human_prefers_own, dtype=bool).ravel()
504
+ if j.size == 0 or j.shape != h.shape:
505
+ raise InputValidationError(
506
+ "judge_prefers_own and human_prefers_own must be non-empty and the same length."
507
+ )
508
+ b, c = int(np.sum(j & ~h)), int(np.sum(~j & h))
509
+ p = float(stats.binomtest(b, b + c, 0.5).pvalue) if b + c else 1.0
510
+ return MetricResult(
511
+ "self_preference_bias",
512
+ "Self-preference bias",
513
+ float(j.mean() - h.mean()),
514
+ {"judge_rate": float(j.mean()), "human_rate": float(h.mean()), "p_value": p, "n": int(j.size)},
515
+ )
516
+
517
+
518
+ # ---------------------------------------------------------------- rubric scores
519
+ @register(
520
+ category=_C,
521
+ task="rubric",
522
+ name="Rubric score",
523
+ definition="Mean of rubric ratings (correctness, helpfulness, relevance, coherence, fluency, completeness, "
524
+ "clarity, conciseness, tone, instruction adherence, reasoning quality, ...) rescaled to [0, 1], with the "
525
+ "mean per criterion.",
526
+ formula="mean((score − min) / (max − min))",
527
+ range="[0, 1]",
528
+ input_requirements=("scores",),
529
+ references=(_REF_JUDGE,),
530
+ )
531
+ @per_item
532
+ def rubric_score(
533
+ scores: Any, *, scale: tuple[float, float] = (1, 5), criteria: Optional[Sequence[str]] = None
534
+ ) -> MetricResult:
535
+ """Rubric ratings as an ``(n, n_criteria)`` array (or one column). Returns the overall normalised mean;
536
+ ``params["per_criterion"]`` maps each criterion to its normalised mean."""
537
+ a = np.asarray(scores, dtype=float)
538
+ if a.ndim == 1:
539
+ a = a[:, None]
540
+ if a.ndim != 2 or a.size == 0:
541
+ raise InputValidationError("scores must be a 2-D array: one row per response, one column per criterion.")
542
+ lo, hi = scale
543
+ if hi <= lo:
544
+ raise InputValidationError("scale must be (min, max) with max > min.")
545
+ if np.any(np.isnan(a)) or a.min() < lo or a.max() > hi:
546
+ raise InputValidationError(f"scores must lie within the scale {scale} without missing values.")
547
+ names = list(criteria) if criteria is not None else [f"criterion_{i + 1}" for i in range(a.shape[1])]
548
+ if len(names) != a.shape[1]:
549
+ raise InputValidationError("criteria must name every column.")
550
+ norm = (a - lo) / (hi - lo)
551
+ return MetricResult(
552
+ "rubric_score",
553
+ "Rubric score",
554
+ float(norm.mean()),
555
+ {"scale": scale, "per_criterion": dict(zip(names, norm.mean(axis=0).tolist())), "n": int(a.shape[0])},
556
+ )
evalsuite/text/qa.py ADDED
@@ -0,0 +1,108 @@
1
+ """Question-answering and correctness metrics: exact match and token-level F1 (SQuAD convention)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import string
7
+ from collections import Counter
8
+ from typing import Any, Optional
9
+
10
+ import numpy as np
11
+
12
+ from ..core.exceptions import InputValidationError
13
+ from ..core.registry import register
14
+ from ..core.result import MetricResult
15
+ from ._common import as_references, as_texts, per_item
16
+
17
+ __all__ = ["exact_match", "normalize_answer", "token_f1"]
18
+
19
+ _C = "qa"
20
+ _REF_SQUAD = (
21
+ "Rajpurkar P, Zhang J, Lopyrev K, Liang P. SQuAD: 100,000+ questions for machine comprehension of text. "
22
+ "EMNLP. 2016:2383-2392."
23
+ )
24
+ _ARTICLES = re.compile(r"\b(a|an|the)\b", re.UNICODE)
25
+ _PUNCT = set(string.punctuation)
26
+
27
+
28
+ def normalize_answer(text: str) -> str:
29
+ """SQuAD normalization: lowercase, drop punctuation and the articles a/an/the, collapse whitespace."""
30
+ text = text.lower()
31
+ text = "".join(ch for ch in text if ch not in _PUNCT)
32
+ text = _ARTICLES.sub(" ", text)
33
+ return " ".join(text.split())
34
+
35
+
36
+ def _norm(normalize: Any) -> Any:
37
+ if normalize is True:
38
+ return normalize_answer
39
+ if normalize is False or normalize is None:
40
+ return lambda s: s
41
+ if callable(normalize):
42
+ return normalize
43
+ raise InputValidationError("normalize must be True (SQuAD), False or a callable str -> str.")
44
+
45
+
46
+ def _f1(pred: str, ref: str) -> float:
47
+ p, r = pred.split(), ref.split()
48
+ common = Counter(p) & Counter(r)
49
+ same = sum(common.values())
50
+ if not p or not r:
51
+ return float(p == r) # both empty -> 1, one empty -> 0
52
+ if same == 0:
53
+ return 0.0
54
+ precision, recall = same / len(p), same / len(r)
55
+ return 2 * precision * recall / (precision + recall)
56
+
57
+
58
+ def _finish(metric: str, name: str, scores: list[float], average: Optional[str], normalize: Any) -> MetricResult:
59
+ arr = np.array(scores, dtype=float)
60
+ value: Any = arr if average is None else float(arr.mean())
61
+ norm = "squad" if normalize is True else ("none" if not normalize else "custom")
62
+ return MetricResult(metric, name, value, {"normalize": norm, "n_examples": len(scores)})
63
+
64
+
65
+ @register(
66
+ category=_C,
67
+ task="question-answering",
68
+ name="Exact match",
69
+ definition="Share of predictions identical to a reference after normalization (SQuAD: lowercase, no "
70
+ "punctuation or articles, single spaces); with several references, any match counts.",
71
+ formula="mean_i max_r [norm(prediction_i) = norm(reference_ir)]",
72
+ range="[0, 1]",
73
+ input_requirements=("references", "predictions"),
74
+ references=(_REF_SQUAD,),
75
+ )
76
+ @per_item
77
+ def exact_match(
78
+ references: Any, predictions: Any, *, normalize: Any = True, average: Optional[str] = "mean"
79
+ ) -> MetricResult:
80
+ """Exact match (0–1). ``normalize=False`` compares raw strings; pass a callable for custom rules."""
81
+ preds = as_texts(predictions, "predictions")
82
+ refs = as_references(references, len(preds))
83
+ f = _norm(normalize)
84
+ scores = [float(any(f(p) == f(r) for r in rs)) for p, rs in zip(preds, refs)]
85
+ return _finish("exact_match", "Exact match", scores, average, normalize)
86
+
87
+
88
+ @register(
89
+ category=_C,
90
+ task="question-answering",
91
+ name="Token F1",
92
+ definition="Harmonic mean of token precision and recall between the normalized prediction and reference "
93
+ "(bag of words, SQuAD); best reference per example, averaged over examples.",
94
+ formula="F1 = 2·P·R/(P + R), P = |common|/|pred tokens|, R = |common|/|ref tokens|",
95
+ range="[0, 1]",
96
+ input_requirements=("references", "predictions"),
97
+ references=(_REF_SQUAD,),
98
+ )
99
+ @per_item
100
+ def token_f1(
101
+ references: Any, predictions: Any, *, normalize: Any = True, average: Optional[str] = "mean"
102
+ ) -> MetricResult:
103
+ """Token-level F1 as in the official SQuAD v1.1 evaluation script (0–1)."""
104
+ preds = as_texts(predictions, "predictions")
105
+ refs = as_references(references, len(preds))
106
+ f = _norm(normalize)
107
+ scores = [max(_f1(f(p), f(r)) for r in rs) for p, rs in zip(preds, refs)]
108
+ return _finish("token_f1", "Token F1", scores, average, normalize)