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.
- 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,339 @@
|
|
|
1
|
+
"""Multilingual and cross-lingual evaluation (v0.5.0).
|
|
2
|
+
|
|
3
|
+
Translation quality uses the existing ``es.bleu``, ``es.chrf`` and ``es.model_score`` (COMET); cross-lingual
|
|
4
|
+
retrieval uses ``es.recall_at_k`` and ``es.mrr``. This module adds language identification, bitext mining over
|
|
5
|
+
multilingual embeddings, performance parity across languages, code-switching robustness, z-normalised direct
|
|
6
|
+
assessment (adequacy / fluency), cultural appropriateness ratings and language / cross-lingual consistency.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Mapping, Sequence
|
|
12
|
+
from itertools import combinations
|
|
13
|
+
from typing import Any, Callable, 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 bools, by_group, floats, rate, same_length, seq
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"bitext_mining_accuracy",
|
|
24
|
+
"code_switching_robustness",
|
|
25
|
+
"cross_lingual_consistency",
|
|
26
|
+
"cultural_appropriateness",
|
|
27
|
+
"direct_assessment",
|
|
28
|
+
"language_consistency",
|
|
29
|
+
"language_id_accuracy",
|
|
30
|
+
"language_parity",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
_C = "multilingual"
|
|
34
|
+
_REF_LANGID = "Lui M, Baldwin T. langid.py: an off-the-shelf language identification tool. ACL Demos. 2012:25-30."
|
|
35
|
+
_REF_LASER = (
|
|
36
|
+
"Artetxe M, Schwenk H. Massively multilingual sentence embeddings for zero-shot cross-lingual transfer and "
|
|
37
|
+
"beyond. TACL. 2019;7:597-610."
|
|
38
|
+
)
|
|
39
|
+
_REF_XTREME = (
|
|
40
|
+
"Hu J, Ruder S, Siddhant A, Neubig G, Firat O, Johnson M. XTREME: a massively multilingual multi-task "
|
|
41
|
+
"benchmark "
|
|
42
|
+
"for evaluating cross-lingual generalization. ICML. 2020:4411-4421."
|
|
43
|
+
)
|
|
44
|
+
_REF_LINCE = (
|
|
45
|
+
"Aguilar G, Kar S, Solorio T. LinCE: a centralized benchmark for linguistic code-switching evaluation. LREC. "
|
|
46
|
+
"2020:1803-1813."
|
|
47
|
+
)
|
|
48
|
+
_REF_DA = (
|
|
49
|
+
"Graham Y, Baldwin T, Moffat A, Zobel J. Continuous measurement scales in human evaluation of machine "
|
|
50
|
+
"translation. LAW. 2013:33-41."
|
|
51
|
+
)
|
|
52
|
+
_REF_BLEND = (
|
|
53
|
+
"Myung J, Lee N, Zhou Y, et al. BLEnD: a benchmark for LLMs on everyday knowledge in diverse cultures and "
|
|
54
|
+
"languages. NeurIPS Datasets and Benchmarks. 2024."
|
|
55
|
+
)
|
|
56
|
+
_REF_XLC = (
|
|
57
|
+
"Qi J, Fernández R, Bisazza A. Cross-lingual consistency of factual knowledge in multilingual language "
|
|
58
|
+
"models. "
|
|
59
|
+
"EMNLP. 2023:10650-10666."
|
|
60
|
+
)
|
|
61
|
+
_REF_MARCHISIO = (
|
|
62
|
+
"Marchisio K, Ko WY, Bérard A, Dehaze T, Ruder S. Understanding and mitigating language confusion in LLMs. "
|
|
63
|
+
"EMNLP. 2024:6653-6677."
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _str_array(x: Any, name: str) -> np.ndarray:
|
|
68
|
+
"""Labels as a NumPy string array (each value's ``str``)."""
|
|
69
|
+
if isinstance(x, np.ndarray) and x.dtype.kind == "U" and x.ndim == 1:
|
|
70
|
+
if x.size == 0:
|
|
71
|
+
seq(x, name) # raises the usual empty-input error
|
|
72
|
+
return x
|
|
73
|
+
return np.asarray([str(v) for v in seq(x, name)], dtype=str)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@register(
|
|
77
|
+
category=_C,
|
|
78
|
+
task="language-identification",
|
|
79
|
+
name="Language identification accuracy",
|
|
80
|
+
definition="Accuracy of predicted language labels, with macro-F1 over languages and per-language recall.",
|
|
81
|
+
formula="mean[pred = true]",
|
|
82
|
+
range="[0, 1]",
|
|
83
|
+
input_requirements=("true_languages", "predicted_languages"),
|
|
84
|
+
references=(_REF_LANGID,),
|
|
85
|
+
)
|
|
86
|
+
def language_id_accuracy(true_languages: Any, predicted_languages: Any) -> MetricResult:
|
|
87
|
+
t = _str_array(true_languages, "true_languages")
|
|
88
|
+
p = _str_array(predicted_languages, "predicted_languages")
|
|
89
|
+
same_length(("true_languages", t), ("predicted_languages", p))
|
|
90
|
+
# One encoding of both arrays, then a confusion matrix by bincount (labels in sorted order).
|
|
91
|
+
labels_arr, codes = np.unique(np.concatenate([t, p]), return_inverse=True)
|
|
92
|
+
k = labels_arr.shape[0]
|
|
93
|
+
n = t.shape[0]
|
|
94
|
+
cm = np.bincount(codes[:n] * k + codes[n:], minlength=k * k).reshape(k, k)
|
|
95
|
+
tp = np.diag(cm)
|
|
96
|
+
fp = cm.sum(axis=0) - tp
|
|
97
|
+
fn = cm.sum(axis=1) - tp
|
|
98
|
+
denom = 2 * tp + fp + fn
|
|
99
|
+
f1s = np.where(tp > 0, 2 * tp / np.maximum(denom, 1), 0.0)
|
|
100
|
+
labels = labels_arr.tolist()
|
|
101
|
+
recall = {lab: int(tp[i]) / int(tp[i] + fn[i]) for i, lab in enumerate(labels) if tp[i] + fn[i]}
|
|
102
|
+
acc = float(tp.sum() / n)
|
|
103
|
+
return MetricResult(
|
|
104
|
+
"language_id_accuracy", "Language-ID accuracy", acc, {"macro_f1": float(f1s.mean()), "recall": recall}
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _unit(x: Any, name: str) -> np.ndarray:
|
|
109
|
+
a = np.asarray(x, dtype=np.float64)
|
|
110
|
+
if a.ndim != 2 or a.shape[0] < 2:
|
|
111
|
+
raise InputValidationError(f"{name} must be a 2-D array with at least two rows (one per sentence).")
|
|
112
|
+
if not np.all(np.isfinite(a)):
|
|
113
|
+
raise InputValidationError(f"{name} contains NaN or infinite values.")
|
|
114
|
+
n = np.linalg.norm(a, axis=1, keepdims=True)
|
|
115
|
+
if np.any(n == 0):
|
|
116
|
+
raise InputValidationError(f"{name} contains a zero vector.")
|
|
117
|
+
return np.asarray(a / n, dtype=np.float64)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@register(
|
|
121
|
+
category=_C,
|
|
122
|
+
task="semantic-similarity",
|
|
123
|
+
name="Multilingual semantic similarity (bitext mining)",
|
|
124
|
+
definition="For aligned sentence pairs in two languages, the share whose nearest neighbour by cosine (or "
|
|
125
|
+
"margin) similarity is the true translation, averaged over both directions (Tatoeba / BUCC style), with the "
|
|
126
|
+
"mean cosine of the true pairs.",
|
|
127
|
+
formula="acc = ½ (mean_i 1[argmax_j cos(s_i, t_j) = i] + mean_j 1[argmax_i cos(s_i, t_j) = j])",
|
|
128
|
+
range="[0, 1]",
|
|
129
|
+
input_requirements=("source_embeddings", "target_embeddings"),
|
|
130
|
+
references=(_REF_LASER, _REF_XTREME),
|
|
131
|
+
)
|
|
132
|
+
def bitext_mining_accuracy(
|
|
133
|
+
source_embeddings: Any, target_embeddings: Any, *, scoring: str = "cosine", k: int = 4
|
|
134
|
+
) -> MetricResult:
|
|
135
|
+
"""``scoring="margin"`` uses the ratio margin of Artetxe & Schwenk with ``k`` neighbours, which removes hub
|
|
136
|
+
effects."""
|
|
137
|
+
s = _unit(source_embeddings, "source_embeddings")
|
|
138
|
+
t = _unit(target_embeddings, "target_embeddings")
|
|
139
|
+
if s.shape != t.shape:
|
|
140
|
+
raise InputValidationError(
|
|
141
|
+
"source_embeddings and target_embeddings must have the same shape (aligned pairs)."
|
|
142
|
+
)
|
|
143
|
+
sim = s @ t.T
|
|
144
|
+
if scoring == "margin":
|
|
145
|
+
kk = min(k, sim.shape[0])
|
|
146
|
+
rs = np.sort(sim, axis=1)[:, -kk:].mean(1)
|
|
147
|
+
rt = np.sort(sim, axis=0)[-kk:, :].mean(0)
|
|
148
|
+
sim = sim / ((rs[:, None] + rt[None, :]) / 2)
|
|
149
|
+
elif scoring != "cosine":
|
|
150
|
+
raise InputValidationError("scoring must be 'cosine' or 'margin'.")
|
|
151
|
+
idx = np.arange(sim.shape[0])
|
|
152
|
+
fwd = float(np.mean(sim.argmax(1) == idx))
|
|
153
|
+
bwd = float(np.mean(sim.argmax(0) == idx))
|
|
154
|
+
return MetricResult(
|
|
155
|
+
"bitext_mining_accuracy",
|
|
156
|
+
"Bitext mining accuracy",
|
|
157
|
+
(fwd + bwd) / 2,
|
|
158
|
+
{
|
|
159
|
+
"source_to_target": fwd,
|
|
160
|
+
"target_to_source": bwd,
|
|
161
|
+
"mean_pair_cosine": float(np.mean(np.sum(s * t, axis=1))),
|
|
162
|
+
"scoring": scoring,
|
|
163
|
+
},
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@register(
|
|
168
|
+
category=_C,
|
|
169
|
+
task="fairness",
|
|
170
|
+
name="Language-specific performance parity",
|
|
171
|
+
definition="How evenly a model performs across languages: the worst-to-best ratio (the value; 1 = parity), "
|
|
172
|
+
"the largest gap, the standard deviation, and per-language scores.",
|
|
173
|
+
formula="parity = min_l score_l / max_l score_l",
|
|
174
|
+
range="[0, 1]",
|
|
175
|
+
input_requirements=("scores_by_language",),
|
|
176
|
+
references=(_REF_XTREME,),
|
|
177
|
+
)
|
|
178
|
+
def language_parity(scores_by_language: Mapping[str, Any]) -> MetricResult:
|
|
179
|
+
"""``scores_by_language``: language -> per-example scores (or one aggregate score)."""
|
|
180
|
+
if not isinstance(scores_by_language, Mapping) or len(scores_by_language) < 2:
|
|
181
|
+
raise InputValidationError("scores_by_language must map at least two languages to scores.")
|
|
182
|
+
means = {}
|
|
183
|
+
for lang, v in scores_by_language.items():
|
|
184
|
+
arr = floats(v if isinstance(v, (list, tuple, np.ndarray)) else [v], f"scores_by_language[{lang!r}]")
|
|
185
|
+
means[str(lang)] = float(arr.mean())
|
|
186
|
+
vals = np.array(list(means.values()))
|
|
187
|
+
if vals.max() <= 0:
|
|
188
|
+
raise InputValidationError("Scores must be positive for some language to compute parity.")
|
|
189
|
+
worst = min(means, key=lambda k: means[k])
|
|
190
|
+
return MetricResult(
|
|
191
|
+
"language_parity",
|
|
192
|
+
"Language parity (worst / best)",
|
|
193
|
+
float(max(0.0, vals.min()) / vals.max()),
|
|
194
|
+
{
|
|
195
|
+
"max_gap": float(vals.max() - vals.min()),
|
|
196
|
+
"std": float(vals.std(ddof=1)),
|
|
197
|
+
"worst_language": worst,
|
|
198
|
+
"by_language": means,
|
|
199
|
+
},
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@register(
|
|
204
|
+
category=_C,
|
|
205
|
+
task="robustness",
|
|
206
|
+
name="Code-switching robustness",
|
|
207
|
+
definition="Accuracy on code-switched inputs (mixing languages within an utterance) compared with the same "
|
|
208
|
+
"content in one language: code-switched accuracy, drop and flip rate.",
|
|
209
|
+
formula="acc_cs; drop = acc_mono − acc_cs",
|
|
210
|
+
range="[0, 1]",
|
|
211
|
+
input_requirements=("monolingual_correct", "code_switched_correct"),
|
|
212
|
+
references=(_REF_LINCE,),
|
|
213
|
+
)
|
|
214
|
+
def code_switching_robustness(monolingual_correct: Any, code_switched_correct: Any) -> MetricResult:
|
|
215
|
+
m, c = bools(monolingual_correct, "monolingual_correct"), bools(code_switched_correct, "code_switched_correct")
|
|
216
|
+
same_length(("monolingual_correct", m), ("code_switched_correct", c))
|
|
217
|
+
am, ac = float(m.mean()), float(c.mean())
|
|
218
|
+
return MetricResult(
|
|
219
|
+
"code_switching_robustness",
|
|
220
|
+
"Code-switched accuracy",
|
|
221
|
+
ac,
|
|
222
|
+
{
|
|
223
|
+
"monolingual_accuracy": am,
|
|
224
|
+
"absolute_drop": am - ac,
|
|
225
|
+
"flip_rate": float((m & ~c).sum() / m.sum()) if m.any() else float("nan"),
|
|
226
|
+
},
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@register(
|
|
231
|
+
category=_C,
|
|
232
|
+
task="translation",
|
|
233
|
+
name="Translation adequacy / fluency (direct assessment)",
|
|
234
|
+
definition="Human direct-assessment scores (0–100 adequacy or fluency) standardised per rater (z-scores) to "
|
|
235
|
+
"remove rater bias, then averaged per system, as in WMT DA.",
|
|
236
|
+
formula="z = (score − mean_rater) / sd_rater; system score = mean z",
|
|
237
|
+
range="(−∞, ∞) for z; [0, 100] raw",
|
|
238
|
+
input_requirements=("scores", "raters"),
|
|
239
|
+
references=(_REF_DA,),
|
|
240
|
+
)
|
|
241
|
+
def direct_assessment(
|
|
242
|
+
scores: Any, raters: Sequence[Any], *, systems: Optional[Sequence[Any]] = None
|
|
243
|
+
) -> MetricResult:
|
|
244
|
+
s = floats(scores, "scores")
|
|
245
|
+
r = [str(v) for v in seq(raters, "raters")]
|
|
246
|
+
same_length(("scores", s), ("raters", r))
|
|
247
|
+
z = np.empty_like(s)
|
|
248
|
+
for rater in set(r):
|
|
249
|
+
m = np.array([x == rater for x in r])
|
|
250
|
+
sd = s[m].std(ddof=1) if m.sum() > 1 else 0.0
|
|
251
|
+
z[m] = (s[m] - s[m].mean()) / sd if sd > 0 else 0.0
|
|
252
|
+
extra: dict[str, Any] = {"raw_mean": float(s.mean()), "n_raters": len(set(r))}
|
|
253
|
+
if systems is not None:
|
|
254
|
+
extra["by_system_z"] = by_group(z, systems, "systems")
|
|
255
|
+
extra["by_system_raw"] = by_group(s, systems, "systems")
|
|
256
|
+
return MetricResult("direct_assessment", "Direct assessment (mean z)", float(z.mean()), extra)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@register(
|
|
260
|
+
category=_C,
|
|
261
|
+
task="culture",
|
|
262
|
+
name="Cultural appropriateness",
|
|
263
|
+
definition="Mean rating of how appropriate responses are for the target culture, rescaled to [0, 1] from the "
|
|
264
|
+
"rating scale, overall and per culture / region (the gap between the best and worst region is reported).",
|
|
265
|
+
formula="mean (rating − lo) / (hi − lo)",
|
|
266
|
+
range="[0, 1]",
|
|
267
|
+
input_requirements=("ratings",),
|
|
268
|
+
references=(_REF_BLEND,),
|
|
269
|
+
)
|
|
270
|
+
def cultural_appropriateness(
|
|
271
|
+
ratings: Any, *, scale: tuple[float, float] = (1, 5), regions: Optional[Sequence[Any]] = None
|
|
272
|
+
) -> MetricResult:
|
|
273
|
+
lo, hi = scale
|
|
274
|
+
if hi <= lo:
|
|
275
|
+
raise InputValidationError("scale must be (low, high) with high > low.")
|
|
276
|
+
r = floats(ratings, "ratings", lo=lo, hi=hi)
|
|
277
|
+
v = (r - lo) / (hi - lo)
|
|
278
|
+
extra: dict[str, Any] = {"scale": scale}
|
|
279
|
+
if regions is not None:
|
|
280
|
+
by = by_group(v, regions, "regions")
|
|
281
|
+
extra["by_region"] = by
|
|
282
|
+
extra["region_gap"] = max(by.values()) - min(by.values())
|
|
283
|
+
return MetricResult("cultural_appropriateness", "Cultural appropriateness", float(v.mean()), extra)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@register(
|
|
287
|
+
category=_C,
|
|
288
|
+
task="consistency",
|
|
289
|
+
name="Language consistency",
|
|
290
|
+
definition="Share of responses written in the language the user asked or wrote in (language confusion), "
|
|
291
|
+
"given the detected language of each response.",
|
|
292
|
+
formula="mean[detected = expected]",
|
|
293
|
+
range="[0, 1]",
|
|
294
|
+
input_requirements=("expected_languages", "detected_languages"),
|
|
295
|
+
references=(_REF_MARCHISIO,),
|
|
296
|
+
)
|
|
297
|
+
def language_consistency(expected_languages: Any, detected_languages: Any) -> MetricResult:
|
|
298
|
+
e = [str(v) for v in seq(expected_languages, "expected_languages")]
|
|
299
|
+
d = [str(v) for v in seq(detected_languages, "detected_languages")]
|
|
300
|
+
same_length(("expected_languages", e), ("detected_languages", d))
|
|
301
|
+
flags = np.array([a == b for a, b in zip(e, d)])
|
|
302
|
+
return rate(
|
|
303
|
+
"language_consistency", "Language consistency", flags, {"by_language": by_group(flags.astype(float), e)}
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
@register(
|
|
308
|
+
category=_C,
|
|
309
|
+
task="consistency",
|
|
310
|
+
name="Cross-lingual factual consistency",
|
|
311
|
+
definition="Whether the model gives the same answer to the same question asked in different languages: share "
|
|
312
|
+
"of questions answered identically in every language and mean pairwise agreement (after mapping answers to a "
|
|
313
|
+
"common form with ``normalize``).",
|
|
314
|
+
formula="mean_q 1[all languages agree]",
|
|
315
|
+
range="[0, 1]",
|
|
316
|
+
input_requirements=("answers_by_language",),
|
|
317
|
+
references=(_REF_XLC,),
|
|
318
|
+
)
|
|
319
|
+
def cross_lingual_consistency(
|
|
320
|
+
answers_by_language: Any, *, normalize: Optional[Callable[[Any], Any]] = None
|
|
321
|
+
) -> MetricResult:
|
|
322
|
+
"""``answers_by_language``: per question, a mapping language -> answer (at least two languages)."""
|
|
323
|
+
rows = seq(answers_by_language, "answers_by_language")
|
|
324
|
+
full, pair = [], []
|
|
325
|
+
for i, r in enumerate(rows):
|
|
326
|
+
if not isinstance(r, Mapping) or len(r) < 2:
|
|
327
|
+
raise InputValidationError(f"answers_by_language[{i}] must map at least two languages to answers.")
|
|
328
|
+
v = [
|
|
329
|
+
normalize(a) if normalize else (" ".join(a.lower().split()) if isinstance(a, str) else a)
|
|
330
|
+
for a in r.values()
|
|
331
|
+
]
|
|
332
|
+
full.append(all(x == v[0] for x in v))
|
|
333
|
+
pair.append(np.mean([x == y for x, y in combinations(v, 2)]))
|
|
334
|
+
return MetricResult(
|
|
335
|
+
"cross_lingual_consistency",
|
|
336
|
+
"Cross-lingual consistency",
|
|
337
|
+
float(np.mean(full)),
|
|
338
|
+
{"pairwise_agreement": float(np.mean(pair)), "n_questions": len(rows)},
|
|
339
|
+
)
|