evalsuite-python 0.7.0__py3-none-any.whl → 0.8.0__py3-none-any.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.
@@ -980,10 +980,17 @@ def calibration_curve(
980
980
  edges = np.quantile(p, np.linspace(0, 1, n_bins + 1))
981
981
  else:
982
982
  raise InputValidationError("strategy must be 'uniform' or 'quantile'.")
983
- idx = np.searchsorted(edges[1:-1], p, side="right")
984
- bin_w = np.bincount(idx, weights=w, minlength=len(edges))
985
- bin_true = np.bincount(idx, weights=w * y, minlength=len(edges))
986
- bin_pred = np.bincount(idx, weights=w * p, minlength=len(edges))
983
+ c = core
984
+ if c is not None and not np.isnan(edges).any():
985
+ # Bin search and the three weighted bin sums in one compiled pass, in input order as np.bincount.
986
+ views = [array_view(a, np.float64) for a in (y, p, w)]
987
+ sums = c.calibration_bins(*(v for _, v in views), [float(e) for e in edges[1:-1]])
988
+ bin_w, bin_true, bin_pred = (np.array(x) for x in sums)
989
+ else:
990
+ idx = np.searchsorted(edges[1:-1], p, side="right")
991
+ bin_w = np.bincount(idx, weights=w, minlength=len(edges))
992
+ bin_true = np.bincount(idx, weights=w * y, minlength=len(edges))
993
+ bin_pred = np.bincount(idx, weights=w * p, minlength=len(edges))
987
994
  keep = bin_w > 0
988
995
  return bin_true[keep] / bin_w[keep], bin_pred[keep] / bin_w[keep], bin_w[keep]
989
996
 
@@ -74,8 +74,13 @@ def _trajectories(x: Any, name: str = "trajectories") -> list[list[dict[str, Any
74
74
  return out
75
75
 
76
76
 
77
+ # One reusable encoder: json.dumps(..., sort_keys=True, default=str) builds a new encoder on every call, which
78
+ # dominated the tool-call metrics; the output is byte-identical.
79
+ _KEY_ENCODER = json.JSONEncoder(sort_keys=True, default=str)
80
+
81
+
77
82
  def _key(call: Mapping[str, Any]) -> str:
78
- return json.dumps([call["name"], call["arguments"]], sort_keys=True, default=str)
83
+ return _KEY_ENCODER.encode([call["name"], call["arguments"]])
79
84
 
80
85
 
81
86
  @register(
@@ -323,10 +323,20 @@ def _unit(x: Any, name: str) -> np.ndarray:
323
323
  higher_is_better=None,
324
324
  )
325
325
  def weat_effect_size(
326
- X: Any, Y: Any, A: Any, B: Any, *, n_permutations: int = 10_000, random_state: Optional[int] = None
326
+ X: Any,
327
+ Y: Any,
328
+ A: Any,
329
+ B: Any,
330
+ *,
331
+ n_permutations: int = 10_000,
332
+ random_state: Optional[int] = None,
333
+ resampling: str = "numpy",
327
334
  ) -> MetricResult:
328
335
  """Embeddings (rows) of the two target sets and two attribute sets. The one-sided p-value uses random
329
- equal-size re-partitions of X ∪ Y (exact enumeration is used when it is smaller)."""
336
+ equal-size re-partitions of X ∪ Y (exact enumeration is used when it is smaller, in the compiled core when
337
+ available, with identical results). ``resampling="native"`` (opt-in) draws the random re-partitions in the
338
+ compiled core, in parallel: reproducible with ``random_state`` but a different random stream from the
339
+ default NumPy one, so the p-value differs slightly."""
330
340
  x, y, a, b = (_unit(v, n) for v, n in ((X, "X"), (Y, "Y"), (A, "A"), (B, "B")))
331
341
  dims = {m.shape[1] for m in (x, y, a, b)}
332
342
  if len(dims) != 1:
@@ -342,13 +352,27 @@ def weat_effect_size(
342
352
  rng = np.random.default_rng(random_state)
343
353
  n, nx = s.size, len(x)
344
354
  total = s.sum()
345
- if math.comb(n, nx) <= n_permutations:
355
+ if resampling not in ("numpy", "native"):
356
+ raise InputValidationError("resampling must be 'numpy' or 'native'.")
357
+ c = core
358
+ if resampling == "native" and c is None:
359
+ raise InputValidationError("resampling='native' needs the compiled core, which is not available.")
360
+ threshold = float(stat - 1e-12)
361
+ exact = math.comb(n, nx) <= n_permutations
362
+ if c is not None and (exact or resampling == "native"):
363
+ # Exact enumeration is bit-identical to the loop below; random splits only on opt-in.
364
+ trials = None if exact else int(n_permutations)
365
+ seed = 0 if exact else int(rng.integers(0, 2**63))
366
+ hits = c.split_permutation_count(s.tolist(), nx, float(total), threshold, trials, seed)
367
+ p = hits / (math.comb(n, nx) if exact else int(n_permutations))
368
+ elif exact:
346
369
  from itertools import combinations
347
370
 
348
- stats_ = np.array([2 * s[list(c)].sum() - total for c in combinations(range(n), nx)])
371
+ stats_ = np.array([2 * s[list(c_)].sum() - total for c_ in combinations(range(n), nx)])
372
+ p = float((stats_ >= threshold).mean())
349
373
  else:
350
374
  stats_ = np.array([2 * s[rng.permutation(n)[:nx]].sum() - total for _ in range(n_permutations)])
351
- p = float((stats_ >= stat - 1e-12).mean())
375
+ p = float((stats_ >= threshold).mean())
352
376
  return MetricResult(
353
377
  "weat_effect_size", "WEAT effect size", float(d), {"p_value": p, "test_statistic": float(stat)}
354
378
  )
@@ -11,7 +11,7 @@ import numpy as np
11
11
  from numpy.typing import NDArray
12
12
 
13
13
  from .._native import array_view, core
14
- from ..core.exceptions import InputValidationError, StatisticalTestError
14
+ from ..core.exceptions import EvalSuiteError, InputValidationError, StatisticalTestError
15
15
  from ..core.validation import target_type, to_numpy
16
16
 
17
17
  MetricFn = Callable[..., Any]
@@ -203,6 +203,78 @@ class MetricCall:
203
203
  counts: NDArray[np.uint64] = np.frombuffer(raw, dtype=np.uint64).reshape(indices.shape[0], kk)
204
204
  return counts
205
205
 
206
+ def _curve_inputs(self) -> Optional[tuple[Any, ...]]:
207
+ """(core, target, score, weights or None) when this call is binary ROC AUC / average precision with class
208
+ labels fixed across subsets (so a subset's 0/1 target is the full target at its indices), else None."""
209
+ from ..classification.metrics import _binary_target, _ctx, average_precision, roc_auc
210
+
211
+ c = core
212
+ if c is None or self.items or self.fn not in (roc_auc, average_precision):
213
+ return None
214
+ kw = self.kwargs
215
+ if "labels" not in kw or set(kw) - {"labels", "pos_label", "average", "multi_class"}:
216
+ return None
217
+ if kw.get("multi_class", "ovr") != "ovr" or kw.get("average", "auto") not in ("auto", "macro", "binary"):
218
+ return None
219
+ try:
220
+ ctx = _ctx(self.y_true, None, y_prob=self.second, labels=kw["labels"], sample_weight=self.weight)
221
+ if ctx.target_type != "binary":
222
+ return None
223
+ target = _binary_target(ctx, kw.get("pos_label"))
224
+ except EvalSuiteError:
225
+ return None
226
+ score = np.ascontiguousarray(ctx.y_prob, dtype=np.float64)
227
+ w = None if self.weight is None else np.ascontiguousarray(ctx.weights, dtype=np.float64)
228
+ return c, np.ascontiguousarray(target, dtype=np.float64), score, w
229
+
230
+ def _curve_values(self, stats: list[tuple[float, float, float, float]]) -> NDArray[np.float64]:
231
+ from ..classification.metrics import roc_auc
232
+
233
+ out = np.empty(len(stats))
234
+ for b, (auc, ap, tp, fp) in enumerate(stats):
235
+ if self.fn is roc_auc:
236
+ out[b] = auc if tp != 0 and fp != 0 else np.nan
237
+ else:
238
+ out[b] = ap if tp != 0 else np.nan
239
+ return out
240
+
241
+ def batch_curves(self, indices: NDArray[np.int64]) -> Optional[NDArray[np.float64]]:
242
+ """Binary ROC AUC or average precision on every resample at once (compiled core, resamples in parallel),
243
+ NaN where undefined; None when not applicable (the caller evaluates resamples one by one). Bit-identical
244
+ to calling the metric on each resample."""
245
+ inputs = self._curve_inputs() if indices.ndim == 2 and indices.shape[0] else None
246
+ if inputs is None:
247
+ return None
248
+ c, target, score, w = inputs
249
+ idx, idx_v = array_view(indices, np.int64)
250
+ stats = c.bootstrap_curves(
251
+ array_view(target, np.float64)[1],
252
+ array_view(score, np.float64)[1],
253
+ None if w is None else array_view(w, np.float64)[1],
254
+ idx_v,
255
+ idx.shape[0],
256
+ )
257
+ return self._curve_values(stats)
258
+
259
+ def leave_out_curves(self, blocks: list[NDArray[Any]]) -> Optional[NDArray[np.float64]]:
260
+ """The metric without each block (jackknife), all blocks at once in the compiled core; None if not
261
+ applicable. Bit-identical to calling the metric on the kept observations."""
262
+ inputs = self._curve_inputs() if blocks else None
263
+ if inputs is None:
264
+ return None
265
+ c, target, score, w = inputs
266
+ group_of = np.empty(self.n, dtype=np.uint32)
267
+ for g, block in enumerate(blocks):
268
+ group_of[block] = g
269
+ stats = c.leave_group_out_curves(
270
+ array_view(target, np.float64)[1],
271
+ array_view(score, np.float64)[1],
272
+ None if w is None else array_view(w, np.float64)[1],
273
+ array_view(group_of, np.uint32)[1],
274
+ len(blocks),
275
+ )
276
+ return self._curve_values(stats)
277
+
206
278
  def from_counts(self, counts: NDArray[Any], idx: Optional[NDArray[np.int64]] = None) -> float:
207
279
  """The metric on observations summarised by ``counts`` (equal to calling it on them directly)."""
208
280
  if self._labels is None: # pragma: no cover - guarded by callers
@@ -101,6 +101,10 @@ def resample_indices(
101
101
 
102
102
  def bootstrap_distribution(call: MetricCall, indices: NDArray[np.int64]) -> tuple[NDArray[np.float64], int]:
103
103
  """Metric value on each resample; resamples where the metric is undefined become NaN."""
104
+ # Binary ROC AUC / average precision: every resample's curve in one parallel compiled call.
105
+ curves = call.batch_curves(indices)
106
+ if curves is not None:
107
+ return curves, int(np.isnan(curves).sum())
104
108
  values = np.empty(indices.shape[0])
105
109
  failed = 0
106
110
  # Confusion-matrix metrics: count every resample's (true, predicted) pairs in one compiled pass.
@@ -119,6 +123,9 @@ def bootstrap_distribution(call: MetricCall, indices: NDArray[np.int64]) -> tupl
119
123
  def _jackknife(call: MetricCall, n: int, rng: np.random.Generator, groups: int) -> NDArray[np.float64]:
120
124
  """Leave-one-out (or leave-one-group-out for large n) estimates for the BCa acceleration."""
121
125
  blocks = [np.array([i]) for i in range(n)] if n <= groups else np.array_split(rng.permutation(n), groups)
126
+ fast = call.leave_out_curves(blocks)
127
+ if fast is not None:
128
+ return fast
122
129
  everything = np.arange(n)
123
130
  out = np.empty(len(blocks))
124
131
  # Confusion-matrix metrics: the counts without a block are the full counts minus the block's.
@@ -317,9 +324,19 @@ def delong_placements(
317
324
  from ..core.exceptions import MetricInputError
318
325
 
319
326
  raise MetricInputError("DeLong's method needs at least one positive and one negative observation.")
320
- tx = np.apply_along_axis(stats.rankdata, 1, pos)
321
- ty = np.apply_along_axis(stats.rankdata, 1, neg)
322
- tz = np.apply_along_axis(stats.rankdata, 1, np.concatenate([pos, neg], axis=1))
327
+ c = core
328
+ if c is not None:
329
+ # One compiled sort per column gives all three rankings (exact half-integer mid-ranks).
330
+ keep = np.ascontiguousarray(y == 1)
331
+ cols = [np.ascontiguousarray(row, dtype=np.float64) for row in scores]
332
+ out = c.delong_ranks(array_view(keep, np.bool_)[1], [array_view(col, np.float64)[1] for col in cols])
333
+ as_rows = [np.vstack([np.frombuffer(r[j], dtype=np.float64) for r in out]) for j in range(4)]
334
+ tz = np.concatenate([as_rows[0], as_rows[1]], axis=1)
335
+ tx, ty = as_rows[2], as_rows[3]
336
+ else:
337
+ tx = np.apply_along_axis(stats.rankdata, 1, pos)
338
+ ty = np.apply_along_axis(stats.rankdata, 1, neg)
339
+ tz = np.apply_along_axis(stats.rankdata, 1, np.concatenate([pos, neg], axis=1))
323
340
  auc = (tz[:, :m].sum(axis=1) - m * (m + 1) / 2) / (m * n)
324
341
  v10 = (tz[:, :m] - tx) / n
325
342
  v01 = 1.0 - (tz[:, m:] - ty) / m
evalsuite/text/qa.py CHANGED
@@ -9,6 +9,7 @@ from typing import Any, Optional
9
9
 
10
10
  import numpy as np
11
11
 
12
+ from .._native import core
12
13
  from ..core.exceptions import InputValidationError
13
14
  from ..core.registry import register
14
15
  from ..core.result import MetricResult
@@ -25,6 +26,14 @@ _ARTICLES = re.compile(r"\b(a|an|the)\b", re.UNICODE)
25
26
  _PUNCT = set(string.punctuation)
26
27
 
27
28
 
29
+ def normalize_answers(texts: list[str]) -> list[str]:
30
+ """``normalize_answer`` of each text: ASCII texts in the compiled core (one call), others in Python."""
31
+ c = core
32
+ if c is None:
33
+ return [normalize_answer(t) for t in texts]
34
+ return [n if n is not None else normalize_answer(t) for n, t in zip(c.squad_normalize(texts), texts)]
35
+
36
+
28
37
  def normalize_answer(text: str) -> str:
29
38
  """SQuAD normalization: lowercase, drop punctuation and the articles a/an/the, collapse whitespace."""
30
39
  text = text.lower()
@@ -55,6 +64,16 @@ def _f1(pred: str, ref: str) -> float:
55
64
  return 2 * precision * recall / (precision + recall)
56
65
 
57
66
 
67
+ def _native_scores(preds: list[str], refs: list[list[str]], normalize: Any, f1: bool) -> Optional[list[float]]:
68
+ """Exact match / token F1 per example from the compiled core, for SQuAD (``True``) or no normalisation on
69
+ ASCII text; None (use Python) without the core, for a custom normaliser or for non-ASCII text."""
70
+ c = core
71
+ if c is None or not (normalize is True or normalize is False or normalize is None):
72
+ return None
73
+ out: Optional[list[float]] = c.qa_scores(preds, refs, normalize is True, f1)
74
+ return out
75
+
76
+
58
77
  def _finish(metric: str, name: str, scores: list[float], average: Optional[str], normalize: Any) -> MetricResult:
59
78
  arr = np.array(scores, dtype=float)
60
79
  value: Any = arr if average is None else float(arr.mean())
@@ -81,7 +100,9 @@ def exact_match(
81
100
  preds = as_texts(predictions, "predictions")
82
101
  refs = as_references(references, len(preds))
83
102
  f = _norm(normalize)
84
- scores = [float(any(f(p) == f(r) for r in rs)) for p, rs in zip(preds, refs)]
103
+ scores = _native_scores(preds, refs, normalize, f1=False)
104
+ if scores is None:
105
+ scores = [float(any(f(p) == f(r) for r in rs)) for p, rs in zip(preds, refs)]
85
106
  return _finish("exact_match", "Exact match", scores, average, normalize)
86
107
 
87
108
 
@@ -104,5 +125,7 @@ def token_f1(
104
125
  preds = as_texts(predictions, "predictions")
105
126
  refs = as_references(references, len(preds))
106
127
  f = _norm(normalize)
107
- scores = [max(_f1(f(p), f(r)) for r in rs) for p, rs in zip(preds, refs)]
128
+ scores = _native_scores(preds, refs, normalize, f1=True)
129
+ if scores is None:
130
+ scores = [max(_f1(f(p), f(r)) for r in rs) for p, rs in zip(preds, refs)]
108
131
  return _finish("token_f1", "Token F1", scores, average, normalize)
@@ -13,7 +13,7 @@ from ..core.exceptions import InputValidationError
13
13
  from ..core.registry import register
14
14
  from ..core.result import MetricResult
15
15
  from ._common import _seq, as_references, check_positive_int, per_item
16
- from .qa import _norm
16
+ from .qa import _norm, normalize_answers
17
17
 
18
18
  __all__ = ["benchmark_accuracy", "extract_answer", "majority_vote_accuracy", "pass_at_k"]
19
19
 
@@ -88,17 +88,30 @@ def majority_vote_accuracy(
88
88
  scores = []
89
89
  c = core
90
90
  if c is not None:
91
- normed = []
92
91
  for i, answers in enumerate(groups):
93
92
  if isinstance(answers, str) or not answers:
94
93
  raise InputValidationError(f"samples[{i}] must be a non-empty list of answer strings.")
95
- normed.append([f(str(a)) for a in answers])
94
+ if normalize is True:
95
+ # SQuAD normalisation of every answer and reference in one compiled call.
96
+ flat = normalize_answers([str(a) for answers in groups for a in answers])
97
+ normed, pos = [], 0
98
+ for answers in groups:
99
+ normed.append(flat[pos : pos + len(answers)])
100
+ pos += len(answers)
101
+ ref_norm = normalize_answers([r for rs in refs for r in rs])
102
+ nrefs, pos = [], 0
103
+ for rs in refs:
104
+ nrefs.append(ref_norm[pos : pos + len(rs)])
105
+ pos += len(rs)
106
+ else:
107
+ normed = [[f(str(a)) for a in answers] for answers in groups]
108
+ nrefs = [[f(r) for r in rs] for rs in refs]
96
109
  v = Vocab()
97
110
  stats = c.group_stats([v.encode(g) for g in normed])
98
111
  table = list(v.ids)
99
- for st, rs in zip(stats, refs):
112
+ for st, rs in zip(stats, nrefs):
100
113
  top = table[st[4]] # the modal answer, first seen among ties, as Counter.most_common
101
- scores.append(float(any(top == f(r) for r in rs)))
114
+ scores.append(float(any(top == r for r in rs)))
102
115
  else:
103
116
  for i, (answers, rs) in enumerate(zip(groups, refs)):
104
117
  if isinstance(answers, str) or not answers:
evalsuite/version.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """Package version (single source of truth, read by the build backend)."""
2
2
 
3
- __version__ = "0.7.0"
3
+ __version__ = "0.8.0"
@@ -36,6 +36,7 @@ else:
36
36
 
37
37
  ndimage = lazy_module("scipy.ndimage")
38
38
 
39
+ from .._native import array_view, core
39
40
  from ..core.exceptions import InputValidationError, UndefinedMetricWarning
40
41
  from ..core.export import PathLike, csv_text, html_document, html_table, save_as
41
42
  from ..core.registry import register
@@ -559,6 +560,21 @@ def _surface_distances(
559
560
  return np.asarray(d_ab, dtype=np.float64), np.asarray(d_ba, dtype=np.float64)
560
561
 
561
562
 
563
+ def _native_surface_distances(
564
+ a: NDArray[np.bool_], b: NDArray[np.bool_], spacing: Optional[Sequence[float]]
565
+ ) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
566
+ """Surface distances of two non-empty masks: the compiled core for 2-D and 3-D masks (surfaces and an
567
+ exact grid nearest-point search, same arithmetic as the direct comparison), Python otherwise."""
568
+ c = core
569
+ if c is None or a.ndim not in (2, 3):
570
+ return _surface_distances(_surface(a), _surface(b), spacing)
571
+ sp = [1.0] * a.ndim if spacing is None else [float(x) for x in spacing]
572
+ _a, va = array_view(a, np.bool_)
573
+ _b, vb = array_view(b, np.bool_)
574
+ da, db = c.surface_distances(va, vb, list(a.shape), sp)
575
+ return np.frombuffer(da, dtype=np.float64), np.frombuffer(db, dtype=np.float64)
576
+
577
+
562
578
  def _check_spacing(spacing: Optional[Sequence[float]], ndim: int) -> Optional[tuple[float, ...]]:
563
579
  if spacing is None:
564
580
  return None
@@ -604,7 +620,7 @@ def _surface_metric(
604
620
  values[i, j] = math.inf
605
621
  one_empty += 1
606
622
  continue
607
- d_ab, d_ba = _surface_distances(_surface(ta), _surface(pb), sp)
623
+ d_ab, d_ba = _native_surface_distances(ta, pb, sp)
608
624
  if which == "hd":
609
625
  if percentile == 100:
610
626
  values[i, j] = max(float(np.max(d_ab)), float(np.max(d_ba)))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: evalsuite-python
3
- Version: 0.7.0
3
+ Version: 0.8.0
4
4
  Summary: A unified Python framework for machine-learning, clinical, statistical, segmentation, object-detection, uncertainty, and model evaluation.
5
5
  Project-URL: Homepage, https://evalsuite-nine.vercel.app
6
6
  Project-URL: Documentation, https://evalsuite-nine.vercel.app/docs
@@ -85,11 +85,15 @@ Description-Content-Type: text/markdown
85
85
  EvalSuite brings classification, regression, clinical, statistical, segmentation and object-detection
86
86
  evaluation into one consistent, validated, documented framework.
87
87
 
88
- > **Status: stable (0.7.0).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
88
+ > **Status: stable (0.8.0).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
89
89
  > **0.6 adds a compiled Rust core**: same API and identical results, with text metrics, COCO evaluation and
90
90
  > bootstrap resampling several times faster and multithreaded (prebuilt wheels for Linux, macOS and Windows).
91
91
  > **0.7.0** moves ROC AUC / average precision (and so `evaluate()`), the LLM-systems consistency metrics,
92
92
  > groundedness, citation coverage, toxicity, exposure and Elo into the core.
93
+ > **0.7.1** adds bootstrapped ROC AUC / AP (4–5× faster intervals), DeLong, QA exact match / F1,
94
+ > Hausdorff / surface distances, calibration and the WEAT permutation test.
95
+ > **0.8.0** adds a **full Rust edition on crates.io** ([`evalsuite`](https://crates.io/crates/evalsuite)): every
96
+ > metric except `code_complexity`, checked case by case against this package.
93
97
  > **LLM systems arrive in 0.5.0**: safety, robustness, calibration and uncertainty, agents and tool use,
94
98
  > multilingual, code generation, long context and summarization, and inference efficiency and cost.
95
99
 
@@ -113,10 +117,26 @@ is needed. Anywhere else pip falls back to a pure-Python wheel that gives exactl
113
117
 
114
118
  The core runs independent examples (sentences, images, classes, resamples) in parallel on all CPU cores; set
115
119
  `EVALSUITE_NUM_THREADS` to cap the number of threads. Results never depend on the thread count: sums are always
116
- taken in example order. Bootstrap functions (`bootstrap_ci`, `paired_bootstrap_test`, `compare`) accept
117
- `resampling="native"` to draw resample indices in the core (seeded xoshiro256++): reproducible with
118
- `random_state` and faster on large inputs, but a different random stream from the default NumPy one, so the
119
- interval endpoints differ slightly (statistically equivalent).
120
+ taken in example order. Bootstrap functions (`bootstrap_ci`, `paired_bootstrap_test`, `compare`) and
121
+ `weat_effect_size` accept `resampling="native"` to draw resamples (or permutations) in the core (seeded
122
+ xoshiro256++): reproducible with `random_state` and faster on large inputs, but a different random stream from
123
+ the default NumPy one, so interval endpoints and p-values differ slightly (statistically equivalent).
124
+
125
+ ### Rust
126
+
127
+ The same metrics are available as a pure-Rust crate, verified against this package on 36,054 recorded cases:
128
+
129
+ ```toml
130
+ [dependencies]
131
+ evalsuite = "0.8"
132
+ ```
133
+
134
+ ```rust
135
+ let acc = evalsuite::classification::accuracy(&[1, 0, 1, 1], &[1, 0, 0, 1], None).unwrap(); // 0.75
136
+ ```
137
+
138
+ See [rust/evalsuite/README.md](rust/evalsuite/README.md) for the module list and the few documented
139
+ differences.
120
140
 
121
141
  ## Why EvalSuite
122
142
 
@@ -358,55 +378,57 @@ Input files can be CSV, TSV, Parquet or JSON. Output format follows `--format` o
358
378
 
359
379
  ## Performance
360
380
 
361
- Benchmarked against reference implementations on the same data (fastest of 5 runs; EvalSuite 0.7.0, Python 3.13,
381
+ Benchmarked against reference implementations on the same data (fastest of 5 runs; EvalSuite 0.7.1, Python 3.13,
362
382
  NumPy 2.5, Linux x86_64). **Overall: 81 of 81 rows agree with the reference** (largest
363
- difference 2.5e-14), 79 are faster (the other 2 are Hochberg correction at 1,000,000 p-values, 0.8–1.05× statsmodels across runs,
364
- and latency percentiles, within timing noise of NumPy), and the geometric-mean speed-up across all
365
- 27 cases and three sizes is **4.22×**. At 1,000,000 samples (pixels for
383
+ difference 2.5e-14), 80 are faster (the other, the maintainability index, runs Python's own `ast` parser
384
+ like radon and lands at 0.89× on this run), and the geometric-mean speed-up across all
385
+ 27 cases and three sizes is **4.30×**. At 1,000,000 samples (pixels for
366
386
  segmentation; 1,000 images for detection and 50 for Hausdorff; 10,000 examples for the LLM cases), in
367
387
  alphabetical order:
368
388
 
369
389
  | Case | Reference | EvalSuite (ms) | Reference (ms) | Speed-up |
370
390
  | --- | --- | ---: | ---: | ---: |
371
- | 10 classes: macro F1 | scikit-learn | 7.1 | 109.5 | **15.5×** |
372
- | agreement: Krippendorff's alpha, interval (4 raters × 10000 items) | krippendorff | 1.3 | 2.7 | **2.2×** |
373
- | binary: 8 label metrics via evaluate() | scikit-learn | 9.8 | 860.9 | **87.6×** |
374
- | binary: ROC AUC | scikit-learn | 84.8 | 267.7 | **3.2×** |
375
- | calibration: slope and intercept | statsmodels | 179.6 | 946.7 | **5.3×** |
376
- | clinical: diagnostic report (7 CIs) | statsmodels | 4.4 | 4.7 | **1.1×** |
377
- | clinical: sensitivity, specificity, LR+, LR− | scikit-learn | 17.7 | 328.1 | **18.5×** |
378
- | decision curve: 99 thresholds | NumPy loop | 133.1 | 168.4 | **1.3×** |
379
- | detection: COCO evaluation (1000 images) | pycocotools | 30.3 | 616.3 | **20.4×** |
380
- | multiple testing: Hochberg (n p-values) | statsmodels | 86.4 | 69.9 | 0.81× |
381
- | regression: MAE, MSE, RMSE, R² via evaluate() | scikit-learn | 6.2 | 9.9 | **1.6×** |
382
- | retrieval: MRR, MAP@20, NDCG@10 (10000 queries) | ranx | 118.3 | 577.6 | **4.9×** |
383
- | segmentation: Dice and IoU per class (n = pixels) | scikit-learn | 29.3 | 215.2 | **7.3×** |
384
- | segmentation: Hausdorff distance (50 images) | SciPy | 8.7 | 14.1 | **1.6×** |
385
- | statistics: Cramér's V (5×5 table) | SciPy | 0.0 | 0.2 | **12.0×** |
386
- | statistics: Mann–Whitney U | SciPy | 115.1 | 305.0 | **2.6×** |
387
- | statistics: Welch t-test | SciPy | 4.9 | 7.2 | **1.5×** |
388
- | structured: JSON Schema compliance (10000 documents) | jsonschema | 100.6 | 224.3 | **2.2×** |
389
- | systems: CodeBLEU n-gram terms (1000 programs) | codebleu | 313.9 | 511.3 | **1.6×** |
390
- | systems: confidence AUROC (n answers) | scikit-learn | 181.2 | 279.3 | **1.5×** |
391
- | systems: distribution-shift drop, Welch CI (n scores) | SciPy | 8.6 | 9.8 | **1.1×** |
392
- | systems: invalid tool calls vs JSON Schema (10000 tasks) | jsonschema | 109.2 | 219.3 | **2.0×** |
393
- | systems: latency p50 / p95 / p99 (n requests) | NumPy | 12.9 | 12.5 | 0.97× |
394
- | systems: maintainability index (1000 programs) | radon | 88.6 | 98.7 | **1.1×** |
395
- | text: corpus BLEU and chrF (10000 sentences) | sacreBLEU | 165.0 | 2030.3 | **12.3×** |
396
- | text: METEOR, exact and stem matches (10000 sentences) | NLTK | 63.8 | 363.8 | **5.7×** |
397
- | text: ROUGE-1, ROUGE-2, ROUGE-L (10000 sentences) | rouge-score | 152.8 | 613.6 | **4.0×** |
391
+ | 10 classes: macro F1 | scikit-learn | 9.2 | 106.2 | **11.5×** |
392
+ | agreement: Krippendorff's alpha, interval (4 raters × 10000 items) | krippendorff | 1.7 | 3.6 | **2.1×** |
393
+ | binary: 8 label metrics via evaluate() | scikit-learn | 10.0 | 932.8 | **93.4×** |
394
+ | binary: ROC AUC | scikit-learn | 86.2 | 305.1 | **3.5×** |
395
+ | calibration: slope and intercept | statsmodels | 209.6 | 1146.2 | **5.5×** |
396
+ | clinical: diagnostic report (7 CIs) | statsmodels | 5.2 | 5.9 | **1.1×** |
397
+ | clinical: sensitivity, specificity, LR+, LR− | scikit-learn | 20.9 | 381.9 | **18.3×** |
398
+ | decision curve: 99 thresholds | NumPy loop | 145.7 | 190.2 | **1.3×** |
399
+ | detection: COCO evaluation (1000 images) | pycocotools | 37.2 | 731.1 | **19.7×** |
400
+ | multiple testing: Hochberg (n p-values) | statsmodels | 74.3 | 79.7 | **1.1×** |
401
+ | regression: MAE, MSE, RMSE, R² via evaluate() | scikit-learn | 7.9 | 13.4 | **1.7×** |
402
+ | retrieval: MRR, MAP@20, NDCG@10 (10000 queries) | ranx | 156.1 | 583.6 | **3.7×** |
403
+ | segmentation: Dice and IoU per class (n = pixels) | scikit-learn | 36.1 | 248.7 | **6.9×** |
404
+ | segmentation: Hausdorff distance (50 images) | SciPy | 4.6 | 16.6 | **3.6×** |
405
+ | statistics: Cramér's V (5×5 table) | SciPy | 0.0 | 0.2 | **12.4×** |
406
+ | statistics: Mann–Whitney U | SciPy | 135.5 | 303.6 | **2.2×** |
407
+ | statistics: Welch t-test | SciPy | 7.1 | 10.4 | **1.5×** |
408
+ | structured: JSON Schema compliance (10000 documents) | jsonschema | 103.6 | 211.7 | **2.0×** |
409
+ | systems: CodeBLEU n-gram terms (1000 programs) | codebleu | 334.9 | 592.4 | **1.8×** |
410
+ | systems: confidence AUROC (n answers) | scikit-learn | 162.4 | 265.7 | **1.6×** |
411
+ | systems: distribution-shift drop, Welch CI (n scores) | SciPy | 8.4 | 9.6 | **1.1×** |
412
+ | systems: invalid tool calls vs JSON Schema (10000 tasks) | jsonschema | 108.1 | 252.4 | **2.3×** |
413
+ | systems: latency p50 / p95 / p99 (n requests) | NumPy | 13.2 | 15.0 | **1.1×** |
414
+ | systems: maintainability index (1000 programs) | radon | 100.8 | 89.5 | 0.89× |
415
+ | text: corpus BLEU and chrF (10000 sentences) | sacreBLEU | 206.2 | 2405.2 | **11.7×** |
416
+ | text: METEOR, exact and stem matches (10000 sentences) | NLTK | 72.2 | 404.0 | **5.6×** |
417
+ | text: ROUGE-1, ROUGE-2, ROUGE-L (10000 sentences) | rouge-score | 179.5 | 678.9 | **3.8×** |
398
418
 
399
419
  **Every metric is benchmarked too** (`evalsuite benchmark --suite metrics`): all 225 registered metrics and
400
420
  statistics functions at 10,000 and 100,000 samples. 86 are compared with a reference library, 118 with an
401
421
  independent textbook formula and 21 (learned, judge-dependent or randomised) are timed alone; **all 204
402
- comparisons agree**, and against the libraries the geometric-mean speed-up is **6.44×** (172 of 172
422
+ comparisons agree**, and against the libraries the geometric-mean speed-up is **6.64×** (171 of 172
403
423
  measurements faster). Per-metric table in BENCHMARKS.md.
404
424
 
405
425
  **Nearly every workload is faster than its reference.** The text metrics (BLEU, chrF, TER, ROUGE, METEOR, CIDEr,
406
426
  CodeBLEU's n-gram terms, distinct-n), the whole COCO evaluation (IoU, score sort, matching, accumulation),
407
427
  ROC AUC and average precision (one sort per column, shared by both inside `evaluate()`), the LLM-systems
408
- consistency, groundedness, citation, toxicity and exposure metrics, Elo ratings and bootstrap resampling run in
409
- the compiled, multithreaded Rust core; bootstrap intervals, paired bootstrap tests and
428
+ consistency, groundedness, citation, toxicity and exposure metrics, Elo ratings, bootstrap resampling (including
429
+ whole bootstrap and jackknife runs of ROC AUC / AP), DeLong, QA exact match and F1,
430
+ Hausdorff and surface distances, calibration bins and the WEAT permutation test run in the compiled,
431
+ multithreaded Rust core; bootstrap intervals, paired bootstrap tests and
410
432
  `compare()` evaluate confusion-matrix metrics from counts of each resample's (true, predicted) pairs instead of
411
433
  copies of the data. `evaluate()` validates inputs once and builds the confusion
412
434
  matrix once for all metrics, and integer labels are encoded without sorting. The rank tests rank the data once
@@ -503,6 +525,7 @@ fallback; `tests/test_native.py` checks that the two give identical results. See
503
525
  ## Links
504
526
 
505
527
  - PyPI: https://pypi.org/project/evalsuite-python/
528
+ - crates.io: https://crates.io/crates/evalsuite
506
529
  - Website and documentation: https://evalsuite-nine.vercel.app
507
530
  - Website source: https://github.com/mkcs28/evalsuite
508
531
 
@@ -9,10 +9,10 @@ evalsuite/calibration.py,sha256=jhCPOmCFGEkUkcx-hSAIb-JCMq9oF6JZt4uDGvg5NaU,1508
9
9
  evalsuite/plot.py,sha256=7eOyzoRbg6Aad6OhtIQG3laIioQ8fs2K0YzodjG5rHA,26049
10
10
  evalsuite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
11
  evalsuite/reporting.py,sha256=-LISv9vvEnltT26GtzLjVlxOCcAwmjv4-HyB8_1UF5o,9615
12
- evalsuite/version.py,sha256=8M6dtrDVoomwqNJzgGQtnZ4mKMsyWATsoYVmgq8bZss,98
12
+ evalsuite/version.py,sha256=WEve49PRk7vN8bX-peJUcFFovY0yuTYmAI9RjuQ29Jg,98
13
13
  evalsuite/classification/__init__.py,sha256=ErBIXbBGnhfW6v-1Cn5SegiERoyxNlmO1tEKcLM15mA,833
14
14
  evalsuite/classification/_common.py,sha256=3ANV33ix_mnOzvOAG8glyJO-iYVhhTGO0S3YG0ZddB8,4543
15
- evalsuite/classification/metrics.py,sha256=frSH4Q7-fljA-XDLFTk3djkMrey6WPqJXQUL8hd-9iA,40160
15
+ evalsuite/classification/metrics.py,sha256=cP9TAVVk6Pob2VUuxMfQpOakzVmuMOXzGzqO2oGhED8,40575
16
16
  evalsuite/cli/__init__.py,sha256=1x48hORLcg_Is2X08A7CPBT6VDJ1QL94zaJP1HTFxUY,96
17
17
  evalsuite/cli/main.py,sha256=ktvy_5D-KfYevKH5ZxO5f0aVFtNXbGeN8zker0tguT0,23994
18
18
  evalsuite/clinical/__init__.py,sha256=xaXLvNvTJsuP525fLb2FyVVNlopIrZczoPrwmEQIvzE,549
@@ -28,22 +28,22 @@ evalsuite/core/types.py,sha256=r6bhUk7CYAcrlQzjmf-6xWQsNqO3EOipZD-e-2yAJTI,720
28
28
  evalsuite/core/validation.py,sha256=nZRWSuShdFBDYgXMnRmspSQ4AJPRO3Zy5M8wTFfkg2E,10988
29
29
  evalsuite/llmsys/__init__.py,sha256=NA-kVMc3hdmBSW-ufPKrgfd2NHI15wCXJRn3ZhIVFsE,4653
30
30
  evalsuite/llmsys/_common.py,sha256=d68CyUaO9f8Olp1001Ms2-9tVSwNf96g0D2BlhpvSF0,10271
31
- evalsuite/llmsys/agents.py,sha256=giiHv3c179fFR6aFUp4VbBjzbdNotS941tZVG7W0UFE,15355
31
+ evalsuite/llmsys/agents.py,sha256=OYLadZTjuviDV90ZffEDYCRuDyU5rPgpNhiZU894bEk,15574
32
32
  evalsuite/llmsys/code.py,sha256=OIyH3aKbuzmH3131wfkj98k5QrrvPwQ1dvCCY4WXD4Y,37528
33
33
  evalsuite/llmsys/efficiency.py,sha256=GlUSWNnzRaeuebv-SZYsB28StwIPYb8AIyMwM057g_A,13895
34
34
  evalsuite/llmsys/longcontext.py,sha256=WkMO_vT1kp4Hr1Q1IBFwq70C6Jud2e-LURSWZzoAlNY,15870
35
35
  evalsuite/llmsys/multilingual.py,sha256=5paFTlIE0eTqBEZWXdhJqwBhklRxHDf92uSfr-z_O60,14524
36
36
  evalsuite/llmsys/robustness.py,sha256=Yr1tut2FTodARF-WOLP5jf17GH-zaI0Qy2ZxWmhMhas,20878
37
- evalsuite/llmsys/safety.py,sha256=fjHrTVtwDrMnda987IuW4uPGTr5OSGc349MyGB_tYIk,23747
37
+ evalsuite/llmsys/safety.py,sha256=_IHkLWw87MPD6xaGzt5UU_1w8ryLw30Us-JJUe17n6Q,24934
38
38
  evalsuite/llmsys/uncertainty.py,sha256=Brm_LT8qHb-EtcPe7YBXq7HYMSTG93OkT3Cnx2SYBts,9367
39
39
  evalsuite/regression/__init__.py,sha256=t2XEHUw6e5tyWBHcEeiog2WWd-wwaxf4m5AIX8dJyng,571
40
40
  evalsuite/regression/metrics.py,sha256=Qv5hFswxfzE-8wOKysERqsEJT-3kvTXPrkLoZ7s9jbQ,23487
41
41
  evalsuite/stats/__init__.py,sha256=mtnEqpvlvscQ3C6ceRr8xLKoSHPQWsWB24pEVlvp6fs,1187
42
- evalsuite/stats/_resolve.py,sha256=T5EUqTbiGM0oor59Nzm18GUr7oLWcpgj1l8gCU56ACc,10276
42
+ evalsuite/stats/_resolve.py,sha256=a2Z9rCJ7yNdsIxlCypk94h7Ho-Vewg2ygHahNa7scBU,13829
43
43
  evalsuite/stats/compare.py,sha256=ooO5STzocKrqNsxKvm_C4Bl1c36_7fziCJc-d2cJASA,18531
44
44
  evalsuite/stats/effect.py,sha256=bgnhdCI4vU_Wnv5q7G2ncmtN3n7N1GWiYO4iO3FDI0w,7286
45
45
  evalsuite/stats/hypothesis.py,sha256=RCu8yPTOhtetFQ5TlZQWaFu2t-aq56ffaNlEqC-lJbg,24546
46
- evalsuite/stats/intervals.py,sha256=6v7JG_lY4DWrAdcBqiwKsxvBMLgu1RKjdcXaIiqeYqc,16712
46
+ evalsuite/stats/intervals.py,sha256=bVvj_Rj78eb45IZBcI1Iz3gM9kaonvYutRRI1OyIVrQ,17602
47
47
  evalsuite/stats/paired.py,sha256=guPwpss0XQWRzL4hWL9xE4mgF6bUQQ2FbkNMkyhxrlc,8663
48
48
  evalsuite/stats/results.py,sha256=nqXHUiW8l0fQJkbMiunU6Gz-2be1NApZ6Fif2B1K_Yw,4407
49
49
  evalsuite/text/__init__.py,sha256=_r0Qi6X7cBcaYMAPRyC15CsTj9Tv8VcqMCtLiSJPogY,3632
@@ -51,9 +51,9 @@ evalsuite/text/_common.py,sha256=acjAoPbXlPtd4DC4YbvOv1frIUjvFa1UtbdA5-6YDsU,379
51
51
  evalsuite/text/factuality.py,sha256=RsZu7fl1KU9elB1oBOgms3bnrN4lXVchwqIcl0JDXtc,21212
52
52
  evalsuite/text/generation.py,sha256=qrpOvt2T_Fom2M_6YquEEnJbMCr_KwR1kEqtUH6N0tc,52420
53
53
  evalsuite/text/judge.py,sha256=5DOc-UOUSUPeXwdnjspVEJ-Yhk5659eTQh3jZLVLRfA,23887
54
- evalsuite/text/qa.py,sha256=rU0ya8TzV5mp7UiWq7w9IqSN9B0tDv8xymSaRzzbzMw,4097
54
+ evalsuite/text/qa.py,sha256=ZInaTXzQjxvliu1b2ArcX74OW1UPLXPvYcHGeIgVQH8,5197
55
55
  evalsuite/text/rag.py,sha256=GF8GUp6Vnt9peBCIcdvFUapLUL36_NDApZisYG_rcqg,9641
56
- evalsuite/text/reasoning.py,sha256=wnVM0dFK1XFODsbQuRo9ngpKfh4tKV9cdhhi2uCILnY,9579
56
+ evalsuite/text/reasoning.py,sha256=Z-c66yq5ADiNHh9ZROIvqh1ACwCJ0c3Q7Q0ciA0OS_0,10254
57
57
  evalsuite/text/report.py,sha256=nUAgt24rcQsnPLiNTVn3PlzZO3Y7fW_ch_lSelgfEc8,6241
58
58
  evalsuite/text/retrieval.py,sha256=otQvOTbbR79kYtMum6o2HOT9UoDlSj0-JYLsFddkV1k,8969
59
59
  evalsuite/text/semantic.py,sha256=TgBBDcRll7vMzQVYStgt1SS9G7e6FTf7SuZDcPL32_g,23004
@@ -61,10 +61,10 @@ evalsuite/text/spice.py,sha256=rdPCeilqKkXLMiSAE-rYOn0Zt2nKFum5Tf1oJdE6k-U,6847
61
61
  evalsuite/text/structured.py,sha256=x08yYf2rdlmiA_D_dI1L-fc9quHiBPMKgAGQbG3kJr8,31981
62
62
  evalsuite/vision/__init__.py,sha256=9gpOBTPveM_srE6BM-SgCssdQurya2LPHhoMLGOh2A0,991
63
63
  evalsuite/vision/detection.py,sha256=Cjr-Y5-pV0wiQk1JiHLYvDdKzMlCEvVQarzY7fqGWw4,32010
64
- evalsuite/vision/segmentation.py,sha256=f41Q8iOELCj8jmAJ3pN5OFr3h3-6QtjnluW8rfkg0V0,41132
65
- evalsuite_python-0.7.0.dist-info/METADATA,sha256=wIsTwjgl4BP6BT-vVQY0B_QHZDYvlHrIYg1TrcWq8sM,28857
66
- evalsuite_python-0.7.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
67
- evalsuite_python-0.7.0.dist-info/entry_points.txt,sha256=YYIwisn4L4sQt3ntzbM0_Z4yZE2KCu3GJ6KfWL1kIwc,54
68
- evalsuite_python-0.7.0.dist-info/licenses/LICENSE,sha256=cRRQ6Kk8w2qCqtDSSUJQGy-0rqjmjJG09cZ6iIiMvdc,1095
69
- evalsuite_python-0.7.0.dist-info/licenses/LICENSE-APACHE,sha256=K4pWYv3dt61u1BuIxjOGBxhgRkpsH4X_dzeIbOILXw0,10784
70
- evalsuite_python-0.7.0.dist-info/RECORD,,
64
+ evalsuite/vision/segmentation.py,sha256=tYYsBfEYdPvi94k3dJgp8ODn8X0qKsLW5QAv7KuQMj0,41953
65
+ evalsuite_python-0.8.0.dist-info/METADATA,sha256=T5LDhNjG9TXW4AhoBKcpTTqFfmkLNaEwP5Myp_3qX1s,29849
66
+ evalsuite_python-0.8.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
67
+ evalsuite_python-0.8.0.dist-info/entry_points.txt,sha256=YYIwisn4L4sQt3ntzbM0_Z4yZE2KCu3GJ6KfWL1kIwc,54
68
+ evalsuite_python-0.8.0.dist-info/licenses/LICENSE,sha256=cRRQ6Kk8w2qCqtDSSUJQGy-0rqjmjJG09cZ6iIiMvdc,1095
69
+ evalsuite_python-0.8.0.dist-info/licenses/LICENSE-APACHE,sha256=K4pWYv3dt61u1BuIxjOGBxhgRkpsH4X_dzeIbOILXw0,10784
70
+ evalsuite_python-0.8.0.dist-info/RECORD,,