"""Group-clustered bootstrap and paired randomization for scored runs.""" from __future__ import annotations import math import random from collections import defaultdict from collections.abc import Mapping, Sequence from typing import Any from .core import EvaluationError def _group_outcomes(rows: Sequence[Mapping[str, Any]], metric: str) -> dict[str, float]: grouped: dict[str, list[Mapping[str, Any]]] = defaultdict(list) for row in rows: group_id = row.get("group_id") if not isinstance(group_id, str) or not group_id: raise EvaluationError("scored row has no group_id") grouped[group_id].append(row) if metric == "strict_group_accuracy": return { group_id: float(all(bool(row.get("correct")) for row in group_rows)) for group_id, group_rows in grouped.items() } if metric == "accuracy": return { group_id: sum(bool(row.get("correct")) for row in group_rows) / len(group_rows) for group_id, group_rows in grouped.items() } raise EvaluationError(f"unsupported paired metric: {metric!r}") def _quantile(values: Sequence[float], probability: float) -> float: if not values: raise EvaluationError("cannot take a quantile of an empty sequence") ordered = sorted(values) position = (len(ordered) - 1) * probability lower = math.floor(position) upper = math.ceil(position) if lower == upper: return ordered[lower] fraction = position - lower return ordered[lower] * (1.0 - fraction) + ordered[upper] * fraction def _holm(raw_p_values: Sequence[float]) -> list[float]: count = len(raw_p_values) order = sorted(range(count), key=lambda index: raw_p_values[index]) adjusted = [0.0] * count running = 0.0 for rank, index in enumerate(order): candidate = min(1.0, (count - rank) * raw_p_values[index]) running = max(running, candidate) adjusted[index] = running return adjusted def compare_runs( runs: Mapping[str, Sequence[Mapping[str, Any]]], *, reference: str, metric: str = "strict_group_accuracy", benchmark: str | None = None, bootstrap_replicates: int = 10_000, permutation_replicates: int = 10_000, seed: int = 20260728, ) -> dict[str, Any]: """Compare every run with one reference using base-group as the unit.""" if reference not in runs: raise EvaluationError(f"reference run {reference!r} is absent") if bootstrap_replicates <= 0 or permutation_replicates <= 0: raise EvaluationError("statistical replicate counts must be positive") selected_runs: dict[str, list[Mapping[str, Any]]] = {} for run_id, rows in runs.items(): selected = [ row for row in rows if benchmark is None or row.get("benchmark") == benchmark ] if not selected: raise EvaluationError( f"run {run_id!r} has no rows for benchmark {benchmark!r}" ) observed_benchmarks = {str(row.get("benchmark", "")) for row in selected} if benchmark is None and len(observed_benchmarks) > 1: raise EvaluationError( "scored rows contain multiple benchmarks; select one with --benchmark" ) selected_runs[run_id] = selected outcomes = {run_id: _group_outcomes(rows, metric) for run_id, rows in selected_runs.items()} reference_groups = set(outcomes[reference]) if not reference_groups: raise EvaluationError("reference score has no groups") for run_id, values in outcomes.items(): if set(values) != reference_groups: raise EvaluationError(f"paired group coverage differs for run {run_id}") group_ids = sorted(reference_groups) comparisons: list[dict[str, Any]] = [] rng = random.Random(seed) for run_id in sorted(run for run in outcomes if run != reference): deltas = [outcomes[run_id][group] - outcomes[reference][group] for group in group_ids] observed = sum(deltas) / len(deltas) bootstrap: list[float] = [] for _ in range(bootstrap_replicates): bootstrap.append( sum(deltas[rng.randrange(len(deltas))] for _ in deltas) / len(deltas) ) exceed = 0 for _ in range(permutation_replicates): permuted = sum(delta if rng.getrandbits(1) else -delta for delta in deltas) / len( deltas ) exceed += abs(permuted) >= abs(observed) comparisons.append( { "run_id": run_id, "reference": reference, "metric": metric, "group_count": len(group_ids), "difference": observed, "bootstrap_95_ci": [ _quantile(bootstrap, 0.025), _quantile(bootstrap, 0.975), ], "paired_permutation_p": (exceed + 1) / (permutation_replicates + 1), } ) adjusted = _holm([float(row["paired_permutation_p"]) for row in comparisons]) for row, value in zip(comparisons, adjusted, strict=True): row["holm_adjusted_p"] = value return { "schema_version": 1, "kind": "paired_group_statistics", "reference": reference, "metric": metric, "benchmark": benchmark, "bootstrap_replicates": bootstrap_replicates, "permutation_replicates": permutation_replicates, "seed": seed, "comparisons": comparisons, }