diffscore 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.
- diffscore/__init__.py +3 -0
- diffscore/api.py +729 -0
- diffscore/calibration.py +374 -0
- diffscore/cli.py +867 -0
- diffscore/config.py +88 -0
- diffscore/db/__init__.py +27 -0
- diffscore/db/base.py +25 -0
- diffscore/db/migrate.py +61 -0
- diffscore/db/models.py +257 -0
- diffscore/db/session.py +37 -0
- diffscore/diffing.py +292 -0
- diffscore/graders.py +281 -0
- diffscore/jobs.py +161 -0
- diffscore/judge.py +355 -0
- diffscore/labeling.py +167 -0
- diffscore/llm.py +120 -0
- diffscore/migrations/README +1 -0
- diffscore/migrations/env.py +84 -0
- diffscore/migrations/script.py.mako +28 -0
- diffscore/migrations/versions/2026_11_30-03d94780829e_run_error_and_cache_latency.py +34 -0
- diffscore/migrations/versions/2026_11_30-8c8961902e49_run_spend.py +34 -0
- diffscore/migrations/versions/2026_11_30-da2445f19a6c_initial_schema.py +280 -0
- diffscore/migrations/versions/2026_12_01-053ee29c31c6_run_case_keys.py +55 -0
- diffscore/migrations/versions/2026_12_01-9dc97334c9d9_judge_calibration.py +69 -0
- diffscore/migrations/versions/2026_12_01-a85ad738bd12_run_provider_keys.py +32 -0
- diffscore/queries.py +165 -0
- diffscore/runner.py +393 -0
- diffscore/secrets.py +130 -0
- diffscore/stats.py +83 -0
- diffscore/suite.py +329 -0
- diffscore/templates/env.example +14 -0
- diffscore/templates/example-prompt.md +14 -0
- diffscore/templates/example.yaml +75 -0
- diffscore-0.1.0.dist-info/METADATA +351 -0
- diffscore-0.1.0.dist-info/RECORD +38 -0
- diffscore-0.1.0.dist-info/WHEEL +4 -0
- diffscore-0.1.0.dist-info/entry_points.txt +2 -0
- diffscore-0.1.0.dist-info/licenses/LICENSE +21 -0
diffscore/calibration.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""How far to trust a judge: agreement with your labels, and its known biases.
|
|
2
|
+
|
|
3
|
+
`calibrate` re-judges every output you have labelled with the judge exactly as
|
|
4
|
+
the suite file defines it now. Rewrite the rubric and calibrate again: only
|
|
5
|
+
the judge is re-asked, no output is regenerated, and an unchanged rubric is
|
|
6
|
+
answered from the cache for free.
|
|
7
|
+
|
|
8
|
+
Reported per judge:
|
|
9
|
+
|
|
10
|
+
- **Cohen's kappa** against your labels. Below 0.6 the judge is close to
|
|
11
|
+
guessing and the rubric needs rewriting.
|
|
12
|
+
- **Verbosity:** correlation of the judge's score with output length. Above
|
|
13
|
+
0.3, length is buying score.
|
|
14
|
+
- **Self-preference:** whether any labelled output came from the judge's own model.
|
|
15
|
+
- **Position:** pairwise comparisons in both orders; how often the verdict
|
|
16
|
+
survives the swap.
|
|
17
|
+
- **Variance:** the same output judged several times; how often the verdict
|
|
18
|
+
flips. Temperature zero is not determinism.
|
|
19
|
+
- **Evidence:** how often the judge's quote really appears in the output.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from collections import defaultdict
|
|
25
|
+
from collections.abc import Callable
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import TYPE_CHECKING
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
from sqlalchemy import select
|
|
31
|
+
from sqlalchemy.orm import Session
|
|
32
|
+
|
|
33
|
+
from diffscore.db import JudgeCalibration, Project, Suite
|
|
34
|
+
from diffscore.graders import GraderRuntimeError, Output
|
|
35
|
+
from diffscore.judge import (
|
|
36
|
+
JudgeConfig,
|
|
37
|
+
JudgeVerdict,
|
|
38
|
+
judge_pair,
|
|
39
|
+
parse_config,
|
|
40
|
+
run_judge,
|
|
41
|
+
same_model,
|
|
42
|
+
)
|
|
43
|
+
from diffscore.labeling import LabeledOutput, LabelVerdict, labeled_outputs
|
|
44
|
+
from diffscore.llm import CompleteFn
|
|
45
|
+
|
|
46
|
+
if TYPE_CHECKING:
|
|
47
|
+
from diffscore.suite import CaseSpec, SuiteFile
|
|
48
|
+
|
|
49
|
+
KAPPA_OK = 0.6
|
|
50
|
+
VERBOSITY_FLAG = 0.3
|
|
51
|
+
POSITION_OK = 0.8
|
|
52
|
+
VARIANCE_FLAG = 0.1
|
|
53
|
+
MIN_LABELS_ADVISED = 50
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CalibrationError(ValueError):
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class Agreement:
|
|
62
|
+
n: int
|
|
63
|
+
kappa: float | None
|
|
64
|
+
observed: float # raw agreement rate
|
|
65
|
+
both_pass: int
|
|
66
|
+
both_fail: int
|
|
67
|
+
judge_pass_human_fail: int # the judge is too lenient here
|
|
68
|
+
judge_fail_human_pass: int # the judge is too strict here
|
|
69
|
+
note: str | None = None
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def ok(self) -> bool:
|
|
73
|
+
return self.kappa is not None and self.kappa >= KAPPA_OK
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class Verbosity:
|
|
78
|
+
n: int
|
|
79
|
+
r: float | None
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def flagged(self) -> bool:
|
|
83
|
+
return self.r is not None and self.r > VERBOSITY_FLAG
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class SelfPreference:
|
|
88
|
+
judge_model: str
|
|
89
|
+
output_models: tuple[str, ...]
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def ok(self) -> bool:
|
|
93
|
+
return not any(same_model(self.judge_model, m) for m in self.output_models)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True)
|
|
97
|
+
class Position:
|
|
98
|
+
pairs: int
|
|
99
|
+
consistent: int
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def rate(self) -> float | None:
|
|
103
|
+
return self.consistent / self.pairs if self.pairs else None
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def flagged(self) -> bool:
|
|
107
|
+
return self.rate is not None and self.rate < POSITION_OK
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True)
|
|
111
|
+
class Variance:
|
|
112
|
+
cases: int
|
|
113
|
+
repeats: int
|
|
114
|
+
flipped: int
|
|
115
|
+
mean_spread: float
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def flip_rate(self) -> float | None:
|
|
119
|
+
return self.flipped / self.cases if self.cases else None
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def flagged(self) -> bool:
|
|
123
|
+
return self.flip_rate is not None and self.flip_rate > VARIANCE_FLAG
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass(frozen=True)
|
|
127
|
+
class Disagreement:
|
|
128
|
+
case_key: str
|
|
129
|
+
output: str
|
|
130
|
+
human: LabelVerdict
|
|
131
|
+
judge: LabelVerdict
|
|
132
|
+
failed_criterion: str | None
|
|
133
|
+
evidence: str
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True)
|
|
137
|
+
class Report:
|
|
138
|
+
suite_id: int
|
|
139
|
+
grader: str
|
|
140
|
+
version: str
|
|
141
|
+
judge_model: str
|
|
142
|
+
label_source: str # which labels were used
|
|
143
|
+
skipped: int # labelled outputs whose case is no longer in the suite file
|
|
144
|
+
errors: int # outputs the judge failed to grade
|
|
145
|
+
agreement: Agreement
|
|
146
|
+
verbosity: Verbosity
|
|
147
|
+
self_preference: SelfPreference
|
|
148
|
+
position: Position | None
|
|
149
|
+
variance: Variance | None
|
|
150
|
+
evidence_found: int
|
|
151
|
+
evidence_total: int
|
|
152
|
+
disagreements: tuple[Disagreement, ...] = ()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
Progress = Callable[[str], None]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def kappa(human: list[bool], judge: list[bool]) -> tuple[float | None, str | None]:
|
|
159
|
+
if len(human) < 2:
|
|
160
|
+
return None, "need at least 2 labelled outputs"
|
|
161
|
+
if len(set(human) | set(judge)) < 2:
|
|
162
|
+
return None, "every label and verdict is the same class, so kappa is undefined"
|
|
163
|
+
from sklearn.metrics import cohen_kappa_score # slow import
|
|
164
|
+
|
|
165
|
+
value = float(cohen_kappa_score(human, judge))
|
|
166
|
+
if np.isnan(value):
|
|
167
|
+
return None, "kappa is undefined for these labels (one class only)"
|
|
168
|
+
return value, None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def pearson(x: list[float], y: list[float]) -> float | None:
|
|
172
|
+
if len(x) < 5 or np.std(x) == 0 or np.std(y) == 0:
|
|
173
|
+
return None
|
|
174
|
+
return float(np.corrcoef(x, y)[0, 1])
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _suite_id(session: Session, spec: SuiteFile) -> int:
|
|
178
|
+
suite_id = session.scalar(
|
|
179
|
+
select(Suite.id)
|
|
180
|
+
.join(Project, Suite.project_id == Project.id)
|
|
181
|
+
.where(Project.name == spec.project, Suite.name == spec.name)
|
|
182
|
+
)
|
|
183
|
+
if suite_id is None:
|
|
184
|
+
raise CalibrationError(f"suite {spec.name!r} has never been run, so nothing is labelled")
|
|
185
|
+
return suite_id
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _judge_config(spec: SuiteFile, grader: str | None) -> tuple[str, str, JudgeConfig]:
|
|
189
|
+
judges = [g for g in spec.all_graders() if g.name == "judge"]
|
|
190
|
+
if not judges:
|
|
191
|
+
raise CalibrationError("this suite has no `judge` grader to calibrate")
|
|
192
|
+
if grader is None:
|
|
193
|
+
if len(judges) > 1:
|
|
194
|
+
names = ", ".join(g.display_name for g in judges)
|
|
195
|
+
raise CalibrationError(
|
|
196
|
+
f"several judges in this suite ({names}); pick one with --grader"
|
|
197
|
+
)
|
|
198
|
+
chosen = judges[0]
|
|
199
|
+
else:
|
|
200
|
+
matches = [g for g in judges if g.display_name == grader]
|
|
201
|
+
if not matches:
|
|
202
|
+
raise CalibrationError(f"no judge named {grader!r} in this suite")
|
|
203
|
+
chosen = matches[0]
|
|
204
|
+
return chosen.display_name, chosen.version, parse_config(chosen.arg)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def calibrate(
|
|
208
|
+
session: Session,
|
|
209
|
+
spec: SuiteFile,
|
|
210
|
+
ask: CompleteFn,
|
|
211
|
+
*,
|
|
212
|
+
grader: str | None = None,
|
|
213
|
+
position_pairs: int = 10,
|
|
214
|
+
variance_cases: int = 20,
|
|
215
|
+
repeats: int = 3,
|
|
216
|
+
progress: Progress | None = None,
|
|
217
|
+
) -> Report:
|
|
218
|
+
name, version, cfg = _judge_config(spec, grader)
|
|
219
|
+
suite_id = _suite_id(session, spec)
|
|
220
|
+
|
|
221
|
+
labels = labeled_outputs(session, suite_id, name)
|
|
222
|
+
source = f"labels for {name}"
|
|
223
|
+
if not labels:
|
|
224
|
+
labels = labeled_outputs(session, suite_id, None)
|
|
225
|
+
source = "overall labels (none recorded for this judge yet)"
|
|
226
|
+
if not labels:
|
|
227
|
+
raise CalibrationError(
|
|
228
|
+
f"no labels yet. Label outputs with `diffscore label <run> --grader {name}`"
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
cases: dict[str, CaseSpec] = {c.id: c for c in spec.cases}
|
|
232
|
+
usable = [lab for lab in labels if lab.case_key in cases]
|
|
233
|
+
skipped = len(labels) - len(usable)
|
|
234
|
+
|
|
235
|
+
def output_for(lab: LabeledOutput) -> Output:
|
|
236
|
+
case = cases[lab.case_key]
|
|
237
|
+
return Output(
|
|
238
|
+
text=lab.output, expect=case.expect, input=spec.messages_for(case)[-1]["content"]
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
# ---- agreement (and evidence, verbosity from the same verdicts)
|
|
242
|
+
human: list[bool] = []
|
|
243
|
+
judged: list[bool] = []
|
|
244
|
+
scores: list[float] = []
|
|
245
|
+
lengths: list[float] = []
|
|
246
|
+
evidence = 0
|
|
247
|
+
errors = 0
|
|
248
|
+
verdicts: dict[int, JudgeVerdict] = {}
|
|
249
|
+
disagreements: list[Disagreement] = []
|
|
250
|
+
for i, lab in enumerate(usable, 1):
|
|
251
|
+
if progress:
|
|
252
|
+
progress(f"judging labelled output {i}/{len(usable)}")
|
|
253
|
+
try:
|
|
254
|
+
v = run_judge(ask, cfg, output_for(lab))
|
|
255
|
+
except GraderRuntimeError:
|
|
256
|
+
errors += 1
|
|
257
|
+
continue
|
|
258
|
+
verdicts[id(lab)] = v
|
|
259
|
+
if v.passed != (lab.verdict == "pass"):
|
|
260
|
+
disagreements.append(
|
|
261
|
+
Disagreement(
|
|
262
|
+
case_key=lab.case_key,
|
|
263
|
+
output=lab.output,
|
|
264
|
+
human=lab.verdict,
|
|
265
|
+
judge="pass" if v.passed else "fail",
|
|
266
|
+
failed_criterion=v.failed_criterion,
|
|
267
|
+
evidence=v.evidence,
|
|
268
|
+
)
|
|
269
|
+
)
|
|
270
|
+
human.append(lab.verdict == "pass")
|
|
271
|
+
judged.append(v.passed)
|
|
272
|
+
scores.append(v.score)
|
|
273
|
+
lengths.append(float(len(lab.output)))
|
|
274
|
+
evidence += v.evidence_found
|
|
275
|
+
|
|
276
|
+
k, note = kappa(human, judged)
|
|
277
|
+
pairs = list(zip(human, judged, strict=True))
|
|
278
|
+
agreement = Agreement(
|
|
279
|
+
n=len(pairs),
|
|
280
|
+
kappa=k,
|
|
281
|
+
observed=sum(h == j for h, j in pairs) / len(pairs) if pairs else 0.0,
|
|
282
|
+
both_pass=sum(h and j for h, j in pairs),
|
|
283
|
+
both_fail=sum(not h and not j for h, j in pairs),
|
|
284
|
+
judge_pass_human_fail=sum(j and not h for h, j in pairs),
|
|
285
|
+
judge_fail_human_pass=sum(h and not j for h, j in pairs),
|
|
286
|
+
note=note,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
# ---- position: two different outputs for the same case, judged in both orders
|
|
290
|
+
position = None
|
|
291
|
+
if position_pairs > 0:
|
|
292
|
+
by_case: dict[str, list[LabeledOutput]] = defaultdict(list)
|
|
293
|
+
for lab in usable:
|
|
294
|
+
if all(lab.output != other.output for other in by_case[lab.case_key]):
|
|
295
|
+
by_case[lab.case_key].append(lab)
|
|
296
|
+
candidates = [outs[:2] for outs in by_case.values() if len(outs) >= 2][:position_pairs]
|
|
297
|
+
consistent = done = 0
|
|
298
|
+
for i, (a, b) in enumerate(candidates, 1):
|
|
299
|
+
if progress:
|
|
300
|
+
progress(f"position check {i}/{len(candidates)}")
|
|
301
|
+
try:
|
|
302
|
+
pv = judge_pair(ask, cfg, output_for(a).input, a.output, b.output)
|
|
303
|
+
except GraderRuntimeError:
|
|
304
|
+
continue
|
|
305
|
+
done += 1
|
|
306
|
+
consistent += pv.consistent
|
|
307
|
+
position = Position(done, consistent)
|
|
308
|
+
|
|
309
|
+
# ---- variance: re-judge a sample with fresh (uncached) samples
|
|
310
|
+
variance = None
|
|
311
|
+
if variance_cases > 0 and repeats > 1:
|
|
312
|
+
sample = [lab for lab in usable if id(lab) in verdicts][:variance_cases]
|
|
313
|
+
flipped = 0
|
|
314
|
+
spreads: list[float] = []
|
|
315
|
+
for i, lab in enumerate(sample, 1):
|
|
316
|
+
if progress:
|
|
317
|
+
progress(f"variance check {i}/{len(sample)}")
|
|
318
|
+
runs = [verdicts[id(lab)]]
|
|
319
|
+
try:
|
|
320
|
+
runs += [run_judge(ask, cfg, output_for(lab), repeat=r) for r in range(1, repeats)]
|
|
321
|
+
except GraderRuntimeError:
|
|
322
|
+
continue
|
|
323
|
+
flipped += len({v.passed for v in runs}) > 1
|
|
324
|
+
spreads.append(max(v.score for v in runs) - min(v.score for v in runs))
|
|
325
|
+
variance = Variance(
|
|
326
|
+
len(spreads), repeats, flipped, float(np.mean(spreads)) if spreads else 0.0
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
return Report(
|
|
330
|
+
suite_id=suite_id,
|
|
331
|
+
grader=name,
|
|
332
|
+
version=version,
|
|
333
|
+
judge_model=cfg.judge_model(),
|
|
334
|
+
label_source=source,
|
|
335
|
+
skipped=skipped,
|
|
336
|
+
errors=errors,
|
|
337
|
+
agreement=agreement,
|
|
338
|
+
verbosity=Verbosity(len(scores), pearson(scores, lengths)),
|
|
339
|
+
self_preference=SelfPreference(
|
|
340
|
+
cfg.judge_model(), tuple(sorted({lab.model for lab in usable}))
|
|
341
|
+
),
|
|
342
|
+
position=position,
|
|
343
|
+
variance=variance,
|
|
344
|
+
evidence_found=evidence,
|
|
345
|
+
evidence_total=len(scores),
|
|
346
|
+
disagreements=tuple(disagreements),
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def save_report(session: Session, report: Report) -> JudgeCalibration:
|
|
351
|
+
"""Keep the result, so screens can show each judge's kappa without re-judging."""
|
|
352
|
+
a, p, va = report.agreement, report.position, report.variance
|
|
353
|
+
row = JudgeCalibration(
|
|
354
|
+
suite_id=report.suite_id,
|
|
355
|
+
grader_name=report.grader,
|
|
356
|
+
grader_version=report.version,
|
|
357
|
+
judge_model=report.judge_model,
|
|
358
|
+
labels=a.n,
|
|
359
|
+
kappa=a.kappa,
|
|
360
|
+
agreement=a.observed,
|
|
361
|
+
judge_pass_human_fail=a.judge_pass_human_fail,
|
|
362
|
+
judge_fail_human_pass=a.judge_fail_human_pass,
|
|
363
|
+
verbosity_r=report.verbosity.r,
|
|
364
|
+
self_preference_ok=report.self_preference.ok,
|
|
365
|
+
position_pairs=p.pairs if p else None,
|
|
366
|
+
position_consistent=p.consistent if p else None,
|
|
367
|
+
variance_cases=va.cases if va else None,
|
|
368
|
+
variance_flipped=va.flipped if va else None,
|
|
369
|
+
evidence_found=report.evidence_found,
|
|
370
|
+
evidence_total=report.evidence_total,
|
|
371
|
+
)
|
|
372
|
+
session.add(row)
|
|
373
|
+
session.commit()
|
|
374
|
+
return row
|