evalsuite-python 0.5.5__py3-none-any.whl → 0.6.1__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,65 @@
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
+ import sys
12
+ from typing import Any, Optional
13
+
14
+ core: Optional[Any]
15
+ if os.environ.get("EVALSUITE_PURE_PYTHON", "").strip().lower() in ("1", "true", "yes", "on"):
16
+ core = None
17
+ else:
18
+ try:
19
+ from . import _core as core # type: ignore[attr-defined, no-redef]
20
+ except ImportError: # pure-Python wheel or source checkout without a build
21
+ core = None
22
+
23
+ HAVE_NATIVE = core is not None
24
+
25
+ # Python >= 3.12 sums floats with compensated (Neumaier) summation in the built-in sum(); kernels that port code
26
+ # using sum() over floats take this flag so their results match the running interpreter bit for bit.
27
+ PY_SUM_COMPENSATED = sys.version_info >= (3, 12)
28
+
29
+
30
+ def backend() -> str:
31
+ """``"rust"`` when the compiled core is in use, ``"python"`` otherwise."""
32
+ return "rust" if HAVE_NATIVE else "python"
33
+
34
+
35
+ def array_view(arr: Any, dtype: Any) -> tuple[Any, tuple[int, int]]:
36
+ """A C-contiguous array of exactly ``dtype`` and its ``(data address, element count)`` view for the core.
37
+
38
+ The returned array must stay referenced (keep it in a local variable) until the core call returns; the
39
+ core only reads from it."""
40
+ import numpy as np
41
+
42
+ a = np.ascontiguousarray(arr, dtype=dtype)
43
+ if not a.flags.c_contiguous or a.dtype != np.dtype(dtype): # pragma: no cover - guaranteed by NumPy
44
+ raise ValueError("array must be C-contiguous with the requested dtype")
45
+ return a, (int(a.ctypes.data), int(a.size))
46
+
47
+
48
+ class Vocab:
49
+ """Maps tokens to consecutive integer ids (0, 1, 2, …) so token sequences can cross into the compiled core."""
50
+
51
+ __slots__ = ("ids",)
52
+
53
+ def __init__(self) -> None:
54
+ self.ids: dict[Any, int] = {}
55
+
56
+ def encode(self, tokens: Any) -> list[int]:
57
+ ids = self.ids
58
+ get = ids.get
59
+ out = []
60
+ for t in tokens:
61
+ i = get(t)
62
+ if i is None:
63
+ i = ids[t] = len(ids)
64
+ out.append(i)
65
+ return out
evalsuite/llmsys/code.py CHANGED
@@ -19,6 +19,7 @@ from typing import Any, Callable, Optional
19
19
 
20
20
  import numpy as np
21
21
 
22
+ from .._native import PY_SUM_COMPENSATED, Vocab, core
22
23
  from ..core.exceptions import InputValidationError
23
24
  from ..core.registry import register
24
25
  from ..core.result import MetricResult
@@ -671,6 +672,15 @@ def _corpus_bleu(refs: list[list[list[str]]], hyps: list[list[str]], weighted: O
671
672
  num: dict[int, float] = {n: 0.0 for n in range(1, 5)}
672
673
  den: dict[int, float] = {n: 0.0 for n in range(1, 5)}
673
674
  hyp_len = ref_len = 0
675
+ if core is not None:
676
+ v = Vocab()
677
+ h_ids = [v.encode(h) for h in hyps]
678
+ r_ids = [[v.encode(r) for r in rs] for rs in refs]
679
+ kw = None if weighted is None else [t in weighted for t in v.ids]
680
+ nums, dens, hyp_len, ref_len = core.codebleu_stats(h_ids, r_ids, kw, PY_SUM_COMPENSATED)
681
+ num = {n: nums[n - 1] for n in range(1, 5)}
682
+ den = {n: dens[n - 1] for n in range(1, 5)}
683
+ refs, hyps = [], [] # already counted
674
684
  for rs, h in zip(refs, hyps):
675
685
  for n in range(1, 5):
676
686
  hc = _ngrams(h, n)
@@ -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:
@@ -17,7 +17,7 @@ from ..core.result import _json_safe, _latex_escape, _latex_table
17
17
  from ..core.types import ArrayLike
18
18
  from ._resolve import MetricCall, as_items, as_observations, is_categorical, resolve_metric
19
19
  from .effect import adjust_pvalues
20
- from .intervals import _check_level, _check_resamples, bootstrap_distribution, resample_indices
20
+ from .intervals import _check_level, _check_resamples, bootstrap_distribution, check_resampling, resample_indices
21
21
  from .paired import delong_test, mcnemar_test
22
22
 
23
23
  if TYPE_CHECKING:
@@ -271,6 +271,7 @@ def compare(
271
271
  stratify: Optional[bool] = None,
272
272
  sample_weight: Optional[ArrayLike] = None,
273
273
  metric_kwargs: Optional[Mapping[str, Mapping[str, Any]]] = None,
274
+ resampling: str = "numpy",
274
275
  ) -> ComparisonResult:
275
276
  """Compare models evaluated on the same test set.
276
277
 
@@ -285,9 +286,11 @@ def compare(
285
286
  Pairs are every model against ``baseline`` if given, otherwise all pairs. p-values are adjusted within
286
287
  each metric (``correction``: "holm", "bonferroni", "hochberg", "bh", "by"); ``significant`` uses the adjusted
287
288
  p-value and ``alpha``. ``metric_kwargs`` passes options per metric, e.g. ``{"f1": {"average": "macro"}}``.
289
+ ``resampling="native"`` (opt-in) draws the bootstrap indices in the compiled core; see :func:`bootstrap_ci`.
288
290
  """
289
291
  level = _check_level(level)
290
292
  n_resamples = _check_resamples(n_resamples)
293
+ resampling = check_resampling(resampling)
291
294
  predictions = dict(predictions or {})
292
295
  probabilities = dict(probabilities or {})
293
296
  names = list(dict.fromkeys([*predictions, *probabilities]))
@@ -343,7 +346,7 @@ def compare(
343
346
 
344
347
  rng = np.random.default_rng(random_state)
345
348
  use_strata = categorical if stratify is None else bool(stratify)
346
- idx = resample_indices(yt.shape[0], n_resamples, rng, yt if use_strata else None)
349
+ idx = resample_indices(yt.shape[0], n_resamples, rng, yt if use_strata else None, resampling)
347
350
  a = (1 - level) / 2
348
351
  boot: dict[tuple[str, str], np.ndarray] = {}
349
352
  estimates: list[dict[str, Any]] = []
@@ -17,6 +17,7 @@ else:
17
17
  special = lazy_module("scipy.special")
18
18
  stats = lazy_module("scipy.stats")
19
19
 
20
+ from .._native import array_view, core
20
21
  from ..core.exceptions import EvalSuiteError, InputValidationError, StatisticalTestError
21
22
  from ..core.types import ArrayLike
22
23
  from ..core.validation import to_numpy
@@ -41,16 +42,57 @@ def _check_resamples(n_resamples: int) -> int:
41
42
  return int(n_resamples)
42
43
 
43
44
 
45
+ RESAMPLING = ("numpy", "native")
46
+
47
+
48
+ def check_resampling(resampling: str) -> str:
49
+ if resampling not in RESAMPLING:
50
+ raise InputValidationError("resampling must be 'numpy' or 'native'.")
51
+ if resampling == "native" and core is None:
52
+ raise InputValidationError(
53
+ "resampling='native' needs the compiled core, which is not available (pure-Python install or "
54
+ "EVALSUITE_PURE_PYTHON=1)."
55
+ )
56
+ return resampling
57
+
58
+
59
+ def _strata_groups(n: int, strata: NDArray[Any]) -> list[NDArray[np.intp]]:
60
+ values = np.unique(strata, axis=0) if strata.ndim > 1 else np.unique(strata)
61
+ return [
62
+ np.flatnonzero(np.all(strata == value, axis=1) if strata.ndim > 1 else strata == value) for value in values
63
+ ]
64
+
65
+
44
66
  def resample_indices(
45
- n: int, n_resamples: int, rng: np.random.Generator, strata: Optional[NDArray[Any]] = None
67
+ n: int,
68
+ n_resamples: int,
69
+ rng: np.random.Generator,
70
+ strata: Optional[NDArray[Any]] = None,
71
+ resampling: str = "numpy",
46
72
  ) -> NDArray[np.int64]:
47
- """(n_resamples, n) indices drawn with replacement, optionally within strata (keeps class balance)."""
73
+ """(n_resamples, n) indices drawn with replacement, optionally within strata (keeps class balance).
74
+
75
+ ``resampling="native"`` draws them in the compiled core (xoshiro256++, in parallel) from one seed taken from
76
+ ``rng``: reproducible for a given ``random_state`` and thread count–independent, but a different stream from
77
+ NumPy's, so intervals differ (statistically equivalently) from the default."""
78
+ if resampling == "native":
79
+ c = core
80
+ if c is None: # pragma: no cover - checked by check_resampling
81
+ raise InputValidationError("resampling='native' needs the compiled core.")
82
+ seed = int(rng.integers(0, 2**63))
83
+ groups = None
84
+ if strata is not None:
85
+ parts = _strata_groups(n, strata)
86
+ members, view = array_view(np.concatenate(parts), np.int64)
87
+ groups = (view, [0, *np.cumsum([p.shape[0] for p in parts]).tolist()])
88
+ out = np.empty((n_resamples, n), dtype=np.int64)
89
+ c.bootstrap_indices((int(out.ctypes.data), int(out.size)), n, seed, groups)
90
+ return out
48
91
  if strata is None:
49
92
  return rng.integers(0, n, size=(n_resamples, n))
50
93
  out = np.empty((n_resamples, n), dtype=np.int64)
51
94
  pos = 0
52
- for value in np.unique(strata, axis=0) if strata.ndim > 1 else np.unique(strata):
53
- members = np.flatnonzero(np.all(strata == value, axis=1) if strata.ndim > 1 else strata == value)
95
+ for members in _strata_groups(n, strata):
54
96
  k = members.shape[0]
55
97
  out[:, pos : pos + k] = members[rng.integers(0, k, size=(n_resamples, k))]
56
98
  pos += k
@@ -61,11 +103,13 @@ def bootstrap_distribution(call: MetricCall, indices: NDArray[np.int64]) -> tupl
61
103
  """Metric value on each resample; resamples where the metric is undefined become NaN."""
62
104
  values = np.empty(indices.shape[0])
63
105
  failed = 0
106
+ # Confusion-matrix metrics: count every resample's (true, predicted) pairs in one compiled pass.
107
+ counts = call.batch_code_counts(indices)
64
108
  with warnings.catch_warnings():
65
109
  warnings.simplefilter("ignore") # zero-division warnings inside resamples are expected noise
66
110
  for b, idx in enumerate(indices):
67
111
  try:
68
- values[b] = call(idx)
112
+ values[b] = call(idx) if counts is None else call.from_counts(counts[b], idx)
69
113
  except EvalSuiteError:
70
114
  values[b] = np.nan
71
115
  failed += 1
@@ -77,12 +121,19 @@ def _jackknife(call: MetricCall, n: int, rng: np.random.Generator, groups: int)
77
121
  blocks = [np.array([i]) for i in range(n)] if n <= groups else np.array_split(rng.permutation(n), groups)
78
122
  everything = np.arange(n)
79
123
  out = np.empty(len(blocks))
124
+ # Confusion-matrix metrics: the counts without a block are the full counts minus the block's.
125
+ full = call.code_counts(everything) if call.compressible else None
80
126
  with warnings.catch_warnings():
81
127
  warnings.simplefilter("ignore")
82
128
  for j, block in enumerate(blocks):
83
- keep = np.setdiff1d(everything, block, assume_unique=True)
84
129
  try:
85
- out[j] = call(keep)
130
+ if full is not None:
131
+ counts = full - call.code_counts(block)
132
+ if np.count_nonzero(counts) >= 2:
133
+ out[j] = call.from_counts(counts)
134
+ continue
135
+ keep = np.setdiff1d(everything, block, assume_unique=True)
136
+ out[j] = call(keep, compress=False)
86
137
  except EvalSuiteError:
87
138
  out[j] = np.nan
88
139
  return out
@@ -101,25 +152,29 @@ def bootstrap_ci(
101
152
  random_state: Optional[int] = None,
102
153
  stratify: Optional[bool] = None,
103
154
  jackknife_groups: int = 1000,
155
+ resampling: str = "numpy",
104
156
  **metric_kwargs: Any,
105
157
  ) -> ConfidenceInterval:
106
158
  """Bootstrap confidence interval for any metric.
107
159
 
108
- ``metric`` is a metric function (``es.f1``) or its name (``"f1"``). Pass ``y_pred`` for label/value
109
- metrics or ``y_prob`` for probability metrics; extra keyword arguments go to the metric (for example
110
- ``average="macro"``). Resampling is stratified by class for classification targets unless
111
- ``stratify=False``, so every resample contains every class. For classification metrics that accept
112
- ``labels``, the full label set is fixed across resamples.
160
+ ``metric`` is a metric function (``es.f1``) or its name (``"f1"``). Pass ``y_pred`` for label/value
161
+ metrics or ``y_prob`` for probability metrics; extra keyword arguments go to the metric (for example
162
+ ``average="macro"``). Resampling is stratified by class for classification targets unless
163
+ ``stratify=False``, so every resample contains every class. For classification metrics that accept
164
+ ``labels``, the full label set is fixed across resamples.
113
165
 
114
- ``method``: ``"bca"`` (bias-corrected and accelerated; default, Efron 1987), ``"percentile"`` or
115
- ``"basic"``. Set ``random_state`` for reproducible intervals. Resamples on which the metric is undefined
116
- are counted in ``params["failed_resamples"]``; more than 10% raises :class:`StatisticalTestError`.
166
+ ``method``: ``"bca"`` (bias-corrected and accelerated; default, Efron 1987), ``"percentile"`` or
167
+ ``"basic"``. Set ``random_state`` for reproducible intervals. Resamples on which the metric is undefined
168
+ are counted in ``params["failed_resamples"]``; more than 10% raises :class:`StatisticalTestError`.
169
+ ``resampling="native"`` (opt-in) draws the resample indices in the compiled core instead of NumPy: faster on
170
+ large inputs and still reproducible with ``random_state``, but a different random stream from the default.
117
171
 
118
- References: Efron B. Better bootstrap confidence intervals. JASA. 1987;82(397):171-185.
119
- Efron B, Tibshirani RJ. An Introduction to the Bootstrap. Chapman & Hall; 1993.
172
+ References: Efron B. Better bootstrap confidence intervals. JASA. 1987;82(397):171-185.
173
+ Efron B, Tibshirani RJ. An Introduction to the Bootstrap. Chapman & Hall; 1993.
120
174
  """
121
175
  level = _check_level(level)
122
176
  n_resamples = _check_resamples(n_resamples)
177
+ resampling = check_resampling(resampling)
123
178
  if method not in ("percentile", "basic", "bca"):
124
179
  raise InputValidationError("method must be 'bca', 'percentile' or 'basic'.")
125
180
  fn, name = resolve_metric(metric)
@@ -127,7 +182,7 @@ def bootstrap_ci(
127
182
  estimate = call()
128
183
  rng = np.random.default_rng(random_state)
129
184
  use_strata = call.categorical if stratify is None else bool(stratify)
130
- idx = resample_indices(call.n, n_resamples, rng, call.y_true if use_strata else None)
185
+ idx = resample_indices(call.n, n_resamples, rng, call.y_true if use_strata else None, resampling)
131
186
  boot, failed = bootstrap_distribution(call, idx)
132
187
  if failed > MAX_FAILED_FRACTION * n_resamples:
133
188
  raise StatisticalTestError(
@@ -141,6 +196,7 @@ def bootstrap_ci(
141
196
  "random_state": random_state,
142
197
  "stratified": use_strata,
143
198
  "failed_resamples": failed,
199
+ "resampling": resampling,
144
200
  **{k: v for k, v in metric_kwargs.items()},
145
201
  }
146
202
  if method == "percentile":
evalsuite/stats/paired.py CHANGED
@@ -23,6 +23,7 @@ from .intervals import (
23
23
  _check_resamples,
24
24
  binary_scores,
25
25
  bootstrap_distribution,
26
+ check_resampling,
26
27
  delong_covariance,
27
28
  delong_placements,
28
29
  resample_indices,
@@ -138,6 +139,7 @@ def paired_bootstrap_test(
138
139
  random_state: Optional[int] = None,
139
140
  stratify: Optional[bool] = None,
140
141
  alternative: Literal["two-sided", "greater", "less"] = "two-sided",
142
+ resampling: str = "numpy",
141
143
  **metric_kwargs: Any,
142
144
  ) -> TestResult:
143
145
  """Paired bootstrap test for any metric: is metric(A) − metric(B) different from 0?
@@ -146,10 +148,13 @@ def paired_bootstrap_test(
146
148
  distribution (difference re-centred on 0 under the null), with the +1 correction so it is never 0:
147
149
  p = (1 + #{|δ* − δ̂| ≥ |δ̂|}) / (B + 1) for a two-sided test. ``ci`` is the percentile interval of δ*.
148
150
 
151
+ ``resampling="native"`` (opt-in) draws the resample indices in the compiled core; see :func:`bootstrap_ci`.
152
+
149
153
  Reference: Efron B, Tibshirani RJ. An Introduction to the Bootstrap. Chapman & Hall; 1993, ch. 16.
150
154
  """
151
155
  level = _check_level(level)
152
156
  n_resamples = _check_resamples(n_resamples)
157
+ resampling = check_resampling(resampling)
153
158
  if alternative not in ("two-sided", "greater", "less"):
154
159
  raise InputValidationError("alternative must be 'two-sided', 'greater' or 'less'.")
155
160
  fn, name = resolve_metric(metric)
@@ -170,7 +175,7 @@ def paired_bootstrap_test(
170
175
  observed = call_a() - call_b()
171
176
  rng = np.random.default_rng(random_state)
172
177
  use_strata = call_a.categorical if stratify is None else bool(stratify)
173
- idx = resample_indices(call_a.n, n_resamples, rng, call_a.y_true if use_strata else None)
178
+ idx = resample_indices(call_a.n, n_resamples, rng, call_a.y_true if use_strata else None, resampling)
174
179
  da, fa = bootstrap_distribution(call_a, idx)
175
180
  db, fb = bootstrap_distribution(call_b, idx)
176
181
  diff = da - db
@@ -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 PY_SUM_COMPENSATED, 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)
@@ -843,13 +968,17 @@ def distinct_n(predictions: Any, *, n: int = 1, lowercase: bool = False) -> Metr
843
968
  """Distinct-n over the whole set of predictions (``n=1`` Distinct-1, ``n=2`` Distinct-2)."""
844
969
  preds = as_texts(predictions, "predictions")
845
970
  n = check_positive_int(n, "n")
846
- counts: Counter[tuple[str, ...]] = Counter()
847
- for p in preds:
848
- counts.update(word_ngrams((p.lower() if lowercase else p).split(), n))
849
- total = sum(counts.values())
971
+ if core is not None:
972
+ v = Vocab()
973
+ unique, total = core.distinct_ngrams([v.encode((p.lower() if lowercase else p).split()) for p in preds], n)
974
+ else:
975
+ counts: Counter[tuple[str, ...]] = Counter()
976
+ for p in preds:
977
+ counts.update(word_ngrams((p.lower() if lowercase else p).split(), n))
978
+ unique, total = len(counts), sum(counts.values())
850
979
  if total == 0:
851
980
  raise InputValidationError(f"The predictions contain no {n}-grams.")
852
- return MetricResult("distinct_n", f"Distinct-{n}", len(counts) / total, {"n": n, "total_ngrams": total})
981
+ return MetricResult("distinct_n", f"Distinct-{n}", unique / total, {"n": n, "total_ngrams": total})
853
982
 
854
983
 
855
984
  @register(
@@ -873,10 +1002,12 @@ def self_bleu(predictions: Any, *, max_order: int = 4, tokenize: Any = "13a") ->
873
1002
  order = check_positive_int(max_order, "max_order")
874
1003
  tok = _tokenizer(tokenize)
875
1004
  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
- ]
1005
+ if core is not None:
1006
+ v = Vocab()
1007
+ segs = core.self_bleu_stats([v.encode(t) for t in toks], order)
1008
+ else:
1009
+ segs = [_bleu_stats(toks[i], toks[:i] + toks[i + 1 :], order) for i in range(len(toks))]
1010
+ scores = [_bleu_from_stats(seg, order, "exp", None, True)[0] for seg in segs]
880
1011
  return MetricResult("self_bleu", "Self-BLEU", float(np.mean(scores)), {"max_order": order})
881
1012
 
882
1013
 
@@ -1102,10 +1233,20 @@ def meteor(
1102
1233
  for name, v in (("alpha", alpha), ("gamma", gamma)):
1103
1234
  if not 0 <= v <= 1:
1104
1235
  raise InputValidationError(f"{name} must be in [0, 1].")
1105
- scores = [
1106
- max(_meteor_single(tok(p), tok(r), stem_fn, synonyms, alpha, beta, gamma) for r in rs)
1107
- for p, rs in zip(preds, refs)
1108
- ]
1236
+ if core is not None and synonyms is None:
1237
+ words = Vocab()
1238
+ h_ids = [words.encode([w.lower() for w in tok(p)]) for p in preds]
1239
+ r_ids = [[words.encode([w.lower() for w in tok(r)]) for r in rs] for rs in refs]
1240
+ stem_of = None
1241
+ if stem_fn is not None: # each distinct word is stemmed once
1242
+ stems = Vocab()
1243
+ stem_of = stems.encode(stem_fn(w) for w in words.ids)
1244
+ scores = core.meteor_scores(h_ids, r_ids, stem_of, float(alpha), float(beta), float(gamma))
1245
+ else:
1246
+ scores = [
1247
+ max(_meteor_single(tok(p), tok(r), stem_fn, synonyms, alpha, beta, gamma) for r in rs)
1248
+ for p, rs in zip(preds, refs)
1249
+ ]
1109
1250
  arr = np.array(scores)
1110
1251
  value: Any = arr if average is None else float(arr.mean())
1111
1252
  return MetricResult(
@@ -1171,6 +1312,18 @@ def cider(
1171
1312
  def words(s: str) -> list[str]:
1172
1313
  return tok(s.lower() if lowercase else s)
1173
1314
 
1315
+ if core is not None:
1316
+ v = Vocab()
1317
+ totals = core.cider_totals(
1318
+ [v.encode(words(p)) for p in preds],
1319
+ [[v.encode(words(r)) for r in rs] for rs in refs],
1320
+ n,
1321
+ float(sigma),
1322
+ PY_SUM_COMPENSATED,
1323
+ )
1324
+ arr = np.array([float(np.mean(np.array(t))) / len(rs) * 10.0 for t, rs in zip(totals, refs)])
1325
+ value_n: Any = arr if average is None else float(arr.mean())
1326
+ return MetricResult("cider", "CIDEr-D", value_n, {"max_order": n, "sigma": sigma})
1174
1327
  ctest = [_cider_counts(words(p), n) for p in preds]
1175
1328
  crefs = [[_cider_counts(words(r), n) for r in rs] for rs in refs]
1176
1329
  df: Counter[tuple[str, ...]] = Counter()
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.5"
3
+ __version__ = "0.6.1"
@@ -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
@@ -252,6 +253,28 @@ def _evaluate_images(
252
253
  if g and d:
253
254
  ious[i, :d, :g] = pr.ious[:, gorder]
254
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
+ ]
255
278
  gtm = np.zeros((p_n, t_n, g_max), dtype=bool)
256
279
  dtm = np.zeros((p_n, t_n, d_max), dtype=bool)
257
280
  dt_ig = np.zeros((p_n, t_n, d_max), dtype=bool)
@@ -287,6 +310,8 @@ def _coco_eval(
287
310
  areas: Sequence[str],
288
311
  ) -> tuple[list[int], NDArray[np.float64], NDArray[np.float64]]:
289
312
  """precision (T, R, K, A, M) and recall (T, K, A, M); -1 where undefined (no ground truth)."""
313
+ if core is not None:
314
+ return _coco_eval_native(images, iou_thrs, max_dets, areas)
290
315
  top = max(max_dets)
291
316
  cats, pairs = _prepare(images, top)
292
317
  t_n, r_n, k_n, a_n, m_n = len(iou_thrs), _REC_THRS.size, len(cats), len(areas), len(max_dets)
@@ -325,6 +350,52 @@ def _coco_eval(
325
350
  return cats, precision, recall
326
351
 
327
352
 
353
+ def _coco_eval_native(
354
+ images: list[_Image],
355
+ iou_thrs: NDArray[np.float64],
356
+ max_dets: Sequence[int],
357
+ areas: Sequence[str],
358
+ ) -> tuple[list[int], NDArray[np.float64], NDArray[np.float64]]:
359
+ """:func:`_coco_eval` in the compiled core: preparation, matching and accumulation, parallel over classes."""
360
+ c = core
361
+ if c is None: # pragma: no cover - only called with the core
362
+ raise RuntimeError("compiled core not available")
363
+
364
+ def cat(parts: list[NDArray[Any]], dtype: Any, shape: tuple[int, ...]) -> NDArray[Any]:
365
+ return np.concatenate(parts).astype(dtype, copy=False) if parts else np.zeros(shape, dtype=dtype)
366
+
367
+ gt_off = np.cumsum([0] + [im.gt_boxes.shape[0] for im in images]).astype(np.int64)
368
+ dt_off = np.cumsum([0] + [im.dt_boxes.shape[0] for im in images]).astype(np.int64)
369
+ arrays = [
370
+ (cat([im.gt_boxes.reshape(-1, 4) for im in images], np.float64, (0, 4)), np.float64),
371
+ (cat([im.gt_labels for im in images], np.int64, (0,)), np.int64),
372
+ (cat([im.gt_crowd for im in images], np.bool_, (0,)), np.bool_),
373
+ (cat([im.gt_area for im in images], np.float64, (0,)), np.float64),
374
+ (gt_off, np.int64),
375
+ (cat([im.dt_boxes.reshape(-1, 4) for im in images], np.float64, (0, 4)), np.float64),
376
+ (cat([im.dt_labels for im in images], np.int64, (0,)), np.int64),
377
+ (cat([im.dt_scores for im in images], np.float64, (0,)), np.float64),
378
+ (dt_off, np.int64),
379
+ ]
380
+ held, views = [], []
381
+ for arr, dtype in arrays:
382
+ a, v = array_view(arr, dtype)
383
+ held.append(a)
384
+ views.append(v)
385
+ cats, raw_p, raw_r = c.coco_evaluate(
386
+ *views,
387
+ [float(t) for t in iou_thrs],
388
+ [int(m) for m in max_dets],
389
+ [_AREAS[a] for a in areas],
390
+ [float(r) for r in _REC_THRS],
391
+ )
392
+ del held
393
+ t_n, r_n, k_n, a_n, m_n = len(iou_thrs), _REC_THRS.size, len(cats), len(areas), len(max_dets)
394
+ precision = np.frombuffer(raw_p, dtype=np.float64).reshape(t_n, r_n, k_n, a_n, m_n).copy()
395
+ recall = np.frombuffer(raw_r, dtype=np.float64).reshape(t_n, k_n, a_n, m_n).copy()
396
+ return [int(k) for k in cats], precision, recall
397
+
398
+
328
399
  def _mean_valid(x: NDArray[np.float64]) -> float:
329
400
  v = x[x > -1]
330
401
  return float(np.mean(v)) if v.size else math.nan
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: evalsuite-python
3
- Version: 0.5.5
3
+ Version: 0.6.1
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,11 @@ 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.5).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
88
+ > **Status: stable (0.6.1).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
89
+ > **0.6 adds a compiled Rust core**: same API and identical results, with text metrics, COCO evaluation and
90
+ > bootstrap resampling several times faster and multithreaded (prebuilt wheels for Linux, macOS and Windows).
91
+ > 0.6.1 moves the whole COCO evaluation, CIDEr, CodeBLEU and distinct-n into the core and adds opt-in
92
+ > `resampling="native"` bootstrap draws.
88
93
  > **LLM systems arrive in 0.5.0**: safety, robustness, calibration and uncertainty, agents and tool use,
89
94
  > multilingual, code generation, long context and summarization, and inference efficiency and cost.
90
95
 
@@ -100,6 +105,19 @@ The package is installed as `evalsuite-python` and imported as `evalsuite`:
100
105
  import evalsuite as es
101
106
  ```
102
107
 
108
+ EvalSuite has a **compiled core written in Rust**. pip installs a prebuilt wheel on Linux (x86_64, aarch64;
109
+ glibc and musl), macOS (Apple silicon, Intel) and Windows (x64, arm64) for Python 3.9 to 3.14, so no compiler
110
+ is needed. Anywhere else pip falls back to a pure-Python wheel that gives exactly the same results, more slowly.
111
+ `evalsuite._native.backend()` says which one is in use (`"rust"` or `"python"`), and
112
+ `EVALSUITE_PURE_PYTHON=1` selects the Python implementations on any install.
113
+
114
+ The core runs independent examples (sentences, images, classes, resamples) in parallel on all CPU cores; set
115
+ `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
+
103
121
  ## Why EvalSuite
104
122
 
105
123
  - **One consistent API.** Every metric returns a result object that behaves like a number and exports to
@@ -340,50 +358,55 @@ Input files can be CSV, TSV, Parquet or JSON. Output format follows `--format` o
340
358
 
341
359
  ## Performance
342
360
 
343
- Benchmarked against reference implementations on the same data (fastest of 5 runs; EvalSuite 0.5.5, Python 3.13,
361
+ Benchmarked against reference implementations on the same data (fastest of 5 runs; EvalSuite 0.6.1, Python 3.13,
344
362
  NumPy 2.5, Linux x86_64). **Overall: 81 of 81 rows agree with the reference** (largest
345
- difference 2.5e-14), 81 are faster, and the geometric-mean speed-up across all
346
- 27 cases and three sizes is **3.29×**. At 1,000,000 samples (pixels for
363
+ difference 2.5e-14), 77 are faster (the other 4 are sub-millisecond or few-millisecond cases within timing noise,
364
+ 0.89–0.99×), and the geometric-mean speed-up across all
365
+ 27 cases and three sizes is **4.08×**. At 1,000,000 samples (pixels for
347
366
  segmentation; 1,000 images for detection and 50 for Hausdorff; 10,000 examples for the LLM cases), in
348
367
  alphabetical order:
349
368
 
350
369
  | Case | Reference | EvalSuite (ms) | Reference (ms) | Speed-up |
351
370
  | --- | --- | ---: | ---: | ---: |
352
- | 10 classes: macro F1 | scikit-learn | 7.1 | 113.7 | **15.9×** |
353
- | agreement: Krippendorff's alpha, interval (4 raters × 10000 items) | krippendorff | 1.4 | 2.8 | **2.0×** |
354
- | binary: 8 label metrics via evaluate() | scikit-learn | 9.3 | 841.2 | **90.2×** |
355
- | binary: ROC AUC | scikit-learn | 171.4 | 294.0 | **1.7×** |
356
- | calibration: slope and intercept | statsmodels | 227.7 | 1188.2 | **5.2×** |
357
- | clinical: diagnostic report (7 CIs) | statsmodels | 5.0 | 5.4 | **1.1×** |
358
- | clinical: sensitivity, specificity, LR+, LR− | scikit-learn | 19.5 | 352.0 | **18.1×** |
359
- | decision curve: 99 thresholds | NumPy loop | 149.2 | 200.9 | **1.3×** |
360
- | detection: COCO evaluation (1000 images) | pycocotools | 369.0 | 683.1 | **1.9×** |
361
- | multiple testing: Hochberg (n p-values) | statsmodels | 78.8 | 84.9 | **1.1×** |
362
- | regression: MAE, MSE, RMSE, R² via evaluate() | scikit-learn | 9.4 | 13.5 | **1.4×** |
363
- | retrieval: MRR, MAP@20, NDCG@10 (10000 queries) | ranx | 120.5 | 589.9 | **4.9×** |
364
- | segmentation: Dice and IoU per class (n = pixels) | scikit-learn | 30.9 | 224.5 | **7.3×** |
365
- | segmentation: Hausdorff distance (50 images) | SciPy | 7.1 | 13.3 | **1.9×** |
366
- | statistics: Cramér's V (5×5 table) | SciPy | 0.0 | 0.2 | **11.1×** |
367
- | statistics: Mann–Whitney U | SciPy | 148.0 | 317.1 | **2.1×** |
368
- | statistics: Welch t-test | SciPy | 7.1 | 9.7 | **1.4×** |
369
- | structured: JSON Schema compliance (10000 documents) | jsonschema | 98.0 | 223.3 | **2.3×** |
370
- | systems: CodeBLEU n-gram terms (1000 programs) | codebleu | 431.3 | 523.0 | **1.2×** |
371
- | systems: confidence AUROC (n answers) | scikit-learn | 160.5 | 273.0 | **1.7×** |
372
- | systems: distribution-shift drop, Welch CI (n scores) | SciPy | 6.7 | 7.2 | **1.1×** |
373
- | systems: invalid tool calls vs JSON Schema (10000 tasks) | jsonschema | 105.0 | 225.6 | **2.1×** |
374
- | systems: latency p50 / p95 / p99 (n requests) | NumPy | 10.8 | 12.2 | **1.1×** |
375
- | systems: maintainability index (1000 programs) | radon | 90.3 | 99.3 | **1.1×** |
376
- | text: corpus BLEU and chrF (10000 sentences) | sacreBLEU | 1435.8 | 2056.4 | **1.4×** |
377
- | text: METEOR, exact and stem matches (10000 sentences) | NLTK | 124.7 | 384.4 | **3.1×** |
378
- | text: ROUGE-1, ROUGE-2, ROUGE-L (10000 sentences) | rouge-score | 354.7 | 618.6 | **1.7×** |
371
+ | 10 classes: macro F1 | scikit-learn | 6.9 | 102.4 | **14.7×** |
372
+ | agreement: Krippendorff's alpha, interval (4 raters × 10000 items) | krippendorff | 1.4 | 3.3 | **2.4×** |
373
+ | binary: 8 label metrics via evaluate() | scikit-learn | 9.1 | 815.4 | **90.0×** |
374
+ | binary: ROC AUC | scikit-learn | 144.4 | 253.0 | **1.8×** |
375
+ | calibration: slope and intercept | statsmodels | 163.2 | 921.9 | **5.6×** |
376
+ | clinical: diagnostic report (7 CIs) | statsmodels | 4.3 | 4.5 | **1.0×** |
377
+ | clinical: sensitivity, specificity, LR+, LR− | scikit-learn | 17.1 | 312.0 | **18.2×** |
378
+ | decision curve: 99 thresholds | NumPy loop | 129.9 | 169.5 | **1.3×** |
379
+ | detection: COCO evaluation (1000 images) | pycocotools | 27.3 | 616.0 | **22.5×** |
380
+ | multiple testing: Hochberg (n p-values) | statsmodels | 85.8 | 82.8 | 0.97× |
381
+ | regression: MAE, MSE, RMSE, R² via evaluate() | scikit-learn | 5.6 | 9.3 | **1.7×** |
382
+ | retrieval: MRR, MAP@20, NDCG@10 (10000 queries) | ranx | 122.2 | 587.7 | **4.8×** |
383
+ | segmentation: Dice and IoU per class (n = pixels) | scikit-learn | 28.9 | 204.9 | **7.1×** |
384
+ | segmentation: Hausdorff distance (50 images) | SciPy | 7.0 | 13.5 | **1.9×** |
385
+ | statistics: Cramér's V (5×5 table) | SciPy | 0.0 | 0.2 | **12.1×** |
386
+ | statistics: Mann–Whitney U | SciPy | 109.9 | 331.5 | **3.0×** |
387
+ | statistics: Welch t-test | SciPy | 4.9 | 7.2 | **1.5×** |
388
+ | structured: JSON Schema compliance (10000 documents) | jsonschema | 95.3 | 224.5 | **2.4×** |
389
+ | systems: CodeBLEU n-gram terms (1000 programs) | codebleu | 324.0 | 521.4 | **1.6×** |
390
+ | systems: confidence AUROC (n answers) | scikit-learn | 168.4 | 278.7 | **1.7×** |
391
+ | systems: distribution-shift drop, Welch CI (n scores) | SciPy | 11.5 | 12.4 | **1.1×** |
392
+ | systems: invalid tool calls vs JSON Schema (10000 tasks) | jsonschema | 109.0 | 209.2 | **1.9×** |
393
+ | systems: latency p50 / p95 / p99 (n requests) | NumPy | 14.9 | 13.3 | 0.89× |
394
+ | systems: maintainability index (1000 programs) | radon | 89.8 | 97.2 | **1.1×** |
395
+ | text: corpus BLEU and chrF (10000 sentences) | sacreBLEU | 175.8 | 1965.7 | **11.2×** |
396
+ | text: METEOR, exact and stem matches (10000 sentences) | NLTK | 61.5 | 369.6 | **6.0×** |
397
+ | text: ROUGE-1, ROUGE-2, ROUGE-L (10000 sentences) | rouge-score | 153.9 | 617.2 | **4.0×** |
379
398
 
380
399
  **Every metric is benchmarked too** (`evalsuite benchmark --suite metrics`): all 225 registered metrics and
381
400
  statistics functions at 10,000 and 100,000 samples. 86 are compared with a reference library, 118 with an
382
401
  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.97×** (172 of 172
402
+ comparisons agree**, and against the libraries the geometric-mean speed-up is **6.32×** (172 of 172
384
403
  measurements faster). Per-metric table in BENCHMARKS.md.
385
404
 
386
- **Every row is faster than its reference.** `evaluate()` validates inputs once and builds the confusion
405
+ **Every substantial workload is faster than its reference.** The text metrics (BLEU, chrF, TER, ROUGE, METEOR, CIDEr,
406
+ CodeBLEU's n-gram terms, distinct-n), the whole COCO evaluation (IoU, score sort, matching, accumulation) and
407
+ bootstrap resampling run in the compiled, multithreaded Rust core; bootstrap intervals, paired bootstrap tests and
408
+ `compare()` evaluate confusion-matrix metrics from counts of each resample's (true, predicted) pairs instead of
409
+ copies of the data. `evaluate()` validates inputs once and builds the confusion
387
410
  matrix once for all metrics, and integer labels are encoded without sorting. The rank tests rank the data once
388
411
  with a single unstable sort; t-tests, χ², Fisher and McNemar compute their statistics directly, and
389
412
  Shapiro–Wilk caches its weights per sample size. Percentiles select exactly from a small bracketed window
@@ -460,13 +483,21 @@ throughput, token usage, cost, resource utilization, energy per request, request
460
483
 
461
484
  ## Development
462
485
 
486
+ Building from source needs a Rust toolchain ([rustup](https://rustup.rs)); the compiled core is in `rust/`
487
+ (`evalsuite-core`, pure Rust, and `evalsuite-py`, the PyO3 bindings), built by maturin.
488
+
463
489
  ```bash
464
490
  python -m venv .venv && source .venv/bin/activate
465
- pip install -e ".[dev]"
491
+ pip install -e ".[dev]" # builds the Rust core into evalsuite._core
466
492
  pytest --cov=evalsuite
493
+ EVALSUITE_PURE_PYTHON=1 pytest -q # the same suite without the compiled core
467
494
  ruff check . && ruff format --check . && mypy
495
+ cargo test --manifest-path rust/Cargo.toml -p evalsuite-core
468
496
  ```
469
497
 
498
+ Every compiled kernel is a port of a Python implementation that stays in the package as the reference and
499
+ fallback; `tests/test_native.py` checks that the two give identical results. See CONTRIBUTING.md.
500
+
470
501
  ## Links
471
502
 
472
503
  - 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=haMBiKqPDmHGoGbq4Cn8iFmm1Vt-tFYYsyRQ3XLyueE,2351
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=zkX3WSKuq1OSPNDgxz_PtvD9HNamLsi-tcTFfNMpvmU,98
12
+ evalsuite/version.py,sha256=p3Fe2L1wp0T3qdA8A55WJIZNiR8w9njp8yc2Ul8I9bg,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
@@ -28,7 +29,7 @@ evalsuite/core/validation.py,sha256=nZRWSuShdFBDYgXMnRmspSQ4AJPRO3Zy5M8wTFfkg2E,
28
29
  evalsuite/llmsys/__init__.py,sha256=NA-kVMc3hdmBSW-ufPKrgfd2NHI15wCXJRn3ZhIVFsE,4653
29
30
  evalsuite/llmsys/_common.py,sha256=Hp9yuO8ItEqr5v1B5fU6-ZVSB3EkvHavnspiPGVmsLM,8713
30
31
  evalsuite/llmsys/agents.py,sha256=giiHv3c179fFR6aFUp4VbBjzbdNotS941tZVG7W0UFE,15355
31
- evalsuite/llmsys/code.py,sha256=6Im0Km5qPHLFTF4S4dnN05OucFFNRixRchDSGHqtJaQ,37004
32
+ evalsuite/llmsys/code.py,sha256=OIyH3aKbuzmH3131wfkj98k5QrrvPwQ1dvCCY4WXD4Y,37528
32
33
  evalsuite/llmsys/efficiency.py,sha256=GlUSWNnzRaeuebv-SZYsB28StwIPYb8AIyMwM057g_A,13895
33
34
  evalsuite/llmsys/longcontext.py,sha256=koX58FMot3ZwUTPPiv9tM8fGvBY2ijYg0npA8pG278A,15145
34
35
  evalsuite/llmsys/multilingual.py,sha256=utAlQfQ2hPgav9-3IzY1yhgwyncaTZ-zFp_0koBEBzE,14241
@@ -38,17 +39,17 @@ 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/compare.py,sha256=TzBYHDbfHU1Uz2FtgXbMATTnmHuaDGUbrV9Eq4IphZY,18311
42
+ evalsuite/stats/_resolve.py,sha256=T5EUqTbiGM0oor59Nzm18GUr7oLWcpgj1l8gCU56ACc,10276
43
+ evalsuite/stats/compare.py,sha256=ooO5STzocKrqNsxKvm_C4Bl1c36_7fziCJc-d2cJASA,18531
43
44
  evalsuite/stats/effect.py,sha256=bgnhdCI4vU_Wnv5q7G2ncmtN3n7N1GWiYO4iO3FDI0w,7286
44
45
  evalsuite/stats/hypothesis.py,sha256=RCu8yPTOhtetFQ5TlZQWaFu2t-aq56ffaNlEqC-lJbg,24546
45
- evalsuite/stats/intervals.py,sha256=a0-SqHE3vYWNjCrtLCGWAFcCPqYki7iSn_0IGhWGNBw,14027
46
- evalsuite/stats/paired.py,sha256=PZV0XED3HnjOD675Tj6z1ILGxUaesBpxXQgC0goi6o4,8439
46
+ evalsuite/stats/intervals.py,sha256=6v7JG_lY4DWrAdcBqiwKsxvBMLgu1RKjdcXaIiqeYqc,16712
47
+ evalsuite/stats/paired.py,sha256=guPwpss0XQWRzL4hWL9xE4mgF6bUQQ2FbkNMkyhxrlc,8663
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=1VVeH23ePRfNkXRCVdIGukwGBY1bZk5BHZxnqggsP_k,46135
52
+ evalsuite/text/generation.py,sha256=qrpOvt2T_Fom2M_6YquEEnJbMCr_KwR1kEqtUH6N0tc,52420
52
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
@@ -59,11 +60,11 @@ evalsuite/text/semantic.py,sha256=TgBBDcRll7vMzQVYStgt1SS9G7e6FTf7SuZDcPL32_g,23
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=I5Poh7mfHojpNKZKv7Gqb8e1coFMpfCnFgsYHJPsZ4Y,28897
63
+ evalsuite/vision/detection.py,sha256=Cjr-Y5-pV0wiQk1JiHLYvDdKzMlCEvVQarzY7fqGWw4,32010
63
64
  evalsuite/vision/segmentation.py,sha256=f41Q8iOELCj8jmAJ3pN5OFr3h3-6QtjnluW8rfkg0V0,41132
64
- evalsuite_python-0.5.5.dist-info/METADATA,sha256=6ToDN7BFpYqtiYRvV-epwFsFGxcXV_nnLs0JA4o8zOw,25958
65
- evalsuite_python-0.5.5.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
66
- evalsuite_python-0.5.5.dist-info/entry_points.txt,sha256=YYIwisn4L4sQt3ntzbM0_Z4yZE2KCu3GJ6KfWL1kIwc,54
67
- evalsuite_python-0.5.5.dist-info/licenses/LICENSE,sha256=cRRQ6Kk8w2qCqtDSSUJQGy-0rqjmjJG09cZ6iIiMvdc,1095
68
- evalsuite_python-0.5.5.dist-info/licenses/LICENSE-APACHE,sha256=K4pWYv3dt61u1BuIxjOGBxhgRkpsH4X_dzeIbOILXw0,10784
69
- evalsuite_python-0.5.5.dist-info/RECORD,,
65
+ evalsuite_python-0.6.1.dist-info/METADATA,sha256=Q407ezIaq42FBsXpbi8kqfbTKwUp3Yn74i5jMjn_P4Q,28579
66
+ evalsuite_python-0.6.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
67
+ evalsuite_python-0.6.1.dist-info/entry_points.txt,sha256=YYIwisn4L4sQt3ntzbM0_Z4yZE2KCu3GJ6KfWL1kIwc,54
68
+ evalsuite_python-0.6.1.dist-info/licenses/LICENSE,sha256=cRRQ6Kk8w2qCqtDSSUJQGy-0rqjmjJG09cZ6iIiMvdc,1095
69
+ evalsuite_python-0.6.1.dist-info/licenses/LICENSE-APACHE,sha256=K4pWYv3dt61u1BuIxjOGBxhgRkpsH4X_dzeIbOILXw0,10784
70
+ evalsuite_python-0.6.1.dist-info/RECORD,,