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,1346 @@
1
+ """Text-generation metrics: BLEU, chrF / chrF++, TER, ROUGE, lexical diversity and language-model likelihood.
2
+
3
+ ``references`` come first (like ``y_true``) and ``predictions`` second. Each example may have one reference
4
+ string or a list of reference strings. BLEU, chrF and TER are corpus-level and reported on a 0–100 scale, with
5
+ the tokenization, smoothing and multi-reference rules of sacreBLEU (Post 2018), so scores are comparable with
6
+ published results; ROUGE follows Google's ``rouge-score`` package (0–1, averaged over examples).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import functools
12
+ import math
13
+ import re
14
+ from collections import Counter
15
+ from collections.abc import Sequence
16
+ from typing import Any, Callable, Literal, Optional
17
+
18
+ import numpy as np
19
+
20
+ from .._native import Vocab, core
21
+ from ..core.exceptions import InputValidationError
22
+ from ..core.registry import register
23
+ from ..core.result import MetricResult
24
+ from ._common import as_references, as_texts, check_positive_int, per_item, word_ngrams
25
+
26
+ __all__ = [
27
+ "bleu",
28
+ "chrf",
29
+ "cider",
30
+ "cross_entropy",
31
+ "distinct_n",
32
+ "meteor",
33
+ "perplexity",
34
+ "rouge_1",
35
+ "rouge_2",
36
+ "rouge_l",
37
+ "rouge_lsum",
38
+ "self_bleu",
39
+ "sentence_bleu",
40
+ "ter",
41
+ ]
42
+
43
+ _C = "text"
44
+ _REF_BLEU = (
45
+ "Papineni K, Roukos S, Ward T, Zhu WJ. BLEU: a method for automatic evaluation of machine translation. "
46
+ "ACL. 2002:311-318."
47
+ )
48
+ _REF_SACRE = "Post M. A call for clarity in reporting BLEU scores. WMT. 2018:186-191."
49
+ _REF_SMOOTH = (
50
+ "Chen B, Cherry C. A systematic comparison of smoothing techniques for sentence-level BLEU. WMT. 2014."
51
+ )
52
+ _REF_CHRF = "Popović M. chrF: character n-gram F-score for automatic MT evaluation. WMT. 2015:392-395."
53
+ _REF_CHRFPP = "Popović M. chrF++: words helping character n-grams. WMT. 2017:612-618."
54
+ _REF_TER = (
55
+ "Snover M, Dorr B, Schwartz R, Micciulla L, Makhoul J. A study of translation edit rate with targeted human "
56
+ "annotation. AMTA. 2006:223-231."
57
+ )
58
+ _REF_ROUGE = (
59
+ "Lin CY. ROUGE: a package for automatic evaluation of summaries. Text Summarization Branches Out. 2004."
60
+ )
61
+ _REF_DISTINCT = (
62
+ "Li J, Galley M, Brockett C, Gao J, Dolan B. A diversity-promoting objective function for neural "
63
+ "conversation models. NAACL. 2016:110-119."
64
+ )
65
+ _REF_SELFBLEU = "Zhu Y, et al. Texygen: a benchmarking platform for text generation models. SIGIR. 2018:1097-1100."
66
+ _REF_PPL = (
67
+ "Jelinek F, Mercer RL, Bahl LR, Baker JK. Perplexity—a measure of the difficulty of speech recognition "
68
+ "tasks. JASA. 1977;62(S1):S63."
69
+ )
70
+
71
+
72
+ # ---------------------------------------------------------------- tokenization (sacreBLEU 13a)
73
+ _RE_13A = [
74
+ (re.compile(r"([\{-\~\[-\` -\&\(-\+\:-\@\/])"), r" \1 "), # punctuation (apostrophe excluded)
75
+ (re.compile(r"([^0-9])([\.,])"), r"\1 \2 "), # period and comma unless preceded by a digit
76
+ (re.compile(r"([\.,])([^0-9])"), r" \1 \2"), # ... unless followed by a digit
77
+ (re.compile(r"([0-9])(-)"), r"\1 \2 "), # dash after a digit
78
+ ]
79
+
80
+
81
+ def _tok_13a(line: str) -> list[str]:
82
+ return list(_tok_13a_cached(line))
83
+
84
+
85
+ @functools.lru_cache(maxsize=2**16)
86
+ def _tok_13a_cached(line: str) -> tuple[str, ...]:
87
+ """13a tokenization, memoised like sacreBLEU's tokenizer (repeated references are tokenized once)."""
88
+ line = line.replace("<skipped>", "").replace("-\n", "").replace("\n", " ")
89
+ if "&" in line:
90
+ line = line.replace("&quot;", '"').replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">")
91
+ line = f" {line} "
92
+ for pattern, repl in _RE_13A:
93
+ line = pattern.sub(repl, line)
94
+ return tuple(line.split())
95
+
96
+
97
+ Tokenize = Literal["13a", "none"]
98
+
99
+
100
+ def _tokenizer(tokenize: Any) -> Callable[[str], list[str]]:
101
+ if tokenize == "13a":
102
+ return _tok_13a
103
+ if tokenize == "none":
104
+ return str.split
105
+ if callable(tokenize):
106
+ return lambda s: list(tokenize(s))
107
+ raise InputValidationError("tokenize must be '13a' (sacreBLEU default), 'none' (whitespace) or a callable.")
108
+
109
+
110
+ # ---------------------------------------------------------------- BLEU
111
+ _SMOOTH_DEFAULTS: dict[str, Optional[float]] = {"none": None, "floor": 0.1, "add-k": 1.0, "exp": None}
112
+
113
+
114
+ def _bleu_stats(hyp: list[str], refs: list[list[str]], order: int) -> list[float]:
115
+ """[hyp_len, ref_len, correct_1..N, total_1..N] for one segment (sacreBLEU)."""
116
+ hyp_len = len(hyp)
117
+ ref_lens = [len(r) for r in refs]
118
+ closest = min(ref_lens, key=lambda r: (abs(hyp_len - r), r))
119
+ correct = [0] * order
120
+ total = [0] * order
121
+ for n in range(1, order + 1):
122
+ # Max count of each n-gram over the references (Counter union), then clipped matches (intersection).
123
+ ref_max = word_ngrams(refs[0], n)
124
+ for r in refs[1:]: # not Counter |=, which rescans the whole counter after every reference
125
+ get = ref_max.get
126
+ for ng, c in word_ngrams(r, n).items():
127
+ if c > get(ng, 0):
128
+ ref_max[ng] = c
129
+ total[n - 1] = max(hyp_len - n + 1, 0)
130
+ correct[n - 1] = sum((word_ngrams(hyp, n) & ref_max).values())
131
+ return [hyp_len, closest, *correct, *total]
132
+
133
+
134
+ def _bleu_segment_stats(
135
+ hyps: list[list[str]], refs: list[list[list[str]]], order: int
136
+ ) -> list[list[int]] | list[list[float]]:
137
+ """BLEU statistics of every segment: compiled core when available, else :func:`_bleu_stats`."""
138
+ if core is not None:
139
+ v = Vocab()
140
+ stats: list[list[int]] = core.bleu_stats(
141
+ [v.encode(h) for h in hyps], [[v.encode(r) for r in rs] for rs in refs], order
142
+ )
143
+ return stats
144
+ return [_bleu_stats(h, rs, order) for h, rs in zip(hyps, refs)]
145
+
146
+
147
+ def _bleu_from_stats(
148
+ stats: Sequence[float], order: int, smooth: str, smooth_value: Optional[float], effective_order: bool
149
+ ) -> tuple[float, list[float], float]:
150
+ sys_len, ref_len = stats[0], stats[1]
151
+ correct = list(stats[2 : 2 + order])
152
+ total = list(stats[2 + order :])
153
+ if smooth_value is None:
154
+ smooth_value = _SMOOTH_DEFAULTS[smooth]
155
+ bp = 1.0 if sys_len >= ref_len else (math.exp(1 - ref_len / sys_len) if sys_len > 0 else 0.0)
156
+ precisions = [0.0] * order
157
+ if not any(correct):
158
+ return 0.0, precisions, bp
159
+ smooth_mteval = 1.0
160
+ eff = order
161
+ for n in range(1, order + 1):
162
+ if smooth == "add-k" and n > 1:
163
+ correct[n - 1] += smooth_value # type: ignore[operator]
164
+ total[n - 1] += smooth_value # type: ignore[operator]
165
+ if total[n - 1] == 0:
166
+ break
167
+ if effective_order:
168
+ eff = n
169
+ if correct[n - 1] == 0:
170
+ if smooth == "exp":
171
+ smooth_mteval *= 2
172
+ precisions[n - 1] = 100.0 / (smooth_mteval * total[n - 1])
173
+ elif smooth == "floor":
174
+ precisions[n - 1] = 100.0 * smooth_value / total[n - 1] # type: ignore[operator]
175
+ else:
176
+ precisions[n - 1] = 100.0 * correct[n - 1] / total[n - 1]
177
+ logs = [math.log(p) if p > 0 else -9999999999.0 for p in precisions[:eff]]
178
+ return bp * math.exp(sum(logs) / eff), precisions, bp
179
+
180
+
181
+ def _check_smooth(smooth: str) -> str:
182
+ if smooth not in _SMOOTH_DEFAULTS:
183
+ raise InputValidationError(f"smooth must be one of {sorted(_SMOOTH_DEFAULTS)}; got {smooth!r}.")
184
+ return smooth
185
+
186
+
187
+ def _prep(texts: list[str], lowercase: bool, tok: Callable[[str], list[str]]) -> list[list[str]]:
188
+ return [tok((t.lower() if lowercase else t).rstrip()) for t in texts]
189
+
190
+
191
+ @register(
192
+ category=_C,
193
+ task="generation",
194
+ name="BLEU",
195
+ definition="Corpus-level geometric mean of clipped n-gram precisions (n = 1..4) times a brevity penalty, "
196
+ "computed exactly as sacreBLEU (13a tokenization, exponential smoothing).",
197
+ formula="BLEU = BP · exp(Σ_n (1/N) log p_n), BP = min(1, exp(1 − r/c))",
198
+ range="[0, 100]",
199
+ input_requirements=("references", "predictions"),
200
+ references=(_REF_BLEU, _REF_SACRE, _REF_SMOOTH),
201
+ )
202
+ @per_item
203
+ def bleu(
204
+ references: Any,
205
+ predictions: Any,
206
+ *,
207
+ max_order: int = 4,
208
+ smooth: str = "exp",
209
+ smooth_value: Optional[float] = None,
210
+ lowercase: bool = False,
211
+ tokenize: Any = "13a",
212
+ effective_order: bool = False,
213
+ ) -> MetricResult:
214
+ """Corpus BLEU (0–100), identical to ``sacrebleu.corpus_bleu`` with the same options.
215
+
216
+ Statistics are summed over the corpus before the precisions are taken, which is what BLEU is defined on;
217
+ averaging sentence BLEU is a different (and noisier) quantity: use :func:`sentence_bleu` for that.
218
+ """
219
+ preds = as_texts(predictions, "predictions")
220
+ refs = as_references(references, len(preds))
221
+ order = check_positive_int(max_order, "max_order")
222
+ smooth = _check_smooth(smooth)
223
+ tok = _tokenizer(tokenize)
224
+ hyp_tok = _prep(preds, lowercase, tok)
225
+ acc = [0.0] * (2 + 2 * order)
226
+ for seg in _bleu_segment_stats(hyp_tok, [_prep(rs, lowercase, tok) for rs in refs], order):
227
+ for i, v in enumerate(seg):
228
+ acc[i] += v
229
+ stats = np.asarray(acc)
230
+ score, precisions, bp = _bleu_from_stats(acc, order, smooth, smooth_value, effective_order)
231
+ return MetricResult(
232
+ "bleu",
233
+ "BLEU",
234
+ score,
235
+ {
236
+ "max_order": order,
237
+ "smooth": smooth,
238
+ "lowercase": lowercase,
239
+ "tokenize": tokenize if isinstance(tokenize, str) else "custom",
240
+ "precisions": [round(p, 6) for p in precisions],
241
+ "brevity_penalty": bp,
242
+ "hyp_len": int(stats[0]),
243
+ "ref_len": int(stats[1]),
244
+ "n_examples": len(preds),
245
+ },
246
+ )
247
+
248
+
249
+ @register(
250
+ category=_C,
251
+ task="generation",
252
+ name="Sentence BLEU",
253
+ definition="BLEU computed for each example separately (exponential smoothing, effective order) and "
254
+ "averaged; use for per-example scores, not for reporting corpus quality.",
255
+ formula="mean_i BLEU(prediction_i, references_i)",
256
+ range="[0, 100]",
257
+ input_requirements=("references", "predictions"),
258
+ references=(_REF_BLEU, _REF_SMOOTH),
259
+ )
260
+ @per_item
261
+ def sentence_bleu(
262
+ references: Any,
263
+ predictions: Any,
264
+ *,
265
+ max_order: int = 4,
266
+ smooth: str = "exp",
267
+ smooth_value: Optional[float] = None,
268
+ lowercase: bool = False,
269
+ tokenize: Any = "13a",
270
+ average: Optional[str] = "mean",
271
+ ) -> MetricResult:
272
+ """Mean sentence-level BLEU (``sacrebleu.sentence_bleu`` per example); ``average=None`` returns the array."""
273
+ preds = as_texts(predictions, "predictions")
274
+ refs = as_references(references, len(preds))
275
+ order = check_positive_int(max_order, "max_order")
276
+ smooth = _check_smooth(smooth)
277
+ tok = _tokenizer(tokenize)
278
+ segs = _bleu_segment_stats(_prep(preds, lowercase, tok), [_prep(rs, lowercase, tok) for rs in refs], order)
279
+ scores = np.array([_bleu_from_stats(seg, order, smooth, smooth_value, True)[0] for seg in segs])
280
+ value: Any = scores if average is None else float(scores.mean())
281
+ return MetricResult("sentence_bleu", "Sentence BLEU", value, {"max_order": order, "smooth": smooth})
282
+
283
+
284
+ # ---------------------------------------------------------------- chrF / chrF++
285
+ _PUNCTS = set("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")
286
+
287
+
288
+ def _chrf_words(sent: str) -> list[str]:
289
+ out: list[str] = []
290
+ for w in sent.split():
291
+ if len(w) == 1:
292
+ out.append(w)
293
+ elif w[-1] in _PUNCTS:
294
+ out += [w[:-1], w[-1]]
295
+ elif w[0] in _PUNCTS:
296
+ out += [w[0], w[1:]]
297
+ else:
298
+ out.append(w)
299
+ return out
300
+
301
+
302
+ def _chrf_ngrams(sent: str, char_order: int, word_order: int, whitespace: bool) -> list[Counter[Any]]:
303
+ line = sent if whitespace else "".join(sent.split())
304
+ out: list[Counter[Any]] = [
305
+ Counter([line[i : i + n] for i in range(len(line) - n + 1)]) for n in range(1, char_order + 1)
306
+ ]
307
+ if word_order:
308
+ words = _chrf_words(sent)
309
+ out += [
310
+ Counter([" ".join(words[i : i + n]) for i in range(len(words) - n + 1)])
311
+ for n in range(1, word_order + 1)
312
+ ]
313
+ return out
314
+
315
+
316
+ def _chrf_native(
317
+ preds: list[str],
318
+ refs: list[list[str]],
319
+ char_order: int,
320
+ word_order: int,
321
+ beta: float,
322
+ lowercase: bool,
323
+ whitespace: bool,
324
+ eps_smoothing: bool,
325
+ ) -> Optional[list[float]]:
326
+ """Summed best-reference chrF statistics from the compiled core, or None to use the Python path (no core,
327
+ or text the core cannot take, such as lone surrogates)."""
328
+ if core is None:
329
+ return None
330
+ v = Vocab()
331
+
332
+ def parts(sent: str) -> tuple[str, list[int]]:
333
+ sent = sent.lower() if lowercase else sent
334
+ # Whitespace is removed here, with Python's definition of whitespace, not in the core.
335
+ line = sent if whitespace else "".join(sent.split())
336
+ return line, (v.encode(_chrf_words(sent)) if word_order else [])
337
+
338
+ try:
339
+ hp = [parts(h) for h in preds]
340
+ rp = [[parts(r) for r in rs] for rs in refs]
341
+ total: list[float] = core.chrf_corpus(
342
+ [h[0] for h in hp],
343
+ [h[1] for h in hp],
344
+ [[r[0] for r in rs] for rs in rp],
345
+ [[r[1] for r in rs] for rs in rp],
346
+ char_order,
347
+ word_order,
348
+ float(beta),
349
+ eps_smoothing,
350
+ )
351
+ except UnicodeEncodeError:
352
+ return None
353
+ return total
354
+
355
+
356
+ def _chrf_f(stats: Sequence[float], order: int, beta: float, eps_smoothing: bool) -> float:
357
+ eps = 1e-16
358
+ factor = beta**2
359
+ score = 0.0
360
+ avg_p = avg_r = 0.0
361
+ eff = 0
362
+ for i in range(order):
363
+ n_hyp, n_ref, n_match = stats[3 * i : 3 * i + 3]
364
+ p = n_match / n_hyp if n_hyp > 0 else eps
365
+ r = n_match / n_ref if n_ref > 0 else eps
366
+ denom = factor * p + r
367
+ score += ((1 + factor) * p * r / denom) if denom > 0 else eps
368
+ if n_hyp > 0 and n_ref > 0:
369
+ avg_p += p
370
+ avg_r += r
371
+ eff += 1
372
+ if eps_smoothing:
373
+ return 100 * score / order
374
+ if eff == 0:
375
+ return 0.0
376
+ avg_p /= eff
377
+ avg_r /= eff
378
+ return 100 * (1 + factor) * avg_p * avg_r / (factor * avg_p + avg_r) if avg_p + avg_r else 0.0
379
+
380
+
381
+ @register(
382
+ category=_C,
383
+ task="generation",
384
+ name="chrF / chrF++",
385
+ definition="F-beta score (β = 2) over character n-grams (n = 1..6), plus word uni- and bigrams for chrF++ "
386
+ "(word_order=2); robust for morphologically rich languages. Computed exactly as sacreBLEU.",
387
+ formula="chrF_β = (1 + β²) · chrP · chrR / (β² · chrP + chrR)",
388
+ range="[0, 100]",
389
+ input_requirements=("references", "predictions"),
390
+ references=(_REF_CHRF, _REF_CHRFPP, _REF_SACRE),
391
+ )
392
+ @per_item
393
+ def chrf(
394
+ references: Any,
395
+ predictions: Any,
396
+ *,
397
+ char_order: int = 6,
398
+ word_order: int = 0,
399
+ beta: float = 2,
400
+ lowercase: bool = False,
401
+ whitespace: bool = False,
402
+ eps_smoothing: bool = False,
403
+ ) -> MetricResult:
404
+ """Corpus chrF (``word_order=0``) or chrF++ (``word_order=2``), identical to ``sacrebleu.corpus_chrf``.
405
+ With several references, each example uses the reference that gives it the best F-score."""
406
+ preds = as_texts(predictions, "predictions")
407
+ refs = as_references(references, len(preds))
408
+ char_order = check_positive_int(char_order, "char_order")
409
+ if isinstance(word_order, bool) or not isinstance(word_order, (int, np.integer)) or word_order < 0:
410
+ raise InputValidationError("word_order must be an integer >= 0 (2 gives chrF++).")
411
+ order = char_order + int(word_order)
412
+ native = _chrf_native(preds, refs, char_order, int(word_order), beta, lowercase, whitespace, eps_smoothing)
413
+ total = native if native is not None else [0.0] * (3 * order)
414
+ for hyp, rs in zip(preds, refs) if native is None else ():
415
+ h = _chrf_ngrams(hyp.lower() if lowercase else hyp, char_order, word_order, whitespace)
416
+ best: Optional[list[float]] = None
417
+ best_f = -1.0
418
+ for ref in rs:
419
+ r = _chrf_ngrams(ref.lower() if lowercase else ref, char_order, word_order, whitespace)
420
+ seg: list[float] = []
421
+ for hc, rc in zip(h, r):
422
+ n_hyp = sum(hc.values())
423
+ small, big = (hc, rc) if len(hc) <= len(rc) else (rc, hc) # iterate the smaller counter
424
+ get = big.get
425
+ match = sum(min(c, get(ng, 0)) for ng, c in small.items())
426
+ seg += [n_hyp if rc else 0, sum(rc.values()), match]
427
+ f = _chrf_f(seg, order, beta, eps_smoothing)
428
+ if f > best_f:
429
+ best_f, best = f, seg
430
+ if best is not None: # every example has at least one reference
431
+ total = [t + v for t, v in zip(total, best)]
432
+ name = f"chrF{beta:g}" + "+" * int(word_order)
433
+ return MetricResult(
434
+ "chrf",
435
+ name,
436
+ _chrf_f(total, order, beta, eps_smoothing),
437
+ {"char_order": char_order, "word_order": int(word_order), "beta": beta, "lowercase": lowercase},
438
+ )
439
+
440
+
441
+ # ---------------------------------------------------------------- TER (Tercom, as in sacreBLEU)
442
+ _MAX_SHIFT_SIZE = 10
443
+ _MAX_SHIFT_DIST = 50
444
+ _BEAM_WIDTH = 25
445
+ _MAX_SHIFT_CANDIDATES = 1000
446
+ _INF = int(1e16)
447
+
448
+
449
+ def _beam(nh: int, nr: int) -> tuple[float, int]:
450
+ ratio = nr / nh if nh else 1
451
+ beam = math.ceil(ratio / 2 + _BEAM_WIDTH) if ratio / 2 > _BEAM_WIDTH else _BEAM_WIDTH
452
+ return ratio, beam
453
+
454
+
455
+ def _edit_rows(
456
+ hyp: list[str], ref: list[str], rows: list[list[int]], start: int, ops: Optional[list[list[str]]] = None
457
+ ) -> None:
458
+ """Fill beam edit-distance rows ``start``..len(hyp) in place (insert/delete/substitute cost 1, as Tercom
459
+ and sacreBLEU). ``rows[0..start-1]`` must already hold the rows of the same hypothesis prefix. With
460
+ ``ops``, also record each cell's operation (ties broken match/substitute, delete, insert)."""
461
+ nh, nr = len(hyp), len(ref)
462
+ ratio, beam = _beam(nh, nr)
463
+ inf = _INF
464
+ for i in range(max(start, 1), nh + 1):
465
+ diag = math.floor(i * ratio)
466
+ lo = max(0, diag - beam)
467
+ hi = nr + 1 if i == nh else min(nr + 1, diag + beam)
468
+ prev = rows[i - 1]
469
+ row = [inf] * (nr + 1)
470
+ oprow = ["x"] * (nr + 1) if ops is not None else None
471
+ w = hyp[i - 1]
472
+ for j in range(lo, hi):
473
+ if j == 0:
474
+ row[0] = prev[0] + 1
475
+ if oprow is not None:
476
+ oprow[0] = "d"
477
+ continue
478
+ match = w == ref[j - 1]
479
+ best = prev[j - 1] + (0 if match else 1)
480
+ op = " " if match else "s"
481
+ d = prev[j] + 1
482
+ if d < best:
483
+ best, op = d, "d"
484
+ ins = row[j - 1] + 1
485
+ if ins < best:
486
+ best, op = ins, "i"
487
+ if best < inf:
488
+ row[j] = best
489
+ if oprow is not None:
490
+ oprow[j] = op
491
+ if i < len(rows):
492
+ rows[i] = row
493
+ else:
494
+ rows.append(row)
495
+ if ops is not None and oprow is not None:
496
+ if i < len(ops):
497
+ ops[i] = oprow
498
+ else:
499
+ ops.append(oprow)
500
+
501
+
502
+ def _edit_distance(hyp: list[str], ref: list[str], rows_out: Optional[list[list[int]]] = None) -> tuple[int, str]:
503
+ """Beam edit distance and its trace, as Tercom/sacreBLEU. ``rows_out`` receives the cost rows."""
504
+ nh, nr = len(hyp), len(ref)
505
+ rows: list[list[int]] = [list(range(nr + 1))]
506
+ ops: list[list[str]] = [["i"] * (nr + 1)]
507
+ _edit_rows(hyp, ref, rows, 1, ops)
508
+ if rows_out is not None:
509
+ rows_out[:] = rows
510
+ trace = []
511
+ i, j = nh, nr
512
+ while i > 0 or j > 0:
513
+ op = ops[i][j]
514
+ trace.append(op)
515
+ if op in ("s", " "):
516
+ i -= 1
517
+ j -= 1
518
+ elif op == "i":
519
+ j -= 1
520
+ elif op == "d":
521
+ i -= 1
522
+ else: # pragma: no cover - unreachable for valid tables
523
+ raise RuntimeError("invalid edit trace")
524
+ return rows[nh][nr], "".join(reversed(trace))
525
+
526
+
527
+ def _ter_shift(hyp: list[str], ref: list[str], checked: int) -> tuple[int, list[str], int, int]:
528
+ """Best shift of ``hyp``: (gain, shifted words, candidates checked, edit distance of ``hyp``)."""
529
+ # Rows of the unshifted hypothesis: a shifted candidate keeps hyp[:min(start, target)] and has the same
530
+ # length (so the same beam), so its edit-distance rows up to that prefix are these and only the rest is
531
+ # recomputed. Costs are identical to recomputing from scratch.
532
+ base: list[list[int]] = []
533
+ pre, inv_trace = _edit_distance(hyp, ref, base)
534
+ trace = inv_trace.translate(str.maketrans("id", "di"))
535
+ align: dict[int, int] = {}
536
+ ref_err: list[int] = []
537
+ hyp_err: list[int] = []
538
+ ph = pr = -1
539
+ for op in trace:
540
+ if op in (" ", "s"):
541
+ ph += 1
542
+ pr += 1
543
+ align[pr] = ph
544
+ e = 0 if op == " " else 1
545
+ hyp_err.append(e)
546
+ ref_err.append(e)
547
+ elif op == "i":
548
+ ph += 1
549
+ hyp_err.append(1)
550
+ else:
551
+ pr += 1
552
+ align[pr] = ph
553
+ ref_err.append(1)
554
+ best: Optional[tuple[int, int, int, int, list[str]]] = None
555
+ for sh, sr, length in _shifted_pairs(hyp, ref):
556
+ if sum(hyp_err[sh : sh + length]) == 0 or sum(ref_err[sr : sr + length]) == 0:
557
+ continue
558
+ if sh <= align[sr] < sh + length:
559
+ continue
560
+ prev_idx = -1
561
+ for off in range(-1, length):
562
+ if sr + off == -1:
563
+ idx = 0
564
+ elif sr + off in align:
565
+ idx = align[sr + off] + 1
566
+ else:
567
+ break
568
+ if idx == prev_idx:
569
+ continue
570
+ prev_idx = idx
571
+ shifted = _perform_shift(hyp, sh, length, idx)
572
+ keep = min(sh, idx)
573
+ rows = base[: keep + 1]
574
+ _edit_rows(shifted, ref, rows, keep + 1)
575
+ cand = (pre - rows[len(shifted)][len(ref)], length, -sh, -idx, shifted)
576
+ checked += 1
577
+ if best is None or cand > best:
578
+ best = cand
579
+ if checked >= _MAX_SHIFT_CANDIDATES:
580
+ break
581
+ if best is None:
582
+ return 0, hyp, checked, pre
583
+ return best[0], best[4], checked, pre
584
+
585
+
586
+ def _shifted_pairs(hyp: list[str], ref: list[str]) -> Any:
587
+ """(start_h, start_r, length) of matching word runs, in Tercom's order."""
588
+ nh, nr = len(hyp), len(ref)
589
+ for sh in range(nh):
590
+ for sr in range(max(0, sh - _MAX_SHIFT_DIST), min(nr, sh + _MAX_SHIFT_DIST + 1)):
591
+ length = 0
592
+ while hyp[sh + length] == ref[sr + length] and length < _MAX_SHIFT_SIZE:
593
+ length += 1
594
+ yield sh, sr, length
595
+ if nh == sh + length or nr == sr + length:
596
+ break
597
+
598
+
599
+ def _perform_shift(words: list[str], start: int, length: int, target: int) -> list[str]:
600
+ if target < start:
601
+ return words[:target] + words[start : start + length] + words[target:start] + words[start + length :]
602
+ if target > start + length:
603
+ return words[:start] + words[start + length : target] + words[start : start + length] + words[target:]
604
+ return (
605
+ words[:start]
606
+ + words[start + length : length + target]
607
+ + words[start : start + length]
608
+ + words[length + target :]
609
+ )
610
+
611
+
612
+ def _ter_edits(hyp: list[str], ref: list[str]) -> int:
613
+ if not ref:
614
+ return len(hyp)
615
+ shifts = 0
616
+ words = hyp
617
+ checked = 0
618
+ while True:
619
+ delta, new_words, checked, dist = _ter_shift(words, ref, checked)
620
+ if checked >= _MAX_SHIFT_CANDIDATES or delta <= 0:
621
+ return shifts + dist # ``words`` is unchanged, so its distance is the one just computed
622
+ shifts += 1
623
+ words = new_words
624
+
625
+
626
+ @register(
627
+ category=_C,
628
+ task="generation",
629
+ name="TER",
630
+ definition="Translation edit rate: minimum number of insertions, deletions, substitutions and block shifts "
631
+ "to turn the prediction into the closest reference, divided by the average reference length (Tercom, as in "
632
+ "sacreBLEU). Lower is better.",
633
+ formula="TER = Σ edits / Σ average reference length × 100",
634
+ range="[0, ∞)",
635
+ input_requirements=("references", "predictions"),
636
+ references=(_REF_TER, _REF_SACRE),
637
+ higher_is_better=False,
638
+ )
639
+ @per_item
640
+ def ter(references: Any, predictions: Any, *, case_sensitive: bool = False) -> MetricResult:
641
+ """Corpus TER (0–100+, lower is better), identical to ``sacrebleu.corpus_ter`` with default settings."""
642
+ preds = as_texts(predictions, "predictions")
643
+ refs = as_references(references, len(preds))
644
+
645
+ def tok(s: str) -> list[str]:
646
+ s = s.rstrip()
647
+ return (s if case_sensitive else s.lower()).split()
648
+
649
+ edits = 0.0
650
+ ref_len = 0.0
651
+ if core is not None:
652
+ v = Vocab()
653
+ edits, ref_len = core.ter_corpus(
654
+ [v.encode(tok(h)) for h in preds], [[v.encode(tok(r)) for r in rs] for rs in refs]
655
+ )
656
+ else:
657
+ for hyp, rs in zip(preds, refs):
658
+ h = tok(hyp)
659
+ rws = [tok(r) for r in rs]
660
+ edits += min(_ter_edits(h, r) for r in rws)
661
+ ref_len += sum(len(r) for r in rws) / len(rws)
662
+ value = 100 * edits / ref_len if ref_len > 0 else (100.0 if edits > 0 else 0.0)
663
+ return MetricResult(
664
+ "ter", "TER", value, {"case_sensitive": case_sensitive, "edits": edits, "ref_len": ref_len}
665
+ )
666
+
667
+
668
+ # ---------------------------------------------------------------- ROUGE (rouge-score)
669
+ _NON_ALNUM = re.compile(r"[^a-z0-9]+")
670
+ _VALID = re.compile(r"^[a-z0-9]+$")
671
+
672
+
673
+ def _rouge_tok(text: str, stemmer: Optional[Callable[[str], str]]) -> list[str]:
674
+ if stemmer is None:
675
+ return list(_rouge_tok_plain(text))
676
+ tokens = re.split(r"\s+", _NON_ALNUM.sub(" ", text.lower()))
677
+ if stemmer is not None:
678
+ tokens = [stemmer(t) if len(t) > 3 else t for t in tokens]
679
+ return [t for t in tokens if _VALID.match(t)]
680
+
681
+
682
+ @functools.lru_cache(maxsize=2**16)
683
+ def _rouge_tok_plain(text: str) -> tuple[str, ...]:
684
+ """rouge-score's tokenizer without stemming, memoised (ROUGE-1/2/L of one corpus tokenize it once)."""
685
+ tokens = re.split(r"\s+", _NON_ALNUM.sub(" ", text.lower()))
686
+ return tuple(t for t in tokens if _VALID.match(t))
687
+
688
+
689
+ def _f(p: float, r: float) -> float:
690
+ return 2 * p * r / (p + r) if p + r > 0 else 0.0
691
+
692
+
693
+ def _rouge_n(t: list[str], p: list[str], n: int) -> tuple[float, float, float]:
694
+ tn, pn = word_ngrams(t, n), word_ngrams(p, n)
695
+ inter = sum(min(c, pn[g]) for g, c in tn.items())
696
+ prec = inter / max(sum(pn.values()), 1)
697
+ rec = inter / max(sum(tn.values()), 1)
698
+ return prec, rec, _f(prec, rec)
699
+
700
+
701
+ def _lcs_table(a: list[str], b: list[str]) -> list[list[int]]:
702
+ t = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
703
+ for i in range(1, len(a) + 1):
704
+ ai = a[i - 1]
705
+ row, prev = t[i], t[i - 1]
706
+ for j in range(1, len(b) + 1):
707
+ row[j] = prev[j - 1] + 1 if ai == b[j - 1] else max(prev[j], row[j - 1])
708
+ return t
709
+
710
+
711
+ def _lcs_length(a: list[str], b: list[str]) -> int:
712
+ """Length of the longest common subsequence with two rolling rows (no full table)."""
713
+ prev = [0] * (len(b) + 1)
714
+ for ai in a:
715
+ row = [0]
716
+ left = 0
717
+ for j, bj in enumerate(b):
718
+ left = prev[j] + 1 if ai == bj else (prev[j + 1] if prev[j + 1] > left else left)
719
+ row.append(left)
720
+ prev = row
721
+ return prev[-1]
722
+
723
+
724
+ def _rouge_l(t: list[str], p: list[str]) -> tuple[float, float, float]:
725
+ if not t or not p:
726
+ return 0.0, 0.0, 0.0
727
+ lcs = _lcs_length(t, p)
728
+ prec, rec = lcs / len(p), lcs / len(t)
729
+ return prec, rec, _f(prec, rec)
730
+
731
+
732
+ def _lcs_indices(ref: list[str], can: list[str]) -> list[int]:
733
+ t = _lcs_table(ref, can)
734
+ i, j = len(ref), len(can)
735
+ out: list[int] = []
736
+ while i > 0 and j > 0:
737
+ if ref[i - 1] == can[j - 1]:
738
+ out.append(i - 1)
739
+ i -= 1
740
+ j -= 1
741
+ elif t[i][j - 1] > t[i - 1][j]:
742
+ j -= 1
743
+ else:
744
+ i -= 1
745
+ return out
746
+
747
+
748
+ def _rouge_lsum(ts: list[list[str]], ps: list[list[str]]) -> tuple[float, float, float]:
749
+ if not ts or not ps:
750
+ return 0.0, 0.0, 0.0
751
+ m, n = sum(map(len, ts)), sum(map(len, ps))
752
+ if not n or not m:
753
+ return 0.0, 0.0, 0.0
754
+ cr: Counter[str] = Counter()
755
+ cc: Counter[str] = Counter()
756
+ for s in ts:
757
+ cr.update(s)
758
+ for s in ps:
759
+ cc.update(s)
760
+ hits = 0
761
+ for r in ts:
762
+ union = sorted(set().union(*[_lcs_indices(r, c) for c in ps]))
763
+ for tok in (r[i] for i in union):
764
+ if cc[tok] > 0 and cr[tok] > 0:
765
+ hits += 1
766
+ cc[tok] -= 1
767
+ cr[tok] -= 1
768
+ prec, rec = hits / n, hits / m
769
+ return prec, rec, _f(prec, rec)
770
+
771
+
772
+ _MEASURES = {"precision": 0, "recall": 1, "fmeasure": 2}
773
+
774
+
775
+ def _rouge_triples_native(
776
+ variant: str,
777
+ preds: list[str],
778
+ refs: list[list[str]],
779
+ stemmer: Optional[Callable[[str], str]],
780
+ sents: Callable[[str], list[list[str]]],
781
+ ) -> list[list[tuple[float, float, float]]]:
782
+ """(precision, recall, F) for every (prediction, reference) pair: counts from the compiled core, then the
783
+ same float formulas as :func:`_rouge_n`, :func:`_rouge_l` and :func:`_rouge_lsum`."""
784
+ c = core
785
+ if c is None: # pragma: no cover - only called with the core
786
+ raise RuntimeError("compiled core not available")
787
+ v = Vocab()
788
+ out: list[list[tuple[float, float, float]]] = []
789
+ flat: list[tuple[float, float, float]] = []
790
+ sizes: list[int] = []
791
+ if variant == "Lsum":
792
+ ts: list[list[list[int]]] = []
793
+ ps: list[list[list[int]]] = []
794
+ for pred, rs in zip(preds, refs):
795
+ psents = [v.encode(s) for s in sents(pred)]
796
+ sizes.append(len(rs))
797
+ for ref in rs:
798
+ ts.append([v.encode(s) for s in sents(ref)])
799
+ ps.append(psents)
800
+ for ts_i, ps_i, (hits, m, n) in zip(ts, ps, c.rouge_lsum_hits(ts, ps)):
801
+ if not ts_i or not ps_i or not m or not n:
802
+ flat.append((0.0, 0.0, 0.0))
803
+ else:
804
+ prec, rec = hits / n, hits / m
805
+ flat.append((prec, rec, _f(prec, rec)))
806
+ else:
807
+ tt: list[list[int]] = []
808
+ pp: list[list[int]] = []
809
+ for pred, rs in zip(preds, refs):
810
+ p = v.encode(_rouge_tok(pred, stemmer))
811
+ sizes.append(len(rs))
812
+ for ref in rs:
813
+ tt.append(v.encode(_rouge_tok(ref, stemmer)))
814
+ pp.append(p)
815
+ if variant == "L":
816
+ for t, p, lcs in zip(tt, pp, c.lcs_lengths(tt, pp)):
817
+ if not t or not p:
818
+ flat.append((0.0, 0.0, 0.0))
819
+ else:
820
+ prec, rec = lcs / len(p), lcs / len(t)
821
+ flat.append((prec, rec, _f(prec, rec)))
822
+ else:
823
+ n = int(variant)
824
+ for t, p, inter in zip(tt, pp, c.ngram_overlaps(tt, pp, n)):
825
+ prec = inter / max(len(p) - n + 1, 1)
826
+ rec = inter / max(len(t) - n + 1, 1)
827
+ flat.append((prec, rec, _f(prec, rec)))
828
+ pos = 0
829
+ for k in sizes:
830
+ out.append(flat[pos : pos + k])
831
+ pos += k
832
+ return out
833
+
834
+
835
+ def _rouge(
836
+ variant: str,
837
+ references: Any,
838
+ predictions: Any,
839
+ measure: str,
840
+ stemmer: Optional[Callable[[str], str]],
841
+ average: Optional[str],
842
+ ) -> MetricResult:
843
+ preds = as_texts(predictions, "predictions")
844
+ refs = as_references(references, len(preds))
845
+ if measure not in _MEASURES:
846
+ raise InputValidationError("measure must be 'fmeasure', 'precision' or 'recall'.")
847
+ if stemmer is not None and not callable(stemmer):
848
+ raise InputValidationError("stemmer must be a callable str -> str, e.g. nltk PorterStemmer().stem.")
849
+ k = _MEASURES[measure]
850
+
851
+ def sents(text: str) -> list[list[str]]:
852
+ return [_rouge_tok(s, stemmer) for s in text.split("\n") if len(s)]
853
+
854
+ all_triples = (
855
+ _rouge_triples_native(variant, preds, refs, stemmer, sents)
856
+ if core is not None
857
+ else [
858
+ [
859
+ _rouge_lsum(sents(ref), sents(pred))
860
+ if variant == "Lsum"
861
+ else (
862
+ _rouge_l(_rouge_tok(ref, stemmer), _rouge_tok(pred, stemmer))
863
+ if variant == "L"
864
+ else _rouge_n(_rouge_tok(ref, stemmer), _rouge_tok(pred, stemmer), int(variant))
865
+ )
866
+ for ref in rs
867
+ ]
868
+ for pred, rs in zip(preds, refs)
869
+ ]
870
+ )
871
+ scores = []
872
+ for triples in all_triples:
873
+ best = max(range(len(triples)), key=lambda i: (triples[i][2], -i)) # highest F, first on ties
874
+ scores.append(triples[best][k])
875
+ arr = np.array(scores)
876
+ value: Any = arr if average is None else float(arr.mean())
877
+ metric = {"1": "rouge_1", "2": "rouge_2", "L": "rouge_l", "Lsum": "rouge_lsum"}[variant]
878
+ return MetricResult(metric, f"ROUGE-{variant}", value, {"measure": measure, "stemmer": stemmer is not None})
879
+
880
+
881
+ def _rouge_doc(variant: str, what: str) -> dict[str, Any]:
882
+ return {
883
+ "category": _C,
884
+ "task": "generation",
885
+ "name": f"ROUGE-{variant}",
886
+ "definition": f"{what} between prediction and reference after lowercasing and splitting on "
887
+ "non-alphanumerics (as Google's rouge-score); F-measure averaged over examples, best reference per "
888
+ "example.",
889
+ "range": "[0, 1]",
890
+ "input_requirements": ("references", "predictions"),
891
+ "references": (_REF_ROUGE,),
892
+ }
893
+
894
+
895
+ @register(formula="F1 of clipped unigram overlap", **_rouge_doc("1", "Unigram overlap"))
896
+ @per_item
897
+ def rouge_1(
898
+ references: Any,
899
+ predictions: Any,
900
+ *,
901
+ measure: str = "fmeasure",
902
+ stemmer: Optional[Callable[[str], str]] = None,
903
+ average: Optional[str] = "mean",
904
+ ) -> MetricResult:
905
+ """ROUGE-1 (identical to ``rouge_score`` ``rouge1``; pass ``stemmer=PorterStemmer().stem`` for stemming)."""
906
+ return _rouge("1", references, predictions, measure, stemmer, average)
907
+
908
+
909
+ @register(formula="F1 of clipped bigram overlap", **_rouge_doc("2", "Bigram overlap"))
910
+ @per_item
911
+ def rouge_2(
912
+ references: Any,
913
+ predictions: Any,
914
+ *,
915
+ measure: str = "fmeasure",
916
+ stemmer: Optional[Callable[[str], str]] = None,
917
+ average: Optional[str] = "mean",
918
+ ) -> MetricResult:
919
+ """ROUGE-2 (identical to ``rouge_score`` ``rouge2``)."""
920
+ return _rouge("2", references, predictions, measure, stemmer, average)
921
+
922
+
923
+ @register(formula="P = LCS/|pred|, R = LCS/|ref|, F1", **_rouge_doc("L", "Longest common subsequence"))
924
+ @per_item
925
+ def rouge_l(
926
+ references: Any,
927
+ predictions: Any,
928
+ *,
929
+ measure: str = "fmeasure",
930
+ stemmer: Optional[Callable[[str], str]] = None,
931
+ average: Optional[str] = "mean",
932
+ ) -> MetricResult:
933
+ """ROUGE-L, sentence-level LCS (identical to ``rouge_score`` ``rougeL``)."""
934
+ return _rouge("L", references, predictions, measure, stemmer, average)
935
+
936
+
937
+ @register(
938
+ formula="union-LCS over newline-separated sentences",
939
+ **_rouge_doc("Lsum", "Summary-level union LCS over sentences (one sentence per line)"),
940
+ )
941
+ @per_item
942
+ def rouge_lsum(
943
+ references: Any,
944
+ predictions: Any,
945
+ *,
946
+ measure: str = "fmeasure",
947
+ stemmer: Optional[Callable[[str], str]] = None,
948
+ average: Optional[str] = "mean",
949
+ ) -> MetricResult:
950
+ """ROUGE-Lsum (identical to ``rouge_score`` ``rougeLsum``); put one sentence per line."""
951
+ return _rouge("Lsum", references, predictions, measure, stemmer, average)
952
+
953
+
954
+ # ---------------------------------------------------------------- diversity
955
+ @register(
956
+ category=_C,
957
+ task="generation",
958
+ name="Distinct-n",
959
+ definition="Number of distinct n-grams divided by the total number of n-grams across all predictions "
960
+ "(whitespace tokens); a simple lexical-diversity indicator.",
961
+ formula="|unique n-grams| / |n-grams|",
962
+ range="[0, 1]",
963
+ input_requirements=("predictions",),
964
+ references=(_REF_DISTINCT,),
965
+ )
966
+ @per_item
967
+ def distinct_n(predictions: Any, *, n: int = 1, lowercase: bool = False) -> MetricResult:
968
+ """Distinct-n over the whole set of predictions (``n=1`` Distinct-1, ``n=2`` Distinct-2)."""
969
+ preds = as_texts(predictions, "predictions")
970
+ n = check_positive_int(n, "n")
971
+ counts: Counter[tuple[str, ...]] = Counter()
972
+ for p in preds:
973
+ counts.update(word_ngrams((p.lower() if lowercase else p).split(), n))
974
+ total = sum(counts.values())
975
+ if total == 0:
976
+ raise InputValidationError(f"The predictions contain no {n}-grams.")
977
+ return MetricResult("distinct_n", f"Distinct-{n}", len(counts) / total, {"n": n, "total_ngrams": total})
978
+
979
+
980
+ @register(
981
+ category=_C,
982
+ task="generation",
983
+ name="Self-BLEU",
984
+ definition="Average sentence BLEU of each prediction against all other predictions as references; higher "
985
+ "means the outputs are more alike (less diverse).",
986
+ formula="mean_i BLEU(p_i, {p_j : j ≠ i})",
987
+ range="[0, 100]",
988
+ input_requirements=("predictions",),
989
+ references=(_REF_SELFBLEU,),
990
+ higher_is_better=False,
991
+ )
992
+ @per_item
993
+ def self_bleu(predictions: Any, *, max_order: int = 4, tokenize: Any = "13a") -> MetricResult:
994
+ """Self-BLEU with sacreBLEU sentence settings (exponential smoothing, effective order)."""
995
+ preds = as_texts(predictions, "predictions")
996
+ if len(preds) < 2:
997
+ raise InputValidationError("Self-BLEU needs at least two predictions.")
998
+ order = check_positive_int(max_order, "max_order")
999
+ tok = _tokenizer(tokenize)
1000
+ toks = [tok(p.rstrip()) for p in preds]
1001
+ if core is not None:
1002
+ v = Vocab()
1003
+ segs = core.self_bleu_stats([v.encode(t) for t in toks], order)
1004
+ else:
1005
+ segs = [_bleu_stats(toks[i], toks[:i] + toks[i + 1 :], order) for i in range(len(toks))]
1006
+ scores = [_bleu_from_stats(seg, order, "exp", None, True)[0] for seg in segs]
1007
+ return MetricResult("self_bleu", "Self-BLEU", float(np.mean(scores)), {"max_order": order})
1008
+
1009
+
1010
+ # ---------------------------------------------------------------- language-model likelihood
1011
+ def _logprob_arrays(token_logprobs: Any) -> list[np.ndarray]:
1012
+ if isinstance(token_logprobs, np.ndarray) and token_logprobs.ndim == 1:
1013
+ token_logprobs = [token_logprobs]
1014
+ seqs = list(token_logprobs) if not isinstance(token_logprobs, (str, bytes)) else None
1015
+ if not seqs:
1016
+ raise InputValidationError("token_logprobs must be a non-empty list of per-token log-probabilities.")
1017
+ if all(isinstance(v, (int, float, np.floating)) for v in seqs):
1018
+ seqs = [seqs]
1019
+ out = [np.asarray(s, dtype=np.float64).ravel() for s in seqs]
1020
+ flat = np.concatenate(out)
1021
+ if np.all(np.isfinite(flat)) and not np.any(flat > 1e-9) and all(a.size for a in out):
1022
+ return out # validated once over all tokens; the loop below only locates the offending sequence
1023
+ for i, a in enumerate(out):
1024
+ if a.size == 0:
1025
+ raise InputValidationError(f"token_logprobs[{i}] is empty.")
1026
+ if not np.all(np.isfinite(a)) or np.any(a > 1e-9):
1027
+ raise InputValidationError(
1028
+ f"token_logprobs[{i}] must contain finite natural-log probabilities (<= 0)."
1029
+ )
1030
+ return out # pragma: no cover - unreachable: the pooled check failed, so some sequence fails
1031
+
1032
+
1033
+ @register(
1034
+ category=_C,
1035
+ task="language-modeling",
1036
+ name="Cross-entropy (negative log-likelihood)",
1037
+ definition="Average negative log-probability the model assigns to the observed tokens, pooled over all "
1038
+ "tokens of all sequences.",
1039
+ formula="H = −(1/T) Σ_t log p(x_t | x_<t)",
1040
+ range="[0, ∞)",
1041
+ input_requirements=("token_logprobs",),
1042
+ references=(_REF_PPL,),
1043
+ higher_is_better=False,
1044
+ )
1045
+ @per_item
1046
+ def cross_entropy(token_logprobs: Any, *, base: float = math.e) -> MetricResult:
1047
+ """Token-pooled cross-entropy from natural-log token probabilities, in nats (``base=2`` for bits)."""
1048
+ seqs = _logprob_arrays(token_logprobs)
1049
+ flat = np.concatenate(seqs)
1050
+ total, n_tokens = float(flat.sum()), int(flat.size)
1051
+ if base <= 0 or base == 1:
1052
+ raise InputValidationError("base must be positive and not 1.")
1053
+ value = -total / n_tokens / math.log(base)
1054
+ return MetricResult("cross_entropy", "Cross-entropy", value, {"base": base, "n_tokens": n_tokens})
1055
+
1056
+
1057
+ @register(
1058
+ category=_C,
1059
+ task="language-modeling",
1060
+ name="Perplexity",
1061
+ definition="Exponentiated token-average negative log-likelihood, pooled over all tokens. Only comparable "
1062
+ "between models that share a tokenizer.",
1063
+ formula="PPL = exp(−(1/T) Σ_t log p(x_t | x_<t))",
1064
+ range="[1, ∞)",
1065
+ input_requirements=("token_logprobs",),
1066
+ references=(_REF_PPL,),
1067
+ higher_is_better=False,
1068
+ )
1069
+ @per_item
1070
+ def perplexity(token_logprobs: Any, *, average: str = "tokens") -> MetricResult:
1071
+ """Perplexity from per-token natural-log probabilities (one array per sequence).
1072
+
1073
+ ``average="tokens"`` pools all tokens (the usual corpus perplexity); ``"sequences"`` averages the
1074
+ per-sequence perplexities instead."""
1075
+ seqs = _logprob_arrays(token_logprobs)
1076
+ if average == "tokens":
1077
+ value = math.exp(-float(np.concatenate(seqs).mean()))
1078
+ elif average == "sequences":
1079
+ value = float(np.mean([math.exp(-float(s.mean())) for s in seqs]))
1080
+ else:
1081
+ raise InputValidationError("average must be 'tokens' or 'sequences'.")
1082
+ return MetricResult("perplexity", "Perplexity", value, {"average": average, "n_sequences": len(seqs)})
1083
+
1084
+
1085
+ # ---------------------------------------------------------------- METEOR
1086
+ _REF_METEOR = (
1087
+ "Lavie A, Agarwal A. METEOR: an automatic metric for MT evaluation with high levels of correlation with "
1088
+ "human judgments. WMT. 2007:228-231."
1089
+ )
1090
+ _REF_BANERJEE = (
1091
+ "Banerjee S, Lavie A. METEOR: an automatic metric for MT evaluation with improved correlation with human "
1092
+ "judgments. ACL Workshop on Evaluation Measures. 2005:65-72."
1093
+ )
1094
+
1095
+
1096
+ @functools.lru_cache(maxsize=1)
1097
+ def _porter_stem() -> Callable[[str], str]:
1098
+ """NLTK's Porter stemmer (the one NLTK's METEOR uses), memoised per word: stemming is a pure function of the
1099
+ word, and the same words recur across a corpus, so each distinct word is stemmed once."""
1100
+ from nltk.stem.porter import PorterStemmer
1101
+
1102
+ return functools.lru_cache(maxsize=2**16)(PorterStemmer().stem)
1103
+
1104
+
1105
+ def _meteor_match(
1106
+ hyp: list[tuple[int, str]], ref: list[tuple[int, str]]
1107
+ ) -> tuple[list[tuple[int, int]], Any, Any]:
1108
+ """NLTK's matcher: each hypothesis word (from the end) takes the latest unused identical reference word."""
1109
+ positions: dict[str, list[int]] = {}
1110
+ for j, (_, w) in enumerate(ref):
1111
+ positions.setdefault(w, []).append(j)
1112
+ pairs, used_h, used_r = [], set(), set()
1113
+ for i in range(len(hyp) - 1, -1, -1):
1114
+ pos = positions.get(hyp[i][1])
1115
+ if pos:
1116
+ j = pos.pop()
1117
+ used_h.add(i)
1118
+ used_r.add(j)
1119
+ pairs.append((hyp[i][0], ref[j][0]))
1120
+ return (
1121
+ pairs,
1122
+ [p for i, p in enumerate(hyp) if i not in used_h],
1123
+ [p for j, p in enumerate(ref) if j not in used_r],
1124
+ )
1125
+
1126
+
1127
+ def _meteor_synonym_match(
1128
+ hyp: list[tuple[int, str]], ref: list[tuple[int, str]], synonyms: Callable[[str], Any]
1129
+ ) -> list[tuple[int, int]]:
1130
+ positions: dict[str, list[int]] = {}
1131
+ for j, (_, w) in enumerate(ref):
1132
+ positions.setdefault(w, []).append(j)
1133
+ pairs = []
1134
+ for i in range(len(hyp) - 1, -1, -1):
1135
+ cands = set(synonyms(hyp[i][1]) or ()) | {hyp[i][1]}
1136
+ best_j, best_w = -1, None
1137
+ for s in cands:
1138
+ pos = positions.get(s)
1139
+ if pos and pos[-1] > best_j:
1140
+ best_j, best_w = pos[-1], s
1141
+ if best_w is not None:
1142
+ positions[best_w].pop()
1143
+ pairs.append((hyp[i][0], ref[best_j][0]))
1144
+ return pairs
1145
+
1146
+
1147
+ def _meteor_single(
1148
+ hyp: list[str],
1149
+ ref: list[str],
1150
+ stemmer: Optional[Callable[[str], str]],
1151
+ synonyms: Optional[Callable[[str], Any]],
1152
+ alpha: float,
1153
+ beta: float,
1154
+ gamma: float,
1155
+ ) -> float:
1156
+ h = list(enumerate(w.lower() for w in hyp))
1157
+ r = list(enumerate(w.lower() for w in ref))
1158
+ n_h, n_r = len(h), len(r)
1159
+ matches, h, r = _meteor_match(h, r)
1160
+ if stemmer is not None:
1161
+ # As NLTK, the unmatched words go on to the synonym stage in their stemmed form.
1162
+ stem_pairs, h, r = _meteor_match([(i, stemmer(w)) for i, w in h], [(j, stemmer(w)) for j, w in r])
1163
+ matches += stem_pairs
1164
+ if synonyms is not None:
1165
+ matches += _meteor_synonym_match(h, r, synonyms)
1166
+ matches.sort(key=lambda m: m[0])
1167
+ m = len(matches)
1168
+ if m == 0 or n_h == 0 or n_r == 0:
1169
+ return 0.0
1170
+ precision, recall = m / n_h, m / n_r
1171
+ fmean = precision * recall / (alpha * precision + (1 - alpha) * recall)
1172
+ chunks = 1
1173
+ for a, b in zip(matches, matches[1:]):
1174
+ if not (b[0] == a[0] + 1 and b[1] == a[1] + 1):
1175
+ chunks += 1
1176
+ return float((1 - gamma * (chunks / m) ** beta) * fmean)
1177
+
1178
+
1179
+ @register(
1180
+ category=_C,
1181
+ task="generation",
1182
+ name="METEOR",
1183
+ definition="Unigram alignment between prediction and reference by exact, stemmed and (optionally) synonym "
1184
+ "matches; harmonic mean weighted towards recall, penalised for fragmented alignments. Best reference per "
1185
+ "example, averaged over examples (NLTK's meteor_score).",
1186
+ formula="(1 − γ (chunks/m)^β) · P·R / (α P + (1 − α) R)",
1187
+ range="[0, 1]",
1188
+ input_requirements=("references", "predictions"),
1189
+ references=(_REF_BANERJEE, _REF_METEOR),
1190
+ )
1191
+ @per_item
1192
+ def meteor(
1193
+ references: Any,
1194
+ predictions: Any,
1195
+ *,
1196
+ stemmer: Any = "porter",
1197
+ synonyms: Optional[Callable[[str], Any]] = None,
1198
+ alpha: float = 0.9,
1199
+ beta: float = 3.0,
1200
+ gamma: float = 0.5,
1201
+ tokenize: Any = "none",
1202
+ average: Optional[str] = "mean",
1203
+ ) -> MetricResult:
1204
+ """METEOR as in NLTK ``meteor_score`` (lowercased, whitespace tokens by default).
1205
+
1206
+ ``stemmer="porter"`` uses NLTK's Porter stemmer when NLTK is installed (``None`` disables stemming, or pass
1207
+ any callable str -> str). WordNet synonyms need a corpus download, so they are off unless you pass
1208
+ ``synonyms``: a callable returning the synonyms of a word, e.g.
1209
+ ``lambda w: {l.name() for s in wordnet.synsets(w) for l in s.lemmas() if "_" not in l.name()}``."""
1210
+ preds = as_texts(predictions, "predictions")
1211
+ refs = as_references(references, len(preds))
1212
+ tok = _tokenizer(tokenize)
1213
+ stem_fn: Optional[Callable[[str], str]]
1214
+ if stemmer == "porter":
1215
+ try:
1216
+ stem_fn = _porter_stem()
1217
+ except ImportError as exc:
1218
+ from ..core.exceptions import OptionalDependencyError
1219
+
1220
+ raise OptionalDependencyError(
1221
+ "nltk", "llm", "METEOR's default Porter stemmer (or pass stemmer=None)"
1222
+ ) from exc
1223
+ elif stemmer is None or callable(stemmer):
1224
+ stem_fn = stemmer
1225
+ else:
1226
+ raise InputValidationError("stemmer must be 'porter', None or a callable str -> str.")
1227
+ if synonyms is not None and not callable(synonyms):
1228
+ raise InputValidationError("synonyms must be a callable returning the synonyms of a word.")
1229
+ for name, v in (("alpha", alpha), ("gamma", gamma)):
1230
+ if not 0 <= v <= 1:
1231
+ raise InputValidationError(f"{name} must be in [0, 1].")
1232
+ if core is not None and synonyms is None:
1233
+ words = Vocab()
1234
+ h_ids = [words.encode([w.lower() for w in tok(p)]) for p in preds]
1235
+ r_ids = [[words.encode([w.lower() for w in tok(r)]) for r in rs] for rs in refs]
1236
+ stem_of = None
1237
+ if stem_fn is not None: # each distinct word is stemmed once
1238
+ stems = Vocab()
1239
+ stem_of = stems.encode(stem_fn(w) for w in words.ids)
1240
+ scores = core.meteor_scores(h_ids, r_ids, stem_of, float(alpha), float(beta), float(gamma))
1241
+ else:
1242
+ scores = [
1243
+ max(_meteor_single(tok(p), tok(r), stem_fn, synonyms, alpha, beta, gamma) for r in rs)
1244
+ for p, rs in zip(preds, refs)
1245
+ ]
1246
+ arr = np.array(scores)
1247
+ value: Any = arr if average is None else float(arr.mean())
1248
+ return MetricResult(
1249
+ "meteor",
1250
+ "METEOR",
1251
+ value,
1252
+ {
1253
+ "stemmer": stem_fn is not None,
1254
+ "synonyms": synonyms is not None,
1255
+ "alpha": alpha,
1256
+ "beta": beta,
1257
+ "gamma": gamma,
1258
+ },
1259
+ )
1260
+
1261
+
1262
+ # ---------------------------------------------------------------- CIDEr-D
1263
+ _REF_CIDER = (
1264
+ "Vedantam R, Zitnick CL, Parikh D. CIDEr: consensus-based image description evaluation. CVPR. 2015:4566-4575."
1265
+ )
1266
+
1267
+
1268
+ def _cider_counts(words: list[str], n: int) -> Counter[tuple[str, ...]]:
1269
+ c: Counter[tuple[str, ...]] = Counter()
1270
+ for k in range(1, n + 1):
1271
+ c.update(word_ngrams(words, k))
1272
+ return c
1273
+
1274
+
1275
+ @register(
1276
+ category=_C,
1277
+ task="captioning",
1278
+ name="CIDEr-D",
1279
+ definition="Consensus with several references: cosine similarity of TF-IDF weighted n-gram vectors "
1280
+ "(n = 1..4), clipped to the reference counts and damped by a Gaussian length penalty; IDF comes from the "
1281
+ "references of the whole evaluated set (the coco-caption implementation).",
1282
+ formula="10 · mean_n mean_refs [Σ min(g_h, g_r)·g_r / (‖g_h‖‖g_r‖)] · exp(−Δ²/2σ²)",
1283
+ range="[0, 10]",
1284
+ input_requirements=("references", "predictions"),
1285
+ references=(_REF_CIDER,),
1286
+ )
1287
+ @per_item
1288
+ def cider(
1289
+ references: Any,
1290
+ predictions: Any,
1291
+ *,
1292
+ max_order: int = 4,
1293
+ sigma: float = 6.0,
1294
+ tokenize: Any = "none",
1295
+ lowercase: bool = False,
1296
+ average: Optional[str] = "mean",
1297
+ ) -> MetricResult:
1298
+ """CIDEr-D identical to ``pycocoevalcap`` (on whitespace tokens; the COCO pipeline first applies its PTB
1299
+ tokenizer and lowercasing, which you can do beforehand). Needs the whole evaluation set, because the
1300
+ document frequencies come from all references; scores of one image depend on the others."""
1301
+ preds = as_texts(predictions, "predictions")
1302
+ refs = as_references(references, len(preds))
1303
+ n = check_positive_int(max_order, "max_order")
1304
+ if sigma <= 0:
1305
+ raise InputValidationError("sigma must be positive.")
1306
+ tok = _tokenizer(tokenize)
1307
+
1308
+ def words(s: str) -> list[str]:
1309
+ return tok(s.lower() if lowercase else s)
1310
+
1311
+ ctest = [_cider_counts(words(p), n) for p in preds]
1312
+ crefs = [[_cider_counts(words(r), n) for r in rs] for rs in refs]
1313
+ df: Counter[tuple[str, ...]] = Counter()
1314
+ for rs in crefs:
1315
+ df.update({g for r in rs for g in r})
1316
+ ref_len = math.log(float(len(crefs)))
1317
+
1318
+ def vec(cnts: Counter[tuple[str, ...]]) -> tuple[list[dict[tuple[str, ...], float]], list[float], int]:
1319
+ v: list[dict[tuple[str, ...], float]] = [{} for _ in range(n)]
1320
+ norm = [0.0] * n
1321
+ length = 0
1322
+ for g, tf in cnts.items():
1323
+ k = len(g) - 1
1324
+ w = float(tf) * (ref_len - math.log(max(1.0, df.get(g, 0))))
1325
+ v[k][g] = w
1326
+ norm[k] += w * w
1327
+ if k == 1: # pycocoevalcap counts bigrams as the "length" (kept for identical scores)
1328
+ length += tf
1329
+ return v, [math.sqrt(x) for x in norm], length
1330
+
1331
+ scores = []
1332
+ for t, rs in zip(ctest, crefs):
1333
+ vh, nh, lh = vec(t)
1334
+ total = np.zeros(n)
1335
+ for r in rs:
1336
+ vr, nr, lr = vec(r)
1337
+ damp = math.exp(-((lh - lr) ** 2) / (2 * sigma**2))
1338
+ for k in range(n):
1339
+ val = sum(min(w, vr[k].get(g, 0.0)) * vr[k].get(g, 0.0) for g, w in vh[k].items())
1340
+ if nh[k] != 0 and nr[k] != 0:
1341
+ val /= nh[k] * nr[k]
1342
+ total[k] += val * damp
1343
+ scores.append(float(np.mean(total)) / len(rs) * 10.0)
1344
+ arr = np.array(scores)
1345
+ value: Any = arr if average is None else float(arr.mean())
1346
+ return MetricResult("cider", "CIDEr-D", value, {"max_order": n, "sigma": sigma})