evalsuite-python 1.1.2__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
@@ -278,6 +278,57 @@ __all__ = [
278
278
  __all__ += list(_text_all)
279
279
  __all__ += list(_llmsys_all)
280
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
+
281
332
  import contextlib as _contextlib # noqa: E402
282
333
 
283
334
  from ._update import UpdateInfo, check_for_update, upgrade # noqa: E402
evalsuite/_evalci.py CHANGED
@@ -171,6 +171,7 @@ def attach(
171
171
  n_resamples: int,
172
172
  random_state: Optional[int],
173
173
  sample_weight: Any,
174
+ clusters: Any = None,
174
175
  ) -> EvaluationResult:
175
176
  """Return ``result`` with intervals in each metric's params (``ci_low``, ``ci_high``, ``ci_level``,
176
177
  ``ci_method``) and, with a baseline, the paired comparison (``baseline_*`` params and ``comparison``)."""
@@ -187,6 +188,22 @@ def attach(
187
188
  return result
188
189
  names = [k for k, m in result.metrics.items() if not isinstance(m.value, np.ndarray)]
189
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
+ )
190
207
  if mode == "analytic" and sample_weight is None:
191
208
  intervals = _analytic(result, y_true, y_pred, y_prob, level)
192
209
  comparison = None
@@ -267,3 +284,126 @@ def attach(
267
284
  },
268
285
  comparison=comparison,
269
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/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,
@@ -509,6 +529,20 @@ def build_parser() -> argparse.ArgumentParser:
509
529
  p.add_argument("--metrics", help="comma-separated metric names, e.g. accuracy,f1,mcc")
510
530
  p.add_argument("--average", default="auto", help="binary, micro, macro, weighted, samples (default: auto)")
511
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
+ )
512
546
  add_output(p)
513
547
  p.set_defaults(func=cmd_evaluate)
514
548
 
@@ -611,9 +645,14 @@ def build_parser() -> argparse.ArgumentParser:
611
645
  p.add_argument("files", nargs="*", help="one JSONL / JSON file per model (the model is named after the file)")
612
646
  p.add_argument("--run", action="append", help="NAME=FILE (repeat; instead of positional files)")
613
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
+ )
614
653
  p.add_argument(
615
654
  "--scorer",
616
- default="exact_match",
655
+ default=None,
617
656
  choices=["exact_match", "contains", "gsm8k", "boxed", "choice", "last_line", "numeric"],
618
657
  help="how predictions are scored against references (records with 'correct' or 'score' are used as given)",
619
658
  )
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(