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
evalsuite/text/rag.py ADDED
@@ -0,0 +1,235 @@
1
+ """Retrieval-augmented generation beyond ranked retrieval: context precision, recall and relevance, retrieval
2
+ latency, end-to-end task success and failure attribution.
3
+
4
+ Retrieval ranking metrics (Precision@k, Recall@k, Hit rate@k, MRR, MAP, NDCG) live in
5
+ ``evalsuite.text.retrieval``; answer-level faithfulness, correctness and citations in
6
+ ``evalsuite.text.factuality``. The functions here take per-chunk or per-claim judgements that a human, a
7
+ retrieval check or an LLM judge produced.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections import Counter
13
+ from typing import Any, Optional
14
+
15
+ import numpy as np
16
+
17
+ from ..core.exceptions import InputValidationError
18
+ from ..core.registry import register
19
+ from ..core.result import MetricResult
20
+ from ._common import per_item
21
+
22
+ __all__ = [
23
+ "context_precision",
24
+ "context_recall",
25
+ "context_relevance",
26
+ "failure_attribution",
27
+ "latency_summary",
28
+ "task_success_rate",
29
+ ]
30
+
31
+ _C = "rag"
32
+ _REF_RAGAS = (
33
+ "Es S, James J, Espinosa-Anke L, Schockaert S. RAGAS: automated evaluation of retrieval augmented "
34
+ "generation. EACL (demos). 2024:150-158."
35
+ )
36
+ _REF_ARES = (
37
+ "Saad-Falcon J, Khattab O, Potts C, Zaharia M. ARES: an automated evaluation framework for retrieval-"
38
+ "augmented generation systems. NAACL. 2024:338-354."
39
+ )
40
+ _REF_RAGCHECKER = (
41
+ "Ru D, Qiu L, Hu X, et al. RAGChecker: a fine-grained framework for diagnosing retrieval-augmented "
42
+ "generation. NeurIPS Datasets and Benchmarks. 2024."
43
+ )
44
+ _REF_WILSON = (
45
+ "Wilson EB. Probable inference, the law of succession, and statistical inference. JASA. 1927;22:209-212."
46
+ )
47
+
48
+
49
+ def _flag_lists(x: Any, name: str) -> list[list[bool]]:
50
+ rows = list(x) if not isinstance(x, (str, bytes)) else []
51
+ if not rows:
52
+ raise InputValidationError(f"{name} must be a non-empty list with one list of booleans per query.")
53
+ return [[bool(v) for v in r] for r in rows]
54
+
55
+
56
+ def _finish(
57
+ metric: str, name: str, per: np.ndarray, average: Optional[str], extra: dict[str, Any]
58
+ ) -> MetricResult:
59
+ if average not in ("mean", None):
60
+ raise InputValidationError("average must be 'mean' or None (per query).")
61
+ keep = ~np.isnan(per)
62
+ if not keep.any():
63
+ raise InputValidationError(f"{name} is undefined for every query.")
64
+ value: Any = per if average is None else float(per[keep].mean())
65
+ return MetricResult(
66
+ metric, name, value, {"n_queries": int(per.size), "n_undefined": int((~keep).sum()), **extra}
67
+ )
68
+
69
+
70
+ @register(
71
+ category=_C,
72
+ task="rag",
73
+ name="Context precision",
74
+ definition="How well the retriever ranks useful chunks first: the mean of precision@k at the rank of each "
75
+ "relevant chunk, over the retrieved list (RAGAS context precision; average precision over retrieved "
76
+ "chunks).",
77
+ formula="Σ_k (precision@k · rel_k) / Σ_k rel_k",
78
+ range="[0, 1]",
79
+ input_requirements=("chunk_relevance",),
80
+ references=(_REF_RAGAS,),
81
+ )
82
+ @per_item
83
+ def context_precision(chunk_relevance: Any, *, average: Optional[str] = "mean") -> MetricResult:
84
+ """``chunk_relevance``: per query, the relevance verdict of each retrieved chunk in rank order. Queries with
85
+ no relevant chunk score 0 (nothing useful was retrieved)."""
86
+ rows = _flag_lists(chunk_relevance, "chunk_relevance")
87
+ per = np.empty(len(rows))
88
+ for i, r in enumerate(rows):
89
+ a = np.asarray(r, dtype=float)
90
+ if a.size == 0 or a.sum() == 0:
91
+ per[i] = 0.0
92
+ continue
93
+ prec = np.cumsum(a) / np.arange(1, a.size + 1)
94
+ per[i] = float((prec * a).sum() / a.sum())
95
+ return _finish("context_precision", "Context precision", per, average, {})
96
+
97
+
98
+ @register(
99
+ category=_C,
100
+ task="rag",
101
+ name="Context recall",
102
+ definition="Share of the reference answer's claims that can be attributed to the retrieved context (RAGAS "
103
+ "context recall): did retrieval find the evidence needed?",
104
+ formula="reference claims supported by the context / reference claims",
105
+ range="[0, 1]",
106
+ input_requirements=("claim_attributed",),
107
+ references=(_REF_RAGAS, _REF_RAGCHECKER),
108
+ )
109
+ @per_item
110
+ def context_recall(claim_attributed: Any, *, average: Optional[str] = "mean") -> MetricResult:
111
+ """``claim_attributed``: per query, one boolean per claim of the reference answer (supported by the
112
+ retrieved context or not). Queries whose reference has no claims are undefined (NaN) and skipped."""
113
+ rows = _flag_lists(claim_attributed, "claim_attributed")
114
+ per = np.array([np.mean(r) if r else np.nan for r in rows], dtype=float)
115
+ return _finish("context_recall", "Context recall", per, average, {})
116
+
117
+
118
+ @register(
119
+ category=_C,
120
+ task="rag",
121
+ name="Context relevance",
122
+ definition="Share of the retrieved context that is relevant to the question (per chunk or per sentence), "
123
+ "a measure of retrieval noise (ARES context relevance).",
124
+ formula="relevant units / retrieved units",
125
+ range="[0, 1]",
126
+ input_requirements=("unit_relevance",),
127
+ references=(_REF_ARES,),
128
+ )
129
+ @per_item
130
+ def context_relevance(unit_relevance: Any, *, average: Optional[str] = "mean") -> MetricResult:
131
+ """``unit_relevance``: per query, one boolean per retrieved chunk or sentence."""
132
+ rows = _flag_lists(unit_relevance, "unit_relevance")
133
+ per = np.array([np.mean(r) if r else np.nan for r in rows], dtype=float)
134
+ return _finish("context_relevance", "Context relevance", per, average, {})
135
+
136
+
137
+ @register(
138
+ category=_C,
139
+ task="operations",
140
+ name="Latency summary",
141
+ definition="Distribution of a latency (retrieval, time to first token, end-to-end): mean and the 50th, "
142
+ "90th, 95th and 99th percentiles (linear interpolation), in the input's unit.",
143
+ formula="mean and percentiles of the observed latencies",
144
+ range="[0, ∞)",
145
+ input_requirements=("latencies",),
146
+ references=("Dean J, Barroso LA. The tail at scale. Commun ACM. 2013;56(2):74-80.",),
147
+ higher_is_better=False,
148
+ )
149
+ def latency_summary(latencies: Any, *, statistic: str = "p95", unit: str = "ms") -> MetricResult:
150
+ """Latency summary; ``statistic`` (``"mean"``, ``"p50"``, ``"p90"``, ``"p95"`` or ``"p99"``) is the
151
+ headline value and all of them are in ``params``."""
152
+ a = np.asarray(latencies, dtype=float).ravel()
153
+ if a.size == 0 or not np.all(np.isfinite(a)) or np.any(a < 0):
154
+ raise InputValidationError("latencies must be non-empty, finite and non-negative.")
155
+ summary = {
156
+ "mean": float(a.mean()),
157
+ **{f"p{q}": float(np.percentile(a, q)) for q in (50, 90, 95, 99)},
158
+ "max": float(a.max()),
159
+ }
160
+ if statistic not in summary or statistic == "max":
161
+ raise InputValidationError("statistic must be 'mean', 'p50', 'p90', 'p95' or 'p99'.")
162
+ return MetricResult(
163
+ "latency_summary", f"Latency {statistic}", summary[statistic], {"unit": unit, "n": int(a.size), **summary}
164
+ )
165
+
166
+
167
+ def _wilson(k: float, n: int, z: float = 1.959963984540054) -> tuple[float, float]:
168
+ p = k / n
169
+ centre = (p + z * z / (2 * n)) / (1 + z * z / n)
170
+ half = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
171
+ return float(centre - half), float(centre + half)
172
+
173
+
174
+ @register(
175
+ category=_C,
176
+ task="rag",
177
+ name="Task success rate",
178
+ definition="Share of requests the whole system resolved to specification (end-to-end query resolution, "
179
+ "tool-assisted task success), with a Wilson 95% interval.",
180
+ formula="successful tasks / tasks",
181
+ range="[0, 1]",
182
+ input_requirements=("success",),
183
+ references=(_REF_WILSON,),
184
+ )
185
+ @per_item
186
+ def task_success_rate(success: Any) -> MetricResult:
187
+ """Success rate from one boolean per task."""
188
+ a = np.asarray(success, dtype=bool).ravel()
189
+ if a.size == 0:
190
+ raise InputValidationError("success is empty.")
191
+ low, high = _wilson(float(a.sum()), int(a.size))
192
+ return MetricResult(
193
+ "task_success_rate",
194
+ "Task success rate",
195
+ float(a.mean()),
196
+ {"n": int(a.size), "ci_low": low, "ci_high": high},
197
+ )
198
+
199
+
200
+ _STAGES = ("retrieval", "generation", "evidence", "orchestration", "other")
201
+
202
+
203
+ @register(
204
+ category=_C,
205
+ task="rag",
206
+ name="Failure attribution",
207
+ definition="Distribution of failed requests over the stage that caused them: retrieval (evidence not "
208
+ "found), evidence (found but insufficient or conflicting), generation (evidence ignored or misused), "
209
+ "orchestration (tools, timeouts, routing) or other.",
210
+ formula="failures attributed to the stage / failures",
211
+ range="[0, 1] per stage",
212
+ input_requirements=("stages",),
213
+ references=(_REF_RAGCHECKER,),
214
+ higher_is_better=None,
215
+ )
216
+ def failure_attribution(stages: Any, *, stage_names: tuple[str, ...] = _STAGES) -> MetricResult:
217
+ """``stages``: the attributed stage of each failed request (``None`` or ``"none"`` for successes, which are
218
+ ignored). Returns the share per stage, aligned with ``labels``."""
219
+ names = tuple(stage_names)
220
+ vals = [None if s is None else str(s).strip().lower() for s in stages]
221
+ failed = [s for s in vals if s not in (None, "none", "success", "")]
222
+ unknown = sorted({s for s in failed if s not in names})
223
+ if unknown:
224
+ raise InputValidationError(f"Unknown stage(s) {unknown}; expected one of {list(names)}.")
225
+ if not failed:
226
+ raise InputValidationError("There are no failures to attribute.")
227
+ counts = Counter(failed)
228
+ share = np.array([counts.get(n, 0) / len(failed) for n in names])
229
+ return MetricResult(
230
+ "failure_attribution",
231
+ "Failure attribution",
232
+ share,
233
+ {"n_failures": len(failed), "n_requests": len(vals), "counts": dict(counts)},
234
+ labels=names,
235
+ )
@@ -0,0 +1,215 @@
1
+ """Sampling-based correctness: pass@k (unbiased estimator) and majority-vote accuracy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import Counter
7
+ from typing import Any, Optional
8
+
9
+ import numpy as np
10
+
11
+ from ..core.exceptions import InputValidationError
12
+ from ..core.registry import register
13
+ from ..core.result import MetricResult
14
+ from ._common import _seq, as_references, check_positive_int, per_item
15
+ from .qa import _norm
16
+
17
+ __all__ = ["benchmark_accuracy", "extract_answer", "majority_vote_accuracy", "pass_at_k"]
18
+
19
+ _C = "reasoning"
20
+ _REF_CHEN = "Chen M, et al. Evaluating large language models trained on code. arXiv:2107.03374. 2021."
21
+ _REF_WANG = (
22
+ "Wang X, Wei J, Schuurmans D, et al. Self-consistency improves chain of thought reasoning in language "
23
+ "models. ICLR. 2023."
24
+ )
25
+
26
+
27
+ def _pass_at_k(n: int, c: int, k: int) -> float:
28
+ if n - c < k:
29
+ return 1.0
30
+ return float(1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1)))
31
+
32
+
33
+ @register(
34
+ category=_C,
35
+ task="sampling",
36
+ name="pass@k",
37
+ definition="Probability that at least one of k samples drawn without replacement from the n generated for "
38
+ "a problem passes its tests, estimated without bias from the c passing samples and averaged over problems.",
39
+ formula="pass@k = mean_problems [1 − C(n − c, k) / C(n, k)]",
40
+ range="[0, 1]",
41
+ input_requirements=("n_samples", "n_correct"),
42
+ references=(_REF_CHEN,),
43
+ )
44
+ @per_item
45
+ def pass_at_k(n_samples: Any, n_correct: Any, *, k: int = 1, average: Optional[str] = "mean") -> MetricResult:
46
+ """Unbiased pass@k (Chen et al. 2021) from per-problem sample counts ``n`` and passing counts ``c``.
47
+
48
+ ``n_samples`` may be one integer for all problems. Every problem needs ``n >= k``."""
49
+ k = check_positive_int(k, "k")
50
+ c = np.asarray(_seq(n_correct, "n_correct"))
51
+ n = np.full(c.shape, n_samples) if np.ndim(n_samples) == 0 else np.asarray(_seq(n_samples, "n_samples"))
52
+ if n.shape != c.shape:
53
+ raise InputValidationError(f"n_samples and n_correct differ in length: {n.size} and {c.size}.")
54
+ if not (np.issubdtype(n.dtype, np.integer) and np.issubdtype(c.dtype, np.integer)):
55
+ raise InputValidationError("n_samples and n_correct must be integers (counts of samples).")
56
+ if np.any(c < 0) or np.any(c > n):
57
+ raise InputValidationError("Each n_correct must be between 0 and its n_samples.")
58
+ if np.any(n < k):
59
+ raise InputValidationError(
60
+ f"pass@{k} needs at least k = {k} samples per problem; the smallest n is {n.min()}."
61
+ )
62
+ scores = np.array([_pass_at_k(int(a), int(b), k) for a, b in zip(n, c)])
63
+ value: Any = scores if average is None else float(scores.mean())
64
+ return MetricResult("pass_at_k", f"pass@{k}", value, {"k": k, "n_problems": int(c.size)})
65
+
66
+
67
+ @register(
68
+ category=_C,
69
+ task="sampling",
70
+ name="Majority-vote accuracy",
71
+ definition="Accuracy of the most frequent answer among several samples per question (self-consistency); "
72
+ "ties go to the answer seen first.",
73
+ formula="mean_i [mode(samples_i) matches a reference]",
74
+ range="[0, 1]",
75
+ input_requirements=("references", "samples"),
76
+ references=(_REF_WANG,),
77
+ )
78
+ @per_item
79
+ def majority_vote_accuracy(
80
+ references: Any, samples: Any, *, normalize: Any = True, average: Optional[str] = "mean"
81
+ ) -> MetricResult:
82
+ """Majority-vote (self-consistency) accuracy. ``samples[i]`` is the list of answers sampled for question i;
83
+ answers are compared after SQuAD normalization unless ``normalize=False``."""
84
+ groups = _seq(samples, "samples")
85
+ refs = as_references(references, len(groups))
86
+ f = _norm(normalize)
87
+ scores = []
88
+ for i, (answers, rs) in enumerate(zip(groups, refs)):
89
+ if isinstance(answers, str) or not answers:
90
+ raise InputValidationError(f"samples[{i}] must be a non-empty list of answer strings.")
91
+ votes = Counter(f(str(a)) for a in answers)
92
+ top = votes.most_common(1)[0][0] # Counter keeps first-seen order among ties
93
+ scores.append(float(any(top == f(r) for r in rs)))
94
+ arr = np.array(scores)
95
+ value: Any = arr if average is None else float(arr.mean())
96
+ return MetricResult("majority_vote_accuracy", "Majority-vote accuracy", value, {"n_questions": len(scores)})
97
+
98
+
99
+ # ---------------------------------------------------------------- answer extraction and benchmark accuracy
100
+ _REF_GSM8K = (
101
+ "Cobbe K, Kosaraju V, Bavarian M, et al. Training verifiers to solve math word problems. "
102
+ "arXiv:2110.14168. 2021."
103
+ )
104
+ _REF_MATH = (
105
+ "Hendrycks D, Burns C, Kadavath S, et al. Measuring mathematical problem solving with the MATH dataset. "
106
+ "NeurIPS Datasets and Benchmarks. 2021."
107
+ )
108
+ _NUMBER = re.compile(r"-?\$?\d[\d,]*(?:\.\d+)?")
109
+
110
+
111
+ def _boxed(text: str) -> Optional[str]:
112
+ start = text.rfind("\\boxed")
113
+ if start < 0:
114
+ start = text.rfind("\\fbox")
115
+ if start < 0:
116
+ return None
117
+ i = text.find("{", start)
118
+ if i < 0:
119
+ return None
120
+ depth = 0
121
+ for j in range(i, len(text)):
122
+ if text[j] == "{":
123
+ depth += 1
124
+ elif text[j] == "}":
125
+ depth -= 1
126
+ if depth == 0:
127
+ return text[i + 1 : j]
128
+ return None
129
+
130
+
131
+ def _clean_number(s: str) -> str:
132
+ s = s.replace(",", "").replace("$", "").strip()
133
+ if re.fullmatch(r"-?\d+\.0+", s):
134
+ s = s.split(".")[0]
135
+ return s
136
+
137
+
138
+ def extract_answer(text: str, *, style: str = "gsm8k") -> Optional[str]:
139
+ """Extract a final answer from a model output.
140
+
141
+ - ``"gsm8k"``: the number after ``####`` if present, else the last number in the text (commas, ``$`` and
142
+ trailing ``.0`` removed);
143
+ - ``"boxed"``: the content of the last ``\\boxed{...}`` (MATH convention);
144
+ - ``"choice"``: the last standalone option letter A–J (multiple choice, e.g. MMLU, GPQA, ARC);
145
+ - ``"last_line"``: the last non-empty line.
146
+
147
+ Returns ``None`` when nothing is found."""
148
+ if not isinstance(text, str):
149
+ raise InputValidationError("text must be a string.")
150
+ if style == "gsm8k":
151
+ if "####" in text:
152
+ tail = text.split("####")[-1]
153
+ m = _NUMBER.search(tail)
154
+ return _clean_number(m.group()) if m else tail.strip() or None
155
+ nums = _NUMBER.findall(text)
156
+ return _clean_number(nums[-1]) if nums else None
157
+ if style == "boxed":
158
+ b = _boxed(text)
159
+ return b.strip() if b is not None else None
160
+ if style == "choice":
161
+ found = re.findall(r"(?:^|[^A-Za-z])\(?([A-J])\)?(?=[^A-Za-z]|$)", text)
162
+ return found[-1] if found else None
163
+ if style == "last_line":
164
+ lines = [ln.strip() for ln in text.strip().splitlines() if ln.strip()]
165
+ return lines[-1] if lines else None
166
+ raise InputValidationError("style must be 'gsm8k', 'boxed', 'choice' or 'last_line'.")
167
+
168
+
169
+ @register(
170
+ category=_C,
171
+ task="reasoning",
172
+ name="Benchmark accuracy",
173
+ definition="Share of benchmark questions answered correctly after extracting the final answer with the "
174
+ "benchmark's convention (GSM8K '####' or last number, MATH \\boxed{}, multiple-choice letter) and "
175
+ "comparing with the gold answer.",
176
+ formula="mean_i [extract(output_i) = gold_i]",
177
+ range="[0, 1]",
178
+ input_requirements=("references", "outputs"),
179
+ references=(_REF_GSM8K, _REF_MATH),
180
+ )
181
+ @per_item
182
+ def benchmark_accuracy(
183
+ references: Any, outputs: Any, *, style: str = "gsm8k", normalize: Any = None, average: Optional[str] = "mean"
184
+ ) -> MetricResult:
185
+ """Accuracy with answer extraction. Gold answers are cleaned the same way (for ``"gsm8k"``, the gold
186
+ solution's ``####`` line is used when present). ``normalize`` optionally maps both sides (for MATH, pass
187
+ an equivalence-normalising function such as the one from the MATH repository)."""
188
+ outs = [str(o) for o in _seq(outputs, "outputs")]
189
+ golds = [str(g) for g in _seq(references, "references")]
190
+ if len(outs) != len(golds):
191
+ raise InputValidationError("references and outputs must have the same length.")
192
+ fix = normalize if callable(normalize) else (lambda s: s)
193
+ hits, missing = [], 0
194
+ for g, o in zip(golds, outs):
195
+ gold = (
196
+ extract_answer(g, style=style)
197
+ if style in ("gsm8k", "boxed") and (("####" in g) or ("\\boxed" in g))
198
+ else g.strip()
199
+ )
200
+ if style == "gsm8k" and gold is not None:
201
+ gold = _clean_number(gold)
202
+ pred = extract_answer(o, style=style)
203
+ if pred is None:
204
+ missing += 1
205
+ hits.append(False)
206
+ continue
207
+ hits.append(fix(pred) == fix(gold))
208
+ arr = np.asarray(hits, dtype=float)
209
+ value: Any = arr if average is None else float(arr.mean())
210
+ return MetricResult(
211
+ "benchmark_accuracy",
212
+ "Benchmark accuracy",
213
+ value,
214
+ {"style": style, "n": len(outs), "no_answer_found": missing},
215
+ )
@@ -0,0 +1,158 @@
1
+ """One report for text generation: the reference-based metrics computed together, with exports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from types import MappingProxyType
8
+ from typing import TYPE_CHECKING, Any, Optional, cast
9
+
10
+ from ..core.exceptions import InputValidationError
11
+ from ..core.export import PathLike, csv_text, html_document, html_table, save_as
12
+ from ..core.result import _fmt, _json_safe, _latex_escape, _latex_table
13
+ from ._common import as_references, as_texts
14
+
15
+ if TYPE_CHECKING:
16
+ import pandas as pd
17
+
18
+ __all__ = ["TextReport", "text_report"]
19
+
20
+ # (key, label, scale note) in report order
21
+ _ALL = (
22
+ ("bleu", "BLEU", "0–100, sacreBLEU"),
23
+ ("chrf", "chrF", "0–100"),
24
+ ("chrf_pp", "chrF++", "0–100"),
25
+ ("ter", "TER", "0–∞, lower is better"),
26
+ ("rouge_1", "ROUGE-1", "F1, 0–1"),
27
+ ("rouge_2", "ROUGE-2", "F1, 0–1"),
28
+ ("rouge_l", "ROUGE-L", "F1, 0–1"),
29
+ ("rouge_lsum", "ROUGE-Lsum", "F1, 0–1"),
30
+ ("meteor", "METEOR", "0–1"),
31
+ ("exact_match", "Exact match", "0–1, SQuAD normalisation"),
32
+ ("token_f1", "Token F1", "0–1, SQuAD normalisation"),
33
+ )
34
+ _KEYS = tuple(k for k, _, _ in _ALL)
35
+
36
+
37
+ @dataclass(frozen=True, eq=False)
38
+ class TextReport:
39
+ """Reference-based text metrics for one system. ``report["bleu"]`` gives one value."""
40
+
41
+ values: Any
42
+ params: Any = field(default_factory=dict)
43
+
44
+ def __post_init__(self) -> None:
45
+ object.__setattr__(self, "values", MappingProxyType(dict(self.values)))
46
+ object.__setattr__(self, "params", MappingProxyType(dict(self.params)))
47
+
48
+ def __getitem__(self, name: str) -> float:
49
+ try:
50
+ return float(self.values[name])
51
+ except KeyError:
52
+ raise KeyError(f"No value {name!r}. Available: {', '.join(self.values)}.") from None
53
+
54
+ def _rows(self, digits: int) -> list[list[str]]:
55
+ return [[label, _fmt(self.values[k], digits), note] for k, label, note in _ALL if k in self.values]
56
+
57
+ def summary(self, *, digits: int = 4) -> str:
58
+ p = self.params
59
+ lines = [f"EvalSuite text evaluation ({p['n_examples']} examples, {p['max_references']} reference(s) max)"]
60
+ rows = self._rows(digits)
61
+ width = max(len(r[0]) for r in rows)
62
+ lines += [f" {r[0]:<{width}} {r[1]:>8} {r[2]}" for r in rows]
63
+ return "\n".join(lines)
64
+
65
+ def __repr__(self) -> str:
66
+ return self.summary()
67
+
68
+ def to_dict(self) -> dict[str, Any]:
69
+ return cast("dict[str, Any]", _json_safe({"values": dict(self.values), "params": dict(self.params)}))
70
+
71
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
72
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
73
+
74
+ def to_dataframe(self) -> pd.DataFrame:
75
+ import pandas as pd
76
+
77
+ frame: pd.DataFrame = pd.DataFrame({"value": dict(self.values)})
78
+ return frame
79
+
80
+ def to_markdown(self, *, digits: int = 4) -> str:
81
+ lines = ["| Metric | Value | Scale |", "| --- | ---: | --- |"]
82
+ return "\n".join(lines + ["| " + " | ".join(r) + " |" for r in self._rows(digits)])
83
+
84
+ def to_latex(self, *, digits: int = 4, caption: Optional[str] = None, label: Optional[str] = None) -> str:
85
+ rows = [[_latex_escape(c) for c in r[:2]] for r in self._rows(digits)]
86
+ return _latex_table(["Metric", "Value"], rows, caption or "Text generation metrics.", label)
87
+
88
+ def to_csv(self, path: Optional[PathLike] = None) -> str:
89
+ text = csv_text(["metric", "value"], [[k, float(v)] for k, v in self.values.items()])
90
+ if path is not None:
91
+ with open(path, "w", encoding="utf-8", newline="") as fh:
92
+ fh.write(text)
93
+ return text
94
+
95
+ def to_html(self, *, digits: int = 4, full: bool = True) -> str:
96
+ body = html_table(["Metric", "Value", "Scale"], self._rows(digits), caption="Text generation metrics")
97
+ return html_document("EvalSuite text evaluation", body) if full else body
98
+
99
+ def save(self, path: PathLike) -> str:
100
+ return save_as(
101
+ path,
102
+ {
103
+ "json": self.to_json,
104
+ "csv": self.to_csv,
105
+ "markdown": self.to_markdown,
106
+ "latex": self.to_latex,
107
+ "html": self.to_html,
108
+ "text": self.summary,
109
+ },
110
+ )
111
+
112
+
113
+ def text_report(
114
+ references: Any,
115
+ predictions: Any,
116
+ *,
117
+ metrics: Optional[Any] = None,
118
+ meteor_stemmer: Any = "porter",
119
+ ) -> TextReport:
120
+ """BLEU, chrF, chrF++, TER (sacreBLEU conventions), ROUGE-1/2/L/Lsum (rouge-score), METEOR (NLTK), exact
121
+ match and token F1 (SQuAD) in one report. ``metrics`` restricts the list (keys as in the report); METEOR
122
+ is skipped automatically when NLTK is missing and ``meteor_stemmer="porter"``."""
123
+ from . import generation as g
124
+ from . import qa
125
+
126
+ preds = as_texts(predictions, "predictions")
127
+ refs = as_references(references, len(preds))
128
+ wanted = list(_KEYS) if metrics is None else list(metrics)
129
+ unknown = [m for m in wanted if m not in _KEYS]
130
+ if unknown:
131
+ raise InputValidationError(f"Unknown report metric(s) {unknown}; choose from {list(_KEYS)}.")
132
+ fns = {
133
+ "bleu": lambda: g.bleu(refs, preds),
134
+ "chrf": lambda: g.chrf(refs, preds),
135
+ "chrf_pp": lambda: g.chrf(refs, preds, word_order=2),
136
+ "ter": lambda: g.ter(refs, preds),
137
+ "rouge_1": lambda: g.rouge_1(refs, preds),
138
+ "rouge_2": lambda: g.rouge_2(refs, preds),
139
+ "rouge_l": lambda: g.rouge_l(refs, preds),
140
+ "rouge_lsum": lambda: g.rouge_lsum(refs, preds),
141
+ "meteor": lambda: g.meteor(refs, preds, stemmer=meteor_stemmer),
142
+ "exact_match": lambda: qa.exact_match(refs, preds),
143
+ "token_f1": lambda: qa.token_f1(refs, preds),
144
+ }
145
+ values: dict[str, float] = {}
146
+ skipped = []
147
+ for key in wanted:
148
+ try:
149
+ values[key] = float(fns[key]())
150
+ except ImportError:
151
+ if key == "meteor" and metrics is None:
152
+ skipped.append("meteor (install nltk)")
153
+ continue
154
+ raise
155
+ return TextReport(
156
+ values,
157
+ {"n_examples": len(preds), "max_references": max(len(r) for r in refs), "skipped": skipped},
158
+ )