evalsuite-python 0.6.0__cp39-abi3-win_amd64.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.
Files changed (72) hide show
  1. evalsuite/__init__.py +268 -0
  2. evalsuite/__main__.py +5 -0
  3. evalsuite/_bench_metrics.py +2080 -0
  4. evalsuite/_core.pyd +0 -0
  5. evalsuite/_lazy.py +32 -0
  6. evalsuite/_native.py +60 -0
  7. evalsuite/api.py +275 -0
  8. evalsuite/benchmarks.py +946 -0
  9. evalsuite/calibration.py +392 -0
  10. evalsuite/classification/__init__.py +51 -0
  11. evalsuite/classification/_common.py +111 -0
  12. evalsuite/classification/metrics.py +945 -0
  13. evalsuite/cli/__init__.py +5 -0
  14. evalsuite/cli/main.py +606 -0
  15. evalsuite/clinical/__init__.py +18 -0
  16. evalsuite/clinical/metrics.py +342 -0
  17. evalsuite/clinical/report.py +366 -0
  18. evalsuite/core/__init__.py +1 -0
  19. evalsuite/core/context.py +199 -0
  20. evalsuite/core/exceptions.py +52 -0
  21. evalsuite/core/export.py +100 -0
  22. evalsuite/core/registry.py +90 -0
  23. evalsuite/core/result.py +379 -0
  24. evalsuite/core/types.py +23 -0
  25. evalsuite/core/validation.py +256 -0
  26. evalsuite/llmsys/__init__.py +189 -0
  27. evalsuite/llmsys/_common.py +215 -0
  28. evalsuite/llmsys/agents.py +384 -0
  29. evalsuite/llmsys/code.py +923 -0
  30. evalsuite/llmsys/efficiency.py +346 -0
  31. evalsuite/llmsys/longcontext.py +361 -0
  32. evalsuite/llmsys/multilingual.py +339 -0
  33. evalsuite/llmsys/robustness.py +504 -0
  34. evalsuite/llmsys/safety.py +509 -0
  35. evalsuite/llmsys/uncertainty.py +229 -0
  36. evalsuite/plot.py +651 -0
  37. evalsuite/py.typed +0 -0
  38. evalsuite/regression/__init__.py +41 -0
  39. evalsuite/regression/metrics.py +629 -0
  40. evalsuite/reporting.py +241 -0
  41. evalsuite/stats/__init__.py +46 -0
  42. evalsuite/stats/_resolve.py +229 -0
  43. evalsuite/stats/compare.py +420 -0
  44. evalsuite/stats/effect.py +159 -0
  45. evalsuite/stats/hypothesis.py +593 -0
  46. evalsuite/stats/intervals.py +338 -0
  47. evalsuite/stats/paired.py +214 -0
  48. evalsuite/stats/results.py +129 -0
  49. evalsuite/text/__init__.py +154 -0
  50. evalsuite/text/_common.py +97 -0
  51. evalsuite/text/factuality.py +469 -0
  52. evalsuite/text/generation.py +1346 -0
  53. evalsuite/text/judge.py +556 -0
  54. evalsuite/text/qa.py +108 -0
  55. evalsuite/text/rag.py +235 -0
  56. evalsuite/text/reasoning.py +215 -0
  57. evalsuite/text/report.py +158 -0
  58. evalsuite/text/retrieval.py +238 -0
  59. evalsuite/text/semantic.py +499 -0
  60. evalsuite/text/spice.py +162 -0
  61. evalsuite/text/structured.py +793 -0
  62. evalsuite/version.py +3 -0
  63. evalsuite/vision/__init__.py +47 -0
  64. evalsuite/vision/detection.py +696 -0
  65. evalsuite/vision/segmentation.py +1028 -0
  66. evalsuite_python-0.6.0.dist-info/METADATA +509 -0
  67. evalsuite_python-0.6.0.dist-info/RECORD +72 -0
  68. evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
  69. evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
  70. evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
  71. evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
  72. evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
evalsuite/_core.pyd ADDED
Binary file
evalsuite/_lazy.py ADDED
@@ -0,0 +1,32 @@
1
+ """Deferred imports for heavy optional-at-import-time dependencies (SciPy submodules).
2
+
3
+ ``import evalsuite`` should not pay for SciPy until a function that needs it runs.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib
9
+ from types import ModuleType
10
+ from typing import Any
11
+
12
+
13
+ class LazyModule(ModuleType):
14
+ """Module proxy that imports the real module on first attribute access."""
15
+
16
+ def __init__(self, name: str) -> None:
17
+ super().__init__(name)
18
+ self.__dict__["_mod"] = None
19
+
20
+ def _load(self) -> ModuleType:
21
+ mod = self.__dict__["_mod"]
22
+ if mod is None:
23
+ mod = importlib.import_module(self.__name__)
24
+ self.__dict__["_mod"] = mod
25
+ return mod # type: ignore[no-any-return]
26
+
27
+ def __getattr__(self, attr: str) -> Any:
28
+ return getattr(self._load(), attr)
29
+
30
+
31
+ def lazy_module(name: str) -> Any:
32
+ return LazyModule(name)
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
evalsuite/api.py ADDED
@@ -0,0 +1,275 @@
1
+ """High-level API: ``evaluate()``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ from collections.abc import Sequence
7
+ from typing import Any, Callable, Optional
8
+
9
+ import numpy as np
10
+
11
+ from .classification import metrics as clf
12
+ from .classification._common import averaged
13
+ from .core.context import ClassificationContext
14
+ from .core.exceptions import InputValidationError, UnsupportedTaskError
15
+ from .core.result import EvaluationResult, MetricResult
16
+ from .core.types import ArrayLike, ZeroDivision
17
+ from .core.validation import target_type, to_numpy
18
+ from .regression import metrics as reg
19
+ from .version import __version__
20
+
21
+ __all__ = ["evaluate"]
22
+
23
+ CtxMetric = Callable[[ClassificationContext], MetricResult]
24
+
25
+
26
+ def _classification_registry(
27
+ average: Optional[str], pos_label: Any, zero_division: ZeroDivision
28
+ ) -> dict[str, tuple[CtxMetric, bool]]:
29
+ """metric id -> (function of a shared context, needs probabilities)."""
30
+
31
+ def avg(fn: Any, metric: str, name: str) -> CtxMetric:
32
+ return lambda ctx: averaged(
33
+ ctx,
34
+ fn,
35
+ metric=metric,
36
+ name=name,
37
+ average=average,
38
+ pos_label=pos_label,
39
+ zero_division=zero_division,
40
+ )
41
+
42
+ return {
43
+ "accuracy": (clf._accuracy, False),
44
+ "balanced_accuracy": (clf._balanced_accuracy, False),
45
+ "precision": (avg(clf._precision, "precision", "Precision"), False),
46
+ "recall": (avg(clf._recall, "recall", "Recall"), False),
47
+ "f1": (avg(clf._fbeta_fn(1.0), "f1", "F1"), False),
48
+ "specificity": (avg(clf._specificity, "specificity", "Specificity"), False),
49
+ "npv": (avg(clf._npv, "npv", "NPV"), False),
50
+ "jaccard": (avg(clf._jaccard, "jaccard", "Jaccard"), False),
51
+ "mcc": (lambda ctx: clf._mcc(ctx, zero_division), False),
52
+ "cohen_kappa": (lambda ctx: clf._cohen_kappa(ctx, None, zero_division), False),
53
+ "hamming_loss": (_hamming, False),
54
+ "roc_auc": (lambda ctx: clf._roc_auc(ctx, average=average, pos_label=pos_label), True),
55
+ "average_precision": (
56
+ lambda ctx: clf._average_precision(ctx, average=average, pos_label=pos_label),
57
+ True,
58
+ ),
59
+ "log_loss": (lambda ctx: clf._log_loss(ctx, pos_label), True),
60
+ "brier_score": (lambda ctx: clf._brier(ctx, pos_label), True),
61
+ }
62
+
63
+
64
+ def _hamming(ctx: ClassificationContext) -> MetricResult:
65
+ if ctx.target_type == "multilabel":
66
+ if ctx.y_pred is None:
67
+ raise InputValidationError("y_pred is required for this metric.")
68
+ wrong = (ctx.y_true != ctx.y_pred).mean(axis=1)
69
+ else:
70
+ wrong = (ctx.true_idx != ctx.pred_idx).astype(float)
71
+ return MetricResult("hamming_loss", "Hamming loss", float(np.average(wrong, weights=ctx.weights)))
72
+
73
+
74
+ _DEFAULT_SINGLE = [
75
+ "accuracy",
76
+ "balanced_accuracy",
77
+ "precision",
78
+ "recall",
79
+ "f1",
80
+ "specificity",
81
+ "mcc",
82
+ "cohen_kappa",
83
+ ]
84
+ _DEFAULT_MULTILABEL = ["accuracy", "hamming_loss", "precision", "recall", "f1", "jaccard"]
85
+ _DEFAULT_PROB = ["roc_auc", "average_precision", "log_loss", "brier_score"]
86
+ _DEFAULT_PROB_MULTILABEL = ["roc_auc", "average_precision"]
87
+
88
+ _REGRESSION: dict[str, Callable[..., MetricResult]] = {
89
+ "mae": reg.mae,
90
+ "mse": reg.mse,
91
+ "rmse": reg.rmse,
92
+ "r2": reg.r2,
93
+ "explained_variance": reg.explained_variance,
94
+ "median_absolute_error": reg.median_absolute_error,
95
+ "max_error": reg.max_error,
96
+ "mean_bias_error": reg.mean_bias_error,
97
+ "mape": reg.mape,
98
+ "smape": reg.smape,
99
+ "msle": reg.msle,
100
+ "rmsle": reg.rmsle,
101
+ "rae": reg.rae,
102
+ "rse": reg.rse,
103
+ "huber_loss": reg.huber_loss,
104
+ "quantile_loss": reg.quantile_loss,
105
+ }
106
+ _DEFAULT_REGRESSION = [
107
+ "mae",
108
+ "mse",
109
+ "rmse",
110
+ "r2",
111
+ "explained_variance",
112
+ "median_absolute_error",
113
+ "max_error",
114
+ "mean_bias_error",
115
+ ]
116
+ _NO_WEIGHTS = {"max_error"}
117
+
118
+
119
+ def _infer_task(y_true: ArrayLike, y_prob: Optional[ArrayLike]) -> str:
120
+ if y_prob is not None:
121
+ return "classification"
122
+ return (
123
+ "regression"
124
+ if target_type(to_numpy(y_true, "y_true", allow_2d=True)) == "continuous"
125
+ else "classification"
126
+ )
127
+
128
+
129
+ def evaluate(
130
+ y_true: ArrayLike,
131
+ y_pred: Optional[ArrayLike] = None,
132
+ *,
133
+ y_prob: Optional[ArrayLike] = None,
134
+ task: Optional[str] = None,
135
+ metrics: Optional[Sequence[str]] = None,
136
+ average: Optional[str] = "auto",
137
+ labels: Optional[ArrayLike] = None,
138
+ pos_label: Any = None,
139
+ sample_weight: Optional[ArrayLike] = None,
140
+ zero_division: ZeroDivision = "warn",
141
+ ) -> EvaluationResult:
142
+ """Evaluate predictions with a standard set of metrics (or the ``metrics`` you name).
143
+
144
+ The task is inferred when omitted: probabilities or integer/string labels mean classification, non-integer
145
+ numbers mean regression. Inputs are validated once and shared intermediate results (the confusion matrix)
146
+ are computed once for all metrics.
147
+
148
+ >>> import evalsuite as es
149
+ >>> r = es.evaluate([0, 1, 1, 0], [0, 1, 0, 0])
150
+ >>> round(r["accuracy"], 2)
151
+ 0.75
152
+ """
153
+ if isinstance(y_true, (list, tuple)) and y_true and isinstance(y_true[0], dict):
154
+ raise UnsupportedTaskError(
155
+ "y_true looks like object detection annotations (one dict per image); use "
156
+ "evalsuite.detection_report(y_true, y_pred) or evalsuite.mean_average_precision(...)."
157
+ )
158
+ if np.ndim(y_true) >= 3:
159
+ raise UnsupportedTaskError(
160
+ "y_true has 3 or more dimensions, which looks like segmentation masks (images first); use "
161
+ "evalsuite.segmentation_report(y_true, y_pred) or evalsuite.dice / evalsuite.iou."
162
+ )
163
+ task = task or _infer_task(y_true, y_prob)
164
+ if task == "classification":
165
+ return _evaluate_classification(
166
+ y_true, y_pred, y_prob, metrics, average, labels, pos_label, sample_weight, zero_division
167
+ )
168
+ if task == "regression":
169
+ if y_pred is None:
170
+ raise InputValidationError("Regression evaluation needs y_pred.")
171
+ return _evaluate_regression(y_true, y_pred, metrics, sample_weight)
172
+ raise UnsupportedTaskError("task must be 'classification' or 'regression' in EvalSuite 0.1.")
173
+
174
+
175
+ def _metadata(**extra: Any) -> dict[str, Any]:
176
+ return {
177
+ "evalsuite_version": __version__,
178
+ "numpy_version": np.__version__,
179
+ "python_version": platform.python_version(),
180
+ **extra,
181
+ }
182
+
183
+
184
+ def _evaluate_classification(
185
+ y_true: ArrayLike,
186
+ y_pred: Optional[ArrayLike],
187
+ y_prob: Optional[ArrayLike],
188
+ metrics: Optional[Sequence[str]],
189
+ average: Optional[str],
190
+ labels: Optional[ArrayLike],
191
+ pos_label: Any,
192
+ sample_weight: Optional[ArrayLike],
193
+ zero_division: ZeroDivision,
194
+ ) -> EvaluationResult:
195
+ if y_pred is None and y_prob is None:
196
+ raise InputValidationError("Classification evaluation needs y_pred, y_prob, or both.")
197
+ ctx = ClassificationContext(y_true, y_pred, y_prob=y_prob, labels=labels, sample_weight=sample_weight)
198
+ registry = _classification_registry(average, pos_label, zero_division)
199
+ if metrics is None:
200
+ multilabel = ctx.target_type == "multilabel"
201
+ names = [] if y_pred is None else list(_DEFAULT_MULTILABEL if multilabel else _DEFAULT_SINGLE)
202
+ if y_prob is not None:
203
+ names += _DEFAULT_PROB_MULTILABEL if multilabel else _DEFAULT_PROB
204
+ else:
205
+ names = list(metrics)
206
+ unknown = [m for m in names if m not in registry]
207
+ if unknown:
208
+ raise InputValidationError(
209
+ f"Unknown classification metric(s): {', '.join(unknown)}. Available: {', '.join(registry)}."
210
+ )
211
+ out: dict[str, MetricResult] = {}
212
+ for name in names:
213
+ fn, needs_prob = registry[name]
214
+ if needs_prob and y_prob is None:
215
+ raise InputValidationError(f"Metric '{name}' needs y_prob (predicted probabilities).")
216
+ if not needs_prob and y_pred is None:
217
+ raise InputValidationError(f"Metric '{name}' needs y_pred (predicted labels).")
218
+ out[name] = fn(ctx)
219
+ cm = None if ctx.target_type == "multilabel" or y_pred is None else ctx.confusion_matrix
220
+ return EvaluationResult(
221
+ task="classification",
222
+ metrics=out,
223
+ n_samples=ctx.n,
224
+ target_type=ctx.target_type,
225
+ labels=tuple(ctx.labels.tolist()),
226
+ confusion_matrix=cm,
227
+ metadata=_metadata(average=average, zero_division=zero_division, weighted=sample_weight is not None),
228
+ )
229
+
230
+
231
+ def _evaluate_regression(
232
+ y_true: ArrayLike, y_pred: ArrayLike, metrics: Optional[Sequence[str]], sample_weight: Optional[ArrayLike]
233
+ ) -> EvaluationResult:
234
+ yt = to_numpy(y_true, "y_true", allow_2d=True)
235
+ multi = yt.ndim == 2
236
+ if metrics is None:
237
+ names = [m for m in _DEFAULT_REGRESSION if not (multi and m == "max_error")]
238
+ else:
239
+ names = list(metrics)
240
+ unknown = [m for m in names if m not in _REGRESSION]
241
+ if unknown:
242
+ raise InputValidationError(
243
+ f"Unknown regression metric(s): {', '.join(unknown)}. Available: {', '.join(_REGRESSION)}."
244
+ )
245
+ out: dict[str, MetricResult] = {}
246
+ shared = reg._Inputs(y_true, y_pred, sample_weight) # validate once for every metric
247
+ token = reg._SHARED.set((id(y_true), id(y_pred), id(sample_weight), shared))
248
+ try:
249
+ _regression_loop(names, out, y_true, y_pred, sample_weight)
250
+ finally:
251
+ reg._SHARED.reset(token)
252
+ return EvaluationResult(
253
+ task="regression",
254
+ metrics=out,
255
+ n_samples=yt.shape[0],
256
+ target_type="continuous",
257
+ metadata=_metadata(weighted=sample_weight is not None, outputs=yt.shape[1] if multi else 1),
258
+ )
259
+
260
+
261
+ def _regression_loop(
262
+ names: list[str],
263
+ out: dict[str, MetricResult],
264
+ y_true: ArrayLike,
265
+ y_pred: ArrayLike,
266
+ sample_weight: Optional[ArrayLike],
267
+ ) -> None:
268
+ for name in names:
269
+ fn = _REGRESSION[name]
270
+ if name in _NO_WEIGHTS:
271
+ if sample_weight is not None:
272
+ raise InputValidationError(f"Metric '{name}' does not support sample_weight.")
273
+ out[name] = fn(y_true, y_pred)
274
+ else:
275
+ out[name] = fn(y_true, y_pred, sample_weight=sample_weight)