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
evalsuite/benchmarks.py
ADDED
|
@@ -0,0 +1,946 @@
|
|
|
1
|
+
"""Speed and memory benchmarks against reference implementations.
|
|
2
|
+
|
|
3
|
+
Each case times the fastest of ``repeat`` runs (after one warm-up) and measures peak traced memory with
|
|
4
|
+
``tracemalloc`` (NumPy reports its allocations to it). EvalSuite and the reference compute the same
|
|
5
|
+
quantities on the same data, and the largest absolute difference between their results is reported, so
|
|
6
|
+
speed is never shown for numbers that disagree.
|
|
7
|
+
|
|
8
|
+
References: scikit-learn for classification and regression (``suite="core"``); scikit-learn, statsmodels
|
|
9
|
+
and SciPy for the v0.2.0 clinical, calibration and statistics functions (``suite="clinical"``);
|
|
10
|
+
scikit-learn, SciPy and pycocotools for segmentation and detection (``suite="vision"``). A case
|
|
11
|
+
whose reference library is not installed is timed for EvalSuite only.
|
|
12
|
+
|
|
13
|
+
>>> from evalsuite.benchmarks import run_benchmarks
|
|
14
|
+
>>> print(run_benchmarks(sizes=(10_000,), repeat=3)) # doctest: +SKIP
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import contextlib
|
|
20
|
+
import importlib
|
|
21
|
+
import json
|
|
22
|
+
import platform
|
|
23
|
+
import re
|
|
24
|
+
import time
|
|
25
|
+
import tracemalloc
|
|
26
|
+
import warnings
|
|
27
|
+
from collections.abc import Callable, Sequence
|
|
28
|
+
from dataclasses import dataclass, field
|
|
29
|
+
from types import MappingProxyType
|
|
30
|
+
from typing import TYPE_CHECKING, Any, Optional, cast
|
|
31
|
+
|
|
32
|
+
import numpy as np
|
|
33
|
+
|
|
34
|
+
from ._bench_metrics import metric_cases
|
|
35
|
+
from .core.exceptions import OptionalDependencyError
|
|
36
|
+
from .core.result import _json_safe, _latex_escape, _latex_table
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
import pandas as pd
|
|
40
|
+
|
|
41
|
+
__all__ = ["BenchmarkResult", "run_benchmarks"]
|
|
42
|
+
|
|
43
|
+
_HEADER = (
|
|
44
|
+
"case",
|
|
45
|
+
"n",
|
|
46
|
+
"reference",
|
|
47
|
+
"evalsuite_ms",
|
|
48
|
+
"reference_ms",
|
|
49
|
+
"speedup",
|
|
50
|
+
"evalsuite_peak_mb",
|
|
51
|
+
"reference_peak_mb",
|
|
52
|
+
"max_abs_diff",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
Case = tuple[str, str, Callable[[], Any], Optional[Callable[[], Any]]]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _measure(fn: Callable[[], Any], repeat: int) -> tuple[float, float, Any]:
|
|
59
|
+
"""(fastest seconds, peak MiB, result)."""
|
|
60
|
+
with warnings.catch_warnings():
|
|
61
|
+
warnings.simplefilter("ignore")
|
|
62
|
+
result = fn() # warm-up
|
|
63
|
+
best = float("inf")
|
|
64
|
+
for _ in range(repeat):
|
|
65
|
+
t0 = time.perf_counter()
|
|
66
|
+
fn()
|
|
67
|
+
best = min(best, time.perf_counter() - t0)
|
|
68
|
+
tracemalloc.start()
|
|
69
|
+
try:
|
|
70
|
+
fn()
|
|
71
|
+
_, peak = tracemalloc.get_traced_memory()
|
|
72
|
+
finally:
|
|
73
|
+
tracemalloc.stop()
|
|
74
|
+
return best, peak / 2**20, result
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _core_cases(n: int, rng: np.random.Generator) -> list[Case]:
|
|
78
|
+
import evalsuite as es
|
|
79
|
+
|
|
80
|
+
y = rng.integers(0, 2, n)
|
|
81
|
+
p = np.where(rng.random(n) < 0.8, y, 1 - y)
|
|
82
|
+
prob = 1 / (1 + np.exp(-(2.0 * (y - 0.5) + rng.normal(0, 1, n))))
|
|
83
|
+
yk = rng.integers(0, 10, n)
|
|
84
|
+
pk = np.where(rng.random(n) < 0.7, yk, rng.integers(0, 10, n))
|
|
85
|
+
yr = rng.normal(10, 3, n)
|
|
86
|
+
pr = yr + rng.normal(0, 1, n)
|
|
87
|
+
names = ["accuracy", "balanced_accuracy", "precision", "recall", "f1", "specificity", "mcc", "cohen_kappa"]
|
|
88
|
+
|
|
89
|
+
def es_binary() -> list[float]:
|
|
90
|
+
r = es.evaluate(y, p, metrics=names)
|
|
91
|
+
return [float(r[m]) for m in names]
|
|
92
|
+
|
|
93
|
+
def es_reg() -> list[float]:
|
|
94
|
+
r = es.evaluate(yr, pr, metrics=["mae", "mse", "rmse", "r2"])
|
|
95
|
+
return [float(r[m]) for m in ("mae", "mse", "rmse", "r2")]
|
|
96
|
+
|
|
97
|
+
cases: list[Case] = [
|
|
98
|
+
("binary: 8 label metrics via evaluate()", "scikit-learn", es_binary, None),
|
|
99
|
+
("10 classes: macro F1", "scikit-learn", lambda: [float(es.f1(yk, pk, average="macro"))], None),
|
|
100
|
+
("binary: ROC AUC", "scikit-learn", lambda: [float(es.roc_auc(y, prob))], None),
|
|
101
|
+
("regression: MAE, MSE, RMSE, R² via evaluate()", "scikit-learn", es_reg, None),
|
|
102
|
+
]
|
|
103
|
+
try:
|
|
104
|
+
import sklearn.metrics as skm # type: ignore[import-untyped]
|
|
105
|
+
except ImportError:
|
|
106
|
+
return cases
|
|
107
|
+
|
|
108
|
+
def sk_binary() -> list[float]:
|
|
109
|
+
return [
|
|
110
|
+
skm.accuracy_score(y, p),
|
|
111
|
+
skm.balanced_accuracy_score(y, p),
|
|
112
|
+
skm.precision_score(y, p),
|
|
113
|
+
skm.recall_score(y, p),
|
|
114
|
+
skm.f1_score(y, p),
|
|
115
|
+
skm.recall_score(y, p, pos_label=0),
|
|
116
|
+
skm.matthews_corrcoef(y, p),
|
|
117
|
+
skm.cohen_kappa_score(y, p),
|
|
118
|
+
]
|
|
119
|
+
|
|
120
|
+
def sk_reg() -> list[float]:
|
|
121
|
+
mse = skm.mean_squared_error(yr, pr)
|
|
122
|
+
return [skm.mean_absolute_error(yr, pr), mse, float(np.sqrt(mse)), skm.r2_score(yr, pr)]
|
|
123
|
+
|
|
124
|
+
sk = [sk_binary, lambda: [skm.f1_score(yk, pk, average="macro")], lambda: [skm.roc_auc_score(y, prob)], sk_reg]
|
|
125
|
+
return [(name, ref, es_fn, sk_fn) for (name, ref, es_fn, _), sk_fn in zip(cases, sk)]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _vision_cases(n: int, rng: np.random.Generator) -> list[Case]:
|
|
129
|
+
"""v0.3.0: segmentation overlap and surface distance (n = pixels) and COCO detection (n / 1000 images)."""
|
|
130
|
+
import evalsuite as es
|
|
131
|
+
|
|
132
|
+
side = 64
|
|
133
|
+
n_img = max(1, n // (side * side))
|
|
134
|
+
k = 5
|
|
135
|
+
yy, xx = np.ogrid[:side, :side]
|
|
136
|
+
true = np.zeros((n_img, side, side), dtype=np.int64)
|
|
137
|
+
for i in range(n_img):
|
|
138
|
+
for c in range(1, k):
|
|
139
|
+
cy, cx, r = rng.integers(8, side - 8), rng.integers(8, side - 8), rng.integers(4, 14)
|
|
140
|
+
true[i][(yy - cy) ** 2 + (xx - cx) ** 2 <= r * r] = c
|
|
141
|
+
pred = np.roll(true, 1, axis=2)
|
|
142
|
+
noise = rng.random(pred.shape) < 0.02
|
|
143
|
+
pred[noise] = rng.integers(0, k, int(noise.sum()))
|
|
144
|
+
labels = list(range(k))
|
|
145
|
+
|
|
146
|
+
def es_overlap() -> list[float]:
|
|
147
|
+
d = np.asarray(es.dice(true, pred, average=None).value)
|
|
148
|
+
j = np.asarray(es.iou(true, pred, average=None).value)
|
|
149
|
+
return [*d, *j]
|
|
150
|
+
|
|
151
|
+
n_hd = min(n_img, 50)
|
|
152
|
+
|
|
153
|
+
def es_hd() -> list[float]:
|
|
154
|
+
return [float(es.hausdorff_distance(true[i], pred[i], labels=[k - 1])) for i in range(n_hd)]
|
|
155
|
+
|
|
156
|
+
n_det = max(10, n // 1000)
|
|
157
|
+
y_true, y_pred = [], []
|
|
158
|
+
for _ in range(n_det):
|
|
159
|
+
m = int(rng.integers(1, 8))
|
|
160
|
+
xy = rng.uniform(0, 500, (m, 2))
|
|
161
|
+
wh = rng.uniform(8, 160, (m, 2))
|
|
162
|
+
boxes = np.column_stack([xy, xy + wh])
|
|
163
|
+
lab = rng.integers(1, 6, m)
|
|
164
|
+
y_true.append({"boxes": boxes, "labels": lab, "iscrowd": np.zeros(m, int)})
|
|
165
|
+
jitter = boxes + rng.normal(0, 4, boxes.shape)
|
|
166
|
+
jitter[:, 2:] = np.maximum(jitter[:, 2:], jitter[:, :2] + 1)
|
|
167
|
+
extra = rng.uniform(0, 500, (3, 2))
|
|
168
|
+
fp = np.column_stack([extra, extra + rng.uniform(10, 80, (3, 2))])
|
|
169
|
+
y_pred.append(
|
|
170
|
+
{
|
|
171
|
+
"boxes": np.vstack([jitter, fp]),
|
|
172
|
+
"labels": np.r_[lab, rng.integers(1, 6, 3)],
|
|
173
|
+
"scores": rng.random(m + 3),
|
|
174
|
+
}
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def es_map() -> list[float]:
|
|
178
|
+
r = es.detection_report(y_true, y_pred)
|
|
179
|
+
return [r["map"], r["map_50"], r["map_75"], r["mar_100"]]
|
|
180
|
+
|
|
181
|
+
cases: list[Case] = [
|
|
182
|
+
("segmentation: Dice and IoU per class (n = pixels)", "scikit-learn", es_overlap, None),
|
|
183
|
+
(f"segmentation: Hausdorff distance ({n_hd} image{'s' if n_hd != 1 else ''})", "SciPy", es_hd, None),
|
|
184
|
+
(f"detection: COCO evaluation ({n_det} images)", "pycocotools", es_map, None),
|
|
185
|
+
]
|
|
186
|
+
refs: dict[str, Callable[[], Any]] = {}
|
|
187
|
+
try:
|
|
188
|
+
import sklearn.metrics as skm
|
|
189
|
+
|
|
190
|
+
def sk_overlap() -> list[float]:
|
|
191
|
+
ft, fp_ = true.ravel(), pred.ravel()
|
|
192
|
+
return [
|
|
193
|
+
*skm.f1_score(ft, fp_, labels=labels, average=None),
|
|
194
|
+
*skm.jaccard_score(ft, fp_, labels=labels, average=None),
|
|
195
|
+
]
|
|
196
|
+
|
|
197
|
+
refs[cases[0][0]] = sk_overlap
|
|
198
|
+
except ImportError:
|
|
199
|
+
pass
|
|
200
|
+
from scipy import ndimage
|
|
201
|
+
from scipy.spatial.distance import directed_hausdorff
|
|
202
|
+
|
|
203
|
+
def scipy_hd() -> list[float]:
|
|
204
|
+
out = []
|
|
205
|
+
for i in range(n_hd):
|
|
206
|
+
pts = []
|
|
207
|
+
for m_ in (true[i] == k - 1, pred[i] == k - 1):
|
|
208
|
+
er = ndimage.binary_erosion(m_, structure=ndimage.generate_binary_structure(2, 1), border_value=0)
|
|
209
|
+
pts.append(np.argwhere(m_ & ~er).astype(float))
|
|
210
|
+
out.append(max(directed_hausdorff(pts[0], pts[1])[0], directed_hausdorff(pts[1], pts[0])[0]))
|
|
211
|
+
return out
|
|
212
|
+
|
|
213
|
+
refs[cases[1][0]] = scipy_hd
|
|
214
|
+
try:
|
|
215
|
+
import contextlib as _ctx
|
|
216
|
+
import io
|
|
217
|
+
|
|
218
|
+
from pycocotools.coco import COCO
|
|
219
|
+
from pycocotools.cocoeval import COCOeval
|
|
220
|
+
|
|
221
|
+
def coco_map() -> list[float]:
|
|
222
|
+
images, anns, dets, aid = [], [], [], 1
|
|
223
|
+
for i, (t, p) in enumerate(zip(y_true, y_pred)):
|
|
224
|
+
images.append({"id": i + 1})
|
|
225
|
+
for b, c in zip(t["boxes"], t["labels"]):
|
|
226
|
+
w, h = b[2] - b[0], b[3] - b[1]
|
|
227
|
+
anns.append(
|
|
228
|
+
{
|
|
229
|
+
"id": aid,
|
|
230
|
+
"image_id": i + 1,
|
|
231
|
+
"category_id": int(c),
|
|
232
|
+
"bbox": [b[0], b[1], w, h],
|
|
233
|
+
"area": w * h,
|
|
234
|
+
"iscrowd": 0,
|
|
235
|
+
}
|
|
236
|
+
)
|
|
237
|
+
aid += 1
|
|
238
|
+
for b, c, sc in zip(p["boxes"], p["labels"], p["scores"]):
|
|
239
|
+
dets.append(
|
|
240
|
+
{
|
|
241
|
+
"image_id": i + 1,
|
|
242
|
+
"category_id": int(c),
|
|
243
|
+
"bbox": [b[0], b[1], b[2] - b[0], b[3] - b[1]],
|
|
244
|
+
"score": float(sc),
|
|
245
|
+
}
|
|
246
|
+
)
|
|
247
|
+
with _ctx.redirect_stdout(io.StringIO()):
|
|
248
|
+
gt = COCO()
|
|
249
|
+
gt.dataset = {
|
|
250
|
+
"images": images,
|
|
251
|
+
"annotations": anns,
|
|
252
|
+
"categories": [{"id": c} for c in range(1, 6)],
|
|
253
|
+
}
|
|
254
|
+
gt.createIndex()
|
|
255
|
+
ev = COCOeval(gt, gt.loadRes(dets), "bbox")
|
|
256
|
+
ev.evaluate()
|
|
257
|
+
ev.accumulate()
|
|
258
|
+
ev.summarize()
|
|
259
|
+
return [ev.stats[0], ev.stats[1], ev.stats[2], ev.stats[8]]
|
|
260
|
+
|
|
261
|
+
refs[cases[2][0]] = coco_map
|
|
262
|
+
except ImportError:
|
|
263
|
+
pass
|
|
264
|
+
return [(name, ref, es_fn, refs.get(name)) for name, ref, es_fn, _ in cases]
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
_LLM_VOCAB = ( # noqa: SIM905
|
|
268
|
+
"the a cat dog sat on mat quickly model models data run running ran 2.5 3,000 well-known state-of-the-art "
|
|
269
|
+
"( ) , . ! ? don't U.S. e-mail Hello WORLD naive cafe results show improves baseline evaluation"
|
|
270
|
+
).split()
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _llm_cases(n: int, rng: np.random.Generator) -> list[Case]:
|
|
274
|
+
"""v0.4.0: text generation, retrieval, rater agreement and structured output (n / 100 examples)."""
|
|
275
|
+
import evalsuite as es
|
|
276
|
+
|
|
277
|
+
m = max(10, n // 100)
|
|
278
|
+
preds, refs_ = [], []
|
|
279
|
+
for _ in range(m):
|
|
280
|
+
base = list(rng.choice(_LLM_VOCAB, int(rng.integers(5, 25))))
|
|
281
|
+
keep = [w for w in base if rng.random() > 0.2] + list(rng.choice(_LLM_VOCAB, int(rng.integers(0, 4))))
|
|
282
|
+
preds.append(" ".join(keep))
|
|
283
|
+
refs_.append(" ".join(base))
|
|
284
|
+
queries = [
|
|
285
|
+
(set(rng.choice(200, int(rng.integers(1, 6)), replace=False).tolist()), rng.permutation(200)[:20].tolist())
|
|
286
|
+
for _ in range(m)
|
|
287
|
+
]
|
|
288
|
+
rel, ret = [q[0] for q in queries], [q[1] for q in queries]
|
|
289
|
+
ratings = rng.integers(1, 6, (4, m)).astype(float)
|
|
290
|
+
ratings[rng.random(ratings.shape) < 0.1] = np.nan
|
|
291
|
+
schema = {
|
|
292
|
+
"type": "object",
|
|
293
|
+
"properties": {
|
|
294
|
+
"name": {"type": "string", "minLength": 1},
|
|
295
|
+
"age": {"type": "integer", "minimum": 0},
|
|
296
|
+
"tags": {"type": "array", "items": {"type": "string"}, "uniqueItems": True},
|
|
297
|
+
},
|
|
298
|
+
"required": ["name", "age"],
|
|
299
|
+
"additionalProperties": False,
|
|
300
|
+
}
|
|
301
|
+
docs = []
|
|
302
|
+
for i in range(m):
|
|
303
|
+
d: dict[str, Any] = {"name": f"n{i}", "age": int(rng.integers(-2, 90)), "tags": ["a", "b"]}
|
|
304
|
+
if rng.random() < 0.1:
|
|
305
|
+
d["extra"] = 1
|
|
306
|
+
if rng.random() < 0.1:
|
|
307
|
+
del d["name"]
|
|
308
|
+
docs.append(d)
|
|
309
|
+
import json as _json
|
|
310
|
+
|
|
311
|
+
docs_text = [_json.dumps(d) for d in docs]
|
|
312
|
+
|
|
313
|
+
cases: list[Case] = [
|
|
314
|
+
(
|
|
315
|
+
f"text: corpus BLEU and chrF ({m} sentences)",
|
|
316
|
+
"sacreBLEU",
|
|
317
|
+
lambda: [float(es.bleu(refs_, preds)), float(es.chrf(refs_, preds))],
|
|
318
|
+
None,
|
|
319
|
+
),
|
|
320
|
+
(
|
|
321
|
+
f"text: ROUGE-1, ROUGE-2, ROUGE-L ({m} sentences)",
|
|
322
|
+
"rouge-score",
|
|
323
|
+
lambda: [
|
|
324
|
+
float(es.rouge_1(refs_, preds)),
|
|
325
|
+
float(es.rouge_2(refs_, preds)),
|
|
326
|
+
float(es.rouge_l(refs_, preds)),
|
|
327
|
+
],
|
|
328
|
+
None,
|
|
329
|
+
),
|
|
330
|
+
(
|
|
331
|
+
f"text: METEOR, exact and stem matches ({m} sentences)",
|
|
332
|
+
"NLTK",
|
|
333
|
+
lambda: [float(es.meteor(refs_, preds))],
|
|
334
|
+
None,
|
|
335
|
+
),
|
|
336
|
+
(
|
|
337
|
+
f"retrieval: MRR, MAP@20, NDCG@10 ({m} queries)",
|
|
338
|
+
"ranx",
|
|
339
|
+
lambda: [
|
|
340
|
+
float(es.mrr(rel, ret)),
|
|
341
|
+
float(es.mean_average_precision_at_k(rel, ret, k=20)),
|
|
342
|
+
float(es.ndcg_at_k(rel, ret, k=10)),
|
|
343
|
+
],
|
|
344
|
+
None,
|
|
345
|
+
),
|
|
346
|
+
(
|
|
347
|
+
f"agreement: Krippendorff's alpha, interval (4 raters × {m} items)",
|
|
348
|
+
"krippendorff",
|
|
349
|
+
lambda: [float(es.krippendorff_alpha(ratings, level="interval"))],
|
|
350
|
+
None,
|
|
351
|
+
),
|
|
352
|
+
(
|
|
353
|
+
f"structured: JSON Schema compliance ({m} documents)",
|
|
354
|
+
"jsonschema",
|
|
355
|
+
lambda: [float(es.json_schema_compliance(docs_text, schema))],
|
|
356
|
+
None,
|
|
357
|
+
),
|
|
358
|
+
]
|
|
359
|
+
refs: dict[str, Callable[[], Any]] = {}
|
|
360
|
+
with contextlib.suppress(ImportError):
|
|
361
|
+
import sacrebleu
|
|
362
|
+
|
|
363
|
+
refs[cases[0][0]] = lambda: [
|
|
364
|
+
sacrebleu.corpus_bleu(preds, [refs_], force=True).score,
|
|
365
|
+
sacrebleu.corpus_chrf(preds, [refs_]).score,
|
|
366
|
+
]
|
|
367
|
+
with contextlib.suppress(ImportError):
|
|
368
|
+
from rouge_score import rouge_scorer
|
|
369
|
+
|
|
370
|
+
def rouge_ref() -> list[float]:
|
|
371
|
+
sc = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"])
|
|
372
|
+
out = [sc.score(r, p) for r, p in zip(refs_, preds)]
|
|
373
|
+
return [float(np.mean([o[k].fmeasure for o in out])) for k in ("rouge1", "rouge2", "rougeL")]
|
|
374
|
+
|
|
375
|
+
refs[cases[1][0]] = rouge_ref
|
|
376
|
+
with contextlib.suppress(ImportError):
|
|
377
|
+
from nltk.translate.meteor_score import meteor_score
|
|
378
|
+
|
|
379
|
+
class _NoWordNet:
|
|
380
|
+
def synsets(self, _w: str) -> list[Any]:
|
|
381
|
+
return []
|
|
382
|
+
|
|
383
|
+
refs[cases[2][0]] = lambda: [
|
|
384
|
+
float(
|
|
385
|
+
np.mean([meteor_score([r.split()], p.split(), wordnet=_NoWordNet()) for r, p in zip(refs_, preds)])
|
|
386
|
+
)
|
|
387
|
+
]
|
|
388
|
+
with contextlib.suppress(ImportError):
|
|
389
|
+
from ranx import Qrels, Run
|
|
390
|
+
from ranx import evaluate as ranx_evaluate
|
|
391
|
+
|
|
392
|
+
def ranx_ref() -> list[float]:
|
|
393
|
+
qrels = Qrels({f"q{i}": {f"d{d}": 1 for d in r} for i, r in enumerate(rel)})
|
|
394
|
+
run = Run({f"q{i}": {f"d{d}": float(len(r) - j) for j, d in enumerate(r)} for i, r in enumerate(ret)})
|
|
395
|
+
res = ranx_evaluate(qrels, run, ["mrr", "map@20", "ndcg@10"])
|
|
396
|
+
return [float(res["mrr"]), float(res["map@20"]), float(res["ndcg@10"])]
|
|
397
|
+
|
|
398
|
+
refs[cases[3][0]] = ranx_ref
|
|
399
|
+
with contextlib.suppress(ImportError):
|
|
400
|
+
import krippendorff
|
|
401
|
+
|
|
402
|
+
refs[cases[4][0]] = lambda: [
|
|
403
|
+
float(krippendorff.alpha(reliability_data=ratings, level_of_measurement="interval"))
|
|
404
|
+
]
|
|
405
|
+
with contextlib.suppress(ImportError):
|
|
406
|
+
import jsonschema
|
|
407
|
+
|
|
408
|
+
def jsonschema_ref() -> list[float]:
|
|
409
|
+
v = jsonschema.Draft202012Validator(schema)
|
|
410
|
+
return [float(np.mean([v.is_valid(_json.loads(t)) for t in docs_text]))]
|
|
411
|
+
|
|
412
|
+
refs[cases[5][0]] = jsonschema_ref
|
|
413
|
+
return [(name, ref, es_fn, refs.get(name)) for name, ref, es_fn, _ in cases]
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _clinical_cases(n: int, rng: np.random.Generator) -> list[Case]:
|
|
417
|
+
"""v0.2.0: diagnostic accuracy, calibration, decision curves and statistical tests."""
|
|
418
|
+
import evalsuite as es
|
|
419
|
+
|
|
420
|
+
y = rng.integers(0, 2, n)
|
|
421
|
+
p = np.where(rng.random(n) < 0.8, y, 1 - y)
|
|
422
|
+
x = rng.normal(size=n)
|
|
423
|
+
yc = (rng.random(n) < 1 / (1 + np.exp(-(0.4 + 1.3 * x)))).astype(int)
|
|
424
|
+
risk = 1 / (1 + np.exp(-(0.1 + 2.0 * x)))
|
|
425
|
+
a, b = rng.normal(0, 1, n), rng.normal(0.05, 1.2, n)
|
|
426
|
+
pvals = rng.random(n) ** 2
|
|
427
|
+
ga, gb = rng.integers(0, 5, n), rng.integers(0, 5, n)
|
|
428
|
+
table = np.zeros((5, 5), dtype=np.int64)
|
|
429
|
+
np.add.at(table, (ga, gb), 1)
|
|
430
|
+
thresholds = np.arange(1, 100) / 100
|
|
431
|
+
|
|
432
|
+
def es_diag() -> list[float]:
|
|
433
|
+
return [
|
|
434
|
+
float(es.sensitivity(y, p)),
|
|
435
|
+
float(es.specificity(y, p)),
|
|
436
|
+
float(es.lr_positive(y, p)),
|
|
437
|
+
float(es.lr_negative(y, p)),
|
|
438
|
+
]
|
|
439
|
+
|
|
440
|
+
report_keys = ("sensitivity", "specificity", "ppv", "npv", "accuracy", "prevalence", "diagnostic_odds_ratio")
|
|
441
|
+
|
|
442
|
+
def es_report() -> list[float]:
|
|
443
|
+
r = es.diagnostic_report(y, p)
|
|
444
|
+
return [v for k in report_keys for v in (r[k].low, r[k].high)]
|
|
445
|
+
|
|
446
|
+
def es_cal() -> list[float]:
|
|
447
|
+
return [float(es.calibration_slope(yc, risk)), float(es.calibration_intercept(yc, risk))]
|
|
448
|
+
|
|
449
|
+
def es_dca() -> list[float]:
|
|
450
|
+
curve: list[float] = es.decision_curve(yc, risk, thresholds=thresholds).net_benefit["model"].tolist()
|
|
451
|
+
return curve
|
|
452
|
+
|
|
453
|
+
def numpy_dca() -> list[float]: # the textbook loop, one threshold at a time
|
|
454
|
+
out = []
|
|
455
|
+
for t in thresholds:
|
|
456
|
+
treat = risk >= t
|
|
457
|
+
tp = np.sum(treat & (yc == 1))
|
|
458
|
+
fp = np.sum(treat & (yc == 0))
|
|
459
|
+
out.append(tp / n - fp / n * t / (1 - t))
|
|
460
|
+
return out
|
|
461
|
+
|
|
462
|
+
cases: list[Case] = [
|
|
463
|
+
("clinical: sensitivity, specificity, LR+, LR−", "scikit-learn", es_diag, None),
|
|
464
|
+
("clinical: diagnostic report (7 CIs)", "statsmodels", es_report, None),
|
|
465
|
+
("calibration: slope and intercept", "statsmodels", es_cal, None),
|
|
466
|
+
("decision curve: 99 thresholds", "NumPy loop", es_dca, numpy_dca),
|
|
467
|
+
("statistics: Welch t-test", "SciPy", lambda: [es.t_test(a, b).p_value], None),
|
|
468
|
+
("statistics: Mann–Whitney U", "SciPy", lambda: [es.mann_whitney_test(a, b).p_value], None),
|
|
469
|
+
("statistics: Cramér's V (5×5 table)", "SciPy", lambda: [es.cramers_v(table)], None),
|
|
470
|
+
(
|
|
471
|
+
"multiple testing: Hochberg (n p-values)",
|
|
472
|
+
"statsmodels",
|
|
473
|
+
lambda: es.adjust_pvalues(pvals, method="hochberg").tolist(),
|
|
474
|
+
None,
|
|
475
|
+
),
|
|
476
|
+
]
|
|
477
|
+
refs: dict[str, Callable[[], Any]] = {}
|
|
478
|
+
try:
|
|
479
|
+
import sklearn.metrics as skm
|
|
480
|
+
|
|
481
|
+
def sk_diag() -> list[float]:
|
|
482
|
+
lr_pos, lr_neg = skm.class_likelihood_ratios(y, p)
|
|
483
|
+
return [skm.recall_score(y, p), skm.recall_score(y, p, pos_label=0), lr_pos, lr_neg]
|
|
484
|
+
|
|
485
|
+
refs["clinical: sensitivity, specificity, LR+, LR−"] = sk_diag
|
|
486
|
+
except (ImportError, AttributeError):
|
|
487
|
+
pass
|
|
488
|
+
from scipy import stats
|
|
489
|
+
|
|
490
|
+
refs["statistics: Welch t-test"] = lambda: [stats.ttest_ind(a, b, equal_var=False).pvalue]
|
|
491
|
+
refs["statistics: Mann–Whitney U"] = lambda: [stats.mannwhitneyu(a, b).pvalue]
|
|
492
|
+
refs["statistics: Cramér's V (5×5 table)"] = lambda: [stats.contingency.association(table, method="cramer")]
|
|
493
|
+
try:
|
|
494
|
+
import statsmodels.api as sm # type: ignore[import-untyped]
|
|
495
|
+
from statsmodels.stats.contingency_tables import Table2x2 # type: ignore[import-untyped]
|
|
496
|
+
from statsmodels.stats.multitest import multipletests # type: ignore[import-untyped]
|
|
497
|
+
from statsmodels.stats.proportion import proportion_confint # type: ignore[import-untyped]
|
|
498
|
+
|
|
499
|
+
def sm_report() -> list[float]:
|
|
500
|
+
tp = int(np.sum((y == 1) & (p == 1)))
|
|
501
|
+
fn = int(np.sum((y == 1) & (p == 0)))
|
|
502
|
+
fp = int(np.sum((y == 0) & (p == 1)))
|
|
503
|
+
tn = int(np.sum((y == 0) & (p == 0)))
|
|
504
|
+
out: list[float] = []
|
|
505
|
+
for k, m in ((tp, tp + fn), (tn, tn + fp), (tp, tp + fp), (tn, tn + fn), (tp + tn, n), (tp + fn, n)):
|
|
506
|
+
out.extend(proportion_confint(k, m, method="wilson"))
|
|
507
|
+
out.extend(Table2x2(np.array([[tp, fn], [fp, tn]])).oddsratio_confint())
|
|
508
|
+
return out
|
|
509
|
+
|
|
510
|
+
def sm_cal() -> list[float]:
|
|
511
|
+
lp = np.log(risk / (1 - risk))
|
|
512
|
+
fam = sm.families.Binomial()
|
|
513
|
+
slope = sm.GLM(yc, sm.add_constant(lp), family=fam).fit().params[1]
|
|
514
|
+
intercept = sm.GLM(yc, np.ones((n, 1)), family=fam, offset=lp).fit().params[0]
|
|
515
|
+
return [slope, intercept]
|
|
516
|
+
|
|
517
|
+
refs["clinical: diagnostic report (7 CIs)"] = sm_report
|
|
518
|
+
refs["calibration: slope and intercept"] = sm_cal
|
|
519
|
+
refs["multiple testing: Hochberg (n p-values)"] = lambda: multipletests(pvals, method="simes-hochberg")[
|
|
520
|
+
1
|
|
521
|
+
].tolist()
|
|
522
|
+
except ImportError:
|
|
523
|
+
pass
|
|
524
|
+
return [(name, ref, es_fn, own if own is not None else refs.get(name)) for name, ref, es_fn, own in cases]
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _llmsys_cases(n: int, rng: np.random.Generator) -> list[Case]:
|
|
528
|
+
"""v0.5.0: LLM systems workloads (code quality, selective prediction, agent tool calls, shift, latency)."""
|
|
529
|
+
import json as _json
|
|
530
|
+
|
|
531
|
+
import evalsuite as es
|
|
532
|
+
|
|
533
|
+
from ._bench_metrics import _CODE_SAMPLES
|
|
534
|
+
|
|
535
|
+
m = max(10, n // 100)
|
|
536
|
+
progs = [str(rng.choice(np.array(_CODE_SAMPLES))) for _ in range(max(4, m // 10))]
|
|
537
|
+
refs_c = progs
|
|
538
|
+
preds_c = [p.replace("a", "x").replace("s", "t") for p in progs]
|
|
539
|
+
conf = rng.uniform(0, 1, n)
|
|
540
|
+
correct = rng.random(n) < conf
|
|
541
|
+
tools = {
|
|
542
|
+
t: {"type": "object", "properties": {"q": {"type": "string"}, "k": {"type": "integer"}}, "required": ["q"]}
|
|
543
|
+
for t in ("search", "calc", "email")
|
|
544
|
+
}
|
|
545
|
+
trajs = [
|
|
546
|
+
[
|
|
547
|
+
{
|
|
548
|
+
"name": str(rng.choice(["search", "calc", "email", "bad"])),
|
|
549
|
+
"arguments": {"q": "x"} if rng.random() > 0.1 else {"k": 1},
|
|
550
|
+
}
|
|
551
|
+
for _ in range(int(rng.integers(1, 6)))
|
|
552
|
+
]
|
|
553
|
+
for _ in range(m)
|
|
554
|
+
]
|
|
555
|
+
src, tgt = rng.normal(0.8, 0.1, n), rng.normal(0.75, 0.12, n)
|
|
556
|
+
lat = rng.lognormal(0, 0.5, n)
|
|
557
|
+
|
|
558
|
+
def es_shift() -> list[float]:
|
|
559
|
+
r = es.distribution_shift_drop(src, tgt)
|
|
560
|
+
return [r.params["ci_low"], r.params["ci_high"]]
|
|
561
|
+
|
|
562
|
+
def es_lat() -> list[float]:
|
|
563
|
+
r = es.latency_percentiles(lat)
|
|
564
|
+
return [r.params["p50"], r.params["p95"], r.params["p99"]]
|
|
565
|
+
|
|
566
|
+
cases: list[Case] = [
|
|
567
|
+
(
|
|
568
|
+
f"systems: maintainability index ({len(progs)} programs)",
|
|
569
|
+
"radon",
|
|
570
|
+
lambda: [float(es.code_complexity(progs).params["maintainability_index"])],
|
|
571
|
+
None,
|
|
572
|
+
),
|
|
573
|
+
(
|
|
574
|
+
f"systems: CodeBLEU n-gram terms ({len(progs)} programs)",
|
|
575
|
+
"codebleu",
|
|
576
|
+
lambda: [es.codebleu(refs_c, preds_c).params[k] for k in ("ngram_match", "weighted_ngram_match")],
|
|
577
|
+
None,
|
|
578
|
+
),
|
|
579
|
+
(
|
|
580
|
+
"systems: confidence AUROC (n answers)",
|
|
581
|
+
"scikit-learn",
|
|
582
|
+
lambda: [float(es.confidence_accuracy_correlation(correct, conf))],
|
|
583
|
+
None,
|
|
584
|
+
),
|
|
585
|
+
(
|
|
586
|
+
f"systems: invalid tool calls vs JSON Schema ({m} tasks)",
|
|
587
|
+
"jsonschema",
|
|
588
|
+
lambda: [float(es.invalid_tool_call_rate(trajs, tools))],
|
|
589
|
+
None,
|
|
590
|
+
),
|
|
591
|
+
("systems: distribution-shift drop, Welch CI (n scores)", "SciPy", es_shift, None),
|
|
592
|
+
(
|
|
593
|
+
"systems: latency p50 / p95 / p99 (n requests)",
|
|
594
|
+
"NumPy",
|
|
595
|
+
es_lat,
|
|
596
|
+
lambda: np.percentile(lat, [50, 95, 99]).tolist(),
|
|
597
|
+
),
|
|
598
|
+
]
|
|
599
|
+
refs: dict[str, Callable[[], Any]] = {}
|
|
600
|
+
with contextlib.suppress(ImportError):
|
|
601
|
+
from radon.metrics import mi_visit
|
|
602
|
+
|
|
603
|
+
refs[cases[0][0]] = lambda: [float(np.mean([mi_visit(p, True) for p in progs]))]
|
|
604
|
+
with contextlib.suppress(Exception):
|
|
605
|
+
from codebleu import calc_codebleu
|
|
606
|
+
|
|
607
|
+
def cb() -> list[float]:
|
|
608
|
+
r = calc_codebleu([[x] for x in refs_c], preds_c, lang="python")
|
|
609
|
+
return [r["ngram_match_score"], r["weighted_ngram_match_score"]]
|
|
610
|
+
|
|
611
|
+
cb()
|
|
612
|
+
refs[cases[1][0]] = cb
|
|
613
|
+
with contextlib.suppress(ImportError):
|
|
614
|
+
import sklearn.metrics as skm
|
|
615
|
+
|
|
616
|
+
refs[cases[2][0]] = lambda: [float(skm.roc_auc_score(correct, conf))]
|
|
617
|
+
with contextlib.suppress(ImportError):
|
|
618
|
+
import jsonschema
|
|
619
|
+
|
|
620
|
+
def js_ref() -> list[float]:
|
|
621
|
+
flags = []
|
|
622
|
+
for traj in trajs:
|
|
623
|
+
for c in traj:
|
|
624
|
+
sch = tools.get(str(c["name"]))
|
|
625
|
+
flags.append(sch is None or not jsonschema.Draft202012Validator(sch).is_valid(c["arguments"]))
|
|
626
|
+
return [float(np.mean(flags))]
|
|
627
|
+
|
|
628
|
+
refs[cases[3][0]] = js_ref
|
|
629
|
+
from scipy import stats as _st
|
|
630
|
+
|
|
631
|
+
res = _st.ttest_ind(src[:3], tgt[:3], equal_var=False)
|
|
632
|
+
if hasattr(res, "confidence_interval"):
|
|
633
|
+
refs[cases[4][0]] = lambda: list(_st.ttest_ind(src, tgt, equal_var=False).confidence_interval(0.95))
|
|
634
|
+
del _json
|
|
635
|
+
return [(name, ref, es_fn, own if own is not None else refs.get(name)) for name, ref, es_fn, own in cases]
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
_GROUPS = (
|
|
639
|
+
("Classification and regression", ("binary", "10 classes", "regression", "classification")),
|
|
640
|
+
("Clinical, calibration and statistics", ("clinical", "calibration", "decision", "statistics", "multiple")),
|
|
641
|
+
("Segmentation and object detection", ("segmentation", "detection")),
|
|
642
|
+
("LLM evaluation", ("text", "retrieval", "agreement", "structured", "qa.", "rag.", "reasoning.")),
|
|
643
|
+
(
|
|
644
|
+
"LLM systems",
|
|
645
|
+
(
|
|
646
|
+
"systems:",
|
|
647
|
+
"safety.",
|
|
648
|
+
"robustness.",
|
|
649
|
+
"uncertainty.",
|
|
650
|
+
"agents.",
|
|
651
|
+
"multilingual.",
|
|
652
|
+
"code.",
|
|
653
|
+
"long_context.",
|
|
654
|
+
"efficiency.",
|
|
655
|
+
),
|
|
656
|
+
),
|
|
657
|
+
)
|
|
658
|
+
MATCH_TOLERANCE = 1e-9
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def benchmark_group(case: str) -> str:
|
|
662
|
+
"""The suite a benchmark case belongs to, by its name."""
|
|
663
|
+
lowered = case.lower()
|
|
664
|
+
for title, prefixes in _GROUPS:
|
|
665
|
+
if lowered.startswith(prefixes):
|
|
666
|
+
return title
|
|
667
|
+
return "Other"
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
def _geomean(values: Sequence[float]) -> Optional[float]:
|
|
671
|
+
vals = [v for v in values if v is not None and v > 0]
|
|
672
|
+
return float(np.exp(np.mean(np.log(vals)))) if vals else None
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
@dataclass(frozen=True, eq=False)
|
|
676
|
+
class BenchmarkResult:
|
|
677
|
+
"""Rows of timings (milliseconds), peak memory (MiB) and agreement, plus the environment they ran in."""
|
|
678
|
+
|
|
679
|
+
rows: tuple[Any, ...]
|
|
680
|
+
environment: Any = field(default_factory=dict)
|
|
681
|
+
|
|
682
|
+
def __post_init__(self) -> None:
|
|
683
|
+
object.__setattr__(self, "rows", tuple(MappingProxyType(dict(r)) for r in self.rows))
|
|
684
|
+
object.__setattr__(self, "environment", MappingProxyType(dict(self.environment)))
|
|
685
|
+
|
|
686
|
+
def sorted_rows(self) -> list[Any]:
|
|
687
|
+
"""Rows in alphabetical order of case, then by size."""
|
|
688
|
+
return sorted(self.rows, key=lambda r: (r["case"].lower(), r["n"]))
|
|
689
|
+
|
|
690
|
+
def overall(self) -> list[dict[str, Any]]:
|
|
691
|
+
"""One summary row per suite and one for everything: cases, how many agree with the reference
|
|
692
|
+
(max |difference| <= 1e-9), and the geometric-mean, smallest and largest speed-up."""
|
|
693
|
+
|
|
694
|
+
def summarise(name: str, rows: Sequence[Any]) -> dict[str, Any]:
|
|
695
|
+
compared = [r for r in rows if r["speedup"] is not None]
|
|
696
|
+
speedups = [r["speedup"] for r in compared]
|
|
697
|
+
return {
|
|
698
|
+
"group": name,
|
|
699
|
+
"cases": len({re.sub(r"\s*\((?=[^)]*\d)[^)]*\)$", "", r["case"]) for r in rows}),
|
|
700
|
+
"rows": len(rows),
|
|
701
|
+
"compared": len(compared),
|
|
702
|
+
"matching": sum(
|
|
703
|
+
r["max_abs_diff"] is not None and r["max_abs_diff"] <= MATCH_TOLERANCE for r in rows
|
|
704
|
+
),
|
|
705
|
+
"faster": sum(sp > 1 for sp in speedups),
|
|
706
|
+
"geomean_speedup": _geomean(speedups),
|
|
707
|
+
"min_speedup": min(speedups) if speedups else None,
|
|
708
|
+
"max_speedup": max(speedups) if speedups else None,
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
groups = sorted({benchmark_group(r["case"]) for r in self.rows})
|
|
712
|
+
out = [summarise(g, [r for r in self.rows if benchmark_group(r["case"]) == g]) for g in groups]
|
|
713
|
+
out.append(summarise("Overall", self.rows))
|
|
714
|
+
return out
|
|
715
|
+
|
|
716
|
+
_OVERALL_TITLES = ("Suite", "Cases", "Rows", "Match reference", "Faster", "Geo-mean speed-up", "Range")
|
|
717
|
+
|
|
718
|
+
def _overall_cells(self) -> list[list[str]]:
|
|
719
|
+
def x(v: Optional[float]) -> str:
|
|
720
|
+
return "–" if v is None else f"{v:.2f}×"
|
|
721
|
+
|
|
722
|
+
return [
|
|
723
|
+
[
|
|
724
|
+
o["group"],
|
|
725
|
+
str(o["cases"]),
|
|
726
|
+
str(o["rows"]),
|
|
727
|
+
f"{o['matching']}/{o['compared']}",
|
|
728
|
+
f"{o['faster']}/{o['compared']}",
|
|
729
|
+
x(o["geomean_speedup"]),
|
|
730
|
+
"–" if o["min_speedup"] is None else f"{x(o['min_speedup'])}–{x(o['max_speedup'])}",
|
|
731
|
+
]
|
|
732
|
+
for o in self.overall()
|
|
733
|
+
]
|
|
734
|
+
|
|
735
|
+
def overall_markdown(self) -> str:
|
|
736
|
+
"""The overall summary as a Markdown table."""
|
|
737
|
+
lines = ["| " + " | ".join(self._OVERALL_TITLES) + " |", "| --- |" + " ---: |" * 6]
|
|
738
|
+
return "\n".join(lines + ["| " + " | ".join(c) + " |" for c in self._overall_cells()])
|
|
739
|
+
|
|
740
|
+
def _cells(self, digits: int) -> list[list[str]]:
|
|
741
|
+
def f(v: Any, d: int = digits) -> str:
|
|
742
|
+
return "–" if v is None else f"{v:.{d}f}"
|
|
743
|
+
|
|
744
|
+
return [
|
|
745
|
+
[
|
|
746
|
+
r["case"],
|
|
747
|
+
f"{r['n']:,}",
|
|
748
|
+
r.get("reference") or "–",
|
|
749
|
+
f(r["evalsuite_ms"]),
|
|
750
|
+
f(r.get("reference_ms")),
|
|
751
|
+
"–" if r["speedup"] is None else f"{r['speedup']:.2f}×",
|
|
752
|
+
f(r["evalsuite_peak_mb"], 2),
|
|
753
|
+
f(r.get("reference_peak_mb"), 2),
|
|
754
|
+
"–" if r["max_abs_diff"] is None else f"{r['max_abs_diff']:.1e}",
|
|
755
|
+
]
|
|
756
|
+
for r in self.sorted_rows()
|
|
757
|
+
]
|
|
758
|
+
|
|
759
|
+
_TITLES = (
|
|
760
|
+
"Case",
|
|
761
|
+
"n",
|
|
762
|
+
"Reference",
|
|
763
|
+
"EvalSuite (ms)",
|
|
764
|
+
"Reference (ms)",
|
|
765
|
+
"Speed-up",
|
|
766
|
+
"EvalSuite peak (MiB)",
|
|
767
|
+
"Reference peak (MiB)",
|
|
768
|
+
"Max |difference|",
|
|
769
|
+
)
|
|
770
|
+
|
|
771
|
+
def summary(self, *, digits: int = 3) -> str:
|
|
772
|
+
cells = self._cells(digits)
|
|
773
|
+
widths = [max(len(t), *(len(c[i]) for c in cells)) for i, t in enumerate(self._TITLES)]
|
|
774
|
+
|
|
775
|
+
def line(c: Sequence[str]) -> str:
|
|
776
|
+
return " ".join(x.ljust(widths[i]) if i in (0, 2) else x.rjust(widths[i]) for i, x in enumerate(c))
|
|
777
|
+
|
|
778
|
+
env = self.environment
|
|
779
|
+
head = (
|
|
780
|
+
f"EvalSuite {env['evalsuite']} benchmarks | Python {env['python']} | NumPy {env['numpy']}"
|
|
781
|
+
+ (f" | scikit-learn {env['sklearn']}" if env.get("sklearn") else "")
|
|
782
|
+
+ (f" | statsmodels {env['statsmodels']}" if env.get("statsmodels") else "")
|
|
783
|
+
+ (f" | SciPy {env['scipy']}" if env.get("scipy") else "")
|
|
784
|
+
+ (f" | pycocotools {env['pycocotools']}" if env.get("pycocotools") else "")
|
|
785
|
+
+ f" | {env['machine']} | fastest of {env['repeat']} runs"
|
|
786
|
+
)
|
|
787
|
+
note = "Speed-up > 1 means EvalSuite is faster. Max |difference| compares EvalSuite with the reference."
|
|
788
|
+
ocells = self._overall_cells()
|
|
789
|
+
owidths = [max(len(t), *(len(c[i]) for c in ocells)) for i, t in enumerate(self._OVERALL_TITLES)]
|
|
790
|
+
|
|
791
|
+
def oline(c: Sequence[str]) -> str:
|
|
792
|
+
return " ".join(x.ljust(owidths[i]) if i == 0 else x.rjust(owidths[i]) for i, x in enumerate(c))
|
|
793
|
+
|
|
794
|
+
overall = ["Overall", oline(self._OVERALL_TITLES), *(oline(c) for c in ocells), ""]
|
|
795
|
+
return "\n".join([head, "", *overall, line(self._TITLES), *(line(c) for c in cells), "", note])
|
|
796
|
+
|
|
797
|
+
def __repr__(self) -> str:
|
|
798
|
+
return self.summary()
|
|
799
|
+
|
|
800
|
+
def to_dict(self) -> dict[str, Any]:
|
|
801
|
+
return cast(
|
|
802
|
+
"dict[str, Any]",
|
|
803
|
+
_json_safe(
|
|
804
|
+
{
|
|
805
|
+
"environment": dict(self.environment),
|
|
806
|
+
"overall": self.overall(),
|
|
807
|
+
"rows": [dict(r) for r in self.rows],
|
|
808
|
+
}
|
|
809
|
+
),
|
|
810
|
+
)
|
|
811
|
+
|
|
812
|
+
def to_json(self, *, indent: Optional[int] = 2) -> str:
|
|
813
|
+
return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
|
|
814
|
+
|
|
815
|
+
def to_dataframe(self) -> pd.DataFrame:
|
|
816
|
+
import pandas as pd
|
|
817
|
+
|
|
818
|
+
frame: pd.DataFrame = pd.DataFrame([dict(r) for r in self.rows])
|
|
819
|
+
return frame
|
|
820
|
+
|
|
821
|
+
def to_csv(self, path: Optional[str] = None) -> str:
|
|
822
|
+
from .core.export import csv_text
|
|
823
|
+
|
|
824
|
+
rows = [[r.get(h) if r.get(h) is not None else float("nan") for h in _HEADER] for r in self.rows]
|
|
825
|
+
text = csv_text(list(_HEADER), rows)
|
|
826
|
+
if path is not None:
|
|
827
|
+
with open(path, "w", encoding="utf-8", newline="") as fh:
|
|
828
|
+
fh.write(text)
|
|
829
|
+
return text
|
|
830
|
+
|
|
831
|
+
def to_markdown(self, *, digits: int = 3) -> str:
|
|
832
|
+
lines = [
|
|
833
|
+
"| " + " | ".join(self._TITLES) + " |",
|
|
834
|
+
"| --- | ---: | --- |" + " ---: |" * (len(self._TITLES) - 3),
|
|
835
|
+
]
|
|
836
|
+
return "\n".join(lines + ["| " + " | ".join(c) + " |" for c in self._cells(digits)])
|
|
837
|
+
|
|
838
|
+
def to_latex(self, *, digits: int = 3, caption: Optional[str] = None, label: Optional[str] = None) -> str:
|
|
839
|
+
return _latex_table(
|
|
840
|
+
[_latex_escape(t) for t in self._TITLES],
|
|
841
|
+
[[_latex_escape(x) for x in c] for c in self._cells(digits)],
|
|
842
|
+
caption=caption or "EvalSuite benchmarks.",
|
|
843
|
+
label=label,
|
|
844
|
+
)
|
|
845
|
+
|
|
846
|
+
def to_html(self, *, digits: int = 3, full: bool = False) -> str:
|
|
847
|
+
from .core.export import html_document, html_table
|
|
848
|
+
|
|
849
|
+
table = html_table(list(self._TITLES), self._cells(digits), caption="Benchmarks")
|
|
850
|
+
env = self.environment
|
|
851
|
+
meta = f"Python {env['python']}, NumPy {env['numpy']}, {env['machine']}"
|
|
852
|
+
return html_document("EvalSuite benchmarks", table, meta) if full else table
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
def run_benchmarks(
|
|
856
|
+
sizes: Sequence[int] = (1_000, 100_000, 1_000_000),
|
|
857
|
+
*,
|
|
858
|
+
repeat: int = 5,
|
|
859
|
+
compare_sklearn: bool = True,
|
|
860
|
+
random_state: Optional[int] = 0,
|
|
861
|
+
suite: str = "all",
|
|
862
|
+
) -> BenchmarkResult:
|
|
863
|
+
"""Time and memory for evaluation workloads at each size, against a reference implementation.
|
|
864
|
+
|
|
865
|
+
``suite``: ``"core"`` (classification and regression vs scikit-learn), ``"clinical"`` (v0.2.0 clinical,
|
|
866
|
+
calibration and statistics vs scikit-learn, statsmodels, SciPy), ``"vision"`` (segmentation and COCO
|
|
867
|
+
detection vs scikit-learn, SciPy, pycocotools), ``"llm"`` (v0.4.0 text, retrieval, agreement and structured
|
|
868
|
+
output vs sacreBLEU, rouge-score, NLTK, ranx, krippendorff, jsonschema), ``"all"`` (default: the four
|
|
869
|
+
workload suites) or ``"metrics"`` (one row for every registered metric and statistics function, against a
|
|
870
|
+
reference library or the textbook formula where one exists; see ``evalsuite._bench_metrics``).
|
|
871
|
+
``compare_sklearn=False`` times EvalSuite alone. Rows keep ``sklearn_ms``/``sklearn_peak_mb`` for rows
|
|
872
|
+
whose reference is scikit-learn, for compatibility with 0.1.x.
|
|
873
|
+
"""
|
|
874
|
+
import scipy
|
|
875
|
+
|
|
876
|
+
import evalsuite as es
|
|
877
|
+
|
|
878
|
+
if repeat < 1:
|
|
879
|
+
raise ValueError("repeat must be at least 1.")
|
|
880
|
+
if suite not in ("all", "core", "clinical", "vision", "llm", "llmsys", "metrics"):
|
|
881
|
+
raise ValueError("suite must be 'all', 'core', 'clinical', 'vision', 'llm', 'llmsys' or 'metrics'.")
|
|
882
|
+
rng = np.random.default_rng(random_state)
|
|
883
|
+
rows: list[dict[str, Any]] = []
|
|
884
|
+
versions: dict[str, Optional[str]] = {"sklearn": None, "statsmodels": None, "pycocotools": None}
|
|
885
|
+
if compare_sklearn:
|
|
886
|
+
for mod in versions:
|
|
887
|
+
with contextlib.suppress(ImportError):
|
|
888
|
+
importlib.import_module(mod) # fixed names only: sklearn, statsmodels, pycocotools
|
|
889
|
+
from importlib.metadata import version as _dist_version
|
|
890
|
+
|
|
891
|
+
versions[mod] = _dist_version("scikit-learn" if mod == "sklearn" else mod)
|
|
892
|
+
builders = {
|
|
893
|
+
"core": [_core_cases],
|
|
894
|
+
"clinical": [_clinical_cases],
|
|
895
|
+
"vision": [_vision_cases],
|
|
896
|
+
"llm": [_llm_cases],
|
|
897
|
+
"llmsys": [_llmsys_cases],
|
|
898
|
+
"all": [_core_cases, _clinical_cases, _vision_cases, _llm_cases, _llmsys_cases],
|
|
899
|
+
"metrics": [metric_cases],
|
|
900
|
+
}[suite]
|
|
901
|
+
for n in sizes:
|
|
902
|
+
for build in builders:
|
|
903
|
+
for name, ref_name, es_fn, ref_fn in build(int(n), rng):
|
|
904
|
+
try:
|
|
905
|
+
es_t, es_mem, es_val = _measure(es_fn, repeat)
|
|
906
|
+
except OptionalDependencyError:
|
|
907
|
+
continue # e.g. METEOR's default stemmer without nltk: nothing to time
|
|
908
|
+
|
|
909
|
+
row: dict[str, Any] = {
|
|
910
|
+
"case": name,
|
|
911
|
+
"n": int(n),
|
|
912
|
+
"reference": None,
|
|
913
|
+
"evalsuite_ms": es_t * 1000,
|
|
914
|
+
"evalsuite_peak_mb": es_mem,
|
|
915
|
+
"reference_ms": None,
|
|
916
|
+
"reference_peak_mb": None,
|
|
917
|
+
"sklearn_ms": None,
|
|
918
|
+
"sklearn_peak_mb": None,
|
|
919
|
+
"speedup": None,
|
|
920
|
+
"max_abs_diff": None,
|
|
921
|
+
}
|
|
922
|
+
if compare_sklearn and ref_fn is not None:
|
|
923
|
+
ref_t, ref_mem, ref_val = _measure(ref_fn, repeat)
|
|
924
|
+
row.update(
|
|
925
|
+
reference=ref_name,
|
|
926
|
+
reference_ms=ref_t * 1000,
|
|
927
|
+
reference_peak_mb=ref_mem,
|
|
928
|
+
speedup=ref_t / es_t if es_t else None,
|
|
929
|
+
max_abs_diff=float(np.max(np.abs(np.asarray(es_val, float) - np.asarray(ref_val, float)))),
|
|
930
|
+
)
|
|
931
|
+
if ref_name == "scikit-learn":
|
|
932
|
+
row.update(sklearn_ms=row["reference_ms"], sklearn_peak_mb=ref_mem)
|
|
933
|
+
rows.append(row)
|
|
934
|
+
env = {
|
|
935
|
+
"evalsuite": es.__version__,
|
|
936
|
+
"python": platform.python_version(),
|
|
937
|
+
"numpy": np.__version__,
|
|
938
|
+
"scipy": scipy.__version__ if suite != "core" else None,
|
|
939
|
+
"sklearn": versions["sklearn"],
|
|
940
|
+
"statsmodels": versions["statsmodels"] if suite != "core" else None,
|
|
941
|
+
"pycocotools": versions["pycocotools"] if suite in ("all", "vision", "metrics") else None,
|
|
942
|
+
"machine": f"{platform.system()} {platform.machine()}",
|
|
943
|
+
"repeat": repeat,
|
|
944
|
+
"suite": suite,
|
|
945
|
+
}
|
|
946
|
+
return BenchmarkResult(tuple(rows), env)
|