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.
- evalsuite/__init__.py +268 -0
- evalsuite/__main__.py +5 -0
- evalsuite/_bench_metrics.py +2080 -0
- evalsuite/_core.pyd +0 -0
- evalsuite/_lazy.py +32 -0
- evalsuite/_native.py +60 -0
- evalsuite/api.py +275 -0
- evalsuite/benchmarks.py +946 -0
- evalsuite/calibration.py +392 -0
- evalsuite/classification/__init__.py +51 -0
- evalsuite/classification/_common.py +111 -0
- evalsuite/classification/metrics.py +945 -0
- evalsuite/cli/__init__.py +5 -0
- evalsuite/cli/main.py +606 -0
- evalsuite/clinical/__init__.py +18 -0
- evalsuite/clinical/metrics.py +342 -0
- evalsuite/clinical/report.py +366 -0
- evalsuite/core/__init__.py +1 -0
- evalsuite/core/context.py +199 -0
- evalsuite/core/exceptions.py +52 -0
- evalsuite/core/export.py +100 -0
- evalsuite/core/registry.py +90 -0
- evalsuite/core/result.py +379 -0
- evalsuite/core/types.py +23 -0
- evalsuite/core/validation.py +256 -0
- evalsuite/llmsys/__init__.py +189 -0
- evalsuite/llmsys/_common.py +215 -0
- evalsuite/llmsys/agents.py +384 -0
- evalsuite/llmsys/code.py +923 -0
- evalsuite/llmsys/efficiency.py +346 -0
- evalsuite/llmsys/longcontext.py +361 -0
- evalsuite/llmsys/multilingual.py +339 -0
- evalsuite/llmsys/robustness.py +504 -0
- evalsuite/llmsys/safety.py +509 -0
- evalsuite/llmsys/uncertainty.py +229 -0
- evalsuite/plot.py +651 -0
- evalsuite/py.typed +0 -0
- evalsuite/regression/__init__.py +41 -0
- evalsuite/regression/metrics.py +629 -0
- evalsuite/reporting.py +241 -0
- evalsuite/stats/__init__.py +46 -0
- evalsuite/stats/_resolve.py +229 -0
- evalsuite/stats/compare.py +420 -0
- evalsuite/stats/effect.py +159 -0
- evalsuite/stats/hypothesis.py +593 -0
- evalsuite/stats/intervals.py +338 -0
- evalsuite/stats/paired.py +214 -0
- evalsuite/stats/results.py +129 -0
- evalsuite/text/__init__.py +154 -0
- evalsuite/text/_common.py +97 -0
- evalsuite/text/factuality.py +469 -0
- evalsuite/text/generation.py +1346 -0
- evalsuite/text/judge.py +556 -0
- evalsuite/text/qa.py +108 -0
- evalsuite/text/rag.py +235 -0
- evalsuite/text/reasoning.py +215 -0
- evalsuite/text/report.py +158 -0
- evalsuite/text/retrieval.py +238 -0
- evalsuite/text/semantic.py +499 -0
- evalsuite/text/spice.py +162 -0
- evalsuite/text/structured.py +793 -0
- evalsuite/version.py +3 -0
- evalsuite/vision/__init__.py +47 -0
- evalsuite/vision/detection.py +696 -0
- evalsuite/vision/segmentation.py +1028 -0
- evalsuite_python-0.6.0.dist-info/METADATA +509 -0
- evalsuite_python-0.6.0.dist-info/RECORD +72 -0
- evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
- evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
- evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
- evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
- evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
"""Factuality, hallucination, citation and abstention metrics.
|
|
2
|
+
|
|
3
|
+
These metrics score *verdicts* that a verification step produced: a human annotator, an NLI model, a
|
|
4
|
+
retrieval check or an LLM judge decides, for each claim of an answer, whether the evidence supports it.
|
|
5
|
+
EvalSuite aggregates those verdicts consistently (micro or macro), so different verification pipelines can be
|
|
6
|
+
compared with intervals and paired tests. How claims are extracted and judged must be reported alongside.
|
|
7
|
+
|
|
8
|
+
Claim verdicts may be booleans (``True`` = supported) or the strings ``"supported"``, ``"contradicted"`` and
|
|
9
|
+
``"unsupported"`` (also ``"not enough info"`` / ``"nei"``).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Any, Optional
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from ..core.exceptions import InputValidationError
|
|
19
|
+
from ..core.registry import register
|
|
20
|
+
from ..core.result import MetricResult
|
|
21
|
+
from ._common import per_item
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"abstention_accuracy",
|
|
25
|
+
"answer_correctness",
|
|
26
|
+
"answer_relevance",
|
|
27
|
+
"citation_precision",
|
|
28
|
+
"citation_recall",
|
|
29
|
+
"claim_verification_accuracy",
|
|
30
|
+
"faithfulness",
|
|
31
|
+
"groundedness",
|
|
32
|
+
"hallucination_rate",
|
|
33
|
+
"knowledge_consistency",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
_C = "text"
|
|
37
|
+
_REF_FACTSCORE = (
|
|
38
|
+
"Min S, Krishna K, Lyu X, et al. FActScore: fine-grained atomic evaluation of factual precision in long "
|
|
39
|
+
"form text generation. EMNLP. 2023:12076-12100."
|
|
40
|
+
)
|
|
41
|
+
_REF_RAGAS = (
|
|
42
|
+
"Es S, James J, Espinosa-Anke L, Schockaert S. RAGAS: automated evaluation of retrieval augmented "
|
|
43
|
+
"generation. EACL (demos). 2024:150-158."
|
|
44
|
+
)
|
|
45
|
+
_REF_ALCE = (
|
|
46
|
+
"Gao T, Yen H, Yu J, Chen D. Enabling large language models to generate text with citations. EMNLP. "
|
|
47
|
+
"2023:6465-6488."
|
|
48
|
+
)
|
|
49
|
+
_REF_FEVER = (
|
|
50
|
+
"Thorne J, Vlachos A, Christodoulopoulos C, Mittal A. FEVER: a large-scale dataset for fact extraction and "
|
|
51
|
+
"VERification. NAACL. 2018:809-819."
|
|
52
|
+
)
|
|
53
|
+
_REF_ABSTAIN = (
|
|
54
|
+
"Feng S, Shi W, Wang Y, Ding W, Balachandran V, Tsvetkov Y. Don't hallucinate, abstain: identifying LLM "
|
|
55
|
+
"knowledge gaps via multi-LLM collaboration. ACL. 2024:14664-14690."
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
_SUPPORTED = {"supported", "support", "entailed", "entailment", "true", "yes"}
|
|
59
|
+
_CONTRA = {"contradicted", "contradiction", "refuted", "false"}
|
|
60
|
+
_UNSUP = {"unsupported", "not enough info", "nei", "neutral", "unknown", "no"}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _verdict(v: Any, where: str) -> str:
|
|
64
|
+
if isinstance(v, (bool, np.bool_)):
|
|
65
|
+
return "supported" if v else "unsupported"
|
|
66
|
+
if isinstance(v, str):
|
|
67
|
+
s = v.strip().lower()
|
|
68
|
+
if s in _SUPPORTED:
|
|
69
|
+
return "supported"
|
|
70
|
+
if s in _CONTRA:
|
|
71
|
+
return "contradicted"
|
|
72
|
+
if s in _UNSUP:
|
|
73
|
+
return "unsupported"
|
|
74
|
+
raise InputValidationError(
|
|
75
|
+
f"{where}: verdict must be a boolean or one of 'supported', 'contradicted', 'unsupported'; got {v!r}."
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _claims(claim_verdicts: Any) -> list[list[str]]:
|
|
80
|
+
if claim_verdicts is None or isinstance(claim_verdicts, (str, bytes)):
|
|
81
|
+
raise InputValidationError("claim_verdicts must be a list with one list of claim verdicts per answer.")
|
|
82
|
+
answers = list(claim_verdicts)
|
|
83
|
+
if not answers:
|
|
84
|
+
raise InputValidationError("claim_verdicts is empty.")
|
|
85
|
+
out = []
|
|
86
|
+
for i, a in enumerate(answers):
|
|
87
|
+
if isinstance(a, (str, bytes, bool)) or not hasattr(a, "__iter__"):
|
|
88
|
+
raise InputValidationError(f"claim_verdicts[{i}] must be a list of verdicts (one per claim).")
|
|
89
|
+
out.append([_verdict(v, f"claim_verdicts[{i}][{j}]") for j, v in enumerate(a)])
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _aggregate(
|
|
94
|
+
metric: str, name: str, hits: list[int], totals: list[int], average: Optional[str], extra: dict[str, Any]
|
|
95
|
+
) -> MetricResult:
|
|
96
|
+
hits_a, totals_a = np.asarray(hits, float), np.asarray(totals, float)
|
|
97
|
+
if average == "micro":
|
|
98
|
+
if totals_a.sum() == 0:
|
|
99
|
+
raise InputValidationError(f"{name} is undefined: there are no claims to score.")
|
|
100
|
+
value: Any = float(np.sum(hits_a)) / float(np.sum(totals_a))
|
|
101
|
+
elif average in ("macro", None):
|
|
102
|
+
keep = totals_a > 0
|
|
103
|
+
if not keep.any():
|
|
104
|
+
raise InputValidationError(f"{name} is undefined: every answer has zero claims.")
|
|
105
|
+
per = np.full(totals_a.shape, np.nan)
|
|
106
|
+
per[keep] = hits_a[keep] / totals_a[keep]
|
|
107
|
+
value = per if average is None else float(np.nanmean(per))
|
|
108
|
+
else:
|
|
109
|
+
raise InputValidationError("average must be 'micro' (pool all claims), 'macro' (mean per answer) or None.")
|
|
110
|
+
return MetricResult(
|
|
111
|
+
metric,
|
|
112
|
+
name,
|
|
113
|
+
value,
|
|
114
|
+
{"average": average, "n_answers": len(totals), "n_claims": int(totals_a.sum()), **extra},
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---------------------------------------------------------------- claims
|
|
119
|
+
@register(
|
|
120
|
+
category=_C,
|
|
121
|
+
task="factuality",
|
|
122
|
+
name="Faithfulness",
|
|
123
|
+
definition="Share of an answer's claims that the evidence supports (FActScore factual precision; RAGAS "
|
|
124
|
+
"faithfulness when the evidence is the retrieved context).",
|
|
125
|
+
formula="supported claims / claims",
|
|
126
|
+
range="[0, 1]",
|
|
127
|
+
input_requirements=("claim_verdicts",),
|
|
128
|
+
references=(_REF_FACTSCORE, _REF_RAGAS),
|
|
129
|
+
)
|
|
130
|
+
@per_item
|
|
131
|
+
def faithfulness(claim_verdicts: Any, *, average: Optional[str] = "macro") -> MetricResult:
|
|
132
|
+
"""Faithfulness / factual precision from per-claim verdicts (``average="macro"`` per answer, as FActScore
|
|
133
|
+
and RAGAS; ``"micro"`` pools all claims). Answers without claims are skipped in the macro mean."""
|
|
134
|
+
claims = _claims(claim_verdicts)
|
|
135
|
+
return _aggregate(
|
|
136
|
+
"faithfulness",
|
|
137
|
+
"Faithfulness",
|
|
138
|
+
[sum(v == "supported" for v in c) for c in claims],
|
|
139
|
+
[len(c) for c in claims],
|
|
140
|
+
average,
|
|
141
|
+
{},
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@register(
|
|
146
|
+
category=_C,
|
|
147
|
+
task="factuality",
|
|
148
|
+
name="Hallucination rate (unsupported-claim rate)",
|
|
149
|
+
definition="Share of an answer's claims that the evidence does not support, i.e. contradicted or "
|
|
150
|
+
"unverifiable claims, under the stated verification protocol.",
|
|
151
|
+
formula="(contradicted + unsupported claims) / claims",
|
|
152
|
+
range="[0, 1]",
|
|
153
|
+
input_requirements=("claim_verdicts",),
|
|
154
|
+
references=(_REF_FACTSCORE,),
|
|
155
|
+
higher_is_better=False,
|
|
156
|
+
)
|
|
157
|
+
@per_item
|
|
158
|
+
def hallucination_rate(
|
|
159
|
+
claim_verdicts: Any, *, count: str = "unsupported", average: Optional[str] = "micro"
|
|
160
|
+
) -> MetricResult:
|
|
161
|
+
"""Unsupported-claim rate. ``count="unsupported"`` counts every claim that is not supported;
|
|
162
|
+
``"contradicted"`` counts only claims the evidence contradicts (an intrinsic-hallucination rate)."""
|
|
163
|
+
if count not in ("unsupported", "contradicted"):
|
|
164
|
+
raise InputValidationError("count must be 'unsupported' or 'contradicted'.")
|
|
165
|
+
claims = _claims(claim_verdicts)
|
|
166
|
+
if count == "unsupported":
|
|
167
|
+
hits = [sum(v != "supported" for v in c) for c in claims]
|
|
168
|
+
else:
|
|
169
|
+
hits = [sum(v == "contradicted" for v in c) for c in claims]
|
|
170
|
+
return _aggregate(
|
|
171
|
+
"hallucination_rate", "Hallucination rate", hits, [len(c) for c in claims], average, {"count": count}
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@register(
|
|
176
|
+
category=_C,
|
|
177
|
+
task="factuality",
|
|
178
|
+
name="Groundedness",
|
|
179
|
+
definition="Average support score of an answer's content given the supplied context, from graded scores in "
|
|
180
|
+
"[0, 1] (e.g. NLI entailment probabilities or judge ratings) rather than binary verdicts.",
|
|
181
|
+
formula="mean over claims (or sentences) of support score",
|
|
182
|
+
range="[0, 1]",
|
|
183
|
+
input_requirements=("support_scores",),
|
|
184
|
+
references=(_REF_RAGAS,),
|
|
185
|
+
)
|
|
186
|
+
@per_item
|
|
187
|
+
def groundedness(support_scores: Any, *, average: Optional[str] = "macro") -> MetricResult:
|
|
188
|
+
"""Groundedness from graded support scores, one list of scores in [0, 1] per answer."""
|
|
189
|
+
answers = list(support_scores) if not isinstance(support_scores, (str, bytes)) else []
|
|
190
|
+
if not answers:
|
|
191
|
+
raise InputValidationError("support_scores must be a non-empty list of score lists (one per answer).")
|
|
192
|
+
sums, counts = [], []
|
|
193
|
+
for i, a in enumerate(answers):
|
|
194
|
+
arr = np.asarray(list(a), dtype=float)
|
|
195
|
+
if arr.size and (not np.all(np.isfinite(arr)) or arr.min() < 0 or arr.max() > 1):
|
|
196
|
+
raise InputValidationError(f"support_scores[{i}] must be finite values in [0, 1].")
|
|
197
|
+
sums.append(float(arr.sum()))
|
|
198
|
+
counts.append(int(arr.size))
|
|
199
|
+
if average == "micro":
|
|
200
|
+
value: Any = float(sum(sums) / sum(counts)) if sum(counts) else None
|
|
201
|
+
if value is None:
|
|
202
|
+
raise InputValidationError("Groundedness is undefined: there are no scores.")
|
|
203
|
+
return MetricResult("groundedness", "Groundedness", value, {"average": "micro", "n_answers": len(answers)})
|
|
204
|
+
per = np.array([s / c if c else np.nan for s, c in zip(sums, counts)])
|
|
205
|
+
if np.all(np.isnan(per)):
|
|
206
|
+
raise InputValidationError("Groundedness is undefined: every answer has zero scores.")
|
|
207
|
+
if average not in ("macro", None):
|
|
208
|
+
raise InputValidationError("average must be 'micro', 'macro' or None.")
|
|
209
|
+
value = per if average is None else float(np.nanmean(per))
|
|
210
|
+
return MetricResult("groundedness", "Groundedness", value, {"average": average, "n_answers": len(answers)})
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# ---------------------------------------------------------------- citations (ALCE)
|
|
214
|
+
def _citation_inputs(citations: Any) -> list[list[tuple[bool, list[bool]]]]:
|
|
215
|
+
"""Per answer, per statement: (statement supported by its citations, [each citation relevant])."""
|
|
216
|
+
answers = list(citations) if not isinstance(citations, (str, bytes)) else []
|
|
217
|
+
if not answers:
|
|
218
|
+
raise InputValidationError("citations must be a non-empty list (one list of statements per answer).")
|
|
219
|
+
out = []
|
|
220
|
+
for i, ans in enumerate(answers):
|
|
221
|
+
stmts = []
|
|
222
|
+
for j, st in enumerate(ans):
|
|
223
|
+
if not isinstance(st, dict) or "supported" not in st:
|
|
224
|
+
raise InputValidationError(
|
|
225
|
+
f"citations[{i}][{j}] must be a dict with 'supported' (bool) and optional 'citations' "
|
|
226
|
+
"(list of "
|
|
227
|
+
"bools: does each cited passage support or partly support the statement)."
|
|
228
|
+
)
|
|
229
|
+
cites = [bool(c) for c in st.get("citations", [])]
|
|
230
|
+
stmts.append((bool(st["supported"]) and len(cites) > 0, cites))
|
|
231
|
+
out.append(stmts)
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@register(
|
|
236
|
+
category=_C,
|
|
237
|
+
task="factuality",
|
|
238
|
+
name="Citation recall",
|
|
239
|
+
definition="Share of statements whose cited passages, taken together, support them (statements without "
|
|
240
|
+
"citations count as unsupported); ALCE citation recall.",
|
|
241
|
+
formula="statements fully supported by their citations / statements",
|
|
242
|
+
range="[0, 1]",
|
|
243
|
+
input_requirements=("citations",),
|
|
244
|
+
references=(_REF_ALCE,),
|
|
245
|
+
)
|
|
246
|
+
@per_item
|
|
247
|
+
def citation_recall(citations: Any, *, average: Optional[str] = "macro") -> MetricResult:
|
|
248
|
+
"""Citation recall. Each statement is ``{"supported": bool, "citations": [bool, ...]}``: whether all its
|
|
249
|
+
citations together entail it, and whether each cited passage is relevant to it."""
|
|
250
|
+
ans = _citation_inputs(citations)
|
|
251
|
+
return _aggregate(
|
|
252
|
+
"citation_recall",
|
|
253
|
+
"Citation recall",
|
|
254
|
+
[sum(s for s, _ in a) for a in ans],
|
|
255
|
+
[len(a) for a in ans],
|
|
256
|
+
average,
|
|
257
|
+
{},
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
@register(
|
|
262
|
+
category=_C,
|
|
263
|
+
task="factuality",
|
|
264
|
+
name="Citation precision",
|
|
265
|
+
definition="Share of citations that are relevant to the statement they are attached to (ALCE: a citation "
|
|
266
|
+
"counts if it supports, or is needed to support, the statement).",
|
|
267
|
+
formula="relevant citations / citations",
|
|
268
|
+
range="[0, 1]",
|
|
269
|
+
input_requirements=("citations",),
|
|
270
|
+
references=(_REF_ALCE,),
|
|
271
|
+
)
|
|
272
|
+
@per_item
|
|
273
|
+
def citation_precision(citations: Any, *, average: Optional[str] = "macro") -> MetricResult:
|
|
274
|
+
"""Citation precision with the same input as ``citation_recall``."""
|
|
275
|
+
ans = _citation_inputs(citations)
|
|
276
|
+
return _aggregate(
|
|
277
|
+
"citation_precision",
|
|
278
|
+
"Citation precision",
|
|
279
|
+
[sum(sum(c) for _, c in a) for a in ans],
|
|
280
|
+
[sum(len(c) for _, c in a) for a in ans],
|
|
281
|
+
average,
|
|
282
|
+
{},
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
# ---------------------------------------------------------------- verification and consistency
|
|
287
|
+
@register(
|
|
288
|
+
category=_C,
|
|
289
|
+
task="factuality",
|
|
290
|
+
name="Claim verification accuracy",
|
|
291
|
+
definition="Accuracy of supported / contradicted / not-enough-info verdicts against gold labels (FEVER "
|
|
292
|
+
"label accuracy); macro F1 is reported alongside because the classes are often imbalanced.",
|
|
293
|
+
formula="correct verdicts / claims",
|
|
294
|
+
range="[0, 1]",
|
|
295
|
+
input_requirements=("gold_verdicts", "predicted_verdicts"),
|
|
296
|
+
references=(_REF_FEVER,),
|
|
297
|
+
)
|
|
298
|
+
def claim_verification_accuracy(gold_verdicts: Any, predicted_verdicts: Any) -> MetricResult:
|
|
299
|
+
"""Label accuracy for claim verification, with macro F1 over the three verdict classes in ``params``."""
|
|
300
|
+
gold = [_verdict(v, "gold_verdicts") for v in gold_verdicts]
|
|
301
|
+
pred = [_verdict(v, "predicted_verdicts") for v in predicted_verdicts]
|
|
302
|
+
if not gold or len(gold) != len(pred):
|
|
303
|
+
raise InputValidationError("gold_verdicts and predicted_verdicts must be non-empty and the same length.")
|
|
304
|
+
g, p = np.array(gold), np.array(pred)
|
|
305
|
+
f1s = {}
|
|
306
|
+
for c in ("supported", "contradicted", "unsupported"):
|
|
307
|
+
tp = int(np.sum((g == c) & (p == c)))
|
|
308
|
+
fp, fn = int(np.sum((g != c) & (p == c))), int(np.sum((g == c) & (p != c)))
|
|
309
|
+
if tp + fp + fn:
|
|
310
|
+
f1s[c] = 2 * tp / (2 * tp + fp + fn)
|
|
311
|
+
return MetricResult(
|
|
312
|
+
"claim_verification_accuracy",
|
|
313
|
+
"Claim verification accuracy",
|
|
314
|
+
float(np.mean(g == p)),
|
|
315
|
+
{"macro_f1": float(np.mean(list(f1s.values()))), "per_class_f1": f1s, "n_claims": len(gold)},
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@register(
|
|
320
|
+
category=_C,
|
|
321
|
+
task="factuality",
|
|
322
|
+
name="Knowledge consistency",
|
|
323
|
+
definition="Share of facts extracted from the outputs (e.g. subject–relation–object triples) that are present "
|
|
324
|
+
"in a specified trusted knowledge source.",
|
|
325
|
+
formula="|extracted facts ∩ knowledge base| / |extracted facts|",
|
|
326
|
+
range="[0, 1]",
|
|
327
|
+
input_requirements=("extracted_facts", "knowledge_base"),
|
|
328
|
+
references=(_REF_FACTSCORE,),
|
|
329
|
+
)
|
|
330
|
+
@per_item
|
|
331
|
+
def knowledge_consistency(
|
|
332
|
+
extracted_facts: Any, knowledge_base: Any, *, average: Optional[str] = "micro"
|
|
333
|
+
) -> MetricResult:
|
|
334
|
+
"""Knowledge consistency: ``extracted_facts`` is one iterable of hashable facts per output (strings or
|
|
335
|
+
tuples), ``knowledge_base`` a set of trusted facts. Normalise facts the same way on both sides."""
|
|
336
|
+
kb = set(knowledge_base)
|
|
337
|
+
if not kb:
|
|
338
|
+
raise InputValidationError("knowledge_base is empty.")
|
|
339
|
+
outs = list(extracted_facts)
|
|
340
|
+
if not outs:
|
|
341
|
+
raise InputValidationError("extracted_facts is empty.")
|
|
342
|
+
hits, totals = [], []
|
|
343
|
+
for facts in outs:
|
|
344
|
+
fs = list(facts)
|
|
345
|
+
hits.append(sum(f in kb for f in fs))
|
|
346
|
+
totals.append(len(fs))
|
|
347
|
+
return _aggregate(
|
|
348
|
+
"knowledge_consistency", "Knowledge consistency", hits, totals, average, {"kb_size": len(kb)}
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
# ---------------------------------------------------------------- answers
|
|
353
|
+
@register(
|
|
354
|
+
category=_C,
|
|
355
|
+
task="question-answering",
|
|
356
|
+
name="Answer correctness",
|
|
357
|
+
definition="Agreement of an answer with the reference at the level of statements: F1 over true-positive "
|
|
358
|
+
"(in both), false-positive (only in the answer) and false-negative (only in the reference) statements, "
|
|
359
|
+
"optionally blended with a semantic similarity score (RAGAS answer correctness).",
|
|
360
|
+
formula="w_f · TP/(TP + ½(FP + FN)) + w_s · similarity",
|
|
361
|
+
range="[0, 1]",
|
|
362
|
+
input_requirements=("tp", "fp", "fn"),
|
|
363
|
+
references=(_REF_RAGAS,),
|
|
364
|
+
)
|
|
365
|
+
@per_item
|
|
366
|
+
def answer_correctness(
|
|
367
|
+
tp: Any,
|
|
368
|
+
fp: Any,
|
|
369
|
+
fn: Any,
|
|
370
|
+
*,
|
|
371
|
+
similarity: Any = None,
|
|
372
|
+
weights: tuple[float, float] = (0.75, 0.25),
|
|
373
|
+
average: Optional[str] = "mean",
|
|
374
|
+
) -> MetricResult:
|
|
375
|
+
"""Answer correctness from statement counts per answer (from a judge or annotators). Without
|
|
376
|
+
``similarity`` it is the statement F1; with it, ``weights`` blend F1 and similarity (RAGAS default
|
|
377
|
+
0.75 / 0.25)."""
|
|
378
|
+
t, f_p, f_n = (np.asarray(v, dtype=float).ravel() for v in (tp, fp, fn))
|
|
379
|
+
if not (t.shape == f_p.shape == f_n.shape) or t.size == 0:
|
|
380
|
+
raise InputValidationError("tp, fp and fn must be non-empty arrays of the same length.")
|
|
381
|
+
if np.any(t < 0) or np.any(f_p < 0) or np.any(f_n < 0):
|
|
382
|
+
raise InputValidationError("Statement counts must be non-negative.")
|
|
383
|
+
denom = t + 0.5 * (f_p + f_n)
|
|
384
|
+
f1 = np.where(denom > 0, t / np.where(denom > 0, denom, 1), 1.0) # nothing to state and nothing stated -> 1
|
|
385
|
+
if similarity is None:
|
|
386
|
+
scores = f1
|
|
387
|
+
else:
|
|
388
|
+
sim = np.asarray(similarity, dtype=float).ravel()
|
|
389
|
+
if sim.shape != t.shape or np.any(sim < 0) or np.any(sim > 1):
|
|
390
|
+
raise InputValidationError("similarity must hold one value in [0, 1] per answer.")
|
|
391
|
+
wf, ws = weights
|
|
392
|
+
if wf < 0 or ws < 0 or wf + ws == 0:
|
|
393
|
+
raise InputValidationError("weights must be non-negative and not both zero.")
|
|
394
|
+
scores = (wf * f1 + ws * sim) / (wf + ws)
|
|
395
|
+
value: Any = scores if average is None else float(scores.mean())
|
|
396
|
+
return MetricResult(
|
|
397
|
+
"answer_correctness", "Answer correctness", value, {"weights": weights if similarity is not None else None}
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
@register(
|
|
402
|
+
category=_C,
|
|
403
|
+
task="question-answering",
|
|
404
|
+
name="Answer relevance",
|
|
405
|
+
definition="How directly an answer addresses the question: mean cosine similarity between the question's "
|
|
406
|
+
"embedding and embeddings of questions regenerated from the answer (RAGAS answer relevancy).",
|
|
407
|
+
formula="mean_k cos(e(question), e(regenerated question_k))",
|
|
408
|
+
range="[-1, 1]",
|
|
409
|
+
input_requirements=("question_embeddings", "generated_question_embeddings"),
|
|
410
|
+
references=(_REF_RAGAS,),
|
|
411
|
+
)
|
|
412
|
+
@per_item
|
|
413
|
+
def answer_relevance(
|
|
414
|
+
question_embeddings: Any, generated_question_embeddings: Any, *, average: Optional[str] = "mean"
|
|
415
|
+
) -> MetricResult:
|
|
416
|
+
"""Answer relevance from embeddings: ``question_embeddings`` is ``(n, dim)``; ``generated_question_embeddings``
|
|
417
|
+
holds, per answer, a ``(k, dim)`` array of embeddings of questions an LLM regenerated from the answer."""
|
|
418
|
+
q = np.asarray(question_embeddings, dtype=float)
|
|
419
|
+
gens = list(generated_question_embeddings)
|
|
420
|
+
if q.ndim != 2 or len(gens) != q.shape[0] or q.shape[0] == 0:
|
|
421
|
+
raise InputValidationError("question_embeddings must be (n, dim) with one generated set per question.")
|
|
422
|
+
scores = np.empty(q.shape[0])
|
|
423
|
+
for i, g in enumerate(gens):
|
|
424
|
+
ga = np.atleast_2d(np.asarray(g, dtype=float))
|
|
425
|
+
if ga.shape[1] != q.shape[1] or ga.shape[0] == 0:
|
|
426
|
+
raise InputValidationError(f"generated_question_embeddings[{i}] must be (k, {q.shape[1]}).")
|
|
427
|
+
qn, gn = np.linalg.norm(q[i]), np.linalg.norm(ga, axis=1)
|
|
428
|
+
if qn == 0 or np.any(gn == 0):
|
|
429
|
+
raise InputValidationError("Embeddings must not be zero vectors.")
|
|
430
|
+
scores[i] = float(np.mean(ga @ q[i] / (gn * qn)))
|
|
431
|
+
value: Any = scores if average is None else float(scores.mean())
|
|
432
|
+
return MetricResult("answer_relevance", "Answer relevance", value, {"n_examples": len(gens)})
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
@register(
|
|
436
|
+
category=_C,
|
|
437
|
+
task="question-answering",
|
|
438
|
+
name="Abstention accuracy",
|
|
439
|
+
definition="Whether a system abstains exactly when it should (the evidence is insufficient or it would "
|
|
440
|
+
"otherwise be wrong): accuracy of the abstain / answer decision; abstention precision, recall and the "
|
|
441
|
+
"accuracy on answered questions are reported alongside.",
|
|
442
|
+
formula="mean[abstained_i = should_abstain_i]",
|
|
443
|
+
range="[0, 1]",
|
|
444
|
+
input_requirements=("should_abstain", "abstained"),
|
|
445
|
+
references=(_REF_ABSTAIN,),
|
|
446
|
+
)
|
|
447
|
+
@per_item
|
|
448
|
+
def abstention_accuracy(should_abstain: Any, abstained: Any, *, correct: Any = None) -> MetricResult:
|
|
449
|
+
"""Abstention accuracy. ``correct`` (optional, one bool per question) gives the selective accuracy on the
|
|
450
|
+
questions the system did answer, and its coverage."""
|
|
451
|
+
s = np.asarray(should_abstain, dtype=bool).ravel()
|
|
452
|
+
a = np.asarray(abstained, dtype=bool).ravel()
|
|
453
|
+
if s.size == 0 or s.shape != a.shape:
|
|
454
|
+
raise InputValidationError("should_abstain and abstained must be non-empty and the same length.")
|
|
455
|
+
tp = int(np.sum(s & a))
|
|
456
|
+
params: dict[str, Any] = {
|
|
457
|
+
"abstention_precision": tp / int(a.sum()) if a.any() else float("nan"),
|
|
458
|
+
"abstention_recall": tp / int(s.sum()) if s.any() else float("nan"),
|
|
459
|
+
"abstention_rate": float(a.mean()),
|
|
460
|
+
"n_questions": int(s.size),
|
|
461
|
+
}
|
|
462
|
+
if correct is not None:
|
|
463
|
+
c = np.asarray(correct, dtype=bool).ravel()
|
|
464
|
+
if c.shape != s.shape:
|
|
465
|
+
raise InputValidationError("correct must have one value per question.")
|
|
466
|
+
answered = ~a
|
|
467
|
+
params["coverage"] = float(answered.mean())
|
|
468
|
+
params["answered_accuracy"] = float(c[answered].mean()) if answered.any() else float("nan")
|
|
469
|
+
return MetricResult("abstention_accuracy", "Abstention accuracy", float(np.mean(s == a)), params)
|