File size: 5,565 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""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,
    }