evalsuite-python 0.6.0__cp39-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. evalsuite/__init__.py +268 -0
  2. evalsuite/__main__.py +5 -0
  3. evalsuite/_bench_metrics.py +2080 -0
  4. evalsuite/_core.pyd +0 -0
  5. evalsuite/_lazy.py +32 -0
  6. evalsuite/_native.py +60 -0
  7. evalsuite/api.py +275 -0
  8. evalsuite/benchmarks.py +946 -0
  9. evalsuite/calibration.py +392 -0
  10. evalsuite/classification/__init__.py +51 -0
  11. evalsuite/classification/_common.py +111 -0
  12. evalsuite/classification/metrics.py +945 -0
  13. evalsuite/cli/__init__.py +5 -0
  14. evalsuite/cli/main.py +606 -0
  15. evalsuite/clinical/__init__.py +18 -0
  16. evalsuite/clinical/metrics.py +342 -0
  17. evalsuite/clinical/report.py +366 -0
  18. evalsuite/core/__init__.py +1 -0
  19. evalsuite/core/context.py +199 -0
  20. evalsuite/core/exceptions.py +52 -0
  21. evalsuite/core/export.py +100 -0
  22. evalsuite/core/registry.py +90 -0
  23. evalsuite/core/result.py +379 -0
  24. evalsuite/core/types.py +23 -0
  25. evalsuite/core/validation.py +256 -0
  26. evalsuite/llmsys/__init__.py +189 -0
  27. evalsuite/llmsys/_common.py +215 -0
  28. evalsuite/llmsys/agents.py +384 -0
  29. evalsuite/llmsys/code.py +923 -0
  30. evalsuite/llmsys/efficiency.py +346 -0
  31. evalsuite/llmsys/longcontext.py +361 -0
  32. evalsuite/llmsys/multilingual.py +339 -0
  33. evalsuite/llmsys/robustness.py +504 -0
  34. evalsuite/llmsys/safety.py +509 -0
  35. evalsuite/llmsys/uncertainty.py +229 -0
  36. evalsuite/plot.py +651 -0
  37. evalsuite/py.typed +0 -0
  38. evalsuite/regression/__init__.py +41 -0
  39. evalsuite/regression/metrics.py +629 -0
  40. evalsuite/reporting.py +241 -0
  41. evalsuite/stats/__init__.py +46 -0
  42. evalsuite/stats/_resolve.py +229 -0
  43. evalsuite/stats/compare.py +420 -0
  44. evalsuite/stats/effect.py +159 -0
  45. evalsuite/stats/hypothesis.py +593 -0
  46. evalsuite/stats/intervals.py +338 -0
  47. evalsuite/stats/paired.py +214 -0
  48. evalsuite/stats/results.py +129 -0
  49. evalsuite/text/__init__.py +154 -0
  50. evalsuite/text/_common.py +97 -0
  51. evalsuite/text/factuality.py +469 -0
  52. evalsuite/text/generation.py +1346 -0
  53. evalsuite/text/judge.py +556 -0
  54. evalsuite/text/qa.py +108 -0
  55. evalsuite/text/rag.py +235 -0
  56. evalsuite/text/reasoning.py +215 -0
  57. evalsuite/text/report.py +158 -0
  58. evalsuite/text/retrieval.py +238 -0
  59. evalsuite/text/semantic.py +499 -0
  60. evalsuite/text/spice.py +162 -0
  61. evalsuite/text/structured.py +793 -0
  62. evalsuite/version.py +3 -0
  63. evalsuite/vision/__init__.py +47 -0
  64. evalsuite/vision/detection.py +696 -0
  65. evalsuite/vision/segmentation.py +1028 -0
  66. evalsuite_python-0.6.0.dist-info/METADATA +509 -0
  67. evalsuite_python-0.6.0.dist-info/RECORD +72 -0
  68. evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
  69. evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
  70. evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
  71. evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
  72. evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
@@ -0,0 +1,361 @@
1
+ """Long-context and summarization evaluation (v0.5.0).
2
+
3
+ ROUGE-L and BERTScore for summaries are the existing ``es.rouge_l`` and ``es.bertscore``; summary factual
4
+ consistency can also be measured with ``es.faithfulness`` over claim verdicts. Truncation robustness is
5
+ ``es.truncation_sensitivity``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from typing import Any, Callable, Optional
12
+
13
+ import numpy as np
14
+
15
+ from ..core.exceptions import InputValidationError
16
+ from ..core.registry import register
17
+ from ..core.result import MetricResult
18
+ from ._common import bools, floats, lists_of, rate, same_length, seq
19
+
20
+ __all__ = [
21
+ "citation_coverage",
22
+ "compression_ratio",
23
+ "context_utilization",
24
+ "cross_document_consistency",
25
+ "lost_in_the_middle",
26
+ "needle_in_haystack",
27
+ "position_accuracy",
28
+ "retrieval_accuracy_by_length",
29
+ "summary_coverage",
30
+ ]
31
+
32
+ _C = "long_context"
33
+ _REF_NIAH = (
34
+ "Kamradt G. Needle in a haystack: pressure testing LLMs. GitHub repository "
35
+ "gkamradt/LLMTest_NeedleInAHaystack. 2023."
36
+ )
37
+ _REF_RULER = (
38
+ "Hsieh CP, Sun S, Kriman S, et al. RULER: what's the real context size of your long-context language models? "
39
+ "COLM. 2024."
40
+ )
41
+ _REF_LITM = (
42
+ "Liu NF, Lin K, Hewitt J, et al. Lost in the middle: how language models use long contexts. TACL. "
43
+ "2024;12:157-173."
44
+ )
45
+ _REF_LONGBENCH = (
46
+ "Bai Y, Lv X, Zhang J, et al. LongBench: a bilingual, multitask benchmark for long context understanding. "
47
+ "ACL. 2024:3119-3137."
48
+ )
49
+ _REF_FACTSCORE = (
50
+ "Min S, Krishna K, Lyu X, et al. FActScore: fine-grained atomic evaluation of factual precision in long form "
51
+ "text generation. EMNLP. 2023:12076-12100."
52
+ )
53
+ _REF_PYRAMID = (
54
+ "Nenkova A, Passonneau R. Evaluating content selection in summarization: the pyramid method. HLT-NAACL. "
55
+ "2004:145-152."
56
+ )
57
+ _REF_GRUSKY = (
58
+ "Grusky M, Naaman M, Artzi Y. Newsroom: a dataset of 1.3 million summaries with diverse extractive "
59
+ "strategies. "
60
+ "NAACL. 2018:708-719."
61
+ )
62
+ _REF_ALCE = (
63
+ "Gao T, Yen H, Yu J, Chen D. Enabling large language models to generate text with citations. EMNLP. "
64
+ "2023:6465-6488."
65
+ )
66
+
67
+
68
+ def _bin_accuracy(c: np.ndarray, x: np.ndarray, edges: np.ndarray) -> dict[str, float]:
69
+ out = {}
70
+ for lo, hi in zip(edges[:-1], edges[1:]):
71
+ m = (x >= lo) & ((x < hi) if hi != edges[-1] else (x <= hi))
72
+ if m.any():
73
+ out[f"{lo:g}-{hi:g}"] = float(c[m].mean())
74
+ return out
75
+
76
+
77
+ @register(
78
+ category=_C,
79
+ task="long-context",
80
+ name="Long-context retrieval accuracy",
81
+ definition="Accuracy of retrieving or answering from long contexts, overall and per context-length level "
82
+ "(RULER reports the accuracy at each length; the effective length is the longest one above a threshold).",
83
+ formula="acc_L = mean[correct | length = L]",
84
+ range="[0, 1]",
85
+ input_requirements=("correct", "context_lengths"),
86
+ references=(_REF_RULER, _REF_LONGBENCH),
87
+ )
88
+ def retrieval_accuracy_by_length(correct: Any, context_lengths: Any, *, threshold: float = 0.85) -> MetricResult:
89
+ c = bools(correct, "correct")
90
+ L = floats(context_lengths, "context_lengths", lo=0)
91
+ same_length(("correct", c), ("context_lengths", L))
92
+ levels = np.unique(L)
93
+ acc = {float(v): float(c[v == L].mean()) for v in levels}
94
+ ok = [v for v in levels if acc[float(v)] >= threshold]
95
+ effective = None
96
+ for v in levels: # longest length such that every shorter length also passes
97
+ if acc[float(v)] >= threshold:
98
+ effective = float(v)
99
+ else:
100
+ break
101
+ return MetricResult(
102
+ "retrieval_accuracy_by_length",
103
+ "Long-context retrieval accuracy",
104
+ float(c.mean()),
105
+ {
106
+ "by_length": {f"{k:g}": a for k, a in acc.items()},
107
+ "effective_length": effective,
108
+ "threshold": threshold,
109
+ "n_passing_lengths": len(ok),
110
+ },
111
+ )
112
+
113
+
114
+ @register(
115
+ category=_C,
116
+ task="long-context",
117
+ name="Needle-in-a-haystack accuracy",
118
+ definition="Retrieval of a planted fact (the needle) from contexts of varying length and insertion depth: "
119
+ "overall accuracy and the length × depth accuracy grid (the usual heat map).",
120
+ formula="acc = mean[correct]; grid[L, d] = mean[correct | L, d]",
121
+ range="[0, 1]",
122
+ input_requirements=("correct", "context_lengths", "depths"),
123
+ references=(_REF_NIAH, _REF_RULER),
124
+ )
125
+ def needle_in_haystack(correct: Any, context_lengths: Any, depths: Any) -> MetricResult:
126
+ """``depths``: where the needle was placed, as a fraction of the context in [0, 1]."""
127
+ c = floats(np.asarray(seq(correct, "correct"), dtype=float), "correct", lo=0, hi=1)
128
+ L = floats(context_lengths, "context_lengths", lo=0)
129
+ d = floats(depths, "depths", lo=0, hi=1)
130
+ same_length(("correct", c), ("context_lengths", L), ("depths", d))
131
+ ls, ds = np.unique(L), np.unique(d)
132
+ grid = np.full((ls.size, ds.size), np.nan)
133
+ for i, lv in enumerate(ls):
134
+ for j, dv in enumerate(ds):
135
+ m = (lv == L) & (d == dv)
136
+ if m.any():
137
+ grid[i, j] = c[m].mean()
138
+ return MetricResult(
139
+ "needle_in_haystack",
140
+ "Needle-in-a-haystack accuracy",
141
+ float(c.mean()),
142
+ {
143
+ "lengths": ls.tolist(),
144
+ "depths": ds.tolist(),
145
+ "grid": grid.tolist(),
146
+ "worst_cell": float(np.nanmin(grid)),
147
+ "by_length": {f"{v:g}": float(c[v == L].mean()) for v in ls},
148
+ "by_depth": {f"{v:g}": float(c[d == v].mean()) for v in ds},
149
+ },
150
+ )
151
+
152
+
153
+ @register(
154
+ category=_C,
155
+ task="long-context",
156
+ name="Position-dependent retrieval accuracy",
157
+ definition="Accuracy as a function of where the relevant information sits in the context (relative position "
158
+ "binned into equal-width bins), with the spread between the best and worst bin.",
159
+ formula="acc_b = mean[correct | position ∈ bin b]; spread = max_b − min_b",
160
+ range="[0, 1]",
161
+ input_requirements=("correct", "positions"),
162
+ references=(_REF_LITM,),
163
+ )
164
+ def position_accuracy(correct: Any, positions: Any, *, n_bins: int = 5) -> MetricResult:
165
+ """``positions``: relative position of the relevant passage in [0, 1] (0 = start)."""
166
+ c = floats(np.asarray(seq(correct, "correct"), dtype=float), "correct", lo=0, hi=1)
167
+ p = floats(positions, "positions", lo=0, hi=1)
168
+ same_length(("correct", c), ("positions", p))
169
+ if isinstance(n_bins, bool) or not isinstance(n_bins, int) or n_bins < 2:
170
+ raise InputValidationError("n_bins must be an integer >= 2.")
171
+ by = _bin_accuracy(c, p, np.linspace(0, 1, n_bins + 1))
172
+ vals = list(by.values())
173
+ return MetricResult(
174
+ "position_accuracy",
175
+ "Position spread (best − worst bin)",
176
+ float(max(vals) - min(vals)),
177
+ {"by_position": by, "accuracy": float(c.mean())},
178
+ )
179
+
180
+
181
+ @register(
182
+ category=_C,
183
+ task="long-context",
184
+ name="Lost-in-the-middle sensitivity",
185
+ definition="How much worse the model does when the relevant passage is in the middle of the context than at "
186
+ "its edges: mean accuracy at the start and end positions minus accuracy in the middle (Liu et al. U-curve).",
187
+ formula="(acc_start + acc_end)/2 − acc_middle",
188
+ range="[−1, 1] (0 = position-invariant)",
189
+ input_requirements=("correct", "positions"),
190
+ references=(_REF_LITM,),
191
+ higher_is_better=False,
192
+ )
193
+ def lost_in_the_middle(correct: Any, positions: Any, *, edge: float = 0.2) -> MetricResult:
194
+ c = floats(np.asarray(seq(correct, "correct"), dtype=float), "correct", lo=0, hi=1)
195
+ p = floats(positions, "positions", lo=0, hi=1)
196
+ same_length(("correct", c), ("positions", p))
197
+ if not 0 < edge < 0.5:
198
+ raise InputValidationError("edge must be in (0, 0.5).")
199
+ start, end = p <= edge, p >= 1 - edge
200
+ mid = ~start & ~end
201
+ if not (start.any() and end.any() and mid.any()):
202
+ raise InputValidationError("Need examples at the start, the middle and the end of the context.")
203
+ a_s, a_e, a_m = float(c[start].mean()), float(c[end].mean()), float(c[mid].mean())
204
+ return MetricResult(
205
+ "lost_in_the_middle",
206
+ "Lost-in-the-middle gap",
207
+ (a_s + a_e) / 2 - a_m,
208
+ {"start_accuracy": a_s, "middle_accuracy": a_m, "end_accuracy": a_e, "edge": edge},
209
+ )
210
+
211
+
212
+ @register(
213
+ category=_C,
214
+ task="long-context",
215
+ name="Context utilization / retention",
216
+ definition="Share of the relevant facts provided in the context that the output actually uses (or recalls "
217
+ "later in a conversation), pooled over examples.",
218
+ formula="Σ |used ∩ provided| / Σ |provided|",
219
+ range="[0, 1]",
220
+ input_requirements=("used_facts", "provided_facts"),
221
+ references=(_REF_LONGBENCH,),
222
+ )
223
+ def context_utilization(used_facts: Any, provided_facts: Any) -> MetricResult:
224
+ used, prov = lists_of(used_facts, "used_facts"), lists_of(provided_facts, "provided_facts")
225
+ same_length(("used_facts", used), ("provided_facts", prov))
226
+ hit = tot = 0
227
+ per = []
228
+ for u, p in zip(used, prov):
229
+ ps, us = set(map(str, p)), set(map(str, u))
230
+ if not ps:
231
+ continue
232
+ hit += len(ps & us)
233
+ tot += len(ps)
234
+ per.append(len(ps & us) / len(ps))
235
+ if tot == 0:
236
+ raise InputValidationError("No example provides any fact.")
237
+ return MetricResult(
238
+ "context_utilization", "Context utilization", hit / tot, {"mean_per_example": float(np.mean(per))}
239
+ )
240
+
241
+
242
+ @register(
243
+ category=_C,
244
+ task="summarization",
245
+ name="Summary factual consistency / coverage / completeness",
246
+ definition="Coverage: share of the reference key points (pyramid content units) the summary covers, weighted "
247
+ "by importance when weights are given; factual consistency (share of summary claims supported by the "
248
+ "source) is reported when claim verdicts are passed.",
249
+ formula="coverage = Σ w·covered / Σ w; consistency = supported claims / claims",
250
+ range="[0, 1]",
251
+ input_requirements=("key_points_covered",),
252
+ references=(_REF_PYRAMID, _REF_FACTSCORE),
253
+ )
254
+ def summary_coverage(
255
+ key_points_covered: Any, *, weights: Any = None, claims_supported: Any = None
256
+ ) -> MetricResult:
257
+ """``key_points_covered``: per summary, one boolean per reference key point. ``weights``: per summary, the
258
+ importance of each key point (pyramid weights). ``claims_supported``: per summary, one boolean per claim."""
259
+ rows = lists_of(key_points_covered, "key_points_covered")
260
+ ws = lists_of(weights, "weights") if weights is not None else [[1.0] * len(r) for r in rows]
261
+ same_length(("key_points_covered", rows), ("weights", ws))
262
+ per = []
263
+ for i, (r, w) in enumerate(zip(rows, ws)):
264
+ if len(r) != len(w) or not r:
265
+ raise InputValidationError(
266
+ f"Summary {i}: key points and weights must be non-empty and the same length."
267
+ )
268
+ wa = floats(w, f"weights[{i}]", lo=0)
269
+ per.append(float(np.dot(wa, [bool(v) for v in r]) / wa.sum()) if wa.sum() else 0.0)
270
+ extra: dict[str, Any] = {}
271
+ if claims_supported is not None:
272
+ cl = lists_of(claims_supported, "claims_supported")
273
+ same_length(("key_points_covered", rows), ("claims_supported", cl))
274
+ flat = [bool(v) for r in cl for v in r]
275
+ extra["factual_consistency"] = float(np.mean(flat)) if flat else float("nan")
276
+ extra["fully_consistent_rate"] = float(np.mean([all(map(bool, r)) for r in cl]))
277
+ return MetricResult("summary_coverage", "Summary coverage", float(np.mean(per)), extra)
278
+
279
+
280
+ @register(
281
+ category=_C,
282
+ task="summarization",
283
+ name="Summary compression ratio",
284
+ definition="How much shorter summaries are than their sources: source words / summary words (Newsroom "
285
+ "compression), the mean over documents, with its median.",
286
+ formula="mean_d |source_d| / |summary_d|",
287
+ range="[1, ∞) typically",
288
+ input_requirements=("sources", "summaries"),
289
+ references=(_REF_GRUSKY,),
290
+ higher_is_better=None,
291
+ )
292
+ def compression_ratio(
293
+ sources: Any, summaries: Any, *, tokenizer: Optional[Callable[[str], list[str]]] = None
294
+ ) -> MetricResult:
295
+ src, summ = seq(sources, "sources"), seq(summaries, "summaries")
296
+ same_length(("sources", src), ("summaries", summ))
297
+ tok = tokenizer or str.split
298
+ ratios = []
299
+ for i, (a, b) in enumerate(zip(src, summ)):
300
+ if not isinstance(a, str) or not isinstance(b, str):
301
+ raise InputValidationError(f"sources[{i}] and summaries[{i}] must be strings.")
302
+ nb = len(tok(b))
303
+ if nb == 0:
304
+ raise InputValidationError(f"summaries[{i}] is empty.")
305
+ ratios.append(len(tok(a)) / nb)
306
+ r = np.array(ratios)
307
+ return MetricResult("compression_ratio", "Compression ratio", float(r.mean()), {"median": float(np.median(r))})
308
+
309
+
310
+ @register(
311
+ category=_C,
312
+ task="summarization",
313
+ name="Citation coverage",
314
+ definition="Share of output statements that carry at least one citation (ALCE: statements that should be "
315
+ "attributable must cite something), pooled over outputs.",
316
+ formula="statements with ≥1 citation / statements",
317
+ range="[0, 1]",
318
+ input_requirements=("citations_per_statement",),
319
+ references=(_REF_ALCE,),
320
+ )
321
+ def citation_coverage(citations_per_statement: Any) -> MetricResult:
322
+ """``citations_per_statement``: per output, the number of citations attached to each statement."""
323
+ rows = lists_of(citations_per_statement, "citations_per_statement")
324
+ flat = np.array([float(v) > 0 for r in rows for v in r])
325
+ if flat.size == 0:
326
+ raise InputValidationError("No statements given.")
327
+ per = [np.mean([float(v) > 0 for v in r]) for r in rows if r]
328
+ return rate("citation_coverage", "Citation coverage", flat, {"mean_per_output": float(np.mean(per))})
329
+
330
+
331
+ @register(
332
+ category=_C,
333
+ task="long-context",
334
+ name="Cross-document consistency",
335
+ definition="Agreement of answers to the same question across different (orderings or subsets of) documents "
336
+ "or truncation levels: share of questions answered identically and mean pairwise agreement.",
337
+ formula="mean_q 1[all answers equal]",
338
+ range="[0, 1]",
339
+ input_requirements=("answers",),
340
+ references=(_REF_LITM, _REF_LONGBENCH),
341
+ )
342
+ def cross_document_consistency(answers: Any, *, normalize: Optional[Callable[[Any], Any]] = None) -> MetricResult:
343
+ from itertools import combinations
344
+
345
+ rows = seq(answers, "answers")
346
+ full, pair = [], []
347
+ for i, r in enumerate(rows):
348
+ vals = list(r.values()) if isinstance(r, Mapping) else list(r) if isinstance(r, (list, tuple)) else None
349
+ if vals is None or len(vals) < 2:
350
+ raise InputValidationError(f"answers[{i}] needs at least two answers.")
351
+ v = [
352
+ normalize(a) if normalize else (" ".join(a.lower().split()) if isinstance(a, str) else a) for a in vals
353
+ ]
354
+ full.append(all(x == v[0] for x in v))
355
+ pair.append(np.mean([x == y for x, y in combinations(v, 2)]))
356
+ return MetricResult(
357
+ "cross_document_consistency",
358
+ "Cross-document consistency",
359
+ float(np.mean(full)),
360
+ {"pairwise_agreement": float(np.mean(pair))},
361
+ )