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,499 @@
1
+ """Embedding-based text metrics: BERTScore, embedding similarity and distance, MoverScore, MAUVE, and an
2
+ adapter for learned metrics (COMET, BLEURT, BARTScore, AlignScore, ...).
3
+
4
+ EvalSuite does not download or run language models. These functions take the embeddings or scores your own
5
+ model produces, so any encoder can be used and results stay reproducible:
6
+
7
+ - ``bertscore`` takes contextual token embeddings (one ``(tokens, dim)`` array per text);
8
+ - ``embedding_similarity`` takes one sentence embedding per text;
9
+ - ``moverscore`` takes token embeddings and optional IDF weights;
10
+ - ``mauve`` takes one feature vector per text for the reference and the generated sets;
11
+ - ``model_score`` wraps any scorer callable (a COMET or BLEURT model, a judge) so its scores get the same
12
+ intervals, comparisons and reports as every other metric.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ from typing import Any, Callable, Optional
19
+
20
+ import numpy as np
21
+ from numpy.typing import NDArray
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__ = ["bertscore", "embedding_similarity", "mauve", "model_score", "moverscore"]
29
+
30
+ _C = "text"
31
+ _REF_BERTSCORE = (
32
+ "Zhang T, Kishore V, Wu F, Weinberger KQ, Artzi Y. BERTScore: evaluating text generation with BERT. "
33
+ "ICLR. 2020."
34
+ )
35
+ _REF_MOVER = (
36
+ "Zhao W, Peyrard M, Liu F, Gao Y, Meyer CM, Eger S. MoverScore: text generation evaluating with "
37
+ "contextualized embeddings and earth mover distance. EMNLP. 2019:563-578."
38
+ )
39
+ _REF_MAUVE = (
40
+ "Pillutla K, Swayamdipta S, Zellers R, Thickstun J, Welleck S, Choi Y, Harchaoui Z. MAUVE: measuring the "
41
+ "gap between neural text and human text using divergence frontiers. NeurIPS. 2021."
42
+ )
43
+ _REF_MAUVE2 = (
44
+ "Pillutla K, Liu L, Thickstun J, Welleck S, Swayamdipta S, Zellers R, Oh S, Choi Y, Harchaoui Z. MAUVE "
45
+ "scores for generative models: theory and practice. JMLR. 2023;24(356):1-92."
46
+ )
47
+ _REF_COMET = "Rei R, Stewart C, Farinha AC, Lavie A. COMET: a neural framework for MT evaluation. EMNLP. 2020."
48
+ _REF_BLEURT = "Sellam T, Das D, Parikh AP. BLEURT: learning robust metrics for text generation. ACL. 2020."
49
+
50
+
51
+ # ---------------------------------------------------------------- input helpers
52
+ def _matrices(x: Any, name: str) -> list[NDArray[np.float64]]:
53
+ if x is None or isinstance(x, (str, bytes)):
54
+ raise InputValidationError(f"{name} must be a list of 2-D token-embedding arrays (tokens × dim).")
55
+ items = list(x) if not (isinstance(x, np.ndarray) and x.ndim == 2) else [x]
56
+ if not items:
57
+ raise InputValidationError(f"{name} is empty.")
58
+ out = []
59
+ dim = None
60
+ for i, m in enumerate(items):
61
+ a = np.asarray(m, dtype=np.float64)
62
+ if a.ndim != 2 or a.shape[0] == 0:
63
+ raise InputValidationError(f"{name}[{i}] must be a non-empty 2-D array (tokens × dim); got {a.shape}.")
64
+ if not np.all(np.isfinite(a)):
65
+ raise InputValidationError(f"{name}[{i}] contains NaN or infinite values.")
66
+ if dim is None:
67
+ dim = a.shape[1]
68
+ elif a.shape[1] != dim:
69
+ raise InputValidationError(f"{name}[{i}] has dimension {a.shape[1]}; expected {dim} like the others.")
70
+ out.append(a)
71
+ return out
72
+
73
+
74
+ def _vectors(x: Any, name: str) -> NDArray[np.float64]:
75
+ a = np.asarray(x, dtype=np.float64)
76
+ if a.ndim == 1:
77
+ a = a[None, :]
78
+ if a.ndim != 2 or a.shape[0] == 0 or a.shape[1] == 0:
79
+ raise InputValidationError(f"{name} must be a 2-D array with one embedding per row; got {a.shape}.")
80
+ if not np.all(np.isfinite(a)):
81
+ raise InputValidationError(f"{name} contains NaN or infinite values.")
82
+ return a
83
+
84
+
85
+ def _weights(w: Any, n: int, name: str) -> NDArray[np.float64]:
86
+ if w is None:
87
+ return np.ones(n)
88
+ a = np.asarray(w, dtype=np.float64).ravel()
89
+ if a.shape[0] != n:
90
+ raise InputValidationError(f"{name} must have one weight per token ({n}); got {a.shape[0]}.")
91
+ if not np.all(np.isfinite(a)) or np.any(a < 0) or a.sum() <= 0:
92
+ raise InputValidationError(f"{name} must be finite, non-negative and not all zero.")
93
+ return a
94
+
95
+
96
+ def _unit(a: NDArray[np.float64]) -> NDArray[np.float64]:
97
+ norms = np.linalg.norm(a, axis=-1, keepdims=True)
98
+ if np.any(norms == 0):
99
+ raise InputValidationError("Embeddings must not be all-zero vectors (cosine similarity is undefined).")
100
+ return a / norms
101
+
102
+
103
+ def _finish(
104
+ metric: str, name: str, scores: NDArray[np.float64], average: Optional[str], params: dict[str, Any]
105
+ ) -> MetricResult:
106
+ if average not in ("mean", None):
107
+ raise InputValidationError("average must be 'mean' or None (per example).")
108
+ value: Any = scores if average is None else float(scores.mean())
109
+ return MetricResult(metric, name, value, {**params, "n_examples": int(scores.shape[0])})
110
+
111
+
112
+ # ---------------------------------------------------------------- BERTScore
113
+ @register(
114
+ category=_C,
115
+ task="semantic-similarity",
116
+ name="BERTScore",
117
+ definition="Greedy matching of contextual token embeddings by cosine similarity: precision averages, over "
118
+ "prediction tokens, the best similarity to any reference token; recall does the reverse; F1 combines them. "
119
+ "Optional IDF weights and baseline rescaling as in the original implementation.",
120
+ formula="P = Σ_j w_j max_i cos(r_i, p_j) / Σ_j w_j; R = Σ_i w_i max_j cos(r_i, p_j) / Σ_i w_i; "
121
+ "F1 = 2PR/(P+R)",
122
+ range="[-1, 1] ([0, 1] in practice)",
123
+ input_requirements=("reference_embeddings", "prediction_embeddings"),
124
+ references=(_REF_BERTSCORE,),
125
+ )
126
+ @per_item
127
+ def bertscore(
128
+ reference_embeddings: Any,
129
+ prediction_embeddings: Any,
130
+ *,
131
+ reference_weights: Any = None,
132
+ prediction_weights: Any = None,
133
+ measure: str = "f1",
134
+ baseline: Optional[float] = None,
135
+ average: Optional[str] = "mean",
136
+ ) -> MetricResult:
137
+ """BERTScore from token embeddings you computed (e.g. a layer of ``roberta-large``, without [CLS]/[SEP]).
138
+
139
+ ``reference_weights`` / ``prediction_weights``: optional IDF weight per token (one array per example).
140
+ ``measure``: ``"f1"``, ``"precision"`` or ``"recall"``. ``baseline``: the model's baseline value ``b`` to
141
+ rescale scores as ``(s − b) / (1 − b)`` (``rescale_with_baseline`` in ``bert_score``)."""
142
+ refs = _matrices(reference_embeddings, "reference_embeddings")
143
+ preds = _matrices(prediction_embeddings, "prediction_embeddings")
144
+ if len(refs) != len(preds):
145
+ raise InputValidationError(
146
+ f"reference_embeddings and prediction_embeddings must contain the same number of examples. "
147
+ f"Received {len(refs)} and {len(preds)}."
148
+ )
149
+ if refs[0].shape[1] != preds[0].shape[1]:
150
+ raise InputValidationError("Reference and prediction embeddings must have the same dimension.")
151
+ if measure not in ("f1", "precision", "recall"):
152
+ raise InputValidationError("measure must be 'f1', 'precision' or 'recall'.")
153
+ rw = [None] * len(refs) if reference_weights is None else list(reference_weights)
154
+ pw = [None] * len(preds) if prediction_weights is None else list(prediction_weights)
155
+ if len(rw) != len(refs) or len(pw) != len(preds):
156
+ raise InputValidationError("Provide one weight array per example (or none).")
157
+ scores = np.empty(len(refs))
158
+ for k, (r, p) in enumerate(zip(refs, preds)):
159
+ sim = _unit(r) @ _unit(p).T # (ref tokens, pred tokens)
160
+ wr, wp = (
161
+ _weights(rw[k], r.shape[0], "reference_weights"),
162
+ _weights(pw[k], p.shape[0], "prediction_weights"),
163
+ )
164
+ precision = float((sim.max(axis=0) * wp).sum() / wp.sum())
165
+ recall = float((sim.max(axis=1) * wr).sum() / wr.sum())
166
+ if baseline is not None:
167
+ precision, recall = ((v - baseline) / (1 - baseline) for v in (precision, recall))
168
+ if measure == "precision":
169
+ scores[k] = precision
170
+ elif measure == "recall":
171
+ scores[k] = recall
172
+ else:
173
+ scores[k] = 0.0 if precision + recall == 0 else 2 * precision * recall / (precision + recall)
174
+ return _finish(
175
+ "bertscore", f"BERTScore {measure}", scores, average, {"measure": measure, "baseline": baseline}
176
+ )
177
+
178
+
179
+ # ---------------------------------------------------------------- sentence embeddings
180
+ @register(
181
+ category=_C,
182
+ task="semantic-similarity",
183
+ name="Embedding similarity",
184
+ definition="Similarity or distance between the sentence embedding of each prediction and of its reference: "
185
+ "cosine similarity, or Euclidean / Manhattan distance. Values depend on the embedding model.",
186
+ formula="cos = a·b / (‖a‖‖b‖); euclidean = ‖a − b‖₂; manhattan = ‖a − b‖₁",
187
+ range="cosine [-1, 1]; distances [0, ∞)",
188
+ input_requirements=("reference_embeddings", "prediction_embeddings"),
189
+ references=("Reimers N, Gurevych I. Sentence-BERT. EMNLP-IJCNLP. 2019:3982-3992.",),
190
+ )
191
+ @per_item
192
+ def embedding_similarity(
193
+ reference_embeddings: Any,
194
+ prediction_embeddings: Any,
195
+ *,
196
+ metric: str = "cosine",
197
+ normalize: bool = False,
198
+ average: Optional[str] = "mean",
199
+ ) -> MetricResult:
200
+ """Row-wise similarity of two ``(n, dim)`` arrays of sentence embeddings. ``metric`` is ``"cosine"``
201
+ (higher is more similar), ``"euclidean"`` or ``"manhattan"`` (lower is more similar). ``normalize=True``
202
+ scales embeddings to unit length before a distance."""
203
+ a = _vectors(reference_embeddings, "reference_embeddings")
204
+ b = _vectors(prediction_embeddings, "prediction_embeddings")
205
+ if a.shape != b.shape:
206
+ raise InputValidationError(f"Embedding arrays must have the same shape; got {a.shape} and {b.shape}.")
207
+ if metric == "cosine":
208
+ scores = np.sum(_unit(a) * _unit(b), axis=1)
209
+ elif metric in ("euclidean", "manhattan"):
210
+ if normalize:
211
+ a, b = _unit(a), _unit(b)
212
+ diff = a - b
213
+ scores = np.sqrt(np.sum(diff * diff, axis=1)) if metric == "euclidean" else np.abs(diff).sum(axis=1)
214
+ else:
215
+ raise InputValidationError("metric must be 'cosine', 'euclidean' or 'manhattan'.")
216
+ return _finish("embedding_similarity", f"Embedding {metric}", scores, average, {"metric": metric})
217
+
218
+
219
+ # ---------------------------------------------------------------- MoverScore
220
+ def _euclidean_cost(x: NDArray[np.float64], y: NDArray[np.float64]) -> NDArray[np.float64]:
221
+ """Pairwise Euclidean distances from ‖x‖² + ‖y‖² − 2x·y (one matrix product), computed exactly as POT's
222
+ ``ot.dist(..., metric="euclidean")`` so transport costs match POT bit for bit."""
223
+ c = -2 * np.dot(x, y.T)
224
+ c += np.einsum("ij,ij->i", x, x)[:, None]
225
+ c += np.einsum("ij,ij->i", y, y)[None, :]
226
+ out: NDArray[np.float64] = np.sqrt(np.maximum(c, 0))
227
+ return out
228
+
229
+
230
+ def _emd(
231
+ a: NDArray[np.float64], b: NDArray[np.float64], cost: NDArray[np.float64], *, uniform: bool = False
232
+ ) -> float:
233
+ """Exact earth mover's distance between histograms a and b (both summing to 1).
234
+
235
+ Uses POT's network simplex when POT is installed. Otherwise, uniform weights (1/n and 1/m) reduce to an
236
+ assignment problem: replicate each row m/g and each column n/g times (g = gcd(n, m)) and solve it with
237
+ SciPy's Hungarian solver; general weights use linear programming (SciPy HiGHS). All three are exact."""
238
+ try:
239
+ import ot
240
+ except ImportError:
241
+ ot = None
242
+ if ot is not None:
243
+ try:
244
+ # The marginals are already validated and the duals are not used, so POT's checks and dual centring
245
+ # are skipped; the transport cost is unchanged.
246
+ return float(ot.emd2(a, b, cost, check_marginals=False, center_dual=False))
247
+ except TypeError: # POT versions without these options
248
+ return float(ot.emd2(a, b, cost))
249
+ n, m = cost.shape
250
+ if uniform:
251
+ from scipy.optimize import linear_sum_assignment
252
+
253
+ size = n * m // math.gcd(n, m)
254
+ big = np.repeat(np.repeat(cost, size // n, axis=0), size // m, axis=1)
255
+ r, c = linear_sum_assignment(big)
256
+ return float(big[r, c].sum() / size)
257
+ from scipy.optimize import linprog
258
+
259
+ a_eq = np.zeros((n + m, n * m))
260
+ for i in range(n):
261
+ a_eq[i, i * m : (i + 1) * m] = 1
262
+ for j in range(m):
263
+ a_eq[n + j, j::m] = 1
264
+ res = linprog(cost.ravel(), A_eq=a_eq[:-1], b_eq=np.concatenate([a, b])[:-1], bounds=(0, None), method="highs")
265
+ if not res.success: # pragma: no cover - the transport problem is always feasible
266
+ raise InputValidationError(f"Earth mover's distance failed: {res.message}")
267
+ return float(res.fun)
268
+
269
+
270
+ @register(
271
+ category=_C,
272
+ task="semantic-similarity",
273
+ name="MoverScore",
274
+ definition="One minus the earth mover's distance between the IDF-weighted token embeddings of prediction "
275
+ "and reference, with Euclidean transport cost between L2-normalised embeddings (MoverScore v2 style).",
276
+ formula="1 − EMD(w_ref, w_pred; ‖r̂_i − p̂_j‖₂)",
277
+ range="(−∞, 1]",
278
+ input_requirements=("reference_embeddings", "prediction_embeddings"),
279
+ references=(_REF_MOVER,),
280
+ )
281
+ @per_item
282
+ def moverscore(
283
+ reference_embeddings: Any,
284
+ prediction_embeddings: Any,
285
+ *,
286
+ reference_weights: Any = None,
287
+ prediction_weights: Any = None,
288
+ average: Optional[str] = "mean",
289
+ ) -> MetricResult:
290
+ """MoverScore from token embeddings (and optional IDF weights) you computed; uses an exact transport
291
+ solver (POT's ``ot.emd2`` when installed, otherwise SciPy), identical to POT."""
292
+ refs = _matrices(reference_embeddings, "reference_embeddings")
293
+ preds = _matrices(prediction_embeddings, "prediction_embeddings")
294
+ if len(refs) != len(preds):
295
+ raise InputValidationError("reference_embeddings and prediction_embeddings must have the same length.")
296
+ rw = [None] * len(refs) if reference_weights is None else list(reference_weights)
297
+ pw = [None] * len(preds) if prediction_weights is None else list(prediction_weights)
298
+ scores = np.empty(len(refs))
299
+ for k, (r, p) in enumerate(zip(refs, preds)):
300
+ wr = _weights(rw[k], r.shape[0], "reference_weights")
301
+ wp = _weights(pw[k], p.shape[0], "prediction_weights")
302
+ cost = _euclidean_cost(_unit(r), _unit(p))
303
+ uniform = rw[k] is None and pw[k] is None
304
+ scores[k] = 1.0 - _emd(wr / wr.sum(), wp / wp.sum(), cost, uniform=uniform)
305
+ return _finish("moverscore", "MoverScore", scores, average, {"weighted": reference_weights is not None})
306
+
307
+
308
+ # ---------------------------------------------------------------- MAUVE
309
+ def _kl(p: NDArray[np.float64], q: NDArray[np.float64]) -> float:
310
+ if np.any((p != 0) & (q == 0)):
311
+ return math.inf
312
+ m = (p != 0) & (q != 0)
313
+ return float(np.sum(p[m] * np.log(p[m] / q[m])))
314
+
315
+
316
+ def _trapezoid(x: NDArray[np.float64], y: NDArray[np.float64]) -> float:
317
+ return float(np.sum((x[1:] - x[:-1]) * (y[1:] + y[:-1]) / 2))
318
+
319
+
320
+ def mauve_from_histograms(
321
+ p_hist: NDArray[np.float64],
322
+ q_hist: NDArray[np.float64],
323
+ *,
324
+ discretization: int = 25,
325
+ scaling_factor: float = 5,
326
+ ) -> float:
327
+ """MAUVE from two quantized distributions (the step after clustering; identical to ``mauve-text``)."""
328
+ weights = np.linspace(1e-6, 1 - 1e-6, discretization)
329
+ curve = [[0.0, math.inf]]
330
+ for w in np.sort(weights):
331
+ r = w * p_hist + (1 - w) * q_hist
332
+ curve.append([_kl(q_hist, r), _kl(p_hist, r)])
333
+ curve.append([math.inf, 0.0])
334
+ xy = np.exp(-scaling_factor * np.asarray(curve))
335
+ x, y = xy[:, 0], xy[:, 1]
336
+ i1, i2 = np.argsort(x), np.argsort(y)
337
+ return 0.5 * (_trapezoid(x[i1], y[i1]) + _trapezoid(y[i2], x[i2]))
338
+
339
+
340
+ def _kmeans(
341
+ x: NDArray[np.float64], k: int, rng: np.random.Generator, n_init: int, max_iter: int
342
+ ) -> NDArray[np.int64]:
343
+ best_labels, best_inertia = None, math.inf
344
+ for _ in range(n_init):
345
+ centers = [x[rng.integers(len(x))]] # k-means++ seeding
346
+ for _ in range(1, k):
347
+ d2 = np.min(((x[:, None, :] - np.asarray(centers)[None]) ** 2).sum(-1), axis=1)
348
+ total = d2.sum()
349
+ centers.append(x[rng.choice(len(x), p=d2 / total)] if total > 0 else x[rng.integers(len(x))])
350
+ c = np.asarray(centers)
351
+ labels = np.zeros(len(x), dtype=np.int64)
352
+ for it in range(max_iter):
353
+ d = ((x[:, None, :] - c[None]) ** 2).sum(-1)
354
+ new = d.argmin(axis=1)
355
+ if it and np.array_equal(new, labels):
356
+ break
357
+ labels = new
358
+ for j in range(k):
359
+ members = x[labels == j]
360
+ if len(members):
361
+ c[j] = members.mean(axis=0)
362
+ inertia = float(((x - c[labels]) ** 2).sum())
363
+ if inertia < best_inertia:
364
+ best_inertia, best_labels = inertia, labels
365
+ if best_labels is None: # pragma: no cover - n_init >= 1 always sets it
366
+ raise InputValidationError("k-means failed to run.")
367
+ return best_labels
368
+
369
+
370
+ @register(
371
+ category=_C,
372
+ task="generation",
373
+ name="MAUVE",
374
+ definition="Gap between the distribution of generated text and of human text: both sets of feature vectors "
375
+ "are quantized together (L2 normalisation, PCA to 90% variance, k-means), and MAUVE is the area under the "
376
+ "divergence frontier of the two histograms. 1 means indistinguishable.",
377
+ formula="area under {(exp(−c·KL(Q‖R_λ)), exp(−c·KL(P‖R_λ))) : R_λ = λP + (1−λ)Q}",
378
+ range="(0, 1]",
379
+ input_requirements=("reference_features", "generated_features"),
380
+ references=(_REF_MAUVE, _REF_MAUVE2),
381
+ )
382
+ def mauve(
383
+ reference_features: Any,
384
+ generated_features: Any,
385
+ *,
386
+ num_buckets: Any = "auto",
387
+ explained_variance: float = 0.9,
388
+ kmeans_n_init: int = 5,
389
+ kmeans_max_iter: int = 500,
390
+ discretization: int = 25,
391
+ scaling_factor: float = 5.0,
392
+ smoothed: bool = False,
393
+ random_state: Optional[int] = 0,
394
+ ) -> MetricResult:
395
+ """MAUVE between human (reference) and model (generated) texts from one feature vector per text (e.g. the
396
+ last-token hidden state of GPT-2 large, as in the paper). ``num_buckets="auto"`` uses n/10 clusters.
397
+ ``smoothed=True`` gives MAUVE* (Krichevsky–Trofimov smoothing, Pillutla et al. 2023). Results depend on the
398
+ clustering; set ``random_state`` and report it."""
399
+ p = _vectors(reference_features, "reference_features")
400
+ q = _vectors(generated_features, "generated_features")
401
+ if p.shape[1] != q.shape[1]:
402
+ raise InputValidationError("reference_features and generated_features must have the same dimension.")
403
+ if not 0 < explained_variance < 1:
404
+ raise InputValidationError("explained_variance must be in (0, 1).")
405
+ if num_buckets == "auto":
406
+ k = max(2, round(min(len(p), len(q)) / 10))
407
+ elif isinstance(num_buckets, (int, np.integer)) and num_buckets >= 2:
408
+ k = int(num_buckets)
409
+ else:
410
+ raise InputValidationError("num_buckets must be 'auto' or an integer >= 2.")
411
+ if k > len(p) + len(q):
412
+ raise InputValidationError(f"num_buckets ({k}) exceeds the number of texts ({len(p) + len(q)}).")
413
+ data = _unit(np.vstack([q, p]))
414
+ centred = data - data.mean(axis=0)
415
+ _, s, vt = np.linalg.svd(centred, full_matrices=False)
416
+ ratio = s**2 / np.sum(s**2) if np.sum(s**2) > 0 else np.ones_like(s) / len(s)
417
+ dims = int(np.argmax(np.cumsum(ratio) >= explained_variance)) + 1
418
+ reduced = centred @ vt[:dims].T
419
+ labels = _kmeans(reduced, k, np.random.default_rng(random_state), int(kmeans_n_init), int(kmeans_max_iter))
420
+ q_counts = np.bincount(labels[: len(q)], minlength=k).astype(float)
421
+ p_counts = np.bincount(labels[len(q) :], minlength=k).astype(float)
422
+ if smoothed:
423
+ p_counts, q_counts = p_counts + 0.5, q_counts + 0.5
424
+ value = mauve_from_histograms(
425
+ p_counts / p_counts.sum(),
426
+ q_counts / q_counts.sum(),
427
+ discretization=discretization,
428
+ scaling_factor=scaling_factor,
429
+ )
430
+ return MetricResult(
431
+ "mauve",
432
+ "MAUVE*" if smoothed else "MAUVE",
433
+ value,
434
+ {
435
+ "num_buckets": k,
436
+ "pca_dims": dims,
437
+ "random_state": random_state,
438
+ "scaling_factor": scaling_factor,
439
+ "n_reference": len(p),
440
+ "n_generated": len(q),
441
+ },
442
+ )
443
+
444
+
445
+ # ---------------------------------------------------------------- learned-metric adapter
446
+ @register(
447
+ category=_C,
448
+ task="learned-metric",
449
+ name="Model-based score (COMET, BLEURT, BARTScore, AlignScore, ...)",
450
+ definition="Scores from any learned evaluation model or judge you supply, per example, so they get the same "
451
+ "confidence intervals, model comparison and reports as every other metric.",
452
+ formula="mean_i scorer(reference_i, prediction_i[, source_i])",
453
+ range="that of the scorer",
454
+ input_requirements=("references", "predictions", "scorer"),
455
+ references=(_REF_COMET, _REF_BLEURT),
456
+ )
457
+ @per_item
458
+ def model_score(
459
+ references: Any,
460
+ predictions: Any,
461
+ *,
462
+ scorer: Callable[..., Any],
463
+ sources: Any = None,
464
+ batch_size: int = 64,
465
+ name: str = "model score",
466
+ higher_is_better: bool = True,
467
+ average: Optional[str] = "mean",
468
+ ) -> MetricResult:
469
+ """Run ``scorer(references, predictions)`` (or ``scorer(references, predictions, sources)``) in batches
470
+ and collect one score per example. Examples:
471
+
472
+ - COMET: ``scorer=lambda r, p, s: model.predict(
473
+ [{"src": a, "mt": b, "ref": c} for a, b, c in zip(s, p, r)]).scores``
474
+ - BLEURT: ``scorer=lambda r, p: bleurt_scorer.score(references=r, candidates=p)``
475
+ """
476
+ if not callable(scorer):
477
+ raise InputValidationError("scorer must be a callable taking (references, predictions[, sources]).")
478
+ refs = list(references)
479
+ preds = list(predictions)
480
+ if len(refs) != len(preds) or not refs:
481
+ raise InputValidationError("references and predictions must be non-empty and the same length.")
482
+ srcs = None if sources is None else list(sources)
483
+ if srcs is not None and len(srcs) != len(refs):
484
+ raise InputValidationError("sources must have one entry per example.")
485
+ if not isinstance(batch_size, int) or batch_size < 1:
486
+ raise InputValidationError("batch_size must be a positive integer.")
487
+ out: list[float] = []
488
+ for start in range(0, len(refs), batch_size):
489
+ sl = slice(start, start + batch_size)
490
+ got = scorer(refs[sl], preds[sl]) if srcs is None else scorer(refs[sl], preds[sl], srcs[sl])
491
+ vals = np.asarray(got, dtype=np.float64).ravel()
492
+ if vals.shape[0] != len(refs[sl]):
493
+ raise InputValidationError(
494
+ f"scorer returned {vals.shape[0]} scores for a batch of {len(refs[sl])} examples."
495
+ )
496
+ if not np.all(np.isfinite(vals)):
497
+ raise InputValidationError("scorer returned NaN or infinite scores.")
498
+ out.extend(vals.tolist())
499
+ return _finish("model_score", name, np.array(out), average, {"higher_is_better": higher_is_better})
@@ -0,0 +1,162 @@
1
+ """SPICE: semantic propositional image caption evaluation (Anderson et al. 2016).
2
+
3
+ SPICE compares the scene graphs of a candidate caption and its references: the F-score between their semantic
4
+ tuples — objects ``(o,)``, attributes ``(o, a)`` and relations ``(s, r, o)`` — where two tuples match when every
5
+ element matches exactly or as synonyms. The reference implementation parses captions with the Stanford
6
+ Scene Graph Parser (Java); EvalSuite takes the tuples directly, or any ``parser`` callable that turns a caption
7
+ into tuples (the Java parser's output, a Python scene-graph parser, an LLM), so the scoring itself runs without
8
+ Java.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Iterable
14
+ from typing import Any, Callable, Optional, Union
15
+
16
+ import numpy as np
17
+
18
+ from ..core.exceptions import InputValidationError, OptionalDependencyError
19
+ from ..core.registry import register
20
+ from ..core.result import MetricResult
21
+ from ._common import per_item
22
+
23
+ __all__ = ["spice"]
24
+
25
+ Tuple_ = tuple[str, ...]
26
+ _REF_SPICE = (
27
+ "Anderson P, Fernando B, Johnson M, Gould S. SPICE: semantic propositional image caption evaluation. ECCV. "
28
+ "2016:382-398."
29
+ )
30
+
31
+
32
+ def _tuples(x: Any, name: str) -> list[Tuple_]:
33
+ if isinstance(x, (str, bytes)) or not isinstance(x, Iterable):
34
+ raise InputValidationError(f"{name} must be a list of tuples (or pass parser= to parse captions).")
35
+ out = []
36
+ for t in x:
37
+ tt = (t,) if isinstance(t, str) else tuple(t)
38
+ if not 1 <= len(tt) <= 3 or not all(isinstance(e, str) and e.strip() for e in tt):
39
+ raise InputValidationError(f"{name}: every tuple needs 1-3 non-empty strings; got {t!r}.")
40
+ out.append(tuple(e.strip().lower() for e in tt))
41
+ return out
42
+
43
+
44
+ def _wordnet_synonyms() -> Callable[[str], set[str]]:
45
+ try:
46
+ from nltk.corpus import wordnet as wn
47
+ except ImportError as exc: # pragma: no cover - nltk is installed with the llm extra
48
+ raise OptionalDependencyError("nltk", "llm", "SPICE synonym matching (synonyms='wordnet')") from exc
49
+
50
+ def syn(word: str) -> set[str]:
51
+ try:
52
+ return {s.name() for s in wn.synsets(word.replace(" ", "_"))}
53
+ except LookupError as exc: # pragma: no cover - depends on the local NLTK data
54
+ raise OptionalDependencyError("nltk wordnet data", "llm", "run nltk.download('wordnet')") from exc
55
+
56
+ return syn
57
+
58
+
59
+ def _match_count(cand: set[Tuple_], ref: set[Tuple_], syn: Optional[Callable[[str], set[str]]]) -> int:
60
+ """Number of candidate tuples matched by some reference tuple (each reference tuple used once)."""
61
+ if syn is None:
62
+ return len(cand & ref)
63
+ cache: dict[str, set[str]] = {}
64
+
65
+ def keys(w: str) -> set[str]:
66
+ if w not in cache:
67
+ cache[w] = {w} | set(syn(w))
68
+ return cache[w]
69
+
70
+ def same(a: Tuple_, b: Tuple_) -> bool:
71
+ return len(a) == len(b) and all(x == y or keys(x) & keys(y) for x, y in zip(a, b))
72
+
73
+ pool = list(ref)
74
+ n = 0
75
+ for c in sorted(cand, key=lambda t: (t not in ref, t)): # exact matches first
76
+ for i, r in enumerate(pool):
77
+ if same(c, r):
78
+ n += 1
79
+ pool.pop(i)
80
+ break
81
+ return n
82
+
83
+
84
+ @register(
85
+ category="text",
86
+ task="captioning",
87
+ name="SPICE",
88
+ definition="F-score between the semantic tuples (objects, attributes, relations) of the candidate caption's "
89
+ "scene graph and the union of the references' scene graphs, with exact or synonym matching; averaged over "
90
+ "images.",
91
+ formula="P = |T(c) ⊗ T(S)| / |T(c)|, R = |T(c) ⊗ T(S)| / |T(S)|, SPICE = 2PR / (P + R)",
92
+ range="[0, 1]",
93
+ input_requirements=("references", "candidates"),
94
+ references=(_REF_SPICE,),
95
+ )
96
+ @per_item
97
+ def spice(
98
+ references: Any,
99
+ candidates: Any,
100
+ *,
101
+ parser: Optional[Callable[[str], Iterable[Any]]] = None,
102
+ synonyms: Union[str, Callable[[str], Iterable[str]], None] = None,
103
+ average: Optional[str] = "mean",
104
+ ) -> MetricResult:
105
+ """``references``: per image, the reference tuples (or, with ``parser``, a list of reference captions).
106
+ ``candidates``: per image, the candidate's tuples (or its caption). ``synonyms``: ``None`` (exact match),
107
+ ``"wordnet"`` (shared WordNet synset, as SPICE does) or a callable word -> synonym keys. Precision and recall
108
+ are in ``params``; tuple-type F-scores (object / attribute / relation) too."""
109
+ refs = list(references) if not isinstance(references, (str, bytes)) else []
110
+ cands = list(candidates) if not isinstance(candidates, (str, bytes)) else []
111
+ if not refs or len(refs) != len(cands):
112
+ raise InputValidationError("references and candidates must be non-empty and the same length.")
113
+ if average not in ("mean", None):
114
+ raise InputValidationError("average must be 'mean' or None (per image).")
115
+ syn: Optional[Callable[[str], set[str]]]
116
+ if synonyms is None:
117
+ syn = None
118
+ elif synonyms == "wordnet":
119
+ syn = _wordnet_synonyms()
120
+ elif callable(synonyms):
121
+ user = synonyms
122
+ syn = lambda w: set(user(w)) # noqa: E731
123
+ else:
124
+ raise InputValidationError("synonyms must be None, 'wordnet' or a callable.")
125
+ f1s, ps, rs = [], [], []
126
+ by_type = {1: [0, 0, 0], 2: [0, 0, 0], 3: [0, 0, 0]} # matched, candidate, reference
127
+ for i, (r, c) in enumerate(zip(refs, cands)):
128
+ if parser is not None:
129
+ rcaps = [r] if isinstance(r, str) else list(r)
130
+ ref_t = {t for cap in rcaps for t in _tuples(parser(cap), f"parser(references[{i}])")}
131
+ cand_t = set(_tuples(parser(c) if isinstance(c, str) else c, f"parser(candidates[{i}])"))
132
+ else:
133
+ ref_t, cand_t = set(_tuples(r, f"references[{i}]")), set(_tuples(c, f"candidates[{i}]"))
134
+ m = _match_count(cand_t, ref_t, syn)
135
+ p = m / len(cand_t) if cand_t else 0.0
136
+ rc = m / len(ref_t) if ref_t else 0.0
137
+ ps.append(p)
138
+ rs.append(rc)
139
+ f1s.append(0.0 if p + rc == 0 else 2 * p * rc / (p + rc))
140
+ for k in by_type:
141
+ ck = {t for t in cand_t if len(t) == k}
142
+ rk = {t for t in ref_t if len(t) == k}
143
+ by_type[k][0] += _match_count(ck, rk, syn)
144
+ by_type[k][1] += len(ck)
145
+ by_type[k][2] += len(rk)
146
+ f = np.array(f1s)
147
+ type_f = {}
148
+ for k, name in ((1, "object"), (2, "attribute"), (3, "relation")):
149
+ mt, nc, nr = by_type[k]
150
+ p_, r_ = (mt / nc if nc else 0.0), (mt / nr if nr else 0.0)
151
+ type_f[name] = 0.0 if p_ + r_ == 0 else 2 * p_ * r_ / (p_ + r_)
152
+ return MetricResult(
153
+ "spice",
154
+ "SPICE",
155
+ f if average is None else float(f.mean()),
156
+ {
157
+ "precision": float(np.mean(ps)),
158
+ "recall": float(np.mean(rs)),
159
+ "by_type": type_f,
160
+ "synonyms": str(synonyms),
161
+ },
162
+ )