evalsuite-python 1.1.1__py3-none-any.whl → 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
evalsuite/__init__.py CHANGED
@@ -277,3 +277,67 @@ __all__ = [
277
277
  ]
278
278
  __all__ += list(_text_all)
279
279
  __all__ += list(_llmsys_all)
280
+
281
+ from .fairness import FairnessReport, fairness_report # noqa: E402
282
+ from .html_report import html_report # noqa: E402
283
+ from .judging import JudgeReport, RubricReport, judge_report, rubric_report # noqa: E402
284
+ from .llm_benchmarks import BENCHMARKS, format_multiple_choice, load_benchmark # noqa: E402
285
+ from .rag_report import RAGReport, rag_report # noqa: E402
286
+ from .stats.planning import ( # noqa: E402
287
+ SampleSize,
288
+ power_auc,
289
+ power_mean_difference,
290
+ power_two_proportions,
291
+ sample_size_auc,
292
+ sample_size_mean_difference,
293
+ sample_size_proportion,
294
+ sample_size_two_proportions,
295
+ )
296
+ from .survival import ( # noqa: E402
297
+ brier_score_survival,
298
+ concordance_index,
299
+ integrated_brier_score,
300
+ kaplan_meier,
301
+ time_dependent_auc,
302
+ )
303
+
304
+ __all__ += [
305
+ "BENCHMARKS",
306
+ "FairnessReport",
307
+ "JudgeReport",
308
+ "RAGReport",
309
+ "RubricReport",
310
+ "SampleSize",
311
+ "brier_score_survival",
312
+ "concordance_index",
313
+ "fairness_report",
314
+ "format_multiple_choice",
315
+ "html_report",
316
+ "integrated_brier_score",
317
+ "judge_report",
318
+ "kaplan_meier",
319
+ "load_benchmark",
320
+ "power_auc",
321
+ "power_mean_difference",
322
+ "power_two_proportions",
323
+ "rag_report",
324
+ "rubric_report",
325
+ "sample_size_auc",
326
+ "sample_size_mean_difference",
327
+ "sample_size_proportion",
328
+ "sample_size_two_proportions",
329
+ "time_dependent_auc",
330
+ ]
331
+
332
+ import contextlib as _contextlib # noqa: E402
333
+
334
+ from ._update import UpdateInfo, check_for_update, upgrade # noqa: E402
335
+
336
+ __all__ += ["UpdateInfo", "check_for_update", "upgrade"]
337
+
338
+ # A cached, once-a-day notice; the PyPI lookup runs in a background thread (see evalsuite._update). It must
339
+ # never affect importing EvalSuite.
340
+ with _contextlib.suppress(Exception):
341
+ from ._update import notify_on_import as _notify
342
+
343
+ _notify()
evalsuite/_evalci.py CHANGED
@@ -35,7 +35,10 @@ def _mean_ci(terms: np.ndarray, level: float) -> tuple[float, float]:
35
35
  if n < 2:
36
36
  return math.nan, math.nan
37
37
  m = float(np.mean(terms))
38
- se = float(np.std(terms, ddof=1)) / math.sqrt(n)
38
+ d = terms - m
39
+ # Sample standard deviation via a BLAS dot product (one pass over the deviations instead of np.std's
40
+ # several temporaries); same two-pass formula, so the same accuracy.
41
+ se = math.sqrt(float(np.dot(d, d)) / (n - 1)) / math.sqrt(n)
39
42
  q = _t_quantile(level, n - 1)
40
43
  return m - q * se, m + q * se
41
44
 
@@ -108,17 +111,32 @@ def _analytic(
108
111
  out[name] = (max(0.0, lo), hi, "t")
109
112
  elif result.task == "regression" and np.ndim(y_true) == 1:
110
113
  e = np.asarray(y_pred, dtype=float) - np.asarray(y_true, dtype=float)
111
- for name in result.metrics:
112
- if name == "mae":
113
- lo, hi = _mean_ci(np.abs(e), level)
114
- out[name] = (max(0.0, lo), hi, "t")
115
- elif name in ("mse", "rmse"):
116
- lo, hi = _mean_ci(e * e, level)
117
- lo = max(0.0, lo)
118
- out[name] = (lo, hi, "t") if name == "mse" else (math.sqrt(lo), math.sqrt(hi), "t (from MSE)")
119
- elif name == "mean_bias_error":
120
- lo, hi = _mean_ci(e, level)
121
- out[name] = (lo, hi, "t")
114
+ n = e.shape[0]
115
+ if n >= 2:
116
+ # One pass of BLAS dot products serves every error metric: Σe², Σe⁴ (and Σe) give the means and
117
+ # sample variances of |e|, e² and e without temporaries for |e| (|e|·|e| = e·e).
118
+ tq = _t_quantile(level, n - 1)
119
+ ee = float(np.dot(e, e))
120
+ sq: Optional[np.ndarray] = None
121
+
122
+ def t_ci(mean: float, sum_sq: float) -> tuple[float, float]:
123
+ var = max(0.0, (sum_sq - n * mean * mean) / (n - 1))
124
+ half = tq * math.sqrt(var / n)
125
+ return mean - half, mean + half
126
+
127
+ for name in result.metrics:
128
+ if name == "mae":
129
+ lo, hi = t_ci(float(result.metrics["mae"].value), ee)
130
+ out[name] = (max(0.0, lo), hi, "t")
131
+ elif name in ("mse", "rmse"):
132
+ if sq is None:
133
+ sq = e * e
134
+ lo, hi = t_ci(ee / n, float(np.dot(sq, sq)))
135
+ lo = max(0.0, lo)
136
+ out[name] = (lo, hi, "t") if name == "mse" else (math.sqrt(lo), math.sqrt(hi), "t (from MSE)")
137
+ elif name == "mean_bias_error":
138
+ lo, hi = t_ci(float(e.mean()), ee)
139
+ out[name] = (lo, hi, "t")
122
140
  return out
123
141
 
124
142
 
@@ -153,6 +171,7 @@ def attach(
153
171
  n_resamples: int,
154
172
  random_state: Optional[int],
155
173
  sample_weight: Any,
174
+ clusters: Any = None,
156
175
  ) -> EvaluationResult:
157
176
  """Return ``result`` with intervals in each metric's params (``ci_low``, ``ci_high``, ``ci_level``,
158
177
  ``ci_method``) and, with a baseline, the paired comparison (``baseline_*`` params and ``comparison``)."""
@@ -169,6 +188,22 @@ def attach(
169
188
  return result
170
189
  names = [k for k, m in result.metrics.items() if not isinstance(m.value, np.ndarray)]
171
190
  intervals: dict[str, tuple[float, float, str]] = {}
191
+ if clusters is not None:
192
+ return _attach_clustered(
193
+ result,
194
+ y_true,
195
+ y_pred,
196
+ y_prob,
197
+ names,
198
+ mode,
199
+ level,
200
+ baseline_pred,
201
+ baseline_prob,
202
+ n_resamples,
203
+ random_state,
204
+ sample_weight,
205
+ clusters,
206
+ )
172
207
  if mode == "analytic" and sample_weight is None:
173
208
  intervals = _analytic(result, y_true, y_pred, y_prob, level)
174
209
  comparison = None
@@ -249,3 +284,126 @@ def attach(
249
284
  },
250
285
  comparison=comparison,
251
286
  )
287
+
288
+
289
+ def _attach_clustered(
290
+ result: EvaluationResult,
291
+ y_true: Any,
292
+ y_pred: Any,
293
+ y_prob: Any,
294
+ names: list[str],
295
+ mode: str,
296
+ level: float,
297
+ baseline_pred: Any,
298
+ baseline_prob: Any,
299
+ n_resamples: int,
300
+ random_state: Optional[int],
301
+ sample_weight: Any,
302
+ clusters: Any,
303
+ ) -> EvaluationResult:
304
+ """Intervals and baseline tests that resample whole clusters (``evaluate(..., clusters=...)``): analytic
305
+ intervals assume independent observations, so with clusters every interval is a cluster bootstrap."""
306
+ import warnings
307
+
308
+ from . import adjust_pvalues
309
+ from .core.exceptions import EvalSuiteError
310
+ from .stats._resolve import resolve_metric
311
+ from .stats.compare import _needs_prob
312
+ from .stats.intervals import _cluster_members
313
+
314
+ yt = np.asarray(y_true)
315
+ members = _cluster_members(clusters, yt.shape[0])
316
+ g = len(members)
317
+ if g < 2:
318
+ raise InputValidationError("Clustered intervals need at least two clusters.")
319
+ kwargs = _metric_kwargs(names, result)
320
+ rng = np.random.default_rng(random_state)
321
+ picks = [np.concatenate([members[k] for k in rng.integers(0, g, g)]) for _ in range(n_resamples)]
322
+ w = None if sample_weight is None else np.asarray(sample_weight, dtype=float)
323
+
324
+ def value(name: str, second: Any, idx: Optional[np.ndarray]) -> float:
325
+ fn, _ = resolve_metric(name)
326
+ s = np.asarray(second)
327
+ kw = dict(kwargs[name])
328
+ if w is not None:
329
+ kw["sample_weight"] = w if idx is None else w[idx]
330
+ if idx is None:
331
+ return float(fn(yt, s, **kw)) if not _needs_prob(name) else float(fn(yt, y_prob=s, **kw))
332
+ return (
333
+ float(fn(yt[idx], s[idx], **kw)) if not _needs_prob(name) else float(fn(yt[idx], y_prob=s[idx], **kw))
334
+ )
335
+
336
+ def dist(name: str, second: Any) -> np.ndarray:
337
+ out = np.empty(n_resamples)
338
+ with warnings.catch_warnings():
339
+ warnings.simplefilter("ignore")
340
+ for b, idx in enumerate(picks):
341
+ try:
342
+ out[b] = value(name, second, idx)
343
+ except EvalSuiteError:
344
+ out[b] = np.nan
345
+ return out
346
+
347
+ a = (1 - level) / 2
348
+ extra: dict[str, dict[str, Any]] = {k: {} for k in names}
349
+ raw_p: dict[str, float] = {}
350
+ for name in names:
351
+ second = y_prob if _needs_prob(name) else y_pred
352
+ if second is None:
353
+ continue
354
+ d_model = dist(name, second)
355
+ if mode != "none" and d_model is not None:
356
+ v = d_model[~np.isnan(d_model)]
357
+ if v.size:
358
+ lo, hi = np.quantile(v, [a, 1 - a])
359
+ extra[name].update(
360
+ ci_low=float(lo),
361
+ ci_high=float(hi),
362
+ ci_level=level,
363
+ ci_method=f"cluster bootstrap ({g} clusters)",
364
+ )
365
+ base = baseline_prob if _needs_prob(name) else baseline_pred
366
+ if base is not None and d_model is not None:
367
+ d_base = dist(name, base)
368
+ diff = d_model - d_base
369
+ diff = diff[~np.isnan(diff)]
370
+ est = result.metrics[name].value
371
+ base_val = value(name, base, None)
372
+ if diff.size:
373
+ lo, hi = np.quantile(diff, [a, 1 - a])
374
+ # two-sided bootstrap p-value with the +1 correction, so it is never reported as exactly 0
375
+ tail = min(int(np.sum(diff <= 0)), int(np.sum(diff >= 0)))
376
+ p = float(min(1.0, 2 * (tail + 1) / (diff.size + 1)))
377
+ raw_p[name] = p
378
+ extra[name].update(
379
+ baseline_value=base_val,
380
+ baseline_difference=float(est) - base_val,
381
+ baseline_ci_low=float(lo),
382
+ baseline_ci_high=float(hi),
383
+ baseline_test="paired cluster bootstrap",
384
+ baseline_p_value=p,
385
+ )
386
+ if raw_p:
387
+ adj = adjust_pvalues(list(raw_p.values()), method="holm")
388
+ for name, p in zip(raw_p, np.atleast_1d(adj)):
389
+ extra[name]["baseline_p_adjusted"] = float(p)
390
+ metrics: dict[str, MetricResult] = {}
391
+ for key, m in result.metrics.items():
392
+ e = extra.get(key) or {}
393
+ metrics[key] = MetricResult(m.metric, m.name, m.value, {**m.params, **e}, m.labels) if e else m
394
+ return EvaluationResult(
395
+ task=result.task,
396
+ metrics=metrics,
397
+ n_samples=result.n_samples,
398
+ target_type=result.target_type,
399
+ labels=result.labels,
400
+ confusion_matrix=result.confusion_matrix,
401
+ metadata={
402
+ **result.metadata,
403
+ "ci": "cluster bootstrap",
404
+ "ci_level": level,
405
+ "clusters": g,
406
+ "n_resamples": n_resamples,
407
+ "random_state": random_state,
408
+ },
409
+ )
evalsuite/_update.py ADDED
@@ -0,0 +1,170 @@
1
+ """Staying current: a once-a-day notice when a newer EvalSuite is on PyPI, and a one-command upgrade.
2
+
3
+ pip itself never replaces an installed package unless asked (``pip install -U``), and no package can change
4
+ that. EvalSuite therefore tells you when a newer release exists and upgrades on request:
5
+
6
+ * On import, if the last check (cached for a day in the user cache directory) found a newer release, one line
7
+ is printed to stderr. The check itself runs in a background thread, so importing never waits on the network.
8
+ * ``evalsuite.upgrade()`` or ``evalsuite upgrade`` installs the latest release into the running interpreter
9
+ (``python -m pip install --upgrade evalsuite-python``).
10
+ * ``evalsuite.check_for_update()`` returns the installed and latest versions.
11
+
12
+ Set ``EVALSUITE_NO_UPDATE_CHECK=1`` to turn the check off; it is also off in CI (``CI`` set) and under pytest.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import subprocess
20
+ import sys
21
+ import threading
22
+ import time
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any, Optional
26
+
27
+ PACKAGE = "evalsuite-python"
28
+ PYPI_URL = f"https://pypi.org/pypi/{PACKAGE}/json"
29
+ DAY = 24 * 3600
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class UpdateInfo:
34
+ """Installed and latest released versions."""
35
+
36
+ installed: str
37
+ latest: Optional[str]
38
+
39
+ @property
40
+ def update_available(self) -> bool:
41
+ return self.latest is not None and _key(self.latest) > _key(self.installed)
42
+
43
+ def __repr__(self) -> str:
44
+ if self.latest is None:
45
+ return f"UpdateInfo(installed={self.installed}, latest=unknown)"
46
+ state = "update available" if self.update_available else "up to date"
47
+ return f"UpdateInfo(installed={self.installed}, latest={self.latest}, {state})"
48
+
49
+
50
+ def _key(version: str) -> tuple[int, ...]:
51
+ """Release tuple of a version string ('1.1.2' -> (1, 1, 2)); pre-release suffixes sort below the release."""
52
+ parts: list[int] = []
53
+ for piece in version.split("."):
54
+ digits = ""
55
+ for ch in piece:
56
+ if not ch.isdigit():
57
+ break
58
+ digits += ch
59
+ parts.append(int(digits) if digits else 0)
60
+ if len(digits) < len(piece): # e.g. "2rc1": a pre-release of 2
61
+ parts[-1] -= 1
62
+ break
63
+ return tuple(parts)
64
+
65
+
66
+ def _installed() -> str:
67
+ from .version import __version__
68
+
69
+ return __version__
70
+
71
+
72
+ def _cache_file() -> Path:
73
+ base = os.environ.get("XDG_CACHE_HOME") or (
74
+ os.path.join(os.environ.get("LOCALAPPDATA", ""), "evalsuite")
75
+ if sys.platform == "win32" and os.environ.get("LOCALAPPDATA")
76
+ else os.path.join(os.path.expanduser("~"), ".cache")
77
+ )
78
+ return Path(base) / "evalsuite" / "update-check.json"
79
+
80
+
81
+ def _read_cache() -> dict[str, Any]:
82
+ try:
83
+ data = json.loads(_cache_file().read_text())
84
+ return data if isinstance(data, dict) else {}
85
+ except (OSError, ValueError):
86
+ return {}
87
+
88
+
89
+ def _write_cache(data: dict[str, Any]) -> None:
90
+ try:
91
+ path = _cache_file()
92
+ path.parent.mkdir(parents=True, exist_ok=True)
93
+ path.write_text(json.dumps(data))
94
+ except OSError:
95
+ pass
96
+
97
+
98
+ def _fetch_latest(timeout: float = 3.0) -> Optional[str]:
99
+ """Latest version on PyPI, or None when PyPI cannot be reached."""
100
+ from urllib.request import Request, urlopen
101
+
102
+ try:
103
+ req = Request(PYPI_URL, headers={"Accept": "application/json", "User-Agent": f"evalsuite/{_installed()}"})
104
+ with urlopen(req, timeout=timeout) as resp: # noqa: S310 - fixed https URL
105
+ version = json.load(resp)["info"]["version"]
106
+ return str(version)
107
+ except Exception: # offline, proxy, firewall, malformed response: never an error for the user
108
+ return None
109
+
110
+
111
+ def check_for_update(*, timeout: float = 3.0) -> UpdateInfo:
112
+ """Ask PyPI for the latest release now (refreshes the daily cache)."""
113
+ latest = _fetch_latest(timeout)
114
+ if latest is not None:
115
+ data = _read_cache()
116
+ data.update({"checked": time.time(), "latest": latest})
117
+ _write_cache(data)
118
+ return UpdateInfo(_installed(), latest)
119
+
120
+
121
+ def upgrade(*, quiet: bool = False) -> int:
122
+ """Install the latest release into this Python environment (``python -m pip install --upgrade``).
123
+
124
+ Returns pip's exit code. In a virtual environment, conda environment or user install, the upgrade goes
125
+ exactly where the running ``evalsuite`` came from, because it uses this interpreter's pip."""
126
+ cmd = [sys.executable, "-m", "pip", "install", "--upgrade", PACKAGE]
127
+ if quiet:
128
+ cmd.append("--quiet")
129
+ return subprocess.call(cmd) # noqa: S603 - fixed arguments
130
+
131
+
132
+ def _disabled() -> bool:
133
+ env = os.environ
134
+ return bool(
135
+ env.get("EVALSUITE_NO_UPDATE_CHECK")
136
+ or env.get("CI")
137
+ or env.get("PYTEST_CURRENT_TEST")
138
+ or "pytest" in sys.modules
139
+ )
140
+
141
+
142
+ def _background_refresh() -> None:
143
+ latest = _fetch_latest()
144
+ if latest is not None:
145
+ data = _read_cache()
146
+ data.update({"checked": time.time(), "latest": latest})
147
+ _write_cache(data)
148
+
149
+
150
+ def notify_on_import() -> None:
151
+ """Print the cached notice (at most once a day) and refresh the cache in the background when stale."""
152
+ if _disabled():
153
+ return
154
+ data = _read_cache()
155
+ now = time.time()
156
+ latest = data.get("latest")
157
+ installed = _installed()
158
+ if isinstance(latest, str) and _key(latest) > _key(installed) and now - float(data.get("notified", 0)) > DAY:
159
+ print(
160
+ f"EvalSuite {latest} is available (you have {installed}). Upgrade with: evalsuite upgrade "
161
+ f"(or pip install -U {PACKAGE}). Silence with EVALSUITE_NO_UPDATE_CHECK=1.",
162
+ file=sys.stderr,
163
+ )
164
+ data["notified"] = now
165
+ _write_cache(data)
166
+ if now - float(data.get("checked", 0)) > DAY:
167
+ threading.Thread(target=_background_refresh, name="evalsuite-update-check", daemon=True).start()
168
+
169
+
170
+ __all__ = ["UpdateInfo", "check_for_update", "upgrade"]
evalsuite/api.py CHANGED
@@ -167,6 +167,7 @@ def evaluate(
167
167
  baseline_prob: Optional[ArrayLike] = None,
168
168
  n_resamples: int = 1000,
169
169
  random_state: Optional[int] = 0,
170
+ clusters: Optional[ArrayLike] = None,
170
171
  ) -> EvaluationResult:
171
172
  """Evaluate predictions with a standard set of metrics (or the ``metrics`` you name), with confidence
172
173
  intervals and, given a baseline, paired significance tests against it.
@@ -188,6 +189,9 @@ def evaluate(
188
189
  ``random_state``); ``ci=False`` turns them off. ``baseline_pred`` / ``baseline_prob`` (e.g. the current model)
189
190
  add the difference, its interval and a paired test per metric (McNemar for accuracy, DeLong for ROC AUC,
190
191
  paired bootstrap otherwise; Holm-adjusted), as ``baseline_*`` params and ``result.comparison``.
192
+ ``clusters`` (one id per observation, e.g. the patient of each scan or the document of each question) makes
193
+ every interval and baseline test a cluster bootstrap that resamples whole clusters; ordinary intervals are
194
+ too narrow when observations within a cluster are correlated.
191
195
  """
192
196
  if isinstance(y_true, (list, tuple)) and y_true and isinstance(y_true[0], dict):
193
197
  raise UnsupportedTaskError(
@@ -228,6 +232,7 @@ def evaluate(
228
232
  n_resamples=n_resamples,
229
233
  random_state=random_state,
230
234
  sample_weight=sample_weight,
235
+ clusters=clusters,
231
236
  )
232
237
 
233
238
 
evalsuite/cli/main.py CHANGED
@@ -176,8 +176,27 @@ def cmd_evaluate(args: argparse.Namespace) -> int:
176
176
  average=args.average,
177
177
  pos_label=label_value(args.pos_label),
178
178
  sample_weight=column(df, args.weight, "--weight") if args.weight else None,
179
+ baseline_pred=column(df, args.baseline_pred, "--baseline-pred") if args.baseline_pred else None,
180
+ baseline_prob=columns(df, args.baseline_prob, "--baseline-prob") if args.baseline_prob else None,
181
+ clusters=column(df, args.clusters, "--clusters") if args.clusters else None,
182
+ ci=False if args.ci == "none" else args.ci,
179
183
  )
180
184
  emit(result, args)
185
+ if args.fail_on_regression:
186
+ worse = []
187
+ for m in result.metrics.values():
188
+ p = m.params
189
+ if "baseline_p_adjusted" not in p or p["baseline_p_adjusted"] >= 0.05:
190
+ continue
191
+ ids = [x for x in es.list_metrics() if x.split(".")[-1] == m.metric]
192
+ info = es.metric_info(ids[0]) if ids else None
193
+ higher = True if info is None or info.higher_is_better is None else bool(info.higher_is_better)
194
+ diff = p["baseline_difference"]
195
+ if (diff < 0) if higher else (diff > 0):
196
+ worse.append(f"{m.name} {diff:+.4f} (p={p['baseline_p_adjusted']:.3g})")
197
+ if worse:
198
+ print("Significant regressions against the baseline: " + "; ".join(worse), file=sys.stderr)
199
+ return 1
181
200
  return 0
182
201
 
183
202
 
@@ -328,6 +347,7 @@ def cmd_leaderboard(args: argparse.Namespace) -> int:
328
347
  lb = es.leaderboard(
329
348
  runs,
330
349
  scorer=args.scorer,
350
+ benchmark=args.benchmark,
331
351
  references=args.references,
332
352
  level=args.level,
333
353
  alpha=args.alpha,
@@ -425,6 +445,38 @@ def cmd_metrics(args: argparse.Namespace) -> int:
425
445
  return 0
426
446
 
427
447
 
448
+ def cmd_upgrade(args: argparse.Namespace) -> int:
449
+ from .._update import check_for_update, upgrade
450
+
451
+ info = check_for_update()
452
+ if info.latest is None and not args.force:
453
+ print(f"evalsuite-python {info.installed}: PyPI could not be reached; upgrading anyway.", file=sys.stderr)
454
+ elif not info.update_available and not args.force:
455
+ print(f"evalsuite-python {info.installed} is the latest release.")
456
+ return 0
457
+ elif info.latest is not None:
458
+ print(f"Upgrading evalsuite-python {info.installed} -> {info.latest} ...")
459
+ if args.check:
460
+ return 0
461
+ return upgrade()
462
+
463
+
464
+ def cmd_version(args: argparse.Namespace) -> int:
465
+ from .._update import check_for_update
466
+
467
+ info = check_for_update() if args.check else None
468
+ line = f"evalsuite-python {__version__}"
469
+ if info is not None:
470
+ if info.latest is None:
471
+ line += " (could not reach PyPI)"
472
+ elif info.update_available:
473
+ line += f" (latest: {info.latest}; upgrade with: evalsuite upgrade)"
474
+ else:
475
+ line += " (latest)"
476
+ print(line)
477
+ return 0
478
+
479
+
428
480
  def cmd_info(args: argparse.Namespace) -> int:
429
481
  import evalsuite as es
430
482
 
@@ -477,6 +529,20 @@ def build_parser() -> argparse.ArgumentParser:
477
529
  p.add_argument("--metrics", help="comma-separated metric names, e.g. accuracy,f1,mcc")
478
530
  p.add_argument("--average", default="auto", help="binary, micro, macro, weighted, samples (default: auto)")
479
531
  p.add_argument("--pos-label", help="positive class for binary metrics (default: 1)")
532
+ p.add_argument("--baseline-pred", help="column with the baseline model's predictions (adds paired tests)")
533
+ p.add_argument("--baseline-prob", nargs="+", help="column(s) with the baseline model's probabilities")
534
+ p.add_argument("--clusters", help="column with a cluster id per row (patient, document): cluster bootstrap")
535
+ p.add_argument(
536
+ "--ci",
537
+ choices=("analytic", "bootstrap", "none"),
538
+ default="analytic",
539
+ help="interval method (default analytic)",
540
+ )
541
+ p.add_argument(
542
+ "--fail-on-regression",
543
+ action="store_true",
544
+ help="exit with code 1 when a metric is significantly worse than the baseline (Holm-adjusted p < 0.05)",
545
+ )
480
546
  add_output(p)
481
547
  p.set_defaults(func=cmd_evaluate)
482
548
 
@@ -579,9 +645,14 @@ def build_parser() -> argparse.ArgumentParser:
579
645
  p.add_argument("files", nargs="*", help="one JSONL / JSON file per model (the model is named after the file)")
580
646
  p.add_argument("--run", action="append", help="NAME=FILE (repeat; instead of positional files)")
581
647
  p.add_argument("--references", help="JSONL with id and reference (when the runs do not carry them)")
648
+ p.add_argument(
649
+ "--benchmark",
650
+ choices=["gsm8k", "mmlu", "arc", "arc-easy", "truthfulqa", "humaneval"],
651
+ help="use that benchmark's scorer (and, with --references from es.load_benchmark, its categories)",
652
+ )
582
653
  p.add_argument(
583
654
  "--scorer",
584
- default="exact_match",
655
+ default=None,
585
656
  choices=["exact_match", "contains", "gsm8k", "boxed", "choice", "last_line", "numeric"],
586
657
  help="how predictions are scored against references (records with 'correct' or 'score' are used as given)",
587
658
  )
@@ -594,6 +665,17 @@ def build_parser() -> argparse.ArgumentParser:
594
665
  add_output(p, digits=3)
595
666
  p.set_defaults(func=cmd_leaderboard)
596
667
 
668
+ p = sub.add_parser(
669
+ "upgrade", help="install the latest EvalSuite release into this Python environment (pip install -U)"
670
+ )
671
+ p.add_argument("--check", action="store_true", help="only report whether a newer release exists")
672
+ p.add_argument("--force", action="store_true", help="run pip even if this is already the latest release")
673
+ p.set_defaults(func=cmd_upgrade)
674
+
675
+ p = sub.add_parser("version", help="show the installed version (--check: compare with PyPI)")
676
+ p.add_argument("--check", action="store_true", help="also look up the latest release on PyPI")
677
+ p.set_defaults(func=cmd_version)
678
+
597
679
  p = sub.add_parser("metrics", help="list available metrics")
598
680
  p.add_argument("--category", choices=("classification", "regression", "clinical", "calibration"))
599
681
  p.set_defaults(func=cmd_metrics)
evalsuite/core/result.py CHANGED
@@ -366,13 +366,23 @@ class EvaluationResult(Mapping[str, MetricResult]):
366
366
  page with inline CSS and no scripts)."""
367
367
  from .export import html_document, html_table
368
368
 
369
- parts = [
370
- html_table(
371
- ["Metric", "Value"],
372
- [[m.name, _fmt(m.value, digits)] for m in self._scalar_rows()],
373
- caption=caption or "Metrics",
374
- )
375
- ]
369
+ rows = self._scalar_rows()
370
+ has_ci = any("ci_low" in m.params for m in rows)
371
+ has_base = any("baseline_difference" in m.params for m in rows)
372
+ head = (
373
+ ["Metric", "Value"]
374
+ + ([f"{_level_pct(rows)} CI"] if has_ci else [])
375
+ + (["Δ vs baseline", "p"] if has_base else [])
376
+ )
377
+ table_rows = []
378
+ for m in rows:
379
+ cells = [m.name, _fmt(m.value, digits)]
380
+ if has_ci:
381
+ cells.append(_ci_cell(m, digits))
382
+ if has_base:
383
+ cells += _base_cells(m, digits)
384
+ table_rows.append(cells)
385
+ parts = [html_table(head, table_rows, caption=caption or "Metrics")]
376
386
  for m in self.metrics.values():
377
387
  if isinstance(m.value, np.ndarray):
378
388
  parts.append(