defacto-eval 0.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.
defacto/io.py ADDED
@@ -0,0 +1,34 @@
1
+ """Loading helpers shared by the CLI and library users."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+
9
+ def load(path: str) -> Any:
10
+ """Load a JSON file, or a newline-delimited text file when JSON parsing fails."""
11
+ with open(path, encoding="utf-8") as f:
12
+ text = f.read()
13
+ try:
14
+ return json.loads(text)
15
+ except json.JSONDecodeError:
16
+ return [line.rstrip("\n") for line in text.splitlines() if line.strip()]
17
+
18
+
19
+ def load_numbers(path: str) -> list:
20
+ return [float(v) for v in load(path)]
21
+
22
+
23
+ def load_records(path: str) -> list:
24
+ """Load a list of record dicts, or a dict-of-columns, into a list of dicts."""
25
+ data = load(path)
26
+ if isinstance(data, list):
27
+ return [dict(r) if isinstance(r, dict) else {"value": r} for r in data]
28
+ if isinstance(data, dict):
29
+ keys = list(data.keys())
30
+ if not keys:
31
+ return []
32
+ n = len(data[keys[0]])
33
+ return [{k: data[k][i] for k in keys} for i in range(n)]
34
+ raise ValueError(f"expected a JSON list or dict of columns, got {type(data).__name__}")
@@ -0,0 +1,150 @@
1
+ """Judge and reward-model reliability analysis.
2
+
3
+ The single entry point is :func:`analyze_judge`, which bundles agreement,
4
+ calibration, risk-coverage and abstention into one auditable result.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Sequence
10
+
11
+ import numpy as np
12
+
13
+ from .agreement import agreement, cohen_kappa, fleiss_kappa
14
+ from .calibration import ece, reliability_curve
15
+ from .metrics import classification_report, confusion_matrix
16
+ from .risk_coverage import abstention_summary, confident_errors, risk_coverage
17
+
18
+ __all__ = [
19
+ "analyze_judge",
20
+ "cohen_kappa",
21
+ "fleiss_kappa",
22
+ "agreement",
23
+ "ece",
24
+ "reliability_curve",
25
+ "risk_coverage",
26
+ "confident_errors",
27
+ "abstention_summary",
28
+ "classification_report",
29
+ "confusion_matrix",
30
+ ]
31
+
32
+
33
+ def _subgroup_bias(gold, judge, groups) -> dict:
34
+ """Per-group accuracy and kappa, plus the maximum between-group gap."""
35
+ from collections import defaultdict
36
+
37
+ by: dict = defaultdict(lambda: {"g": [], "j": []})
38
+ for g, j, grp in zip(gold, judge, groups, strict=False):
39
+ by[grp]["g"].append(g)
40
+ by[grp]["j"].append(j)
41
+ rows = {}
42
+ for grp, d in sorted(by.items(), key=lambda kv: str(kv[0])):
43
+ g = d["g"]
44
+ j = d["j"]
45
+ acc = sum(
46
+ 1 for a, b in zip(g, j, strict=False) if a is not None and b is not None and a == b
47
+ ) / max(sum(1 for a, b in zip(g, j, strict=False) if a is not None and b is not None), 1)
48
+ rows[str(grp)] = {
49
+ "n": len(g),
50
+ "accuracy": acc,
51
+ "kappa": cohen_kappa(g, j),
52
+ }
53
+ accs = [r["accuracy"] for r in rows.values()]
54
+ gap = (max(accs) - min(accs)) if accs else float("nan")
55
+ return {"per_group": rows, "max_accuracy_gap": gap}
56
+
57
+
58
+ def analyze_judge(
59
+ gold: Sequence,
60
+ judge: Sequence,
61
+ confidence: Sequence[float] | None = None,
62
+ groups: Sequence | None = None,
63
+ clusters: Sequence | None = None,
64
+ labels: Sequence | None = None,
65
+ ci: bool = True,
66
+ n_bootstrap: int = 2000,
67
+ seed: int = 0,
68
+ confident_threshold: float = 0.8,
69
+ ) -> dict:
70
+ """Full reliability analysis of an LLM judge (or reward model) vs gold labels.
71
+
72
+ Parameters
73
+ ----------
74
+ gold:
75
+ Ground-truth labels.
76
+ judge:
77
+ Judge's predictions; ``None`` marks an abstention.
78
+ confidence:
79
+ Optional judge confidence in ``[0, 1]`` per row. Enables calibration and
80
+ risk-coverage sections.
81
+ groups:
82
+ Optional subgroup ids (one per row) for a bias/parity breakdown.
83
+ clusters:
84
+ Optional cluster ids (one per row) for cluster-bootstrap confidence
85
+ intervals on kappa.
86
+ labels:
87
+ Category labels, inferred when omitted.
88
+ ci:
89
+ Compute a bootstrap CI on kappa.
90
+ n_bootstrap, seed:
91
+ Bootstrap parameters.
92
+ confident_threshold:
93
+ Confidence above which an answer is "confident" for the
94
+ confident-error audit.
95
+
96
+ Returns
97
+ -------
98
+ dict
99
+ A JSON-serializable result with ``agreement``, ``calibration``,
100
+ ``risk_coverage``, ``abstention``, ``confident_errors`` and (when
101
+ ``groups`` is given) ``subgroup_bias`` sections.
102
+ """
103
+ gold = list(gold)
104
+ judge = list(judge)
105
+ if len(gold) != len(judge):
106
+ raise ValueError("gold and judge must have equal length")
107
+ if confidence is not None:
108
+ confidence = list(confidence)
109
+ if len(confidence) != len(gold):
110
+ raise ValueError("confidence must have the same length as gold/judge")
111
+ if groups is not None:
112
+ groups = list(groups)
113
+ if len(groups) != len(gold):
114
+ raise ValueError("groups must have the same length as gold/judge")
115
+ if clusters is not None:
116
+ clusters = list(clusters)
117
+ if len(clusters) != len(gold):
118
+ raise ValueError("clusters must have the same length as gold/judge")
119
+
120
+ result: dict = {
121
+ "agreement": agreement(
122
+ gold,
123
+ judge,
124
+ labels=labels,
125
+ clusters=clusters,
126
+ ci=ci,
127
+ n_bootstrap=n_bootstrap,
128
+ seed=seed,
129
+ ),
130
+ "abstention": abstention_summary(gold, judge),
131
+ "classification": classification_report(gold, judge, labels=labels),
132
+ }
133
+
134
+ # Confidence-based metrics are computed over answered items only.
135
+ if confidence is not None:
136
+ conf_arr = np.asarray(confidence, dtype=float)
137
+ answered_mask = np.array([j is not None for j in judge], dtype=bool)
138
+ conf_ans = conf_arr[answered_mask]
139
+ correct_ans = np.array([g == j for g, j in zip(gold, judge, strict=False)])[answered_mask]
140
+ result["calibration"] = ece(conf_ans, correct_ans)
141
+ result["calibration"]["reliability_curve"] = reliability_curve(conf_ans, correct_ans)
142
+ result["risk_coverage"] = risk_coverage(conf_ans, correct_ans)
143
+ result["confident_errors"] = confident_errors(
144
+ conf_ans, correct_ans, threshold=confident_threshold
145
+ )
146
+
147
+ if groups is not None:
148
+ result["subgroup_bias"] = _subgroup_bias(gold, judge, groups)
149
+
150
+ return result
@@ -0,0 +1,209 @@
1
+ """Agreement statistics for LLM judges and reward-model labels.
2
+
3
+ Cohen's kappa (unweighted, linear and quadratic weighted), Fleiss' kappa for
4
+ multiple raters, and cluster-bootstrap confidence intervals. Abstentions (a
5
+ judge refusing to answer) are excluded from the agreement computation and
6
+ reported separately.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections import defaultdict
12
+ from collections.abc import Callable, Sequence
13
+
14
+ import numpy as np
15
+
16
+ from .._stats import cluster_bootstrap
17
+
18
+
19
+ def _weight_matrix(k: int, kind: str) -> np.ndarray:
20
+ i = np.arange(k)[:, None]
21
+ j = np.arange(k)[None, :]
22
+ d = np.abs(i - j)
23
+ if kind == "linear":
24
+ return 1.0 - d / (k - 1)
25
+ if kind == "quadratic":
26
+ return 1.0 - (d / (k - 1)) ** 2
27
+ raise ValueError(f"unknown weight kind {kind!r}; use 'linear' or 'quadratic'")
28
+
29
+
30
+ def cohen_kappa(
31
+ gold: Sequence,
32
+ judge: Sequence,
33
+ labels: Sequence | None = None,
34
+ weights: str | None = None,
35
+ ) -> float:
36
+ """Cohen's kappa between two raters, excluding abstentions (``None`` values).
37
+
38
+ ``weights`` may be ``None`` (unweighted), ``"linear"`` or ``"quadratic"``.
39
+ """
40
+ gold = list(gold)
41
+ judge = list(judge)
42
+ if len(gold) != len(judge):
43
+ raise ValueError("gold and judge must have equal length")
44
+ pairs = [(g, j) for g, j in zip(gold, judge, strict=False) if g is not None and j is not None]
45
+ if not pairs:
46
+ return 0.0
47
+ g = [p[0] for p in pairs]
48
+ j = [p[1] for p in pairs]
49
+ if labels is None:
50
+ labels = sorted(set(g) | set(j))
51
+ labels = list(labels)
52
+ k = len(labels)
53
+ if k < 2:
54
+ if all(x == labels[0] for x in g) and all(x == labels[0] for x in j):
55
+ return 1.0
56
+ return 0.0
57
+ idx = {lab: i for i, lab in enumerate(labels)}
58
+ cm = np.zeros((k, k), dtype=float)
59
+ for a, b in zip(g, j, strict=False):
60
+ cm[idx[a], idx[b]] += 1.0
61
+ n = cm.sum()
62
+ row = cm.sum(axis=1)
63
+ col = cm.sum(axis=0)
64
+ if weights is None:
65
+ po = float(np.trace(cm) / n)
66
+ pe = float((row @ col) / (n * n))
67
+ return (po - pe) / (1.0 - pe) if pe < 1.0 else 0.0
68
+ w = _weight_matrix(k, weights)
69
+ o = cm / n
70
+ e = np.outer(row, col) / (n * n)
71
+ num = float((w * o).sum()) # weighted observed agreement
72
+ den = float((w * e).sum()) # weighted chance agreement
73
+ return (num - den) / (1.0 - den) if den < 1.0 else 0.0
74
+
75
+
76
+ def fleiss_kappa(ratings: Sequence[Sequence], labels: Sequence | None = None) -> float:
77
+ """Fleiss' kappa for ``ratings`` of shape (n_subjects, n_raters)."""
78
+ ratings = [list(r) for r in ratings]
79
+ n = len(ratings)
80
+ if n == 0:
81
+ return 0.0
82
+ m = len(ratings[0])
83
+ if m < 2:
84
+ raise ValueError("Fleiss' kappa requires at least two raters per subject")
85
+ if labels is None:
86
+ labels = sorted({v for r in ratings for v in r})
87
+ labels = list(labels)
88
+ k = len(labels)
89
+ idx = {lab: i for i, lab in enumerate(labels)}
90
+ counts = np.zeros((n, k), dtype=float)
91
+ for i, r in enumerate(ratings):
92
+ if len(r) != m:
93
+ raise ValueError("all subjects must have the same number of raters")
94
+ for v in r:
95
+ counts[i, idx[v]] += 1.0
96
+ pi = (np.sum(counts**2, axis=1) - m) / (m * (m - 1))
97
+ pbar = float(pi.mean())
98
+ pj = counts.sum(axis=0) / (n * m)
99
+ pe = float((pj**2).sum())
100
+ return (pbar - pe) / (1.0 - pe) if pe < 1.0 else 0.0
101
+
102
+
103
+ def _pair_statistic(labels: Sequence | None, weights: str | None) -> Callable[[Sequence], float]:
104
+ def stat(groups: Sequence) -> float:
105
+ g: list = []
106
+ j: list = []
107
+ for grp in groups:
108
+ for a, b in grp:
109
+ g.append(a)
110
+ j.append(b)
111
+ return cohen_kappa(g, j, labels=labels, weights=weights)
112
+
113
+ return stat
114
+
115
+
116
+ def agreement(
117
+ gold: Sequence,
118
+ judge: Sequence,
119
+ labels: Sequence | None = None,
120
+ weights: str | None = None,
121
+ clusters: Sequence | None = None,
122
+ ci: bool = True,
123
+ n_bootstrap: int = 2000,
124
+ seed: int = 0,
125
+ alpha: float = 0.05,
126
+ method: str = "bca",
127
+ ) -> dict:
128
+ """Agreement between a judge and ground-truth labels.
129
+
130
+ Parameters
131
+ ----------
132
+ gold, judge:
133
+ Parallel label sequences. ``None`` in ``judge`` is an abstention and is
134
+ excluded from the kappa computation.
135
+ labels:
136
+ Category labels. Inferred from the data when omitted.
137
+ weights:
138
+ ``None``, ``"linear"`` or ``"quadratic"``.
139
+ clusters:
140
+ Optional cluster ids (one per row) for cluster bootstrap. When omitted,
141
+ rows are resampled independently (i.i.d. bootstrap).
142
+ ci:
143
+ Whether to compute a bootstrap confidence interval.
144
+ n_bootstrap, seed, alpha, method:
145
+ Passed to :func:`defacto._stats.cluster_bootstrap`.
146
+
147
+ Returns
148
+ -------
149
+ dict with ``kappa``, ``po``, ``pe``, ``n_pairs``, ``n_total``,
150
+ ``n_abstained``, ``labels`` and (when ``ci``) ``ci_lower``/``ci_upper``.
151
+ """
152
+ gold = list(gold)
153
+ judge = list(judge)
154
+ if len(gold) != len(judge):
155
+ raise ValueError("gold and judge must have equal length")
156
+ n_total = len(gold)
157
+ if clusters is None:
158
+ clusters = list(range(n_total))
159
+ else:
160
+ clusters = list(clusters)
161
+ if len(clusters) != n_total:
162
+ raise ValueError("clusters must have the same length as gold/judge")
163
+
164
+ by_cluster: dict = defaultdict(list)
165
+ for g, j, c in zip(gold, judge, clusters, strict=False):
166
+ if g is not None and j is not None:
167
+ by_cluster[c].append((g, j))
168
+ groups = list(by_cluster.values())
169
+
170
+ pairs = [p for grp in groups for p in grp]
171
+ if labels is None:
172
+ labels = sorted({p[0] for p in pairs} | {p[1] for p in pairs})
173
+ labels = list(labels)
174
+
175
+ stat = _pair_statistic(labels, weights)
176
+ kappa = stat(groups)
177
+
178
+ result: dict = {
179
+ "kappa": kappa,
180
+ "n_pairs": len(pairs),
181
+ "n_total": n_total,
182
+ "n_abstained": n_total - len(pairs),
183
+ "labels": labels,
184
+ }
185
+ if labels and len(pairs):
186
+ g_arr = [p[0] for p in pairs]
187
+ j_arr = [p[1] for p in pairs]
188
+ idx = {lab: i for i, lab in enumerate(labels)}
189
+ cm = np.zeros((len(labels), len(labels)), dtype=float)
190
+ for a, b in zip(g_arr, j_arr, strict=False):
191
+ cm[idx[a], idx[b]] += 1.0
192
+ n = cm.sum()
193
+ row = cm.sum(axis=1)
194
+ col = cm.sum(axis=0)
195
+ result["po"] = float(np.trace(cm) / n)
196
+ result["pe"] = float((row @ col) / (n * n))
197
+ else:
198
+ result["po"] = float("nan")
199
+ result["pe"] = float("nan")
200
+
201
+ if ci and groups:
202
+ ci_res = cluster_bootstrap(
203
+ groups, stat, n_bootstrap=n_bootstrap, seed=seed, alpha=alpha, method=method
204
+ )
205
+ result["ci_lower"] = ci_res["lower"]
206
+ result["ci_upper"] = ci_res["upper"]
207
+ result["ci_se"] = ci_res["se"]
208
+ result["ci_method"] = method
209
+ return result
@@ -0,0 +1,93 @@
1
+ """Confidence calibration for LLM judges and reward models.
2
+
3
+ A well-calibrated judge reports confidence that matches its empirical accuracy.
4
+ Calibration error is the gap between the two; a large gap is a silent-failure
5
+ signal ("the judge is confidently wrong").
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Sequence
11
+
12
+ import numpy as np
13
+
14
+
15
+ def _bin_indices(conf: np.ndarray, n_bins: int, scheme: str) -> tuple[np.ndarray, np.ndarray]:
16
+ """Return (bin_assignments, bin_edges) for confidence values in [0, 1]."""
17
+ if scheme == "equal_width":
18
+ edges = np.linspace(0.0, 1.0, n_bins + 1)
19
+ bins = np.minimum((conf * n_bins).astype(int), n_bins - 1)
20
+ return bins, edges
21
+ if scheme == "equal_mass":
22
+ quantiles = np.quantile(conf, np.linspace(0.0, 1.0, n_bins + 1))
23
+ quantiles[0] = 0.0
24
+ quantiles[-1] = 1.0 + 1e-12
25
+ bins = np.digitize(conf, quantiles[1:-1])
26
+ return bins, quantiles
27
+ raise ValueError(f"unknown scheme {scheme!r}; use 'equal_width' or 'equal_mass'")
28
+
29
+
30
+ def reliability_curve(
31
+ confidences: Sequence[float],
32
+ correct: Sequence,
33
+ n_bins: int = 10,
34
+ scheme: str = "equal_width",
35
+ ) -> dict:
36
+ """Binned confidence vs accuracy (a reliability diagram's data)."""
37
+ conf = np.asarray(confidences, dtype=float)
38
+ y = np.asarray(correct, dtype=int).astype(bool)
39
+ if conf.shape != y.shape:
40
+ raise ValueError("confidences and correct must have equal length")
41
+ if np.any(conf < 0) or np.any(conf > 1):
42
+ raise ValueError("confidences must be in [0, 1]")
43
+ bins, edges = _bin_indices(conf, n_bins, scheme)
44
+ bin_conf = np.full(n_bins, np.nan)
45
+ bin_acc = np.full(n_bins, np.nan)
46
+ bin_count = np.zeros(n_bins, dtype=int)
47
+ for b in range(n_bins):
48
+ sel = bins == b
49
+ bin_count[b] = int(sel.sum())
50
+ if bin_count[b]:
51
+ bin_conf[b] = float(conf[sel].mean())
52
+ bin_acc[b] = float(y[sel].mean())
53
+ return {
54
+ "n_bins": n_bins,
55
+ "scheme": scheme,
56
+ "bin_edges": edges.tolist(),
57
+ "bin_confidence": bin_conf.tolist(),
58
+ "bin_accuracy": bin_acc.tolist(),
59
+ "bin_count": bin_count.tolist(),
60
+ }
61
+
62
+
63
+ def ece(
64
+ confidences: Sequence[float],
65
+ correct: Sequence,
66
+ n_bins: int = 15,
67
+ scheme: str = "equal_width",
68
+ ) -> dict:
69
+ """Expected calibration error (ECE) and maximum calibration error (MCE)."""
70
+ conf = np.asarray(confidences, dtype=float)
71
+ y = np.asarray(correct, dtype=int).astype(bool)
72
+ if conf.shape != y.shape:
73
+ raise ValueError("confidences and correct must have equal length")
74
+ n = conf.size
75
+ if n == 0:
76
+ return {"ece": float("nan"), "mce": float("nan"), "n": 0}
77
+ bins, edges = _bin_indices(conf, n_bins, scheme)
78
+ ece_acc = 0.0
79
+ mce = 0.0
80
+ detail: list[dict | None] = []
81
+ for b in range(n_bins):
82
+ sel = bins == b
83
+ count = int(sel.sum())
84
+ if count == 0:
85
+ detail.append(None)
86
+ continue
87
+ acc = float(y[sel].mean())
88
+ conf_mean = float(conf[sel].mean())
89
+ gap = abs(acc - conf_mean)
90
+ ece_acc += (count / n) * gap
91
+ mce = max(mce, gap)
92
+ detail.append({"bin": b, "count": count, "confidence": conf_mean, "accuracy": acc})
93
+ return {"ece": ece_acc, "mce": mce, "n": n, "n_bins": n_bins, "scheme": scheme, "bins": detail}
@@ -0,0 +1,94 @@
1
+ """Classification metrics for a judge treated as a classifier against gold labels.
2
+
3
+ Precision, recall, and F1 make the judge's reliability concrete per category,
4
+ which matters more than a single accuracy number when categories are imbalanced.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Sequence
10
+
11
+ import numpy as np
12
+
13
+
14
+ def confusion_matrix(
15
+ gold: Sequence,
16
+ judge: Sequence,
17
+ labels: Sequence | None = None,
18
+ ) -> tuple[np.ndarray, list]:
19
+ """Build a confusion matrix (rows are gold, columns are judge predictions).
20
+
21
+ Abstentions (``None`` in ``judge``) are excluded. Returns the matrix and the
22
+ ordered label list.
23
+ """
24
+ gold = list(gold)
25
+ judge = list(judge)
26
+ if len(gold) != len(judge):
27
+ raise ValueError("gold and judge must have equal length")
28
+ pairs = [(g, j) for g, j in zip(gold, judge, strict=False) if g is not None and j is not None]
29
+ if labels is None:
30
+ labels = sorted({p[0] for p in pairs} | {p[1] for p in pairs})
31
+ labels = list(labels)
32
+ idx = {lab: i for i, lab in enumerate(labels)}
33
+ cm = np.zeros((len(labels), len(labels)), dtype=int)
34
+ for g, j in pairs:
35
+ cm[idx[g], idx[j]] += 1
36
+ return cm, labels
37
+
38
+
39
+ def classification_report(
40
+ gold: Sequence,
41
+ judge: Sequence,
42
+ labels: Sequence | None = None,
43
+ ) -> dict:
44
+ """Per-label precision, recall, F1, and support, plus aggregates.
45
+
46
+ Zero-division cases return 0.0 for that metric. Abstentions are excluded
47
+ from all counts.
48
+ """
49
+ cm, labels = confusion_matrix(gold, judge, labels=labels)
50
+ n = int(cm.sum())
51
+ if n == 0:
52
+ return {
53
+ "accuracy": float("nan"),
54
+ "macro_f1": float("nan"),
55
+ "weighted_f1": float("nan"),
56
+ "labels": {},
57
+ "n": 0,
58
+ }
59
+
60
+ row = cm.sum(axis=1) # gold counts (support)
61
+ col = cm.sum(axis=0) # predicted counts
62
+ diag = np.diag(cm).astype(float)
63
+
64
+ per_label = {}
65
+ f1s = []
66
+ weighted = 0.0
67
+ for i, lab in enumerate(labels):
68
+ tp = diag[i]
69
+ fp = float(col[i] - tp)
70
+ fn = float(row[i] - tp)
71
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
72
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
73
+ f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0
74
+ support = int(row[i])
75
+ per_label[str(lab)] = {
76
+ "precision": float(precision),
77
+ "recall": float(recall),
78
+ "f1": float(f1),
79
+ "support": support,
80
+ }
81
+ f1s.append(f1)
82
+ weighted += f1 * support
83
+
84
+ accuracy = float(diag.sum() / n)
85
+ macro_f1 = float(np.mean(f1s))
86
+ weighted_f1 = weighted / n if n else 0.0
87
+
88
+ return {
89
+ "accuracy": accuracy,
90
+ "macro_f1": macro_f1,
91
+ "weighted_f1": weighted_f1,
92
+ "labels": per_label,
93
+ "n": n,
94
+ }
@@ -0,0 +1,108 @@
1
+ """Risk-coverage, confident-error, and abstention analysis.
2
+
3
+ These metrics express the core trade-off from regulated-domain evaluation:
4
+ risk (error among answered items) versus coverage (share of items answered).
5
+ A system that abstains or refuses low-confidence answers trades coverage for
6
+ lower risk; the audit reports where confident-but-wrong answers survive:
7
+ "confident errors that pass the checks".
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Sequence
13
+
14
+ import numpy as np
15
+
16
+
17
+ def risk_coverage(
18
+ confidences: Sequence[float],
19
+ correct: Sequence,
20
+ abstained: Sequence | None = None,
21
+ n_thresholds: int = 50,
22
+ ) -> dict:
23
+ """Risk-coverage curve for a judge/verifier with confidence scores.
24
+
25
+ ``abstained`` (optional) is a boolean mask; abstained items are never
26
+ counted as covered. ``correct`` should align with the full sequence.
27
+ """
28
+ conf = np.asarray(confidences, dtype=float)
29
+ y = np.asarray(correct, dtype=int).astype(bool)
30
+ if conf.shape != y.shape:
31
+ raise ValueError("confidences and correct must have equal length")
32
+ if abstained is None:
33
+ abst = np.zeros(conf.shape, dtype=bool)
34
+ else:
35
+ abst = np.asarray(abstained, dtype=bool)
36
+ if abst.shape != conf.shape:
37
+ raise ValueError("abstained must have the same length as confidences")
38
+ answered = ~abst
39
+ n_answered = int(answered.sum())
40
+ if n_answered == 0:
41
+ return {"thresholds": [], "coverage": [], "risk": [], "n_answered": 0}
42
+
43
+ thresholds = np.linspace(1.0, 0.0, n_thresholds)
44
+ coverage = np.empty(n_thresholds)
45
+ risk = np.empty(n_thresholds)
46
+ n_covered = np.empty(n_thresholds, dtype=int)
47
+ for t, thr in enumerate(thresholds):
48
+ covered = answered & (conf >= thr)
49
+ n_covered[t] = int(covered.sum())
50
+ coverage[t] = n_covered[t] / n_answered
51
+ risk[t] = float(np.mean(~y[covered])) if n_covered[t] else 0.0
52
+ return {
53
+ "thresholds": thresholds.tolist(),
54
+ "coverage": coverage.tolist(),
55
+ "risk": risk.tolist(),
56
+ "n_covered": n_covered.tolist(),
57
+ "n_answered": n_answered,
58
+ }
59
+
60
+
61
+ def confident_errors(
62
+ confidences: Sequence[float],
63
+ correct: Sequence,
64
+ threshold: float = 0.8,
65
+ abstained: Sequence | None = None,
66
+ ) -> dict:
67
+ """Confident-but-wrong items: high-confidence answers that fail the check."""
68
+ conf = np.asarray(confidences, dtype=float)
69
+ y = np.asarray(correct, dtype=int).astype(bool)
70
+ if abstained is None:
71
+ abst = np.zeros(conf.shape, dtype=bool)
72
+ else:
73
+ abst = np.asarray(abstained, dtype=bool)
74
+ answered = ~abst
75
+ covered = answered & (conf >= threshold)
76
+ errors = covered & ~y
77
+ n_covered = int(covered.sum())
78
+ return {
79
+ "threshold": threshold,
80
+ "n_answered": int(answered.sum()),
81
+ "n_confident": n_covered,
82
+ "n_confident_errors": int(errors.sum()),
83
+ "confident_error_rate": float(errors.sum() / n_covered) if n_covered else 0.0,
84
+ "confident_error_indices": np.nonzero(errors)[0].tolist(),
85
+ }
86
+
87
+
88
+ def abstention_summary(gold: Sequence, judge: Sequence) -> dict:
89
+ """Summary of abstention: how often the judge refuses and its effect on accuracy."""
90
+ gold = list(gold)
91
+ judge = list(judge)
92
+ if len(gold) != len(judge):
93
+ raise ValueError("gold and judge must have equal length")
94
+ abstained = [j is None for j in judge]
95
+ answered = [not a for a in abstained]
96
+ n_total = len(gold)
97
+ n_answered = int(sum(answered))
98
+ n_abstained = n_total - n_answered
99
+ correct_answered = sum(
100
+ 1 for g, j, a in zip(gold, judge, answered, strict=False) if a and g == j
101
+ )
102
+ return {
103
+ "n_total": n_total,
104
+ "n_answered": n_answered,
105
+ "n_abstained": n_abstained,
106
+ "abstention_rate": n_abstained / n_total if n_total else 0.0,
107
+ "accuracy_answered": correct_answered / n_answered if n_answered else float("nan"),
108
+ }