mozenjii-evalgate 0.1.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.
evalgate/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """evalgate: a CI check that fails a pull request when an LLM feature gets worse.
2
+
3
+ Modules, from the bottom up: `dataset` loads and validates versioned datasets, `scorers`
4
+ turns one output into one number, `stats` holds the paired statistics, `results` stores run
5
+ records, `runner` executes a dataset against a target, `gate` turns two runs into
6
+ per-slice verdicts, and `cli` is the `evalgate` command.
7
+
8
+ The package root exports only the version; import from the module you need. Keeping the
9
+ root that small means nothing reaches the public surface without a test behind it.
10
+ """
11
+
12
+ __all__ = ["__version__"]
13
+
14
+ __version__ = "0.1.0"
15
+ """The version shared by the runtime and distribution metadata."""
@@ -0,0 +1,442 @@
1
+ """Measure a binary judge against independently supplied human judgments.
2
+
3
+ The calibration guide specifies the sampling design, optional paired probes and cost evidence.
4
+ This module reads only decisions and optional costs, never raw outputs, and performs no inference
5
+ calls or writes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable, Sequence
11
+ from dataclasses import dataclass
12
+ from math import log, sqrt
13
+ from pathlib import Path
14
+ from statistics import mean, pstdev
15
+ from typing import Annotated
16
+
17
+ import typer
18
+ from pydantic import BaseModel, ConfigDict, Field, StringConstraints, ValidationError
19
+
20
+ __all__ = [
21
+ "CalibrationError",
22
+ "CalibrationRow",
23
+ "calibrate",
24
+ "calibrate_command",
25
+ "read_calibration",
26
+ ]
27
+
28
+ _Interval = tuple[float, float]
29
+ _Label = Annotated[str, Field(min_length=1, max_length=128, pattern=r"^[^\x00-\x1f\x7f-\x9f]+$")]
30
+ _Cost = Annotated[float, Field(ge=0, allow_inf_nan=False)]
31
+ _Fingerprint = Annotated[
32
+ str,
33
+ StringConstraints(
34
+ strip_whitespace=False, min_length=64, max_length=64, pattern=r"^[a-f0-9]{64}$"
35
+ ),
36
+ ]
37
+
38
+
39
+ class CalibrationError(ValueError):
40
+ """Invalid calibration data or inference settings."""
41
+
42
+
43
+ class CalibrationRow(BaseModel):
44
+ """A frozen judge decision for one item and rubric, with optional audit evidence."""
45
+
46
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid", str_strip_whitespace=True)
47
+
48
+ id: _Label
49
+ rubric: _Label
50
+ judge: bool
51
+ human: bool | None = None
52
+ judgement_sha256: _Fingerprint | None = None
53
+ second_human: bool | None = None
54
+ repeat: bool | None = None
55
+ position_swap: bool | None = None
56
+ length_variant: bool | None = None
57
+ family_variant: bool | None = None
58
+ ensemble_2: bool | None = None
59
+ ensemble_3: bool | None = None
60
+ judge_cost_usd: _Cost | None = None
61
+ ensemble_2_cost_usd: _Cost | None = None
62
+ ensemble_3_cost_usd: _Cost | None = None
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class _Confusion:
67
+ true_positive: int
68
+ true_negative: int
69
+ false_positive: int
70
+ false_negative: int
71
+
72
+ @property
73
+ def kappa(self) -> float | None:
74
+ """Return agreement above chance when the marginal totals define it."""
75
+ tp, tn, fp, fn = (
76
+ self.true_positive,
77
+ self.true_negative,
78
+ self.false_positive,
79
+ self.false_negative,
80
+ )
81
+ count = tp + tn + fp + fn
82
+ agreement = count * (tp + tn)
83
+ expected = (tp + fp) * (tp + fn) + (tn + fp) * (tn + fn)
84
+ denominator = count**2 - expected
85
+ return (agreement - expected) / denominator if denominator else None
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class _ProbeResult:
90
+ name: str
91
+ count: int
92
+ flips: int
93
+ acceptance_delta: float | None
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class _EnsembleResult:
98
+ judges: int
99
+ kappa: float | None
100
+ total_cost_usd: float | None
101
+ gain_per_added_usd: float | None = None
102
+
103
+
104
+ @dataclass(frozen=True)
105
+ class _RubricReport:
106
+ rubric: str
107
+ count: int
108
+ labeled: int
109
+ confusion: _Confusion
110
+ bias: float | None
111
+ judge_rate: float
112
+ human_rate: float | None
113
+ corrected_rate: float | None
114
+ corrected_interval: _Interval | None
115
+ human_interval: _Interval | None
116
+ probes: tuple[_ProbeResult, ...]
117
+ second_rater_count: int
118
+ second_rater_kappa: float | None
119
+ ensemble_count: int
120
+ ensembles: tuple[_EnsembleResult, ...]
121
+
122
+ @property
123
+ def kappa(self) -> float | None:
124
+ """Return the judge's Cohen kappa for the reviewed cases."""
125
+ return self.confusion.kappa
126
+
127
+
128
+ _PROBES: tuple[tuple[str, Callable[[CalibrationRow], bool | None]], ...] = (
129
+ ("Repeat", lambda row: row.repeat),
130
+ ("Position swap", lambda row: row.position_swap),
131
+ ("Length variant", lambda row: row.length_variant),
132
+ ("Family variant", lambda row: row.family_variant),
133
+ )
134
+
135
+
136
+ def _remember_fingerprint(
137
+ fingerprints: dict[str, str | None], row: CalibrationRow, *, location: str = ""
138
+ ) -> None:
139
+ recorded = fingerprints.setdefault(row.rubric, row.judgement_sha256)
140
+ if recorded != row.judgement_sha256:
141
+ raise CalibrationError(f"{location}mixed judgement fingerprints within a rubric")
142
+
143
+
144
+ def read_calibration(path: Path) -> tuple[CalibrationRow, ...]:
145
+ """Read strict UTF-8 JSONL with one decision record per item and rubric."""
146
+ rows: list[CalibrationRow] = []
147
+ seen: set[tuple[str, str]] = set()
148
+ fingerprints: dict[str, str | None] = {}
149
+ try:
150
+ with path.open(encoding="utf-8") as source:
151
+ for number, line in enumerate(source, start=1):
152
+ if not line.strip():
153
+ continue
154
+ try:
155
+ row = CalibrationRow.model_validate_json(line)
156
+ except ValidationError as error:
157
+ issues = error.errors(include_input=False, include_context=False)
158
+ # Do not echo external labels, costs, invalid JSON, or unexpected keys.
159
+ kind = issues[0]["type"]
160
+ raise CalibrationError(
161
+ f"{path}:{number}: invalid calibration row ({kind})"
162
+ ) from None
163
+ key = row.rubric, row.id
164
+ if key in seen:
165
+ raise CalibrationError(f"{path}:{number}: duplicate item and rubric")
166
+ seen.add(key)
167
+ _remember_fingerprint(fingerprints, row, location=f"{path}:{number}: ")
168
+ rows.append(row)
169
+ except (OSError, UnicodeError) as error:
170
+ raise CalibrationError(f"{path}: cannot read UTF-8 calibration JSONL") from error
171
+ if not rows:
172
+ raise CalibrationError(f"{path}: no calibration rows")
173
+ return tuple(rows)
174
+
175
+
176
+ def calibrate(
177
+ rows: Sequence[CalibrationRow], *, random_sample: bool = False, confidence: float = 0.95
178
+ ) -> tuple[_RubricReport, ...]:
179
+ """Summarize agreement per rubric and infer population accuracy when labels support it."""
180
+ if not rows:
181
+ raise CalibrationError("no calibration rows")
182
+ if not 0 < confidence < 1:
183
+ raise CalibrationError("confidence must be strictly between 0 and 1")
184
+ groups: dict[str, list[CalibrationRow]] = {}
185
+ fingerprints: dict[str, str | None] = {}
186
+ for row in rows:
187
+ _remember_fingerprint(fingerprints, row)
188
+ groups.setdefault(row.rubric, []).append(row)
189
+ return tuple(
190
+ _report(rubric, group, random_sample=random_sample, confidence=confidence)
191
+ for rubric, group in sorted(groups.items())
192
+ )
193
+
194
+
195
+ def _confusion(pairs: Sequence[tuple[bool, bool]]) -> _Confusion:
196
+ return _Confusion(
197
+ true_positive=sum(reference and tested for reference, tested in pairs),
198
+ true_negative=sum(not reference and not tested for reference, tested in pairs),
199
+ false_positive=sum(not reference and tested for reference, tested in pairs),
200
+ false_negative=sum(reference and not tested for reference, tested in pairs),
201
+ )
202
+
203
+
204
+ def _probe(
205
+ rows: Sequence[CalibrationRow], name: str, value: Callable[[CalibrationRow], bool | None]
206
+ ) -> _ProbeResult:
207
+ changes = tuple(
208
+ int(probe) - int(row.judge) for row in rows if (probe := value(row)) is not None
209
+ )
210
+ return _ProbeResult(
211
+ name, len(changes), sum(map(abs, changes)), mean(changes) if changes else None
212
+ )
213
+
214
+
215
+ @dataclass(frozen=True)
216
+ class _Estimates:
217
+ corrected_rate: float | None = None
218
+ corrected_interval: _Interval | None = None
219
+ human_interval: _Interval | None = None
220
+
221
+
222
+ def _estimates(
223
+ pairs: Sequence[tuple[bool, bool]],
224
+ *,
225
+ size: int,
226
+ judge_rate: float,
227
+ random_sample: bool,
228
+ confidence: float,
229
+ ) -> _Estimates:
230
+ count = len(pairs)
231
+ if count == 0:
232
+ return _Estimates()
233
+ observed = tuple(int(human) for human, _ in pairs)
234
+ successes = sum(observed)
235
+ if count == size:
236
+ truth = successes / size
237
+ return _Estimates(truth, (truth, truth), (truth, truth))
238
+ if not random_sample:
239
+ return _Estimates()
240
+ differences = tuple(int(human) - int(judge) for human, judge in pairs)
241
+ corrected = judge_rate + mean(differences)
242
+ # These deterministic bounds hold for every completion of the unreviewed cases.
243
+ feasible = successes / size, (successes + size - count) / size
244
+ return _Estimates(
245
+ corrected,
246
+ _bounded(corrected, _radius(differences, size, 2.0, confidence), feasible),
247
+ _bounded(mean(observed), _radius(observed, size, 1.0, confidence), feasible),
248
+ )
249
+
250
+
251
+ def _radius(values: Sequence[int], size: int, width: float, confidence: float) -> float:
252
+ # Bardenet & Maillard Theorem 4.3 has one-sided error at most 5 * delta.
253
+ # Apply it to X and -X with delta = alpha / 10. Its variance uses divisor n.
254
+ count = len(values)
255
+ fraction = count / size
256
+ correction = (1 - (count - 1) / size) if fraction <= 0.5 else (1 - fraction) * (1 + 1 / count)
257
+ threshold = log(10 / (1 - confidence))
258
+ kappa = 7 / 3 + sqrt(3) / 2
259
+ return (
260
+ pstdev(values) * sqrt(2 * correction * threshold / count)
261
+ + kappa * width * threshold / count
262
+ )
263
+
264
+
265
+ def _bounded(estimate: float, radius: float, feasible: _Interval) -> _Interval:
266
+ low = max(feasible[0], estimate - radius)
267
+ high = min(feasible[1], estimate + radius)
268
+ # An empty intersection has already missed the target. Use the deterministic
269
+ # envelope rather than emitting an impossible interval.
270
+ return (low, high) if low <= high else feasible
271
+
272
+
273
+ def _sum_costs(costs: Sequence[float | None]) -> float | None:
274
+ if any(cost is None for cost in costs):
275
+ return None
276
+ return sum(cost for cost in costs if cost is not None)
277
+
278
+
279
+ @dataclass(frozen=True)
280
+ class _EnsembleRow:
281
+ human: bool
282
+ judge: bool
283
+ two: bool
284
+ three: bool
285
+ costs: tuple[float | None, float | None, float | None]
286
+
287
+
288
+ def _ensemble(rows: Sequence[CalibrationRow]) -> tuple[int, tuple[_EnsembleResult, ...]]:
289
+ matched = tuple(
290
+ _EnsembleRow(
291
+ row.human,
292
+ row.judge,
293
+ row.ensemble_2,
294
+ row.ensemble_3,
295
+ (row.judge_cost_usd, row.ensemble_2_cost_usd, row.ensemble_3_cost_usd),
296
+ )
297
+ for row in rows
298
+ if row.human is not None and row.ensemble_2 is not None and row.ensemble_3 is not None
299
+ )
300
+ if not matched:
301
+ return 0, ()
302
+ kappas = tuple(
303
+ _confusion(tuple(zip((row.human for row in matched), verdicts, strict=True))).kappa
304
+ for verdicts in (
305
+ (row.judge for row in matched),
306
+ (row.two for row in matched),
307
+ (row.three for row in matched),
308
+ )
309
+ )
310
+ costs = tuple(
311
+ _sum_costs(column) for column in zip(*(row.costs for row in matched), strict=True)
312
+ )
313
+ reports = tuple(
314
+ _EnsembleResult(judges, kappa, cost, _cost_gain(kappas[0], costs[0], kappa, cost))
315
+ for judges, (kappa, cost) in enumerate(zip(kappas, costs, strict=True), start=1)
316
+ )
317
+ return len(matched), reports
318
+
319
+
320
+ def _cost_gain(
321
+ baseline: float | None, baseline_cost: float | None, kappa: float | None, cost: float | None
322
+ ) -> float | None:
323
+ if (
324
+ baseline is None
325
+ or baseline_cost is None
326
+ or kappa is None
327
+ or cost is None
328
+ or cost <= baseline_cost
329
+ ):
330
+ return None
331
+ return (kappa - baseline) / (cost - baseline_cost)
332
+
333
+
334
+ def _report(
335
+ rubric: str, rows: Sequence[CalibrationRow], *, random_sample: bool, confidence: float
336
+ ) -> _RubricReport:
337
+ if len({row.id for row in rows}) != len(rows):
338
+ raise CalibrationError("duplicate item and rubric")
339
+ pairs = tuple((row.human, row.judge) for row in rows if row.human is not None)
340
+ second = tuple(
341
+ (row.human, row.second_human)
342
+ for row in rows
343
+ if row.human is not None and row.second_human is not None
344
+ )
345
+ judge_rate = mean(row.judge for row in rows)
346
+ inference = _estimates(
347
+ pairs,
348
+ size=len(rows),
349
+ judge_rate=judge_rate,
350
+ random_sample=random_sample,
351
+ confidence=confidence,
352
+ )
353
+ ensemble_count, ensembles = _ensemble(rows)
354
+ return _RubricReport(
355
+ rubric=rubric,
356
+ count=len(rows),
357
+ labeled=len(pairs),
358
+ confusion=_confusion(pairs),
359
+ bias=mean(int(judge) - int(human) for human, judge in pairs) if pairs else None,
360
+ judge_rate=judge_rate,
361
+ human_rate=mean(human for human, _ in pairs) if pairs else None,
362
+ corrected_rate=inference.corrected_rate,
363
+ corrected_interval=inference.corrected_interval,
364
+ human_interval=inference.human_interval,
365
+ probes=tuple(_probe(rows, name, value) for name, value in _PROBES),
366
+ second_rater_count=len(second),
367
+ second_rater_kappa=_confusion(second).kappa,
368
+ ensemble_count=ensemble_count,
369
+ ensembles=ensembles,
370
+ )
371
+
372
+
373
+ def _number(value: float | None) -> str:
374
+ return "unavailable" if value is None else f"{value:.4f}"
375
+
376
+
377
+ def _interval(value: _Interval | None) -> str:
378
+ return "unavailable" if value is None else f"[{value[0]:.4f}, {value[1]:.4f}]"
379
+
380
+
381
+ def _render(report: _RubricReport) -> tuple[str, ...]:
382
+ counts = report.confusion
383
+ lines = [
384
+ f"{report.rubric}: {report.labeled}/{report.count} human-labeled",
385
+ f" kappa: {_number(report.kappa)}",
386
+ f" confusion: true positive={counts.true_positive}, true negative={counts.true_negative}, "
387
+ f"false positive={counts.false_positive}, false negative={counts.false_negative}",
388
+ f" label bias (judge minus human): {_number(report.bias)}",
389
+ f" judge rate: {_number(report.judge_rate)}",
390
+ f" human sample rate: {_number(report.human_rate)}",
391
+ f" human-only interval: {_interval(report.human_interval)}",
392
+ f" PPI corrected rate: {_number(report.corrected_rate)} "
393
+ f"{_interval(report.corrected_interval)}",
394
+ f" second rater kappa: {_number(report.second_rater_kappa)} "
395
+ f"({report.second_rater_count} matched)",
396
+ ]
397
+ for probe in report.probes:
398
+ detail = (
399
+ f"{probe.flips}/{probe.count} flips, acceptance delta {_number(probe.acceptance_delta)}"
400
+ if probe.count
401
+ else "not measured"
402
+ )
403
+ lines.append(f" {probe.name}: {detail}")
404
+ if report.ensembles:
405
+ lines.append(f" Judge ensemble ({report.ensemble_count} matched)")
406
+ for ensemble in report.ensembles:
407
+ lines.append(
408
+ f" {ensemble.judges} judge(s): kappa {_number(ensemble.kappa)}, "
409
+ f"total USD {_number(ensemble.total_cost_usd)}, "
410
+ f"kappa gain per added USD {_number(ensemble.gain_per_added_usd)}"
411
+ )
412
+ else:
413
+ lines.append(" Judge ensemble: not measured")
414
+ return tuple(lines)
415
+
416
+
417
+ def calibrate_command(
418
+ labels: Annotated[
419
+ Path, typer.Argument(help="JSONL with frozen judge decisions and human labels.")
420
+ ],
421
+ random_sample: Annotated[
422
+ bool,
423
+ typer.Option("--random-sample", help="Assert uniform random review within each rubric."),
424
+ ] = False,
425
+ confidence: Annotated[float, typer.Option("--confidence")] = 0.95,
426
+ ) -> None:
427
+ """Report human agreement, paired bias probes and corrected finite-set acceptance."""
428
+ try:
429
+ reports = calibrate(
430
+ read_calibration(labels), random_sample=random_sample, confidence=confidence
431
+ )
432
+ except CalibrationError as error:
433
+ typer.echo(f"error: {error}", err=True)
434
+ raise typer.Exit(3) from error
435
+ typer.echo(
436
+ f"Per-rubric intervals use {confidence:g} confidence with a declared random sample. "
437
+ "A fully reviewed set is exact."
438
+ )
439
+ if not random_sample:
440
+ typer.echo("Partial-label intervals withheld unless --random-sample is declared.")
441
+ for report in reports:
442
+ typer.echo("\n".join(_render(report)))