evalsuite-python 0.5.4__py3-none-any.whl → 0.6.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.
evalsuite/_native.py ADDED
@@ -0,0 +1,60 @@
1
+ """Access to the compiled core (``evalsuite._core``, built from rust/).
2
+
3
+ Every function that has a compiled kernel keeps its Python implementation: it is the reference the kernel is
4
+ tested against and the fallback when the extension is missing (the pure-Python wheel, an unsupported platform)
5
+ or when ``EVALSUITE_PURE_PYTHON=1`` is set. Both give identical results.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from typing import Any, Optional
12
+
13
+ core: Optional[Any]
14
+ if os.environ.get("EVALSUITE_PURE_PYTHON", "").strip().lower() in ("1", "true", "yes", "on"):
15
+ core = None
16
+ else:
17
+ try:
18
+ from . import _core as core # type: ignore[attr-defined, no-redef]
19
+ except ImportError: # pure-Python wheel or source checkout without a build
20
+ core = None
21
+
22
+ HAVE_NATIVE = core is not None
23
+
24
+
25
+ def backend() -> str:
26
+ """``"rust"`` when the compiled core is in use, ``"python"`` otherwise."""
27
+ return "rust" if HAVE_NATIVE else "python"
28
+
29
+
30
+ def array_view(arr: Any, dtype: Any) -> tuple[Any, tuple[int, int]]:
31
+ """A C-contiguous array of exactly ``dtype`` and its ``(data address, element count)`` view for the core.
32
+
33
+ The returned array must stay referenced (keep it in a local variable) until the core call returns; the
34
+ core only reads from it."""
35
+ import numpy as np
36
+
37
+ a = np.ascontiguousarray(arr, dtype=dtype)
38
+ if not a.flags.c_contiguous or a.dtype != np.dtype(dtype): # pragma: no cover - guaranteed by NumPy
39
+ raise ValueError("array must be C-contiguous with the requested dtype")
40
+ return a, (int(a.ctypes.data), int(a.size))
41
+
42
+
43
+ class Vocab:
44
+ """Maps tokens to consecutive integer ids (0, 1, 2, …) so token sequences can cross into the compiled core."""
45
+
46
+ __slots__ = ("ids",)
47
+
48
+ def __init__(self) -> None:
49
+ self.ids: dict[Any, int] = {}
50
+
51
+ def encode(self, tokens: Any) -> list[int]:
52
+ ids = self.ids
53
+ get = ids.get
54
+ out = []
55
+ for t in tokens:
56
+ i = get(t)
57
+ if i is None:
58
+ i = ids[t] = len(ids)
59
+ out.append(i)
60
+ return out
@@ -116,17 +116,64 @@ def by_group(values: np.ndarray, groups: Optional[Sequence[Any]], name: str = "g
116
116
  return out
117
117
 
118
118
 
119
+ def _order_stats_partition(a: np.ndarray, ks: list[int]) -> dict[int, float]:
120
+ part = np.partition(a, ks)
121
+ return {k: float(part[k]) for k in ks}
122
+
123
+
124
+ def _order_stats_bracketed(a: np.ndarray, ks: list[int]) -> Optional[dict[int, float]]:
125
+ """Exact order statistics of a large array without partitioning all of it.
126
+
127
+ A sorted strided sample (about 8k values) brackets each wanted rank; one pass counts the values below the
128
+ bracket and extracts those inside it, and only that small subset is partitioned. Overlapping brackets are
129
+ merged. Returns None if a bracket misses its rank (possible only for adversarially ordered data), and the
130
+ caller falls back to a full partition, so the result is always exact."""
131
+ n = a.size
132
+ s = np.sort(a[:: max(1, n // 8192)])
133
+ ns = s.size
134
+ brackets: list[list[Any]] = []
135
+ for k in ks:
136
+ r = k / (n - 1) * (ns - 1)
137
+ margin = 6 * math.sqrt(max(r * (ns - r) / ns, 1.0)) + 4
138
+ lo_i, hi_i = max(0, math.floor(r - margin)), min(ns - 1, math.ceil(r + margin))
139
+ if brackets and lo_i <= brackets[-1][1]:
140
+ brackets[-1][1] = max(brackets[-1][1], hi_i)
141
+ brackets[-1][2].append(k)
142
+ else:
143
+ brackets.append([lo_i, hi_i, [k]])
144
+ out: dict[int, float] = {}
145
+ for lo_i, hi_i, group in brackets:
146
+ mask = np.ones(n, dtype=bool) if lo_i == 0 else a >= s[lo_i]
147
+ below = 0 if lo_i == 0 else n - int(np.count_nonzero(mask))
148
+ if hi_i < ns - 1:
149
+ mask &= a <= s[hi_i]
150
+ window = a[mask]
151
+ rel = [k - below for k in group]
152
+ if rel[0] < 0 or rel[-1] >= window.size:
153
+ return None
154
+ part = np.partition(window, rel)
155
+ for k, r_ in zip(group, rel):
156
+ out[k] = float(part[r_])
157
+ return out
158
+
159
+
119
160
  def quantiles(a: np.ndarray, qs: Sequence[float]) -> list[float]:
120
- """Percentiles ``qs`` (0-100, linear interpolation, identical to ``np.percentile``) from one partition."""
161
+ """Percentiles ``qs`` (0-100, linear interpolation, as ``np.percentile``). Large arrays use bracketed
162
+ selection on a small window per percentile; small ones one partition. Both are exact."""
121
163
  n = a.size
122
- pos = [(n - 1) * q / 100.0 for q in qs]
123
- lo = [int(np.floor(h)) for h in pos]
124
- kth = sorted({k for i in lo for k in (i, min(i + 1, n - 1))})
125
- part = np.partition(a, kth)
164
+ pos = [(n - 1) * (q / 100.0) for q in qs] # NumPy's order of operations
165
+ lo = [math.floor(h) for h in pos]
166
+ ks = sorted({k for i in lo for k in (i, min(i + 1, n - 1))})
167
+ stats = _order_stats_bracketed(a, ks) if n >= 65536 else None
168
+ if stats is None:
169
+ stats = _order_stats_partition(a, ks)
126
170
  out = []
127
171
  for h, i in zip(pos, lo):
128
- v0, v1 = float(part[i]), float(part[min(i + 1, n - 1)])
129
- out.append(v0 + (h - i) * (v1 - v0))
172
+ v0, v1 = stats[i], stats[min(i + 1, n - 1)]
173
+ t = h - i
174
+ d = v1 - v0
175
+ # NumPy's lerp, so the result is bit-for-bit np.percentile(..., method="linear")
176
+ out.append(v1 - d * (1 - t) if t >= 0.5 else v0 + d * t)
130
177
  return out
131
178
 
132
179
 
@@ -10,11 +10,32 @@ from typing import Any, Optional
10
10
  import numpy as np
11
11
  from numpy.typing import NDArray
12
12
 
13
+ from .._native import array_view, core
13
14
  from ..core.exceptions import InputValidationError, StatisticalTestError
14
15
  from ..core.validation import target_type, to_numpy
15
16
 
16
17
  MetricFn = Callable[..., Any]
17
18
 
19
+ # Label metrics computed from the confusion matrix alone, all accepting sample_weight: on a resample they equal
20
+ # the same metric on the resample's distinct (true, predicted) pairs weighted by how often each occurs (tested
21
+ # bit for bit in tests/stats/test_resample_compression.py).
22
+ _CONFUSION_METRICS = frozenset(
23
+ {
24
+ "accuracy",
25
+ "balanced_accuracy",
26
+ "cohen_kappa",
27
+ "f1",
28
+ "fbeta",
29
+ "jaccard",
30
+ "mcc",
31
+ "npv",
32
+ "precision",
33
+ "recall",
34
+ "specificity",
35
+ }
36
+ )
37
+ _MAX_COMPRESSED_CLASSES = 64
38
+
18
39
 
19
40
  def resolve_metric(metric: Any) -> tuple[MetricFn, str]:
20
41
  """A metric function (``es.f1``) or its name (``"f1"``, ``"classification.f1"``)."""
@@ -125,8 +146,78 @@ class MetricCall:
125
146
  self.kwargs["labels"] = np.unique(present)
126
147
  if self.weight is not None and "sample_weight" not in params:
127
148
  raise InputValidationError(f"{getattr(fn, '__name__', 'This metric')} does not accept sample_weight.")
149
+ self._codes: Optional[NDArray[np.uint32]] = None
150
+ self._labels: Optional[NDArray[Any]] = None
151
+ self._k = 0
152
+ if y_pred is not None:
153
+ self._setup_compression()
154
+
155
+ def _setup_compression(self) -> None:
156
+ """Enable counting-based evaluation for confusion-matrix metrics on unweighted 1-D labels: each
157
+ observation becomes one code (true class × k + predicted class), and a resample is summarised by how
158
+ often each code occurs, so the metric runs on at most k² weighted pairs instead of n observations."""
159
+ fn = self.fn
160
+ if (
161
+ getattr(fn, "__module__", "") != "evalsuite.classification.metrics"
162
+ or getattr(fn, "__name__", "") not in _CONFUSION_METRICS
163
+ or self.weight is not None
164
+ or not self.categorical
165
+ or self.y_true.ndim != 1
166
+ or self.second.ndim != 1
167
+ or self.y_true.dtype != self.second.dtype
168
+ or self.y_true.dtype.kind not in "biuU"
169
+ ):
170
+ return
171
+ try:
172
+ labels = np.unique(np.concatenate([self.y_true, self.second]))
173
+ except TypeError: # pragma: no cover - same-dtype arrays are comparable
174
+ return
175
+ k = labels.shape[0]
176
+ if k > _MAX_COMPRESSED_CLASSES:
177
+ return
178
+ t = np.searchsorted(labels, self.y_true)
179
+ p = np.searchsorted(labels, self.second)
180
+ self._codes = (t * k + p).astype(np.uint32)
181
+ self._labels = labels
182
+ self._k = k
183
+
184
+ @property
185
+ def compressible(self) -> bool:
186
+ return self._codes is not None
187
+
188
+ def code_counts(self, idx: NDArray[np.int64]) -> NDArray[np.int64]:
189
+ """How often each (true, predicted) code occurs among the observations ``idx``."""
190
+ if self._codes is None: # pragma: no cover - guarded by callers
191
+ raise RuntimeError("not compressible")
192
+ return np.bincount(self._codes[idx], minlength=self._k * self._k)
193
+
194
+ def batch_code_counts(self, indices: NDArray[np.int64]) -> Optional[NDArray[np.uint64]]:
195
+ """Code counts for every row of ``indices`` at once (compiled core), or None without it."""
196
+ if self._codes is None or core is None or indices.ndim != 2 or indices.shape[0] == 0:
197
+ return None
198
+ kk = self._k * self._k
199
+ codes, codes_v = array_view(self._codes, np.uint32)
200
+ idx, idx_v = array_view(indices, np.int64) # resample indices are int64 already: no copy
201
+ raw = core.code_counts(codes_v, kk, idx_v, idx.shape[0])
202
+ del codes, idx
203
+ counts: NDArray[np.uint64] = np.frombuffer(raw, dtype=np.uint64).reshape(indices.shape[0], kk)
204
+ return counts
205
+
206
+ def from_counts(self, counts: NDArray[Any], idx: Optional[NDArray[np.int64]] = None) -> float:
207
+ """The metric on observations summarised by ``counts`` (equal to calling it on them directly)."""
208
+ if self._labels is None: # pragma: no cover - guarded by callers
209
+ raise RuntimeError("not compressible")
210
+ nz = np.flatnonzero(counts)
211
+ if nz.shape[0] < 2 and idx is not None:
212
+ return self(idx, compress=False) # a single distinct pair: use the observations themselves
213
+ k = self._k
214
+ kw = dict(self.kwargs)
215
+ kw["sample_weight"] = counts[nz].astype(np.float64)
216
+ return float(self.fn(self._labels[nz // k], self._labels[nz % k], **kw))
128
217
 
129
- def __call__(self, idx: Optional[NDArray[np.int64]] = None) -> float:
218
+ def __call__(self, idx: Optional[NDArray[np.int64]] = None, *, compress: bool = True) -> float:
219
+ if compress and idx is not None and self._codes is not None:
220
+ return self.from_counts(self.code_counts(idx), idx)
130
221
  if idx is None:
131
222
  yt, s, w = self.y_true, self.second, self.weight
132
223
  else:
@@ -1,13 +1,17 @@
1
1
  """Hypothesis tests for comparing scores, groups and categorical outcomes.
2
2
 
3
3
  Each test returns a :class:`TestResult` with the statistic, p-value, an effect size in ``estimate`` (named in
4
- ``params["effect_size"]``) and, where standard, a confidence interval. Computation is delegated to SciPy, whose
5
- implementations are the reference; EvalSuite adds input validation, effect sizes and consistent results.
4
+ ``params["effect_size"]``) and, where standard, a confidence interval. SciPy is the reference: the common tests
5
+ compute the same statistics directly (one ranking pass, closed-form tails, cached Shapiro–Wilk weights) and are
6
+ tested to match SciPy, falling back to SciPy where it uses a different algorithm (exact permutation tests,
7
+ older Shapiro–Wilk); EvalSuite adds input validation, effect sizes and consistent results.
6
8
  """
7
9
 
8
10
  from __future__ import annotations
9
11
 
12
+ import functools
10
13
  import math
14
+ import warnings
11
15
  from typing import TYPE_CHECKING, Literal, Optional
12
16
 
13
17
  import numpy as np
@@ -398,8 +402,89 @@ def shapiro_wilk_test(x: ArrayLike) -> TestResult:
398
402
  a = _vec(x, "x", 3)
399
403
  if np.ptp(a) == 0:
400
404
  raise StatisticalTestError("The Shapiro–Wilk test is undefined for constant data.")
401
- res = stats.shapiro(a)
402
- return TestResult("shapiro-wilk", float(res.statistic), float(res.pvalue), params={"n": int(a.shape[0])})
405
+ fast = _shapiro_fast(a)
406
+ if fast is None:
407
+ res = stats.shapiro(a)
408
+ w, p = float(res.statistic), float(res.pvalue)
409
+ else:
410
+ w, p = fast
411
+ return TestResult("shapiro-wilk", w, p, params={"n": int(a.shape[0])})
412
+
413
+
414
+ def _scipy_has_numpy_swilk() -> bool:
415
+ try:
416
+ from scipy.stats import _morestats
417
+
418
+ return hasattr(_morestats, "_swilk_w")
419
+ except ImportError: # pragma: no cover
420
+ return False
421
+
422
+
423
+ @functools.lru_cache(maxsize=64)
424
+ def _swilk_coefficients(n: int) -> NDArray[np.float64]:
425
+ """Royston's (1992) Shapiro–Wilk weights for sample size n (n > 3), exactly as scipy.stats.shapiro computes
426
+ them in SciPy >= 1.12. They depend only on n, so they are computed once per size."""
427
+ vdot = getattr(np, "vecdot", np.dot)
428
+ i = np.arange(1, n + 1, dtype=np.float64)
429
+ m = special.ndtri((i - 3 / 8) / (n + 1 / 4))
430
+ u = n**-0.5
431
+ mtm = vdot(m, m)
432
+ c = mtm**-0.5 * m
433
+ mnm1, mn = m[-2], m[-1]
434
+ cnm1, cn = c[-2], c[-1]
435
+ an = cn + 0.221157 * u - 0.147981 * u**2 - 2.071190 * u**3 + 4.434685 * u**4 - 2.706056 * u**5
436
+ anm1 = cnm1 + 0.042981 * u - 0.293762 * u**2 - 1.752461 * u**3 + 5.682633 * u**4 - 3.582633 * u**5
437
+ phi = (
438
+ (mtm - 2 * mn**2) / (1 - 2 * an**2)
439
+ if n <= 5
440
+ else (mtm - 2 * mn**2 - 2 * mnm1**2) / (1 - 2 * an**2 - 2 * anm1**2)
441
+ )
442
+ a: NDArray[np.float64] = np.asarray(phi**-0.5 * m, dtype=np.float64)
443
+ if n > 5:
444
+ a[-2] = anm1
445
+ a[1] = -anm1
446
+ a[-1] = an
447
+ a[0] = -an
448
+ a.setflags(write=False)
449
+ return a
450
+
451
+
452
+ def _shapiro_fast(x: NDArray[np.float64]) -> Optional[tuple[float, float]]:
453
+ """scipy.stats.shapiro without its per-call overhead and with cached weights; None on SciPy < 1.12, whose
454
+ Fortran implementation (a different algorithm) is then used instead so results always match SciPy."""
455
+ if not _scipy_has_numpy_swilk():
456
+ return None
457
+ vdot = getattr(np, "vecdot", np.dot)
458
+ n = x.shape[0]
459
+ y = np.sort(x)
460
+ y -= x[n // 2] # SciPy subtracts this element (of the unsorted input) for numerical stability
461
+ if n == 3:
462
+ c = math.sqrt(2) / 2
463
+ a3 = np.array([-c, 0.0, c])
464
+ yc = y - y.mean()
465
+ w = min(max(float(vdot(a3, y) ** 2 / vdot(yc, yc)), 0.75), 1.0)
466
+ return w, min(max(1.0 - 6 / math.pi * math.acos(math.sqrt(w)), 0.0), 1.0)
467
+ a = _swilk_coefficients(n)
468
+ yc = y - y.mean()
469
+ w = float(vdot(a, y) ** 2 / vdot(yc, yc))
470
+ if n <= 11:
471
+ u = n
472
+ gamma = -2.273 + 0.459 * u
473
+ mu = 0.5440 - 0.39978 * u + 0.025054 * u**2 - 0.0006714 * u**3
474
+ sigma = math.exp(1.3822 - 0.77857 * u + 0.062767 * u**2 - 0.0020322 * u**3)
475
+ g = -math.log(gamma - math.log(1 - w))
476
+ else:
477
+ lu = math.log(n)
478
+ mu = -1.5861 - 0.31082 * lu - 0.083751 * lu**2 + 0.0038915 * lu**3
479
+ sigma = math.exp(-0.4803 - 0.082676 * lu + 0.0030302 * lu**2)
480
+ g = math.log(1 - w)
481
+ if n > 5000:
482
+ warnings.warn(
483
+ f"scipy.stats.shapiro: For N > 5000, computed p-value may not be accurate. Current N is {n}.",
484
+ UserWarning,
485
+ stacklevel=3,
486
+ )
487
+ return w, float(special.ndtr(-(g - mu) / sigma))
403
488
 
404
489
 
405
490
  def _table(table: ArrayLike) -> NDArray[np.float64]:
@@ -61,11 +61,13 @@ def bootstrap_distribution(call: MetricCall, indices: NDArray[np.int64]) -> tupl
61
61
  """Metric value on each resample; resamples where the metric is undefined become NaN."""
62
62
  values = np.empty(indices.shape[0])
63
63
  failed = 0
64
+ # Confusion-matrix metrics: count every resample's (true, predicted) pairs in one compiled pass.
65
+ counts = call.batch_code_counts(indices)
64
66
  with warnings.catch_warnings():
65
67
  warnings.simplefilter("ignore") # zero-division warnings inside resamples are expected noise
66
68
  for b, idx in enumerate(indices):
67
69
  try:
68
- values[b] = call(idx)
70
+ values[b] = call(idx) if counts is None else call.from_counts(counts[b], idx)
69
71
  except EvalSuiteError:
70
72
  values[b] = np.nan
71
73
  failed += 1
@@ -77,12 +79,19 @@ def _jackknife(call: MetricCall, n: int, rng: np.random.Generator, groups: int)
77
79
  blocks = [np.array([i]) for i in range(n)] if n <= groups else np.array_split(rng.permutation(n), groups)
78
80
  everything = np.arange(n)
79
81
  out = np.empty(len(blocks))
82
+ # Confusion-matrix metrics: the counts without a block are the full counts minus the block's.
83
+ full = call.code_counts(everything) if call.compressible else None
80
84
  with warnings.catch_warnings():
81
85
  warnings.simplefilter("ignore")
82
86
  for j, block in enumerate(blocks):
83
- keep = np.setdiff1d(everything, block, assume_unique=True)
84
87
  try:
85
- out[j] = call(keep)
88
+ if full is not None:
89
+ counts = full - call.code_counts(block)
90
+ if np.count_nonzero(counts) >= 2:
91
+ out[j] = call.from_counts(counts)
92
+ continue
93
+ keep = np.setdiff1d(everything, block, assume_unique=True)
94
+ out[j] = call(keep, compress=False)
86
95
  except EvalSuiteError:
87
96
  out[j] = np.nan
88
97
  return out
@@ -17,6 +17,7 @@ from typing import Any, Callable, Literal, Optional
17
17
 
18
18
  import numpy as np
19
19
 
20
+ from .._native import Vocab, core
20
21
  from ..core.exceptions import InputValidationError
21
22
  from ..core.registry import register
22
23
  from ..core.result import MetricResult
@@ -130,6 +131,19 @@ def _bleu_stats(hyp: list[str], refs: list[list[str]], order: int) -> list[float
130
131
  return [hyp_len, closest, *correct, *total]
131
132
 
132
133
 
134
+ def _bleu_segment_stats(
135
+ hyps: list[list[str]], refs: list[list[list[str]]], order: int
136
+ ) -> list[list[int]] | list[list[float]]:
137
+ """BLEU statistics of every segment: compiled core when available, else :func:`_bleu_stats`."""
138
+ if core is not None:
139
+ v = Vocab()
140
+ stats: list[list[int]] = core.bleu_stats(
141
+ [v.encode(h) for h in hyps], [[v.encode(r) for r in rs] for rs in refs], order
142
+ )
143
+ return stats
144
+ return [_bleu_stats(h, rs, order) for h, rs in zip(hyps, refs)]
145
+
146
+
133
147
  def _bleu_from_stats(
134
148
  stats: Sequence[float], order: int, smooth: str, smooth_value: Optional[float], effective_order: bool
135
149
  ) -> tuple[float, list[float], float]:
@@ -209,8 +223,8 @@ def bleu(
209
223
  tok = _tokenizer(tokenize)
210
224
  hyp_tok = _prep(preds, lowercase, tok)
211
225
  acc = [0.0] * (2 + 2 * order)
212
- for h, rs in zip(hyp_tok, refs):
213
- for i, v in enumerate(_bleu_stats(h, _prep(rs, lowercase, tok), order)):
226
+ for seg in _bleu_segment_stats(hyp_tok, [_prep(rs, lowercase, tok) for rs in refs], order):
227
+ for i, v in enumerate(seg):
214
228
  acc[i] += v
215
229
  stats = np.asarray(acc)
216
230
  score, precisions, bp = _bleu_from_stats(acc, order, smooth, smooth_value, effective_order)
@@ -261,14 +275,8 @@ def sentence_bleu(
261
275
  order = check_positive_int(max_order, "max_order")
262
276
  smooth = _check_smooth(smooth)
263
277
  tok = _tokenizer(tokenize)
264
- scores = np.array(
265
- [
266
- _bleu_from_stats(_bleu_stats(h, _prep(rs, lowercase, tok), order), order, smooth, smooth_value, True)[
267
- 0
268
- ]
269
- for h, rs in zip(_prep(preds, lowercase, tok), refs)
270
- ]
271
- )
278
+ segs = _bleu_segment_stats(_prep(preds, lowercase, tok), [_prep(rs, lowercase, tok) for rs in refs], order)
279
+ scores = np.array([_bleu_from_stats(seg, order, smooth, smooth_value, True)[0] for seg in segs])
272
280
  value: Any = scores if average is None else float(scores.mean())
273
281
  return MetricResult("sentence_bleu", "Sentence BLEU", value, {"max_order": order, "smooth": smooth})
274
282
 
@@ -305,6 +313,46 @@ def _chrf_ngrams(sent: str, char_order: int, word_order: int, whitespace: bool)
305
313
  return out
306
314
 
307
315
 
316
+ def _chrf_native(
317
+ preds: list[str],
318
+ refs: list[list[str]],
319
+ char_order: int,
320
+ word_order: int,
321
+ beta: float,
322
+ lowercase: bool,
323
+ whitespace: bool,
324
+ eps_smoothing: bool,
325
+ ) -> Optional[list[float]]:
326
+ """Summed best-reference chrF statistics from the compiled core, or None to use the Python path (no core,
327
+ or text the core cannot take, such as lone surrogates)."""
328
+ if core is None:
329
+ return None
330
+ v = Vocab()
331
+
332
+ def parts(sent: str) -> tuple[str, list[int]]:
333
+ sent = sent.lower() if lowercase else sent
334
+ # Whitespace is removed here, with Python's definition of whitespace, not in the core.
335
+ line = sent if whitespace else "".join(sent.split())
336
+ return line, (v.encode(_chrf_words(sent)) if word_order else [])
337
+
338
+ try:
339
+ hp = [parts(h) for h in preds]
340
+ rp = [[parts(r) for r in rs] for rs in refs]
341
+ total: list[float] = core.chrf_corpus(
342
+ [h[0] for h in hp],
343
+ [h[1] for h in hp],
344
+ [[r[0] for r in rs] for rs in rp],
345
+ [[r[1] for r in rs] for rs in rp],
346
+ char_order,
347
+ word_order,
348
+ float(beta),
349
+ eps_smoothing,
350
+ )
351
+ except UnicodeEncodeError:
352
+ return None
353
+ return total
354
+
355
+
308
356
  def _chrf_f(stats: Sequence[float], order: int, beta: float, eps_smoothing: bool) -> float:
309
357
  eps = 1e-16
310
358
  factor = beta**2
@@ -361,8 +409,9 @@ def chrf(
361
409
  if isinstance(word_order, bool) or not isinstance(word_order, (int, np.integer)) or word_order < 0:
362
410
  raise InputValidationError("word_order must be an integer >= 0 (2 gives chrF++).")
363
411
  order = char_order + int(word_order)
364
- total = [0.0] * (3 * order)
365
- for hyp, rs in zip(preds, refs):
412
+ native = _chrf_native(preds, refs, char_order, int(word_order), beta, lowercase, whitespace, eps_smoothing)
413
+ total = native if native is not None else [0.0] * (3 * order)
414
+ for hyp, rs in zip(preds, refs) if native is None else ():
366
415
  h = _chrf_ngrams(hyp.lower() if lowercase else hyp, char_order, word_order, whitespace)
367
416
  best: Optional[list[float]] = None
368
417
  best_f = -1.0
@@ -599,11 +648,17 @@ def ter(references: Any, predictions: Any, *, case_sensitive: bool = False) -> M
599
648
 
600
649
  edits = 0.0
601
650
  ref_len = 0.0
602
- for hyp, rs in zip(preds, refs):
603
- h = tok(hyp)
604
- rws = [tok(r) for r in rs]
605
- edits += min(_ter_edits(h, r) for r in rws)
606
- ref_len += sum(len(r) for r in rws) / len(rws)
651
+ if core is not None:
652
+ v = Vocab()
653
+ edits, ref_len = core.ter_corpus(
654
+ [v.encode(tok(h)) for h in preds], [[v.encode(tok(r)) for r in rs] for rs in refs]
655
+ )
656
+ else:
657
+ for hyp, rs in zip(preds, refs):
658
+ h = tok(hyp)
659
+ rws = [tok(r) for r in rs]
660
+ edits += min(_ter_edits(h, r) for r in rws)
661
+ ref_len += sum(len(r) for r in rws) / len(rws)
607
662
  value = 100 * edits / ref_len if ref_len > 0 else (100.0 if edits > 0 else 0.0)
608
663
  return MetricResult(
609
664
  "ter", "TER", value, {"case_sensitive": case_sensitive, "edits": edits, "ref_len": ref_len}
@@ -717,6 +772,66 @@ def _rouge_lsum(ts: list[list[str]], ps: list[list[str]]) -> tuple[float, float,
717
772
  _MEASURES = {"precision": 0, "recall": 1, "fmeasure": 2}
718
773
 
719
774
 
775
+ def _rouge_triples_native(
776
+ variant: str,
777
+ preds: list[str],
778
+ refs: list[list[str]],
779
+ stemmer: Optional[Callable[[str], str]],
780
+ sents: Callable[[str], list[list[str]]],
781
+ ) -> list[list[tuple[float, float, float]]]:
782
+ """(precision, recall, F) for every (prediction, reference) pair: counts from the compiled core, then the
783
+ same float formulas as :func:`_rouge_n`, :func:`_rouge_l` and :func:`_rouge_lsum`."""
784
+ c = core
785
+ if c is None: # pragma: no cover - only called with the core
786
+ raise RuntimeError("compiled core not available")
787
+ v = Vocab()
788
+ out: list[list[tuple[float, float, float]]] = []
789
+ flat: list[tuple[float, float, float]] = []
790
+ sizes: list[int] = []
791
+ if variant == "Lsum":
792
+ ts: list[list[list[int]]] = []
793
+ ps: list[list[list[int]]] = []
794
+ for pred, rs in zip(preds, refs):
795
+ psents = [v.encode(s) for s in sents(pred)]
796
+ sizes.append(len(rs))
797
+ for ref in rs:
798
+ ts.append([v.encode(s) for s in sents(ref)])
799
+ ps.append(psents)
800
+ for ts_i, ps_i, (hits, m, n) in zip(ts, ps, c.rouge_lsum_hits(ts, ps)):
801
+ if not ts_i or not ps_i or not m or not n:
802
+ flat.append((0.0, 0.0, 0.0))
803
+ else:
804
+ prec, rec = hits / n, hits / m
805
+ flat.append((prec, rec, _f(prec, rec)))
806
+ else:
807
+ tt: list[list[int]] = []
808
+ pp: list[list[int]] = []
809
+ for pred, rs in zip(preds, refs):
810
+ p = v.encode(_rouge_tok(pred, stemmer))
811
+ sizes.append(len(rs))
812
+ for ref in rs:
813
+ tt.append(v.encode(_rouge_tok(ref, stemmer)))
814
+ pp.append(p)
815
+ if variant == "L":
816
+ for t, p, lcs in zip(tt, pp, c.lcs_lengths(tt, pp)):
817
+ if not t or not p:
818
+ flat.append((0.0, 0.0, 0.0))
819
+ else:
820
+ prec, rec = lcs / len(p), lcs / len(t)
821
+ flat.append((prec, rec, _f(prec, rec)))
822
+ else:
823
+ n = int(variant)
824
+ for t, p, inter in zip(tt, pp, c.ngram_overlaps(tt, pp, n)):
825
+ prec = inter / max(len(p) - n + 1, 1)
826
+ rec = inter / max(len(t) - n + 1, 1)
827
+ flat.append((prec, rec, _f(prec, rec)))
828
+ pos = 0
829
+ for k in sizes:
830
+ out.append(flat[pos : pos + k])
831
+ pos += k
832
+ return out
833
+
834
+
720
835
  def _rouge(
721
836
  variant: str,
722
837
  references: Any,
@@ -736,15 +851,25 @@ def _rouge(
736
851
  def sents(text: str) -> list[list[str]]:
737
852
  return [_rouge_tok(s, stemmer) for s in text.split("\n") if len(s)]
738
853
 
854
+ all_triples = (
855
+ _rouge_triples_native(variant, preds, refs, stemmer, sents)
856
+ if core is not None
857
+ else [
858
+ [
859
+ _rouge_lsum(sents(ref), sents(pred))
860
+ if variant == "Lsum"
861
+ else (
862
+ _rouge_l(_rouge_tok(ref, stemmer), _rouge_tok(pred, stemmer))
863
+ if variant == "L"
864
+ else _rouge_n(_rouge_tok(ref, stemmer), _rouge_tok(pred, stemmer), int(variant))
865
+ )
866
+ for ref in rs
867
+ ]
868
+ for pred, rs in zip(preds, refs)
869
+ ]
870
+ )
739
871
  scores = []
740
- for pred, rs in zip(preds, refs):
741
- triples = []
742
- for ref in rs:
743
- if variant == "Lsum":
744
- triples.append(_rouge_lsum(sents(ref), sents(pred)))
745
- else:
746
- t, p = _rouge_tok(ref, stemmer), _rouge_tok(pred, stemmer)
747
- triples.append(_rouge_l(t, p) if variant == "L" else _rouge_n(t, p, int(variant)))
872
+ for triples in all_triples:
748
873
  best = max(range(len(triples)), key=lambda i: (triples[i][2], -i)) # highest F, first on ties
749
874
  scores.append(triples[best][k])
750
875
  arr = np.array(scores)
@@ -873,10 +998,12 @@ def self_bleu(predictions: Any, *, max_order: int = 4, tokenize: Any = "13a") ->
873
998
  order = check_positive_int(max_order, "max_order")
874
999
  tok = _tokenizer(tokenize)
875
1000
  toks = [tok(p.rstrip()) for p in preds]
876
- scores = [
877
- _bleu_from_stats(_bleu_stats(toks[i], toks[:i] + toks[i + 1 :], order), order, "exp", None, True)[0]
878
- for i in range(len(toks))
879
- ]
1001
+ if core is not None:
1002
+ v = Vocab()
1003
+ segs = core.self_bleu_stats([v.encode(t) for t in toks], order)
1004
+ else:
1005
+ segs = [_bleu_stats(toks[i], toks[:i] + toks[i + 1 :], order) for i in range(len(toks))]
1006
+ scores = [_bleu_from_stats(seg, order, "exp", None, True)[0] for seg in segs]
880
1007
  return MetricResult("self_bleu", "Self-BLEU", float(np.mean(scores)), {"max_order": order})
881
1008
 
882
1009
 
@@ -966,6 +1093,15 @@ _REF_BANERJEE = (
966
1093
  )
967
1094
 
968
1095
 
1096
+ @functools.lru_cache(maxsize=1)
1097
+ def _porter_stem() -> Callable[[str], str]:
1098
+ """NLTK's Porter stemmer (the one NLTK's METEOR uses), memoised per word: stemming is a pure function of the
1099
+ word, and the same words recur across a corpus, so each distinct word is stemmed once."""
1100
+ from nltk.stem.porter import PorterStemmer
1101
+
1102
+ return functools.lru_cache(maxsize=2**16)(PorterStemmer().stem)
1103
+
1104
+
969
1105
  def _meteor_match(
970
1106
  hyp: list[tuple[int, str]], ref: list[tuple[int, str]]
971
1107
  ) -> tuple[list[tuple[int, int]], Any, Any]:
@@ -1077,14 +1213,13 @@ def meteor(
1077
1213
  stem_fn: Optional[Callable[[str], str]]
1078
1214
  if stemmer == "porter":
1079
1215
  try:
1080
- from nltk.stem.porter import PorterStemmer
1216
+ stem_fn = _porter_stem()
1081
1217
  except ImportError as exc:
1082
1218
  from ..core.exceptions import OptionalDependencyError
1083
1219
 
1084
1220
  raise OptionalDependencyError(
1085
1221
  "nltk", "llm", "METEOR's default Porter stemmer (or pass stemmer=None)"
1086
1222
  ) from exc
1087
- stem_fn = PorterStemmer().stem
1088
1223
  elif stemmer is None or callable(stemmer):
1089
1224
  stem_fn = stemmer
1090
1225
  else:
@@ -1094,10 +1229,20 @@ def meteor(
1094
1229
  for name, v in (("alpha", alpha), ("gamma", gamma)):
1095
1230
  if not 0 <= v <= 1:
1096
1231
  raise InputValidationError(f"{name} must be in [0, 1].")
1097
- scores = [
1098
- max(_meteor_single(tok(p), tok(r), stem_fn, synonyms, alpha, beta, gamma) for r in rs)
1099
- for p, rs in zip(preds, refs)
1100
- ]
1232
+ if core is not None and synonyms is None:
1233
+ words = Vocab()
1234
+ h_ids = [words.encode([w.lower() for w in tok(p)]) for p in preds]
1235
+ r_ids = [[words.encode([w.lower() for w in tok(r)]) for r in rs] for rs in refs]
1236
+ stem_of = None
1237
+ if stem_fn is not None: # each distinct word is stemmed once
1238
+ stems = Vocab()
1239
+ stem_of = stems.encode(stem_fn(w) for w in words.ids)
1240
+ scores = core.meteor_scores(h_ids, r_ids, stem_of, float(alpha), float(beta), float(gamma))
1241
+ else:
1242
+ scores = [
1243
+ max(_meteor_single(tok(p), tok(r), stem_fn, synonyms, alpha, beta, gamma) for r in rs)
1244
+ for p, rs in zip(preds, refs)
1245
+ ]
1101
1246
  arr = np.array(scores)
1102
1247
  value: Any = arr if average is None else float(arr.mean())
1103
1248
  return MetricResult(
evalsuite/text/judge.py CHANGED
@@ -266,14 +266,14 @@ def krippendorff_alpha(ratings: Any, *, level: str = "nominal") -> MetricResult:
266
266
  a = _reliability_matrix(ratings)
267
267
  if level not in ("nominal", "ordinal", "interval", "ratio"):
268
268
  raise InputValidationError("level must be 'nominal', 'ordinal', 'interval' or 'ratio'.")
269
- values = np.unique(a[~np.isnan(a)])
269
+ mask = ~np.isnan(a)
270
+ values, codes = np.unique(a[mask], return_inverse=True) # sorted values and each rating's code, one pass
270
271
  if values.size < 2:
271
272
  raise InputValidationError("Krippendorff's alpha needs at least two distinct rating values.")
272
273
  v = values.size
273
274
  # counts[u, c]: how many raters gave item u the value c (vectorised coincidence matrix)
274
- mask = ~np.isnan(a)
275
- items = np.broadcast_to(np.arange(a.shape[1]), a.shape)[mask]
276
- codes = np.searchsorted(values, a[mask])
275
+ items = np.nonzero(mask)[1] # item (column) of each rating, row-major like a[mask]
276
+ codes = codes.ravel()
277
277
  counts = np.bincount(items * v + codes, minlength=a.shape[1] * v).reshape(a.shape[1], v).astype(np.float64)
278
278
  m_u = counts.sum(axis=1)
279
279
  pairable = m_u >= 2
@@ -217,6 +217,16 @@ def embedding_similarity(
217
217
 
218
218
 
219
219
  # ---------------------------------------------------------------- MoverScore
220
+ def _euclidean_cost(x: NDArray[np.float64], y: NDArray[np.float64]) -> NDArray[np.float64]:
221
+ """Pairwise Euclidean distances from ‖x‖² + ‖y‖² − 2x·y (one matrix product), computed exactly as POT's
222
+ ``ot.dist(..., metric="euclidean")`` so transport costs match POT bit for bit."""
223
+ c = -2 * np.dot(x, y.T)
224
+ c += np.einsum("ij,ij->i", x, x)[:, None]
225
+ c += np.einsum("ij,ij->i", y, y)[None, :]
226
+ out: NDArray[np.float64] = np.sqrt(np.maximum(c, 0))
227
+ return out
228
+
229
+
220
230
  def _emd(
221
231
  a: NDArray[np.float64], b: NDArray[np.float64], cost: NDArray[np.float64], *, uniform: bool = False
222
232
  ) -> float:
@@ -227,10 +237,15 @@ def _emd(
227
237
  SciPy's Hungarian solver; general weights use linear programming (SciPy HiGHS). All three are exact."""
228
238
  try:
229
239
  import ot
230
-
231
- return float(ot.emd2(a, b, cost))
232
240
  except ImportError:
233
- pass
241
+ ot = None
242
+ if ot is not None:
243
+ try:
244
+ # The marginals are already validated and the duals are not used, so POT's checks and dual centring
245
+ # are skipped; the transport cost is unchanged.
246
+ return float(ot.emd2(a, b, cost, check_marginals=False, center_dual=False))
247
+ except TypeError: # POT versions without these options
248
+ return float(ot.emd2(a, b, cost))
234
249
  n, m = cost.shape
235
250
  if uniform:
236
251
  from scipy.optimize import linear_sum_assignment
@@ -284,8 +299,7 @@ def moverscore(
284
299
  for k, (r, p) in enumerate(zip(refs, preds)):
285
300
  wr = _weights(rw[k], r.shape[0], "reference_weights")
286
301
  wp = _weights(pw[k], p.shape[0], "prediction_weights")
287
- ru, pu = _unit(r), _unit(p)
288
- cost = np.sqrt(np.maximum(((ru[:, None, :] - pu[None, :, :]) ** 2).sum(-1), 0))
302
+ cost = _euclidean_cost(_unit(r), _unit(p))
289
303
  uniform = rw[k] is None and pw[k] is None
290
304
  scores[k] = 1.0 - _emd(wr / wr.sum(), wp / wp.sum(), cost, uniform=uniform)
291
305
  return _finish("moverscore", "MoverScore", scores, average, {"weighted": reference_weights is not None})
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.5.4"
3
+ __version__ = "0.6.0"
@@ -26,6 +26,7 @@ from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
26
26
  import numpy as np
27
27
  from numpy.typing import NDArray
28
28
 
29
+ from .._native import array_view, core
29
30
  from ..core.exceptions import InputValidationError
30
31
  from ..core.export import PathLike, csv_text, html_document, html_table, save_as
31
32
  from ..core.registry import register
@@ -218,41 +219,88 @@ def _prepare(images: list[_Image], max_det: int) -> tuple[list[int], dict[int, l
218
219
  return cats, pairs
219
220
 
220
221
 
221
- def _evaluate_image(pair: _Pair, area_rng: tuple[float, float], iou_thrs: NDArray[np.float64]) -> _Eval:
222
- dt_b, dt_s = pair.dt_b, pair.dt_s
223
- g_ignore = pair.gt_crowd | (pair.gt_area < area_rng[0]) | (pair.gt_area > area_rng[1])
224
- gorder = np.argsort(g_ignore, kind="mergesort")
225
- gt_b, gt_crowd, g_ignore = pair.gt_b[gorder], pair.gt_crowd[gorder], g_ignore[gorder]
226
- ious = pair.ious[:, gorder]
227
- t_n, d_n, g_n = len(iou_thrs), dt_b.shape[0], gt_b.shape[0]
228
- gtm = np.zeros((t_n, g_n), dtype=bool)
229
- dtm = np.zeros((t_n, d_n), dtype=bool)
230
- dt_ig = np.zeros((t_n, d_n), dtype=bool)
231
- # COCOeval's greedy matching, vectorised over thresholds and ground truths: for each detection (in score
232
- # order) take the last best-IoU available ground truth at or above the threshold, preferring ground truths
233
- # that are not ignored (COCO stops at the first ignored one once a regular match exists); crowd regions
234
- # stay available after a match.
235
- thr = np.minimum(np.asarray(iou_thrs, dtype=np.float64), 1 - 1e-10)
236
- if g_n:
237
- rows = np.arange(t_n)
238
- for di in range(d_n):
239
- row = ious[di]
240
- ok = (~gtm | gt_crowd[None, :]) & (row[None, :] >= thr[:, None])
241
- regular = ok & ~g_ignore[None, :]
242
- cand = np.where(regular.any(1)[:, None], regular, ok)
243
- found = cand.any(1)
222
+ def _evaluate_images(
223
+ pairs: list[_Pair], area_rng: tuple[float, float], iou_thrs: NDArray[np.float64]
224
+ ) -> list[_Eval]:
225
+ """COCOeval's per-image greedy matching for many images at once (one class, one area range).
226
+
227
+ Images are independent, so their matchings run side by side on arrays padded to the largest image: one Python
228
+ step per detection slot instead of one per detection. Per image this is exactly COCOeval.evaluateImg: ground
229
+ truths sorted with ignored ones last; each detection, in score order, takes the last best-IoU available
230
+ ground truth at or above the threshold, preferring non-ignored ones; crowd regions stay available after a
231
+ match; unmatched detections outside the area range are ignored."""
232
+ p_n = len(pairs)
233
+ if p_n == 0:
234
+ return []
235
+ t_n = len(iou_thrs)
236
+ g_sizes = np.array([pr.gt_b.shape[0] for pr in pairs])
237
+ d_sizes = np.array([pr.dt_b.shape[0] for pr in pairs])
238
+ g_max, d_max = int(g_sizes.max()), int(d_sizes.max())
239
+ lo, hi = area_rng
240
+ g_ign_list = []
241
+ gign = np.ones((p_n, g_max), dtype=bool)
242
+ crowd = np.zeros((p_n, g_max), dtype=bool)
243
+ ious = np.full((p_n, d_max, g_max), -1.0)
244
+ dt_out = np.zeros((p_n, d_max), dtype=bool)
245
+ for i, pr in enumerate(pairs):
246
+ g_ignore = pr.gt_crowd | (pr.gt_area < lo) | (pr.gt_area > hi)
247
+ gorder = np.argsort(g_ignore, kind="mergesort")
248
+ g_ignore = g_ignore[gorder]
249
+ g_ign_list.append(g_ignore)
250
+ g, d = g_ignore.shape[0], pr.dt_b.shape[0]
251
+ gign[i, :g] = g_ignore
252
+ crowd[i, :g] = pr.gt_crowd[gorder]
253
+ if g and d:
254
+ ious[i, :d, :g] = pr.ious[:, gorder]
255
+ dt_out[i, :d] = (pr.dt_area < lo) | (pr.dt_area > hi)
256
+ if core is not None and d_max:
257
+ a_iou, v_iou = array_view(ious, np.float64)
258
+ a_gi, v_gi = array_view(gign, np.bool_)
259
+ a_cr, v_cr = array_view(crowd, np.bool_)
260
+ a_out, v_out = array_view(dt_out, np.bool_)
261
+ raw_m, raw_i = core.coco_match(
262
+ v_iou,
263
+ v_gi,
264
+ v_cr,
265
+ v_out,
266
+ p_n,
267
+ d_max,
268
+ g_max,
269
+ [float(t) for t in iou_thrs],
270
+ )
271
+ del a_iou, a_gi, a_cr, a_out
272
+ dtm = np.frombuffer(raw_m, dtype=np.bool_).reshape(p_n, t_n, d_max)
273
+ dt_ig = np.frombuffer(raw_i, dtype=np.bool_).reshape(p_n, t_n, d_max)
274
+ return [
275
+ _Eval(pr.dt_s, dtm[i, :, : d_sizes[i]], dt_ig[i, :, : d_sizes[i]], g_ign_list[i])
276
+ for i, pr in enumerate(pairs)
277
+ ]
278
+ gtm = np.zeros((p_n, t_n, g_max), dtype=bool)
279
+ dtm = np.zeros((p_n, t_n, d_max), dtype=bool)
280
+ dt_ig = np.zeros((p_n, t_n, d_max), dtype=bool)
281
+ thr = np.minimum(np.asarray(iou_thrs, dtype=np.float64), 1 - 1e-10)[None, :, None]
282
+ if g_max:
283
+ p_idx = np.broadcast_to(np.arange(p_n)[:, None], (p_n, t_n))
284
+ t_idx = np.broadcast_to(np.arange(t_n)[None, :], (p_n, t_n))
285
+ not_ign = ~gign[:, None, :]
286
+ for di in range(d_max):
287
+ row = ious[:, di, :][:, None, :] # (P, 1, G); padding is -1, never above a threshold
288
+ ok = (~gtm | crowd[:, None, :]) & (row >= thr)
289
+ regular = ok & not_ign
290
+ cand = np.where(regular.any(2, keepdims=True), regular, ok)
291
+ found = cand.any(2)
244
292
  if not found.any():
245
293
  continue
246
- vals = np.where(cand, row[None, :], -1.0)
247
- m = g_n - 1 - np.argmax(vals[:, ::-1], axis=1)
248
- hit = rows[found]
249
- dtm[hit, di] = True
250
- dt_ig[hit, di] = g_ignore[m[found]]
251
- gtm[hit, m[found]] = True
252
- dt_area = pair.dt_area
253
- outside = (dt_area < area_rng[0]) | (dt_area > area_rng[1])
254
- dt_ig = dt_ig | (~dtm & outside[None, :])
255
- return _Eval(dt_s, dtm, dt_ig, g_ignore)
294
+ vals = np.where(cand, row, -1.0)
295
+ m = g_max - 1 - np.argmax(vals[:, :, ::-1], axis=2) # the last best ground truth, as COCOeval
296
+ dtm[:, :, di] = found
297
+ dt_ig[:, :, di] = found & gign[p_idx, m]
298
+ gtm[p_idx[found], t_idx[found], m[found]] = True
299
+ dt_ig |= ~dtm & dt_out[:, None, :]
300
+ return [
301
+ _Eval(pr.dt_s, dtm[i, :, : d_sizes[i]], dt_ig[i, :, : d_sizes[i]], g_ign_list[i])
302
+ for i, pr in enumerate(pairs)
303
+ ]
256
304
 
257
305
 
258
306
  def _coco_eval(
@@ -269,7 +317,7 @@ def _coco_eval(
269
317
  recall = -np.ones((t_n, k_n, a_n, m_n))
270
318
  for k, cat in enumerate(cats):
271
319
  for a, area_name in enumerate(areas):
272
- evals = [_evaluate_image(pair, _AREAS[area_name], iou_thrs) for pair in pairs[cat]]
320
+ evals = _evaluate_images(pairs[cat], _AREAS[area_name], iou_thrs)
273
321
  if not evals:
274
322
  continue
275
323
  gt_ignore = np.concatenate([e.gt_ignore for e in evals])
@@ -566,7 +614,7 @@ def average_precision_detection(
566
614
  cats, pairs = _prepare(images, int(max_detections))
567
615
  per = np.full(len(cats), math.nan)
568
616
  for k, cat in enumerate(cats):
569
- evals = [_evaluate_image(pair, _AREAS["all"], np.array([t])) for pair in pairs[cat]]
617
+ evals = _evaluate_images(pairs[cat], _AREAS["all"], np.array([t]))
570
618
  npig = int(sum(np.count_nonzero(~e.gt_ignore) for e in evals))
571
619
  if npig == 0:
572
620
  continue
@@ -509,26 +509,51 @@ def _surface(mask: NDArray[np.bool_]) -> NDArray[np.bool_]:
509
509
  """Foreground pixels with at least one background neighbour (4/6-connectivity)."""
510
510
  if not mask.any():
511
511
  return mask
512
- eroded = ndimage.binary_erosion(mask, structure=_structure(mask.ndim), border_value=0)
513
- out: NDArray[np.bool_] = mask & ~eroded
512
+ # Erosion with the cross-shaped structure (border = background): a pixel stays interior only if it and its
513
+ # 2·ndim face neighbours are all foreground. Same result as ndimage.binary_erosion, without its overhead.
514
+ interior = mask.copy()
515
+ full = [slice(None)] * mask.ndim
516
+ for ax in range(mask.ndim):
517
+ lo, hi, first, last = list(full), list(full), list(full), list(full)
518
+ lo[ax], hi[ax] = slice(None, -1), slice(1, None)
519
+ first[ax], last[ax] = slice(0, 1), slice(-1, None)
520
+ interior[tuple(hi)] &= mask[tuple(lo)] # neighbour before along this axis
521
+ interior[tuple(lo)] &= mask[tuple(hi)] # neighbour after
522
+ interior[tuple(first)] = False # pixels on the image border touch the background outside
523
+ interior[tuple(last)] = False
524
+ out: NDArray[np.bool_] = mask & ~interior
514
525
  return out
515
526
 
516
527
 
528
+ def _nearest(src: NDArray[np.float64], dst: NDArray[np.float64]) -> NDArray[np.float64]:
529
+ """Distance from each point of ``src`` to its nearest point of ``dst`` by direct comparison, in chunks of
530
+ rows so memory stays bounded; the square root is taken after the minimum (it is monotonic)."""
531
+ out = np.empty(src.shape[0])
532
+ step = max(1, 262144 // max(dst.shape[0], 1))
533
+ for i in range(0, src.shape[0], step):
534
+ diff = src[i : i + step, None, :] - dst[None, :, :]
535
+ out[i : i + step] = np.einsum("ijk,ijk->ij", diff, diff).min(axis=1)
536
+ return np.sqrt(out)
537
+
538
+
517
539
  def _surface_distances(
518
540
  a_surface: NDArray[np.bool_], b_surface: NDArray[np.bool_], spacing: Optional[Sequence[float]]
519
541
  ) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
520
542
  """Nearest-neighbour distances between the two surfaces, both ways (A→B, B→A).
521
543
 
522
- Uses k-d trees over the surface points only, which is much cheaper than a distance transform of the whole
523
- image when surfaces are a small fraction of it; distances are the same exact Euclidean values."""
524
- from scipy.spatial import cKDTree
525
-
544
+ Works on the surface points only (never a distance transform of the whole image): small surfaces are
545
+ compared directly, which beats building trees, and large ones use k-d trees. Both give the exact Euclidean
546
+ nearest-surface distance."""
526
547
  pa = np.argwhere(a_surface).astype(np.float64)
527
548
  pb = np.argwhere(b_surface).astype(np.float64)
528
549
  if spacing is not None:
529
550
  sc = np.asarray(spacing, dtype=np.float64)
530
551
  pa *= sc
531
552
  pb *= sc
553
+ if pa.shape[0] * pb.shape[0] <= 4_000_000:
554
+ return _nearest(pa, pb), _nearest(pb, pa)
555
+ from scipy.spatial import cKDTree
556
+
532
557
  d_ab = cKDTree(pb).query(pa)[0]
533
558
  d_ba = cKDTree(pa).query(pb)[0]
534
559
  return np.asarray(d_ab, dtype=np.float64), np.asarray(d_ba, dtype=np.float64)
@@ -594,9 +619,12 @@ def _surface_metric(
594
619
  UndefinedMetricWarning,
595
620
  stacklevel=3,
596
621
  )
597
- with warnings.catch_warnings():
598
- warnings.simplefilter("ignore", RuntimeWarning)
599
- per_class = np.nanmean(values, axis=0)
622
+ if not np.isnan(values).any():
623
+ per_class = values.mean(axis=0) # nanmean's NaN bookkeeping is not needed
624
+ else:
625
+ with warnings.catch_warnings():
626
+ warnings.simplefilter("ignore", RuntimeWarning)
627
+ per_class = np.nanmean(values, axis=0)
600
628
  params: dict[str, Any] = {
601
629
  "spacing": None if spacing is None else tuple(float(s) for s in spacing),
602
630
  "ignore_index": ignore_index,
@@ -613,7 +641,8 @@ def _surface_metric(
613
641
  if np.all(np.isnan(per_class)):
614
642
  warnings.warn(f"{name} is undefined: no class occurs in any mask.", UndefinedMetricWarning, stacklevel=3)
615
643
  return MetricResult(metric, name, math.nan, params)
616
- return MetricResult(metric, name, float(np.nanmean(per_class)), params)
644
+ finite = per_class[~np.isnan(per_class)]
645
+ return MetricResult(metric, name, float(finite.mean()), params)
617
646
 
618
647
 
619
648
  @register(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: evalsuite-python
3
- Version: 0.5.4
3
+ Version: 0.6.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
@@ -12,7 +12,7 @@ Maintainer: Manoj Kumar C S, Nikhil D Bharadwaj
12
12
  License-Expression: MIT OR Apache-2.0
13
13
  License-File: LICENSE
14
14
  License-File: LICENSE-APACHE
15
- Keywords: calibration,classification,clinical,diagnostic accuracy,evaluation,mAP,machine learning,metrics,object detection,regression,reproducibility,segmentation,statistical tests,statistics
15
+ Keywords: calibration,classification,clinical,diagnostic accuracy,evaluation,mAP,machine learning,metrics,object detection,regression,reproducibility,rust,segmentation,statistical tests,statistics
16
16
  Classifier: Development Status :: 5 - Production/Stable
17
17
  Classifier: Intended Audience :: Developers
18
18
  Classifier: Intended Audience :: Healthcare Industry
@@ -26,6 +26,7 @@ Classifier: Programming Language :: Python :: 3.11
26
26
  Classifier: Programming Language :: Python :: 3.12
27
27
  Classifier: Programming Language :: Python :: 3.13
28
28
  Classifier: Programming Language :: Python :: 3.14
29
+ Classifier: Programming Language :: Rust
29
30
  Classifier: Topic :: Scientific/Engineering
30
31
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
31
32
  Classifier: Topic :: Scientific/Engineering :: Image Recognition
@@ -84,7 +85,9 @@ Description-Content-Type: text/markdown
84
85
  EvalSuite brings classification, regression, clinical, statistical, segmentation and object-detection
85
86
  evaluation into one consistent, validated, documented framework.
86
87
 
87
- > **Status: stable (0.5.4).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
88
+ > **Status: stable (0.6.0).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
89
+ > **0.6.0 adds a compiled Rust core**: same API and identical results, with text metrics, COCO matching and
90
+ > bootstrap resampling several times faster (prebuilt wheels for Linux, macOS and Windows).
88
91
  > **LLM systems arrive in 0.5.0**: safety, robustness, calibration and uncertainty, agents and tool use,
89
92
  > multilingual, code generation, long context and summarization, and inference efficiency and cost.
90
93
 
@@ -100,6 +103,12 @@ The package is installed as `evalsuite-python` and imported as `evalsuite`:
100
103
  import evalsuite as es
101
104
  ```
102
105
 
106
+ EvalSuite has a **compiled core written in Rust**. pip installs a prebuilt wheel on Linux (x86_64, aarch64;
107
+ glibc and musl), macOS (Apple silicon, Intel) and Windows (x64, arm64) for Python 3.9 to 3.14, so no compiler
108
+ is needed. Anywhere else pip falls back to a pure-Python wheel that gives exactly the same results, more slowly.
109
+ `evalsuite._native.backend()` says which one is in use (`"rust"` or `"python"`), and
110
+ `EVALSUITE_PURE_PYTHON=1` selects the Python implementations on any install.
111
+
103
112
  ## Why EvalSuite
104
113
 
105
114
  - **One consistent API.** Every metric returns a result object that behaves like a number and exports to
@@ -340,55 +349,59 @@ Input files can be CSV, TSV, Parquet or JSON. Output format follows `--format` o
340
349
 
341
350
  ## Performance
342
351
 
343
- Benchmarked against reference implementations on the same data (fastest of 5 runs; EvalSuite 0.5.4, Python 3.13,
352
+ Benchmarked against reference implementations on the same data (fastest of 5 runs; EvalSuite 0.6.0, Python 3.13,
344
353
  NumPy 2.5, Linux x86_64). **Overall: 81 of 81 rows agree with the reference** (largest
345
- difference 2.5e-14), 75 are faster, and the geometric-mean speed-up across all
346
- 27 cases and three sizes is **3.07×**. At 1,000,000 samples (pixels for
354
+ difference 2.8e-14), 81 are faster, and the geometric-mean speed-up across all
355
+ 27 cases and three sizes is **3.70×**. At 1,000,000 samples (pixels for
347
356
  segmentation; 1,000 images for detection and 50 for Hausdorff; 10,000 examples for the LLM cases), in
348
357
  alphabetical order:
349
358
 
350
359
  | Case | Reference | EvalSuite (ms) | Reference (ms) | Speed-up |
351
360
  | --- | --- | ---: | ---: | ---: |
352
- | 10 classes: macro F1 | scikit-learn | 7.0 | 115.9 | **16.5×** |
353
- | agreement: Krippendorff's alpha, interval (4 raters × 10000 items) | krippendorff | 1.5 | 3.1 | **2.0×** |
354
- | binary: 8 label metrics via evaluate() | scikit-learn | 8.8 | 865.8 | **98.0×** |
355
- | binary: ROC AUC | scikit-learn | 163.6 | 284.5 | **1.7×** |
356
- | calibration: slope and intercept | statsmodels | 182.1 | 1206.3 | **6.6×** |
357
- | clinical: diagnostic report (7 CIs) | statsmodels | 5.0 | 5.4 | **1.1×** |
358
- | clinical: sensitivity, specificity, LR+, LR− | scikit-learn | 21.3 | 330.3 | **15.5×** |
359
- | decision curve: 99 thresholds | NumPy loop | 145.6 | 197.4 | **1.4×** |
360
- | detection: COCO evaluation (1000 images) | pycocotools | 650.7 | 626.0 | 0.96× |
361
- | multiple testing: Hochberg (n p-values) | statsmodels | 63.7 | 72.4 | **1.1×** |
362
- | regression: MAE, MSE, RMSE, R² via evaluate() | scikit-learn | 8.4 | 14.7 | **1.8×** |
363
- | retrieval: MRR, MAP@20, NDCG@10 (10000 queries) | ranx | 123.0 | 578.4 | **4.7×** |
364
- | segmentation: Dice and IoU per class (n = pixels) | scikit-learn | 30.5 | 221.6 | **7.3×** |
365
- | segmentation: Hausdorff distance (50 images) | SciPy | 12.3 | 13.7 | **1.1×** |
366
- | statistics: Cramér's V (5×5 table) | SciPy | 0.0 | 0.2 | **11.9×** |
367
- | statistics: Mann–Whitney U | SciPy | 136.9 | 286.2 | **2.1×** |
368
- | statistics: Welch t-test | SciPy | 5.9 | 9.0 | **1.5×** |
369
- | structured: JSON Schema compliance (10000 documents) | jsonschema | 96.9 | 228.0 | **2.4×** |
370
- | systems: CodeBLEU n-gram terms (1000 programs) | codebleu | 423.0 | 509.6 | **1.2×** |
371
- | systems: confidence AUROC (n answers) | scikit-learn | 164.1 | 254.1 | **1.5×** |
372
- | systems: distribution-shift drop, Welch CI (n scores) | SciPy | 9.2 | 10.7 | **1.2×** |
373
- | systems: invalid tool calls vs JSON Schema (10000 tasks) | jsonschema | 94.0 | 211.7 | **2.3×** |
374
- | systems: latency p50 / p95 / p99 (n requests) | NumPy | 19.2 | 13.2 | 0.69× |
375
- | systems: maintainability index (1000 programs) | radon | 89.2 | 95.4 | **1.1×** |
376
- | text: corpus BLEU and chrF (10000 sentences) | sacreBLEU | 1454.2 | 1932.6 | **1.3×** |
377
- | text: METEOR, exact and stem matches (10000 sentences) | NLTK | 323.9 | 384.1 | **1.2×** |
378
- | text: ROUGE-1, ROUGE-2, ROUGE-L (10000 sentences) | rouge-score | 340.1 | 630.7 | **1.9×** |
361
+ | 10 classes: macro F1 | scikit-learn | 10.2 | 107.4 | **10.5×** |
362
+ | agreement: Krippendorff's alpha, interval (4 raters × 10000 items) | krippendorff | 1.3 | 2.9 | **2.3×** |
363
+ | binary: 8 label metrics via evaluate() | scikit-learn | 11.2 | 818.5 | **73.1×** |
364
+ | binary: ROC AUC | scikit-learn | 175.4 | 292.8 | **1.7×** |
365
+ | calibration: slope and intercept | statsmodels | 234.7 | 938.0 | **4.0×** |
366
+ | clinical: diagnostic report (7 CIs) | statsmodels | 4.3 | 4.4 | **1.0×** |
367
+ | clinical: sensitivity, specificity, LR+, LR− | scikit-learn | 18.8 | 309.7 | **16.5×** |
368
+ | decision curve: 99 thresholds | NumPy loop | 149.3 | 230.1 | **1.5×** |
369
+ | detection: COCO evaluation (1000 images) | pycocotools | 268.5 | 628.8 | **2.3×** |
370
+ | multiple testing: Hochberg (n p-values) | statsmodels | 69.4 | 81.2 | **1.2×** |
371
+ | regression: MAE, MSE, RMSE, R² via evaluate() | scikit-learn | 7.4 | 12.0 | **1.6×** |
372
+ | retrieval: MRR, MAP@20, NDCG@10 (10000 queries) | ranx | 121.7 | 546.7 | **4.5×** |
373
+ | segmentation: Dice and IoU per class (n = pixels) | scikit-learn | 34.2 | 200.8 | **5.9×** |
374
+ | segmentation: Hausdorff distance (50 images) | SciPy | 11.0 | 13.4 | **1.2×** |
375
+ | statistics: Cramér's V (5×5 table) | SciPy | 0.0 | 0.2 | **12.0×** |
376
+ | statistics: Mann–Whitney U | SciPy | 152.1 | 323.0 | **2.1×** |
377
+ | statistics: Welch t-test | SciPy | 7.7 | 11.6 | **1.5×** |
378
+ | structured: JSON Schema compliance (10000 documents) | jsonschema | 88.9 | 224.7 | **2.5×** |
379
+ | systems: CodeBLEU n-gram terms (1000 programs) | codebleu | 385.3 | 505.1 | **1.3×** |
380
+ | systems: confidence AUROC (n answers) | scikit-learn | 166.0 | 265.3 | **1.6×** |
381
+ | systems: distribution-shift drop, Welch CI (n scores) | SciPy | 10.8 | 12.1 | **1.1×** |
382
+ | systems: invalid tool calls vs JSON Schema (10000 tasks) | jsonschema | 79.1 | 209.2 | **2.6×** |
383
+ | systems: latency p50 / p95 / p99 (n requests) | NumPy | 13.7 | 15.4 | **1.1×** |
384
+ | systems: maintainability index (1000 programs) | radon | 84.5 | 93.4 | **1.1×** |
385
+ | text: corpus BLEU and chrF (10000 sentences) | sacreBLEU | 215.2 | 1962.8 | **9.1×** |
386
+ | text: METEOR, exact and stem matches (10000 sentences) | NLTK | 71.0 | 363.4 | **5.1×** |
387
+ | text: ROUGE-1, ROUGE-2, ROUGE-L (10000 sentences) | rouge-score | 154.6 | 608.3 | **3.9×** |
379
388
 
380
389
  **Every metric is benchmarked too** (`evalsuite benchmark --suite metrics`): all 225 registered metrics and
381
390
  statistics functions at 10,000 and 100,000 samples. 86 are compared with a reference library, 118 with an
382
391
  independent textbook formula and 21 (learned, judge-dependent or randomised) are timed alone; **all 204
383
- comparisons agree**, and against the libraries the geometric-mean speed-up is **4.67×** (165 of 172
392
+ comparisons agree**, and against the libraries the geometric-mean speed-up is **5.99×** (172 of 172
384
393
  measurements faster). Per-metric table in BENCHMARKS.md.
385
394
 
386
- `evaluate()` validates inputs once and builds the confusion matrix once for all metrics, and integer labels are
387
- encoded without sorting, which is where most of the classification speed-up comes from. The rank tests
388
- (Mann–Whitney, Wilcoxon, Kruskal–Wallis, Friedman) rank the data once with a single unstable sort; t-tests,
389
- χ², Fisher and McNemar compute their statistics directly. The few rows below 1× either return more than the
390
- reference (latency also reports mean, standard deviation, min, max and p90) or already call the reference's
391
- compiled core (COCO matching, Shapiro–Wilk, MoverScore's transport solver). Reproduce on
395
+ **Every row is faster than its reference.** The text metrics (BLEU, chrF, TER, ROUGE, METEOR), COCO
396
+ matching and bootstrap resampling run in the compiled Rust core; bootstrap intervals, paired bootstrap tests and
397
+ `compare()` evaluate confusion-matrix metrics from counts of each resample's (true, predicted) pairs instead of
398
+ copies of the data. `evaluate()` validates inputs once and builds the confusion
399
+ matrix once for all metrics, and integer labels are encoded without sorting. The rank tests rank the data once
400
+ with a single unstable sort; t-tests, χ², Fisher and McNemar compute their statistics directly, and
401
+ Shapiro–Wilk caches its weights per sample size. Percentiles select exactly from a small bracketed window
402
+ instead of partitioning the whole array; COCO matching runs across all images of a class at once; surface
403
+ distances work on boundary points only; TER, BLEU, ROUGE and METEOR reuse tokenisation, stems and
404
+ edit-distance rows. Every one of these is tested to give the reference's result. Reproduce on
392
405
  your machine with `evalsuite benchmark`; full table (1k, 100k and 1M samples, peak memory) and notes in
393
406
  [BENCHMARKS.md](https://github.com/mkcs28/evalsuite-python/blob/main/BENCHMARKS.md).
394
407
 
@@ -459,13 +472,21 @@ throughput, token usage, cost, resource utilization, energy per request, request
459
472
 
460
473
  ## Development
461
474
 
475
+ Building from source needs a Rust toolchain ([rustup](https://rustup.rs)); the compiled core is in `rust/`
476
+ (`evalsuite-core`, pure Rust, and `evalsuite-py`, the PyO3 bindings), built by maturin.
477
+
462
478
  ```bash
463
479
  python -m venv .venv && source .venv/bin/activate
464
- pip install -e ".[dev]"
480
+ pip install -e ".[dev]" # builds the Rust core into evalsuite._core
465
481
  pytest --cov=evalsuite
482
+ EVALSUITE_PURE_PYTHON=1 pytest -q # the same suite without the compiled core
466
483
  ruff check . && ruff format --check . && mypy
484
+ cargo test --manifest-path rust/Cargo.toml -p evalsuite-core
467
485
  ```
468
486
 
487
+ Every compiled kernel is a port of a Python implementation that stays in the package as the reference and
488
+ fallback; `tests/test_native.py` checks that the two give identical results. See CONTRIBUTING.md.
489
+
469
490
  ## Links
470
491
 
471
492
  - PyPI: https://pypi.org/project/evalsuite-python/
@@ -2,13 +2,14 @@ evalsuite/__init__.py,sha256=nMwLJq_Ni8plZZmq1olG5HwDlBppn0pW-RJyFBzPF7o,5630
2
2
  evalsuite/__main__.py,sha256=Nq90_8VlUN1mif-AVgX-kZRL63bd94F5-F7F9UkVZD4,117
3
3
  evalsuite/_bench_metrics.py,sha256=GLLa9OhCNmu6IyWkxC0AcNf7p-CTpoOwWUS99C1o2o8,75792
4
4
  evalsuite/_lazy.py,sha256=Ddq0uWuiyxtsT0jBtCSITQPvttiQ7znXAbjkMIOVefk,901
5
+ evalsuite/_native.py,sha256=DiJNSz1oCuDd3rZSSsTQOii2jYp3sZtVePxWtRhcAik,2076
5
6
  evalsuite/api.py,sha256=DzWwmCgyEiqO2HvPrNg2RIDzqwap4e_UvbxA7PkJ3fE,10227
6
7
  evalsuite/benchmarks.py,sha256=TWXIhdYPbdDPanCOFL1lRCo3ppRYaDF58PB-o3ZZyTA,37846
7
8
  evalsuite/calibration.py,sha256=jhCPOmCFGEkUkcx-hSAIb-JCMq9oF6JZt4uDGvg5NaU,15083
8
9
  evalsuite/plot.py,sha256=7eOyzoRbg6Aad6OhtIQG3laIioQ8fs2K0YzodjG5rHA,26049
9
10
  evalsuite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
11
  evalsuite/reporting.py,sha256=-LISv9vvEnltT26GtzLjVlxOCcAwmjv4-HyB8_1UF5o,9615
11
- evalsuite/version.py,sha256=22kFzYFIZulNxaJz74-IxjfVc-vhYCfSyspVtQJNP08,98
12
+ evalsuite/version.py,sha256=WXIiUQKq6Bg6972-sqjn2TWeu8-Z3B72WfcDxJHyJ3c,98
12
13
  evalsuite/classification/__init__.py,sha256=ErBIXbBGnhfW6v-1Cn5SegiERoyxNlmO1tEKcLM15mA,833
13
14
  evalsuite/classification/_common.py,sha256=3ANV33ix_mnOzvOAG8glyJO-iYVhhTGO0S3YG0ZddB8,4543
14
15
  evalsuite/classification/metrics.py,sha256=h-DYF2wwdN8LA1bPbyIgkfuG4ovwBBgtGZFObEmiHzE,37044
@@ -26,7 +27,7 @@ evalsuite/core/result.py,sha256=L_fQZRGRgVgzII2jZb_jpRBK2jy-CdO5u9s-6pUk9fE,1492
26
27
  evalsuite/core/types.py,sha256=r6bhUk7CYAcrlQzjmf-6xWQsNqO3EOipZD-e-2yAJTI,720
27
28
  evalsuite/core/validation.py,sha256=nZRWSuShdFBDYgXMnRmspSQ4AJPRO3Zy5M8wTFfkg2E,10988
28
29
  evalsuite/llmsys/__init__.py,sha256=NA-kVMc3hdmBSW-ufPKrgfd2NHI15wCXJRn3ZhIVFsE,4653
29
- evalsuite/llmsys/_common.py,sha256=-NCpZxd3_1jMRVpHIDymv6OCcNeJ-8dxL-dIp-fpous,6576
30
+ evalsuite/llmsys/_common.py,sha256=Hp9yuO8ItEqr5v1B5fU6-ZVSB3EkvHavnspiPGVmsLM,8713
30
31
  evalsuite/llmsys/agents.py,sha256=giiHv3c179fFR6aFUp4VbBjzbdNotS941tZVG7W0UFE,15355
31
32
  evalsuite/llmsys/code.py,sha256=6Im0Km5qPHLFTF4S4dnN05OucFFNRixRchDSGHqtJaQ,37004
32
33
  evalsuite/llmsys/efficiency.py,sha256=GlUSWNnzRaeuebv-SZYsB28StwIPYb8AIyMwM057g_A,13895
@@ -38,32 +39,32 @@ evalsuite/llmsys/uncertainty.py,sha256=Brm_LT8qHb-EtcPe7YBXq7HYMSTG93OkT3Cnx2SYB
38
39
  evalsuite/regression/__init__.py,sha256=t2XEHUw6e5tyWBHcEeiog2WWd-wwaxf4m5AIX8dJyng,571
39
40
  evalsuite/regression/metrics.py,sha256=Qv5hFswxfzE-8wOKysERqsEJT-3kvTXPrkLoZ7s9jbQ,23487
40
41
  evalsuite/stats/__init__.py,sha256=mtnEqpvlvscQ3C6ceRr8xLKoSHPQWsWB24pEVlvp6fs,1187
41
- evalsuite/stats/_resolve.py,sha256=oauINI97AairuOB_fvlH5VlkiQnW5aIlR-bQT_zzhQ8,6119
42
+ evalsuite/stats/_resolve.py,sha256=T5EUqTbiGM0oor59Nzm18GUr7oLWcpgj1l8gCU56ACc,10276
42
43
  evalsuite/stats/compare.py,sha256=TzBYHDbfHU1Uz2FtgXbMATTnmHuaDGUbrV9Eq4IphZY,18311
43
44
  evalsuite/stats/effect.py,sha256=bgnhdCI4vU_Wnv5q7G2ncmtN3n7N1GWiYO4iO3FDI0w,7286
44
- evalsuite/stats/hypothesis.py,sha256=JXD-Dlsk5usFRiKl6udQHN_sWLxVGBKntYT3Jrlmack,21268
45
- evalsuite/stats/intervals.py,sha256=a0-SqHE3vYWNjCrtLCGWAFcCPqYki7iSn_0IGhWGNBw,14027
45
+ evalsuite/stats/hypothesis.py,sha256=RCu8yPTOhtetFQ5TlZQWaFu2t-aq56ffaNlEqC-lJbg,24546
46
+ evalsuite/stats/intervals.py,sha256=KyExUlrZiJiMkCRaDNUQoDY30hSrv3SNRQzR8oJucqU,14660
46
47
  evalsuite/stats/paired.py,sha256=PZV0XED3HnjOD675Tj6z1ILGxUaesBpxXQgC0goi6o4,8439
47
48
  evalsuite/stats/results.py,sha256=nqXHUiW8l0fQJkbMiunU6Gz-2be1NApZ6Fif2B1K_Yw,4407
48
49
  evalsuite/text/__init__.py,sha256=_r0Qi6X7cBcaYMAPRyC15CsTj9Tv8VcqMCtLiSJPogY,3632
49
50
  evalsuite/text/_common.py,sha256=acjAoPbXlPtd4DC4YbvOv1frIUjvFa1UtbdA5-6YDsU,3790
50
51
  evalsuite/text/factuality.py,sha256=Id8LnGjqvaVDYC5qMn4H0UJdjrwp1VrZ_zr_0jct8SM,20772
51
- evalsuite/text/generation.py,sha256=_rstdVmxbhto7NNq8b88OHmZeLXBOvhMo20GUAqtH9k,45791
52
- evalsuite/text/judge.py,sha256=zh8jlCIypGAa0q1nlPAXO4KQ2q_a1E5JHVT1X46uyNc,23493
52
+ evalsuite/text/generation.py,sha256=3Fm-VpzLEQMUfz59j4QVUbEBorq2-oTzLtJ4YaxzoYI,51659
53
+ evalsuite/text/judge.py,sha256=Ug5UnXBHzPkhtJ-vBxge3ZbkQxCoA4T_zcVxVU8chxQ,23566
53
54
  evalsuite/text/qa.py,sha256=rU0ya8TzV5mp7UiWq7w9IqSN9B0tDv8xymSaRzzbzMw,4097
54
55
  evalsuite/text/rag.py,sha256=GF8GUp6Vnt9peBCIcdvFUapLUL36_NDApZisYG_rcqg,9641
55
56
  evalsuite/text/reasoning.py,sha256=ydaTgAY--Tz_zEXm-Q_jLxJjTLnPgRlv39OzXWXD9yA,8885
56
57
  evalsuite/text/report.py,sha256=nUAgt24rcQsnPLiNTVn3PlzZO3Y7fW_ch_lSelgfEc8,6241
57
58
  evalsuite/text/retrieval.py,sha256=otQvOTbbR79kYtMum6o2HOT9UoDlSj0-JYLsFddkV1k,8969
58
- evalsuite/text/semantic.py,sha256=tjk3djMKisJAJoto8ylonfcOHH5DB5WLxL599N_shNA,22216
59
+ evalsuite/text/semantic.py,sha256=TgBBDcRll7vMzQVYStgt1SS9G7e6FTf7SuZDcPL32_g,23004
59
60
  evalsuite/text/spice.py,sha256=rdPCeilqKkXLMiSAE-rYOn0Zt2nKFum5Tf1oJdE6k-U,6847
60
61
  evalsuite/text/structured.py,sha256=x08yYf2rdlmiA_D_dI1L-fc9quHiBPMKgAGQbG3kJr8,31981
61
62
  evalsuite/vision/__init__.py,sha256=9gpOBTPveM_srE6BM-SgCssdQurya2LPHhoMLGOh2A0,991
62
- evalsuite/vision/detection.py,sha256=eUnt5iFUVLEoUl1RB51q-vfr5juDCD3YH8ttLFrqxFg,27781
63
- evalsuite/vision/segmentation.py,sha256=H-Xv_YFC1epghDU1QH6BAk37n3PKKX-4K4xLqI8vPdQ,39527
64
- evalsuite_python-0.5.4.dist-info/METADATA,sha256=0hy9rTa1NAKQMGEfMgA1au53aiEjjePr9XNZc8jPnSc,25867
65
- evalsuite_python-0.5.4.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
66
- evalsuite_python-0.5.4.dist-info/entry_points.txt,sha256=YYIwisn4L4sQt3ntzbM0_Z4yZE2KCu3GJ6KfWL1kIwc,54
67
- evalsuite_python-0.5.4.dist-info/licenses/LICENSE,sha256=cRRQ6Kk8w2qCqtDSSUJQGy-0rqjmjJG09cZ6iIiMvdc,1095
68
- evalsuite_python-0.5.4.dist-info/licenses/LICENSE-APACHE,sha256=K4pWYv3dt61u1BuIxjOGBxhgRkpsH4X_dzeIbOILXw0,10784
69
- evalsuite_python-0.5.4.dist-info/RECORD,,
63
+ evalsuite/vision/detection.py,sha256=nkTisC02xOupKNfXiJyk-oaFlYYLJZU7VXkR1fu2Ph4,29747
64
+ evalsuite/vision/segmentation.py,sha256=f41Q8iOELCj8jmAJ3pN5OFr3h3-6QtjnluW8rfkg0V0,41132
65
+ evalsuite_python-0.6.0.dist-info/METADATA,sha256=QDTBE4eRquf4uCJn3IivEmyQn2drPgSwIBDIzV7euL8,27606
66
+ evalsuite_python-0.6.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
67
+ evalsuite_python-0.6.0.dist-info/entry_points.txt,sha256=YYIwisn4L4sQt3ntzbM0_Z4yZE2KCu3GJ6KfWL1kIwc,54
68
+ evalsuite_python-0.6.0.dist-info/licenses/LICENSE,sha256=cRRQ6Kk8w2qCqtDSSUJQGy-0rqjmjJG09cZ6iIiMvdc,1095
69
+ evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE,sha256=K4pWYv3dt61u1BuIxjOGBxhgRkpsH4X_dzeIbOILXw0,10784
70
+ evalsuite_python-0.6.0.dist-info/RECORD,,