evalsuite-python 2.1.0__py3-none-any.whl → 2.1.3__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.
Files changed (59) hide show
  1. evalsuite/_bench_metrics.py +2 -1
  2. evalsuite/_evalci.py +1 -1
  3. evalsuite/_http.py +87 -0
  4. evalsuite/_models.py +293 -0
  5. evalsuite/_parquet.py +631 -0
  6. evalsuite/_spatial.py +194 -0
  7. evalsuite/_special.py +785 -0
  8. evalsuite/_stats.py +1403 -0
  9. evalsuite/_table.py +214 -0
  10. evalsuite/agreement.py +9 -5
  11. evalsuite/auto_report.py +20 -1
  12. evalsuite/bayes.py +2 -2
  13. evalsuite/benchmarks.py +30 -14
  14. evalsuite/calibration.py +1 -7
  15. evalsuite/cards.py +3 -1
  16. evalsuite/cli/main.py +22 -2
  17. evalsuite/clinical/report.py +1 -7
  18. evalsuite/comparisons.py +28 -31
  19. evalsuite/core/registry.py +2 -0
  20. evalsuite/data_quality.py +6 -8
  21. evalsuite/drift.py +4 -5
  22. evalsuite/forecasting.py +30 -12
  23. evalsuite/html_report.py +5 -0
  24. evalsuite/judging.py +1 -15
  25. evalsuite/llm_benchmarks.py +65 -17
  26. evalsuite/llm_eval.py +79 -46
  27. evalsuite/llmsys/robustness.py +1 -1
  28. evalsuite/llmsys/uncertainty.py +1 -1
  29. evalsuite/monitor.py +1 -1
  30. evalsuite/rag_report.py +1 -1
  31. evalsuite/recalibration.py +9 -4
  32. evalsuite/reclassification.py +2 -3
  33. evalsuite/slices.py +1 -2
  34. evalsuite/stats/effect.py +2 -8
  35. evalsuite/stats/hypothesis.py +12 -38
  36. evalsuite/stats/intervals.py +12 -13
  37. evalsuite/stats/paired.py +2 -9
  38. evalsuite/stats/planning.py +2 -16
  39. evalsuite/streaming.py +1 -1
  40. evalsuite/survival.py +1 -1
  41. evalsuite/text/_porter.py +260 -0
  42. evalsuite/text/_wordnet.py +76 -0
  43. evalsuite/text/data/WORDNET_LICENSE +31 -0
  44. evalsuite/text/data/wordnet30.txt.xz +0 -0
  45. evalsuite/text/generation.py +6 -13
  46. evalsuite/text/judge.py +2 -8
  47. evalsuite/text/report.py +3 -9
  48. evalsuite/text/semantic.py +7 -36
  49. evalsuite/text/spice.py +5 -13
  50. evalsuite/text/structured.py +2 -0
  51. evalsuite/version.py +1 -1
  52. evalsuite/vision/segmentation.py +9 -16
  53. evalsuite/workflow.py +7 -0
  54. {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.3.dist-info}/METADATA +26 -15
  55. {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.3.dist-info}/RECORD +59 -48
  56. {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.3.dist-info}/WHEEL +0 -0
  57. {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.3.dist-info}/entry_points.txt +0 -0
  58. {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.3.dist-info}/licenses/LICENSE +0 -0
  59. {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.3.dist-info}/licenses/LICENSE-APACHE +0 -0
@@ -580,7 +580,8 @@ def _statistics(c: _Cases, n: int, rng: np.random.Generator) -> None:
580
580
  "statistics.shapiro_wilk_test",
581
581
  lambda: _numeric(es.shapiro_wilk_test(xs)),
582
582
  "SciPy",
583
- lambda: list(stats.shapiro(xs)),
583
+ # SciPy runs Royston's algorithm in NumPy (as EvalSuite does) only from 1.18; older SciPy differs
584
+ (lambda: list(stats.shapiro(xs))) if hasattr(getattr(stats, "_morestats", None), "_swilk_w") else None,
584
585
  )
585
586
  c.add(
586
587
  "statistics.t_test",
evalsuite/_evalci.py CHANGED
@@ -25,7 +25,7 @@ _MEAN_LOSSES = {"brier_score", "log_loss", "mae", "mse", "rmse", "mean_bias_erro
25
25
 
26
26
 
27
27
  def _t_quantile(level: float, df: int) -> float:
28
- from scipy import stats
28
+ from . import _stats as stats
29
29
 
30
30
  return float(stats.t.ppf(1 - (1 - level) / 2, df))
31
31
 
evalsuite/_http.py ADDED
@@ -0,0 +1,87 @@
1
+ """Minimal JSON-over-HTTPS client on the standard library (``urllib``), used to call model providers and to
2
+ download benchmark files without third-party SDKs.
3
+
4
+ Errors keep what the retry policy in ``llm_eval`` needs: ``status_code`` and ``response.headers`` (for
5
+ ``Retry-After``). API keys are passed in by the caller from environment variables and are never logged or put in
6
+ error messages.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import urllib.error
13
+ import urllib.request
14
+ from collections.abc import Mapping
15
+ from types import SimpleNamespace
16
+ from typing import Any, Optional
17
+
18
+ __all__ = ["HTTPStatusError", "get_bytes", "post_json"]
19
+
20
+ USER_AGENT = "evalsuite-python"
21
+
22
+
23
+ class HTTPStatusError(Exception):
24
+ """A non-2xx HTTP response. ``status_code`` and ``response.headers`` mirror the provider SDKs' errors."""
25
+
26
+ def __init__(self, status_code: int, message: str, headers: Optional[Mapping[str, str]] = None) -> None:
27
+ super().__init__(f"HTTP {status_code}: {message}")
28
+ self.status_code = status_code
29
+ self.response = SimpleNamespace(
30
+ status_code=status_code, headers={k.lower(): v for k, v in (headers or {}).items()}
31
+ )
32
+
33
+
34
+ def _error_message(body: bytes) -> str:
35
+ """The provider's own error text (OpenAI / Anthropic / Gemini all nest it under ``error.message``)."""
36
+ try:
37
+ data = json.loads(body.decode("utf-8", "replace"))
38
+ except ValueError:
39
+ return body.decode("utf-8", "replace")[:300]
40
+ err = data.get("error") if isinstance(data, dict) else None
41
+ if isinstance(err, dict):
42
+ return str(err.get("message") or err)[:300]
43
+ return str(err or data)[:300]
44
+
45
+
46
+ def _checked(url: str) -> str:
47
+ """Only http(s): urllib would also open file: and other schemes, which a URL from a config must not reach."""
48
+ if not url.lower().startswith(("https://", "http://")):
49
+ from .core.exceptions import InputValidationError
50
+
51
+ raise InputValidationError(f"Only http(s) URLs are allowed; got {url.split(':', 1)[0]!r}.")
52
+ return url
53
+
54
+
55
+ def _open(req: urllib.request.Request, timeout: float) -> tuple[bytes, Mapping[str, str]]:
56
+ try:
57
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 - https / user-given base URL
58
+ return resp.read(), dict(resp.headers.items())
59
+ except urllib.error.HTTPError as exc:
60
+ body = exc.read() if hasattr(exc, "read") else b""
61
+ raise HTTPStatusError(
62
+ exc.code, _error_message(body), dict(exc.headers.items()) if exc.headers else {}
63
+ ) from None
64
+
65
+
66
+ def post_json(url: str, body: Mapping[str, Any], headers: Mapping[str, str], *, timeout: float = 600.0) -> Any:
67
+ """POST ``body`` as JSON and return the decoded JSON reply."""
68
+ data = json.dumps(body).encode("utf-8")
69
+ req = urllib.request.Request(_checked(url), data=data, method="POST") # noqa: S310 - scheme checked
70
+ req.add_header("Content-Type", "application/json")
71
+ req.add_header("User-Agent", USER_AGENT)
72
+ for k, v in headers.items():
73
+ req.add_header(k, v)
74
+ raw, _ = _open(req, timeout)
75
+ try:
76
+ return json.loads(raw.decode("utf-8"))
77
+ except ValueError as exc:
78
+ raise HTTPStatusError(502, f"response is not JSON: {raw[:120]!r}") from exc
79
+
80
+
81
+ def get_bytes(url: str, headers: Optional[Mapping[str, str]] = None, *, timeout: float = 600.0) -> bytes:
82
+ """GET ``url`` (following redirects) and return the body."""
83
+ req = urllib.request.Request(_checked(url), method="GET") # noqa: S310 - scheme checked
84
+ req.add_header("User-Agent", USER_AGENT)
85
+ for k, v in (headers or {}).items():
86
+ req.add_header(k, v)
87
+ return _open(req, timeout)[0]
evalsuite/_models.py ADDED
@@ -0,0 +1,293 @@
1
+ """Clustered-data models written from their estimating equations, so ``clustered_comparison`` needs no statsmodels.
2
+
3
+ ``gee_exchangeable`` is a port of statsmodels' ``GEE`` with an exchangeable working correlation (same starting
4
+ GLM fit by IRLS, same update and stopping rules, same robust sandwich covariance), so it returns statsmodels'
5
+ numbers. ``lmm_random_intercept`` fits a linear mixed model with one random intercept per cluster by restricted
6
+ maximum likelihood: σ² is profiled out and the variance ratio λ = τ²/σ² is found by a bounded one-dimensional
7
+ search, then β̂ = (Σ Xᵢ'Vᵢ⁻¹Xᵢ)⁻¹ Σ Xᵢ'Vᵢ⁻¹yᵢ with Vᵢ⁻¹ ∝ I − λ/(1 + λnᵢ) J.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from dataclasses import dataclass
14
+ from typing import Any
15
+
16
+ import numpy as np
17
+ from numpy.typing import NDArray
18
+
19
+ __all__ = ["FitResult", "gee_exchangeable", "lmm_random_intercept"]
20
+
21
+ _FEPS = float(np.finfo(float).eps)
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class FitResult:
26
+ params: NDArray[np.float64]
27
+ bse: NDArray[np.float64]
28
+ pvalues: NDArray[np.float64]
29
+ converged: bool
30
+ boundary: bool = False
31
+
32
+
33
+ def _clean(p: NDArray[np.float64]) -> NDArray[np.float64]:
34
+ return np.clip(p, _FEPS, 1.0 - _FEPS)
35
+
36
+
37
+ class _Family:
38
+ def __init__(self, binomial: bool) -> None:
39
+ self.binomial = binomial
40
+
41
+ def link(self, mu: NDArray[np.float64]) -> NDArray[np.float64]:
42
+ if self.binomial:
43
+ p = _clean(mu)
44
+ return np.asarray(np.log(p / (1.0 - p)))
45
+ return mu
46
+
47
+ def inverse(self, z: NDArray[np.float64]) -> NDArray[np.float64]:
48
+ return np.asarray(1.0 / (1 + np.exp(-z))) if self.binomial else z
49
+
50
+ def inverse_deriv(self, z: NDArray[np.float64]) -> NDArray[np.float64]:
51
+ if self.binomial:
52
+ t = np.exp(z)
53
+ return np.asarray(t / (1 + t) ** 2)
54
+ return np.ones_like(z)
55
+
56
+ def deriv(self, mu: NDArray[np.float64]) -> NDArray[np.float64]:
57
+ if self.binomial:
58
+ p = _clean(mu)
59
+ return np.asarray(1.0 / (p * (1 - p)))
60
+ return np.ones_like(mu)
61
+
62
+ def variance(self, mu: NDArray[np.float64]) -> NDArray[np.float64]:
63
+ if self.binomial:
64
+ p = _clean(mu)
65
+ return np.asarray(p * (1 - p))
66
+ return np.ones_like(mu)
67
+
68
+ def starting_mu(self, y: NDArray[np.float64]) -> NDArray[np.float64]:
69
+ return (y + 0.5) / 2 if self.binomial else (y + y.mean()) / 2.0
70
+
71
+ def deviance(self, y: NDArray[np.float64], mu: NDArray[np.float64], scale: float) -> float:
72
+ if self.binomial:
73
+ a = _clean(y / mu)
74
+ b = _clean((1 - y) / (1 - mu))
75
+ return float(np.sum(2 * (y * np.log(a) + (1 - y) * np.log(b))))
76
+ return float(np.sum((y - mu) ** 2)) / scale
77
+
78
+
79
+ def _glm_start(y: NDArray[np.float64], x: NDArray[np.float64], fam: _Family) -> NDArray[np.float64]:
80
+ """GLM by IRLS, as statsmodels ``GLM.fit()`` (deviance convergence, tol 1e-8; final pinv WLS solve)."""
81
+ n, k = x.shape
82
+
83
+ def scale_of(mu: NDArray[np.float64]) -> float:
84
+ if fam.binomial:
85
+ return 1.0
86
+ return float(np.sum((y - mu) ** 2 / fam.variance(mu))) / float(n - k)
87
+
88
+ mu = fam.starting_mu(y)
89
+ lin = fam.link(mu)
90
+ dev = [math.inf, fam.deviance(y, mu, scale_of(mu))]
91
+ w = np.ones(n)
92
+ z = lin
93
+ for it in range(100):
94
+ w = 1.0 / (fam.deriv(mu) ** 2 * fam.variance(mu))
95
+ z = lin + fam.deriv(mu) * (y - mu)
96
+ sw = np.sqrt(w)
97
+ params = np.linalg.lstsq(x * sw[:, None], z * sw, rcond=-1)[0]
98
+ lin = x @ params
99
+ mu = fam.inverse(lin)
100
+ dev.append(fam.deviance(y, mu, scale_of(mu)))
101
+ if np.allclose(dev[it + 1], dev[it + 2], atol=1e-8, rtol=0.0):
102
+ break
103
+ sw = np.sqrt(w)
104
+ return np.asarray(np.linalg.pinv(x * sw[:, None]) @ (z * sw), dtype=np.float64)
105
+
106
+
107
+ def gee_exchangeable(
108
+ y: NDArray[np.float64], x: NDArray[np.float64], groups: NDArray[Any], *, binomial: bool
109
+ ) -> FitResult:
110
+ """GEE with an exchangeable working correlation and robust (sandwich) standard errors; logit link for a
111
+ binary ``y`` (``binomial=True``), identity otherwise. Port of statsmodels' ``GEE.fit()`` defaults."""
112
+ fam = _Family(binomial)
113
+ n, k = x.shape
114
+ labels, inv = np.unique(groups, return_inverse=True)
115
+ idx = [np.flatnonzero(inv == g) for g in range(labels.size)]
116
+ ys = [y[i] for i in idx]
117
+ xs = [x[i] for i in idx]
118
+ params = _glm_start(y, x, fam)
119
+ dep = 0.0
120
+
121
+ def means(b: NDArray[np.float64]) -> list[tuple[NDArray[np.float64], NDArray[np.float64]]]:
122
+ out = []
123
+ for xi in xs:
124
+ lp = xi @ b
125
+ out.append((fam.inverse(lp), lp))
126
+ return out
127
+
128
+ def solve(expval: NDArray[np.float64], sdev: NDArray[np.float64], rhs: NDArray[np.float64]) -> Any:
129
+ kk = len(expval)
130
+ c = dep / (1.0 - dep)
131
+ c /= 1.0 + dep * (kk - 1)
132
+ if rhs.ndim == 1:
133
+ x1 = rhs / sdev
134
+ out = x1 / (1.0 - dep)
135
+ out -= c * sum(x1)
136
+ return out / sdev
137
+ x1 = rhs / sdev[:, None]
138
+ out = x1 / (1.0 - dep)
139
+ out -= c * x1.sum(0)
140
+ return out / sdev[:, None]
141
+
142
+ def pieces(cached: list[Any]) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]:
143
+ bmat: Any = 0
144
+ score: Any = 0
145
+ cmat: Any = 0
146
+ for i in range(len(xs)):
147
+ expval, lpr = cached[i]
148
+ resid = ys[i] - expval
149
+ dmat = xs[i] * fam.inverse_deriv(lpr)[:, None]
150
+ sdev = np.sqrt(fam.variance(expval))
151
+ vd = solve(expval, sdev, dmat)
152
+ vr = solve(expval, sdev, resid)
153
+ bmat = bmat + np.dot(dmat.T, vd)
154
+ s_i = np.dot(dmat.T, vr)
155
+ score = score + s_i
156
+ cmat = cmat + np.outer(s_i, s_i)
157
+ return np.asarray(bmat), np.asarray(score), np.asarray(cmat)
158
+
159
+ cached = means(params)
160
+ del_params = -1.0
161
+ n_assoc = 0
162
+ for _ in range(60):
163
+ bmat, score, _c = pieces(cached)
164
+ try:
165
+ update = np.linalg.solve(bmat, score)
166
+ except np.linalg.LinAlgError: # pragma: no cover - a singular design (as statsmodels: pseudo-inverse)
167
+ update = np.dot(np.linalg.pinv(bmat), score)
168
+ params = params + update
169
+ cached = means(params)
170
+ del_params = float(np.sqrt(np.sum(score**2)))
171
+ if del_params < 1e-6 and n_assoc > 0:
172
+ break
173
+ # exchangeable update of the working correlation (statsmodels ``Exchangeable.update``)
174
+ rs_sum = 0.0
175
+ sc = 0.0
176
+ fsum1 = fsum2 = n_pairs = 0.0
177
+ for i in range(len(xs)):
178
+ expval, _ = cached[i]
179
+ r = (ys[i] - expval) / np.sqrt(fam.variance(expval))
180
+ ssr = float(np.sum(r * r))
181
+ sc += ssr
182
+ fsum1 += len(ys[i])
183
+ rs_sum += (float(r.sum()) ** 2 - ssr) / 2
184
+ npr = 0.5 * len(r) * (len(r) - 1)
185
+ fsum2 += npr
186
+ n_pairs += npr
187
+ sc /= fsum1 * (n - k) / float(n)
188
+ rs_sum /= sc
189
+ den = fsum2 * (n_pairs - k) / float(n_pairs) if n_pairs > 0 else 0.0
190
+ dep = rs_sum / den if den > 0 else 0.0 # too few within-cluster pairs: independence
191
+ n_assoc += 1 # noqa: SIM113 - counts association updates (the loop may stop before one)
192
+ bmat, _s, cmat = pieces(cached)
193
+ try:
194
+ bmati = np.linalg.inv(bmat)
195
+ except np.linalg.LinAlgError: # pragma: no cover - a singular design
196
+ bmati = np.linalg.pinv(bmat)
197
+ cov = bmati @ cmat @ bmati
198
+ bse = np.sqrt(np.diag(cov))
199
+ zval = params / bse
200
+ from ._special import ndtr
201
+
202
+ pv = 2 * np.asarray(ndtr(-np.abs(zval)), dtype=np.float64)
203
+ return FitResult(params, bse, pv, del_params < 1e-6)
204
+
205
+
206
+ def lmm_random_intercept(y: NDArray[np.float64], x: NDArray[np.float64], groups: NDArray[Any]) -> FitResult:
207
+ """Linear mixed model y = Xβ + uᵢ + ε with one random intercept per cluster, by REML."""
208
+ n, k = x.shape
209
+ labels, inv = np.unique(groups, return_inverse=True)
210
+ g = labels.size
211
+ ni = np.bincount(inv, minlength=g).astype(np.float64)
212
+ # per-cluster sums let every λ be evaluated in O(k²) after one pass
213
+ sx = np.zeros((g, k))
214
+ np.add.at(sx, inv, x)
215
+ sy = np.bincount(inv, weights=y, minlength=g)
216
+ xtx = x.T @ x
217
+ xty = x.T @ y
218
+ yty = float(y @ y)
219
+
220
+ def parts(lam: float) -> tuple[float, NDArray[np.float64], NDArray[np.float64], float]:
221
+ c = lam / (1.0 + lam * ni) # V⁻¹ ∝ I − c J per cluster
222
+ a = xtx - (sx * c[:, None]).T @ sx
223
+ b = xty - (sx * c[:, None]).T @ sy
224
+ beta = np.linalg.solve(a, b)
225
+ q = yty - float(np.sum(c * sy * sy)) - 2 * float(beta @ b) + float(beta @ a @ beta)
226
+ q = max(q, 0.0)
227
+ logdet_v = float(np.sum(np.log1p(lam * ni)))
228
+ _sign, logdet_a = np.linalg.slogdet(a)
229
+ obj = (n - k) * math.log(q / (n - k)) + logdet_v + float(logdet_a)
230
+ return obj, beta, a, q
231
+
232
+ from ._special import ndtr
233
+ from ._stats import minimize_scalar_bounded
234
+
235
+ res = minimize_scalar_bounded(lambda t: parts(math.exp(t))[0], (-20.0, 12.0), xatol=1e-12)
236
+ lam = math.exp(res.x)
237
+ boundary = parts(0.0)[0] <= res.fun
238
+ if boundary:
239
+ lam = 0.0
240
+ _obj, beta, a, q = parts(lam)
241
+ if boundary or lam < 1e-10:
242
+ # the cluster variance is estimated at zero: ordinary least squares (statsmodels' Hessian is singular here)
243
+ cov = q / (n - k) * np.linalg.inv(a)
244
+ else:
245
+ cov = _lmm_cov(x, y, inv, ni, sx, lam, beta, n, k)
246
+ bse = np.sqrt(np.diag(cov))
247
+ pv = 2 * np.asarray(ndtr(-np.abs(beta / bse)), dtype=np.float64)
248
+ return FitResult(np.asarray(beta), bse, pv, True, boundary or lam < 1e-8)
249
+
250
+
251
+ def _lmm_cov(
252
+ x: NDArray[np.float64],
253
+ y: NDArray[np.float64],
254
+ inv: NDArray[np.intp],
255
+ ni: NDArray[np.float64],
256
+ sx: NDArray[np.float64],
257
+ psi: float,
258
+ beta: NDArray[np.float64],
259
+ n: int,
260
+ k: int,
261
+ ) -> NDArray[np.float64]:
262
+ """Covariance of β̂ from the observed information of the REML log-likelihood in (β, ψ), ψ = τ²/σ² — the
263
+ random-intercept case of statsmodels' ``MixedLM.hessian`` (cross terms between β and ψ included)."""
264
+ r = y - x @ beta
265
+ g = ni.size
266
+ sr = np.bincount(inv, weights=r, minlength=g)
267
+ srr = np.bincount(inv, weights=r * r, minlength=g)
268
+ d = 1.0 + ni * psi
269
+ c = psi / d
270
+ xtvix = x.T @ x - (sx * c[:, None]).T @ sx
271
+ rvir = float(np.sum(srr - c * sr * sr))
272
+ s_ = ni / d # 1'V⁻¹1 per cluster
273
+ w = sx / d[:, None] # X'V⁻¹1
274
+ t = sr / d # 1'V⁻¹r
275
+ hess_fere = (w * t[:, None]).sum(axis=0)
276
+ xtax = w.T @ w
277
+ bb = float(np.sum(t * t))
278
+ dd = float(np.sum(2 * t * t * s_))
279
+ hess_re = float(np.sum(s_ * s_)) / 2
280
+ ff = 2 * (w * s_[:, None]).T @ w
281
+ fac = n - k
282
+ hess_fe = -fac * xtvix / rvir
283
+ hess_re = hess_re - 0.5 * fac * (dd / rvir - bb * bb / rvir**2)
284
+ hess_fere = -fac * hess_fere / rvir
285
+ ql = np.linalg.solve(xtvix, xtax)
286
+ hess_re += 0.5 * (float(np.sum(ql.T * ql)) - float(np.trace(np.linalg.solve(xtvix, ff))))
287
+ hess = np.zeros((k + 1, k + 1))
288
+ hess[:k, :k] = hess_fe
289
+ hess[:k, k] = hess_fere
290
+ hess[k, :k] = hess_fere
291
+ hess[k, k] = hess_re
292
+ cov: NDArray[np.float64] = np.linalg.inv(-hess)[:k, :k]
293
+ return cov