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.
Files changed (38) hide show
  1. diffscore/__init__.py +3 -0
  2. diffscore/api.py +729 -0
  3. diffscore/calibration.py +374 -0
  4. diffscore/cli.py +867 -0
  5. diffscore/config.py +88 -0
  6. diffscore/db/__init__.py +27 -0
  7. diffscore/db/base.py +25 -0
  8. diffscore/db/migrate.py +61 -0
  9. diffscore/db/models.py +257 -0
  10. diffscore/db/session.py +37 -0
  11. diffscore/diffing.py +292 -0
  12. diffscore/graders.py +281 -0
  13. diffscore/jobs.py +161 -0
  14. diffscore/judge.py +355 -0
  15. diffscore/labeling.py +167 -0
  16. diffscore/llm.py +120 -0
  17. diffscore/migrations/README +1 -0
  18. diffscore/migrations/env.py +84 -0
  19. diffscore/migrations/script.py.mako +28 -0
  20. diffscore/migrations/versions/2026_11_30-03d94780829e_run_error_and_cache_latency.py +34 -0
  21. diffscore/migrations/versions/2026_11_30-8c8961902e49_run_spend.py +34 -0
  22. diffscore/migrations/versions/2026_11_30-da2445f19a6c_initial_schema.py +280 -0
  23. diffscore/migrations/versions/2026_12_01-053ee29c31c6_run_case_keys.py +55 -0
  24. diffscore/migrations/versions/2026_12_01-9dc97334c9d9_judge_calibration.py +69 -0
  25. diffscore/migrations/versions/2026_12_01-a85ad738bd12_run_provider_keys.py +32 -0
  26. diffscore/queries.py +165 -0
  27. diffscore/runner.py +393 -0
  28. diffscore/secrets.py +130 -0
  29. diffscore/stats.py +83 -0
  30. diffscore/suite.py +329 -0
  31. diffscore/templates/env.example +14 -0
  32. diffscore/templates/example-prompt.md +14 -0
  33. diffscore/templates/example.yaml +75 -0
  34. diffscore-0.1.0.dist-info/METADATA +351 -0
  35. diffscore-0.1.0.dist-info/RECORD +38 -0
  36. diffscore-0.1.0.dist-info/WHEEL +4 -0
  37. diffscore-0.1.0.dist-info/entry_points.txt +2 -0
  38. diffscore-0.1.0.dist-info/licenses/LICENSE +21 -0
diffscore/jobs.py ADDED
@@ -0,0 +1,161 @@
1
+ """Queue jobs for runs started from the API: one job per case, then a final one.
2
+
3
+ One job per case, not per run: a 500-case suite that dies at case 400 resumes
4
+ from 400 (a case that already has a result is skipped), and the progress bar is
5
+ real. A final job, which runs even if some case jobs failed, closes the run.
6
+
7
+ Workers run on Linux (RQ forks): `docker compose up worker`. With
8
+ QUEUE_SYNC=true jobs run inline in the API process instead, for development
9
+ without a worker and for tests.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from decimal import Decimal
15
+ from functools import lru_cache
16
+ from typing import Any
17
+
18
+ from redis import Redis
19
+ from rq import Queue
20
+ from rq.job import Dependency, Job, Retry
21
+ from sqlalchemy import select, update
22
+
23
+ from diffscore.config import get_settings
24
+ from diffscore.db import Case, Result, Run
25
+ from diffscore.db.session import make_session
26
+ from diffscore.diffing import adopt_if_no_baseline
27
+ from diffscore.graders import GraderDeps
28
+ from diffscore.llm import CompleteFn, Completion, Message, complete, throttled
29
+ from diffscore.runner import SKIPPED, RunSummary, cached_ask, finalize_run, run_case, spec_for_run
30
+ from diffscore.secrets import decrypt_keys, install_log_redaction, provider_for
31
+
32
+ QUEUE_NAME = "diffscore"
33
+
34
+
35
+ @lru_cache
36
+ def redis_connection() -> Redis:
37
+ return Redis.from_url(get_settings().redis_url)
38
+
39
+
40
+ def get_queue(connection: Redis | None = None) -> Queue:
41
+ settings = get_settings()
42
+ return Queue(
43
+ QUEUE_NAME,
44
+ connection=connection or redis_connection(),
45
+ is_async=not settings.queue_sync,
46
+ )
47
+
48
+
49
+ def enqueue_run(queue: Queue, run_id: int, case_keys: list[str]) -> list[Job]:
50
+ """Queue every case of a run, then a job that closes it once all have finished."""
51
+ jobs = [
52
+ queue.enqueue(case_job, run_id, key, job_timeout=600, retry=Retry(max=2))
53
+ for key in case_keys
54
+ ]
55
+ final = queue.enqueue(
56
+ finalize_job, run_id, depends_on=Dependency(jobs=jobs, allow_failure=True)
57
+ )
58
+ return [*jobs, final]
59
+
60
+
61
+ # ------------------------------------------------------------------ model access
62
+
63
+
64
+ @lru_cache
65
+ def _paced() -> CompleteFn:
66
+ """The real model call, paced per model, shared by every job in this worker."""
67
+ settings = get_settings()
68
+ return throttled(
69
+ complete,
70
+ settings.model_rpm,
71
+ per_model={settings.judge_model: settings.judge_rpm or settings.model_rpm},
72
+ )
73
+
74
+
75
+ def model_fn(provider_keys: dict[str, str]) -> CompleteFn:
76
+ """Call models with the project's own keys where it has them.
77
+
78
+ The key is added after the cache layer, so it never enters a cache key, a
79
+ stored row or a log line. Without a project key the server's env key is used.
80
+ """
81
+ paced = _paced()
82
+
83
+ def call(model: str, messages: list[Message], params: dict[str, Any]) -> Completion:
84
+ provider = provider_for(model)
85
+ if provider and provider in provider_keys:
86
+ params = {**params, "api_key": provider_keys[provider]}
87
+ return paced(model, messages, params)
88
+
89
+ return call
90
+
91
+
92
+ # ------------------------------------------------------------------ jobs
93
+
94
+
95
+ def case_job(run_id: int, case_key: str) -> str:
96
+ install_log_redaction()
97
+ session = make_session()
98
+ try:
99
+ run = session.get(Run, run_id)
100
+ if run is None or run.status != "running":
101
+ return "run not running"
102
+ case_row = session.scalar(
103
+ select(Case).where(Case.suite_id == run.suite_id, Case.key == case_key)
104
+ )
105
+ if case_row is None:
106
+ return "case not found"
107
+ done = session.scalar(
108
+ select(Result.id).where(Result.run_id == run_id, Result.case_id == case_row.id)
109
+ )
110
+ if done is not None:
111
+ return "already done" # a retried or resumed job
112
+
113
+ settings = get_settings()
114
+ if (run.tokens_spent or 0) >= settings.max_tokens_per_run:
115
+ session.add(Result(run=run, case=case_row, error=f"{SKIPPED}token budget reached"))
116
+ session.commit()
117
+ return "skipped"
118
+
119
+ spec = spec_for_run(session, run)
120
+ cs = next(c for c in spec.cases if c.id == case_key)
121
+ summary = RunSummary(run_id=run_id, status=run.status, total=len(spec.cases))
122
+
123
+ def spent(c: Completion) -> None:
124
+ summary.tokens_spent += c.input_tokens + c.output_tokens
125
+ summary.cost_spent += Decimal(str(c.cost_usd or 0))
126
+
127
+ # A visitor's per-run keys win over the project's stored ones.
128
+ keys = decrypt_keys(run.suite.project.provider_keys_encrypted)
129
+ keys |= decrypt_keys(run.provider_keys_encrypted)
130
+ ask = cached_ask(session, model_fn(keys), on_spend=spent)
131
+ outcome = run_case(
132
+ session, spec, cs, case_row, run, ask, GraderDeps(ask, run.model), summary
133
+ )
134
+ # Atomic, so concurrent workers can't lose each other's spend.
135
+ session.execute(
136
+ update(Run)
137
+ .where(Run.id == run_id)
138
+ .values(
139
+ tokens_spent=Run.tokens_spent + summary.tokens_spent,
140
+ cost_spent=Run.cost_spent + summary.cost_spent,
141
+ )
142
+ )
143
+ session.commit()
144
+ return outcome.outcome
145
+ finally:
146
+ session.close()
147
+
148
+
149
+ def finalize_job(run_id: int) -> str:
150
+ session = make_session()
151
+ try:
152
+ run = session.get(Run, run_id)
153
+ if run is None:
154
+ return "no run"
155
+ if run.status == "running":
156
+ run.provider_keys_encrypted = None # a visitor's keys live only as long as the run
157
+ finalize_run(session, run)
158
+ adopt_if_no_baseline(session, run_id)
159
+ return run.status
160
+ finally:
161
+ session.close()
diffscore/judge.py ADDED
@@ -0,0 +1,355 @@
1
+ """The LLM judge: a rubric, a blinded prompt, and verdicts that must cite evidence.
2
+
3
+ Reach for it last. A deterministic grader is free and never drifts; the judge
4
+ is for what string matching cannot express (faithfulness, tone, helpfulness),
5
+ and it is only worth trusting once `diffscore calibrate` says it agrees with you.
6
+
7
+ Controls built in here:
8
+
9
+ - **Blinding.** The judge sees the case input, the output and optional
10
+ reference material. Never the prompt under test, its version, or the model
11
+ that produced the output.
12
+ - **Structured output.** A pass/fail per rubric criterion, the criterion that
13
+ failed, and a verbatim quote from the output as evidence. The score is the
14
+ fraction of criteria met, computed here rather than invented by the judge.
15
+ - **Evidence check.** A quote that does not appear in the output is flagged:
16
+ a judge that cannot cite is usually hallucinating its verdict.
17
+ - **Self-preference.** A model may not judge its own outputs.
18
+ - **Position bias.** Pairwise comparisons run in both orders, and only verdicts
19
+ that survive the swap are kept.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import json
26
+ import re
27
+ from dataclasses import dataclass, field
28
+ from typing import Any, Literal
29
+
30
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
31
+
32
+ from diffscore.config import get_settings
33
+ from diffscore.graders import (
34
+ Grade,
35
+ Grader,
36
+ GraderConfigError,
37
+ GraderDeps,
38
+ GraderRuntimeError,
39
+ Output,
40
+ register,
41
+ )
42
+ from diffscore.llm import CompleteFn, Message
43
+
44
+ # ------------------------------------------------------------------ config
45
+
46
+
47
+ class Criterion(BaseModel):
48
+ model_config = ConfigDict(extra="forbid")
49
+
50
+ name: str = Field(pattern=r"^[A-Za-z][\w-]{0,39}$")
51
+ description: str = Field(min_length=10)
52
+
53
+
54
+ class JudgeConfig(BaseModel):
55
+ """`judge:` in a suite file."""
56
+
57
+ model_config = ConfigDict(extra="forbid")
58
+
59
+ name: str | None = Field(default=None, pattern=r"^[A-Za-z][\w-]{0,39}$")
60
+ model: str | None = None
61
+ rubric: list[Criterion] = Field(min_length=1, max_length=8)
62
+ # Ground truth the judge may consult, e.g. the policy a support bot must follow.
63
+ # A suite file may give `context_file:` instead; the loader inlines it.
64
+ context: str | None = None
65
+ max_tokens: int = Field(default=2048, ge=256, le=16384)
66
+
67
+ @field_validator("rubric")
68
+ @classmethod
69
+ def _unique(cls, rubric: list[Criterion]) -> list[Criterion]:
70
+ names = [c.name for c in rubric]
71
+ dupes = sorted({n for n in names if names.count(n) > 1})
72
+ if dupes:
73
+ raise ValueError(f"rubric criteria must have unique names; repeated: {dupes}")
74
+ return rubric
75
+
76
+ def judge_model(self) -> str:
77
+ return self.model or get_settings().judge_model
78
+
79
+ def fingerprint(self) -> str:
80
+ """Changes whenever the rubric, context or judge model does: the grader version."""
81
+ blob = json.dumps(
82
+ {**self.model_dump(exclude={"name"}), "model": self.judge_model()}, sort_keys=True
83
+ )
84
+ return hashlib.sha256(blob.encode()).hexdigest()[:8]
85
+
86
+
87
+ def parse_config(arg: Any) -> JudgeConfig:
88
+ if not isinstance(arg, dict):
89
+ raise GraderConfigError("judge needs a mapping with at least a `rubric:` list")
90
+ if "context_file" in arg:
91
+ raise GraderConfigError("context_file is only supported in suite files")
92
+ try:
93
+ return JudgeConfig.model_validate(arg)
94
+ except ValidationError as exc:
95
+ first = exc.errors()[0]
96
+ where = ".".join(str(p) for p in first["loc"])
97
+ raise GraderConfigError(
98
+ f"judge {where}: {str(first['msg']).removeprefix('Value error, ')}"
99
+ ) from exc
100
+
101
+
102
+ def same_model(a: str, b: str) -> bool:
103
+ """`gemini/gemini-3.5-flash` and `openrouter/google/gemini-3.5-flash` are one model."""
104
+ return a.rsplit("/", 1)[-1].lower() == b.rsplit("/", 1)[-1].lower()
105
+
106
+
107
+ def check_not_self_judging(cfg: JudgeConfig, candidate_model: str) -> None:
108
+ if same_model(cfg.judge_model(), candidate_model):
109
+ raise GraderConfigError(
110
+ f"the judge model ({cfg.judge_model()}) is the model under test; models rate "
111
+ "their own outputs generously. Set `model:` on the judge or JUDGE_MODEL "
112
+ "to a different model."
113
+ )
114
+
115
+
116
+ # ------------------------------------------------------------------ prompts
117
+
118
+ SYSTEM = (
119
+ "You are a strict, impartial evaluator. You grade one response against a rubric. "
120
+ "Judge only what the response actually says; do not reward length, confidence or "
121
+ "style beyond what the rubric asks. You do not know, and must not guess, which "
122
+ "system or prompt produced the response. Reply with JSON only."
123
+ )
124
+
125
+
126
+ def _rubric_lines(cfg: JudgeConfig) -> str:
127
+ return "\n".join(f"- {c.name}: {c.description}" for c in cfg.rubric)
128
+
129
+
130
+ def judge_messages(cfg: JudgeConfig, out: Output) -> list[Message]:
131
+ """The full judge prompt. Contains the input and output, never the prompt under test."""
132
+ parts = [f"## Input\n{out.input or '(none)'}"]
133
+ if cfg.context:
134
+ parts.append(f"## Reference material (ground truth)\n{cfg.context}")
135
+ if out.expect:
136
+ parts.append(f"## Reference answer\n{out.expect}")
137
+ parts.append(f"## Response to grade\n<response>\n{out.text}\n</response>")
138
+ shape = ", ".join(f'"{c.name}": "pass" | "fail"' for c in cfg.rubric)
139
+ parts.append(
140
+ f"## Rubric\n{_rubric_lines(cfg)}\n\n"
141
+ "## Reply\nJSON only, exactly this shape:\n"
142
+ f'{{"criteria": {{{shape}}}, "failed_criterion": "<name of the most serious '
143
+ 'failed criterion, or null if all pass>", "evidence": "<a short verbatim quote '
144
+ 'copied exactly from the response that supports your verdict>"}'
145
+ )
146
+ return [{"role": "system", "content": SYSTEM}, {"role": "user", "content": "\n\n".join(parts)}]
147
+
148
+
149
+ def pairwise_messages(cfg: JudgeConfig, input_text: str, first: str, second: str) -> list[Message]:
150
+ parts = [f"## Input\n{input_text or '(none)'}"]
151
+ if cfg.context:
152
+ parts.append(f"## Reference material (ground truth)\n{cfg.context}")
153
+ parts += [
154
+ f"## Response 1\n<response_1>\n{first}\n</response_1>",
155
+ f"## Response 2\n<response_2>\n{second}\n</response_2>",
156
+ f"## Rubric\n{_rubric_lines(cfg)}",
157
+ "## Reply\nWhich response better satisfies the rubric overall? JSON only: "
158
+ '{"better": "1" | "2" | "tie", "reason": "<one sentence>"}',
159
+ ]
160
+ return [{"role": "system", "content": SYSTEM}, {"role": "user", "content": "\n\n".join(parts)}]
161
+
162
+
163
+ # ------------------------------------------------------------------ parsing
164
+
165
+
166
+ class JudgeReplyError(ValueError):
167
+ """The judge's reply was not the JSON we asked for."""
168
+
169
+
170
+ _FENCE = re.compile(r"```(?:json)?\s*(.*?)```", re.DOTALL)
171
+
172
+
173
+ def _json_object(raw: str) -> dict[str, Any]:
174
+ text = raw.strip()
175
+ fenced = _FENCE.search(text)
176
+ if fenced:
177
+ text = fenced.group(1).strip()
178
+ start, end = text.find("{"), text.rfind("}")
179
+ if start < 0 or end <= start:
180
+ raise JudgeReplyError(f"no JSON object in judge reply: {raw[:120]!r}")
181
+ try:
182
+ data = json.loads(text[start : end + 1])
183
+ except json.JSONDecodeError as exc:
184
+ raise JudgeReplyError(f"judge reply is not valid JSON ({exc.msg})") from exc
185
+ if not isinstance(data, dict):
186
+ raise JudgeReplyError("judge reply is not a JSON object")
187
+ return data
188
+
189
+
190
+ # Curly quotes -> straight, so a quote copied with "smart" punctuation still matches.
191
+ _STRAIGHTEN = str.maketrans({0x2018: "'", 0x2019: "'", 0x201C: '"', 0x201D: '"'})
192
+
193
+
194
+ def _normalise(text: str) -> str:
195
+ return " ".join(text.translate(_STRAIGHTEN).split()).casefold()
196
+
197
+
198
+ @dataclass(frozen=True)
199
+ class JudgeVerdict:
200
+ criteria: dict[str, bool]
201
+ failed_criterion: str | None
202
+ evidence: str
203
+ evidence_found: bool
204
+
205
+ @property
206
+ def score(self) -> float:
207
+ return sum(self.criteria.values()) / len(self.criteria)
208
+
209
+ @property
210
+ def passed(self) -> bool:
211
+ return all(self.criteria.values())
212
+
213
+ def details(self, model: str) -> dict[str, Any]:
214
+ return {
215
+ "judge_model": model,
216
+ "criteria": {k: "pass" if v else "fail" for k, v in self.criteria.items()},
217
+ "failed_criterion": self.failed_criterion,
218
+ "evidence": self.evidence,
219
+ "evidence_found": self.evidence_found,
220
+ }
221
+
222
+
223
+ def parse_verdict(raw: str, cfg: JudgeConfig, output_text: str) -> JudgeVerdict:
224
+ data = _json_object(raw)
225
+ given = data.get("criteria")
226
+ if not isinstance(given, dict):
227
+ raise JudgeReplyError("judge reply has no `criteria` object")
228
+ criteria: dict[str, bool] = {}
229
+ for c in cfg.rubric:
230
+ value = str(given.get(c.name, "")).strip().lower()
231
+ if value not in {"pass", "fail"}:
232
+ raise JudgeReplyError(f"judge gave no pass/fail for criterion {c.name!r}")
233
+ criteria[c.name] = value == "pass"
234
+
235
+ failed = data.get("failed_criterion")
236
+ failed = failed if isinstance(failed, str) and failed in criteria else None
237
+ if failed is None and not all(criteria.values()):
238
+ failed = next(name for name, ok in criteria.items() if not ok)
239
+ if all(criteria.values()):
240
+ failed = None
241
+
242
+ evidence = data.get("evidence")
243
+ evidence = evidence.strip().strip('"') if isinstance(evidence, str) else ""
244
+ found = bool(evidence) and _normalise(evidence) in _normalise(output_text)
245
+ if not output_text.strip():
246
+ found = True # nothing to quote from an empty response
247
+ return JudgeVerdict(criteria, failed, evidence, found)
248
+
249
+
250
+ # ------------------------------------------------------------------ calling
251
+
252
+
253
+ def run_judge(ask: CompleteFn, cfg: JudgeConfig, out: Output, repeat: int = 0) -> JudgeVerdict:
254
+ """Ask the judge once, retrying once on a malformed reply.
255
+
256
+ `repeat` > 0 asks again for a fresh sample instead of the cached answer;
257
+ the variance check uses it.
258
+ """
259
+ model = cfg.judge_model()
260
+ messages = judge_messages(cfg, out)
261
+ last: Exception | None = None
262
+ for attempt in range(2):
263
+ params: dict[str, Any] = {"max_tokens": cfg.max_tokens}
264
+ if repeat or attempt:
265
+ params["_repeat"] = f"{repeat}.{attempt}"
266
+ try:
267
+ reply = ask(model, messages, params)
268
+ except Exception as exc:
269
+ raise GraderRuntimeError(f"judge model call failed: {exc}") from exc
270
+ try:
271
+ return parse_verdict(reply.text, cfg, out.text)
272
+ except JudgeReplyError as exc:
273
+ last = exc
274
+ raise GraderRuntimeError(f"judge reply unusable after a retry: {last}")
275
+
276
+
277
+ Preference = Literal["first", "second", "tie"]
278
+
279
+
280
+ @dataclass(frozen=True)
281
+ class PairVerdict:
282
+ a_first: Preference # verdict with output A shown first
283
+ b_first: Preference # verdict with output B shown first, mapped back to A/B
284
+
285
+ @property
286
+ def consistent(self) -> bool:
287
+ return self.a_first == self.b_first
288
+
289
+ @property
290
+ def winner(self) -> Preference | None:
291
+ """Only a verdict that survives swapping the order counts."""
292
+ return self.a_first if self.consistent else None
293
+
294
+
295
+ def _preference(raw: str) -> Literal["1", "2", "tie"]:
296
+ data = _json_object(raw)
297
+ better = str(data.get("better", "")).strip().lower()
298
+ if better not in {"1", "2", "tie"}:
299
+ raise JudgeReplyError(f"pairwise reply has no usable `better`: {better!r}")
300
+ return better # type: ignore[return-value]
301
+
302
+
303
+ def judge_pair(ask: CompleteFn, cfg: JudgeConfig, input_text: str, a: str, b: str) -> PairVerdict:
304
+ """Compare outputs A and B in both orders. 'first' means A is better."""
305
+ model = cfg.judge_model()
306
+ params: dict[str, Any] = {"max_tokens": cfg.max_tokens}
307
+ try:
308
+ ab = _preference(ask(model, pairwise_messages(cfg, input_text, a, b), params).text)
309
+ ba = _preference(ask(model, pairwise_messages(cfg, input_text, b, a), params).text)
310
+ except JudgeReplyError as exc:
311
+ raise GraderRuntimeError(str(exc)) from exc
312
+ except Exception as exc:
313
+ raise GraderRuntimeError(f"judge model call failed: {exc}") from exc
314
+ to_ab: dict[str, Preference] = {"1": "first", "2": "second", "tie": "tie"}
315
+ swapped: dict[str, Preference] = {"1": "second", "2": "first", "tie": "tie"}
316
+ return PairVerdict(to_ab[ab], swapped[ba])
317
+
318
+
319
+ # ------------------------------------------------------------------ the grader
320
+
321
+
322
+ @dataclass
323
+ class _JudgeGrader:
324
+ cfg: JudgeConfig
325
+ deps: GraderDeps
326
+ calls: list[JudgeVerdict] = field(default_factory=list)
327
+
328
+ def __call__(self, out: Output) -> Grade:
329
+ if self.deps.ask is None:
330
+ raise GraderRuntimeError("judge was built without model access")
331
+ if self.deps.candidate_model:
332
+ try:
333
+ check_not_self_judging(self.cfg, self.deps.candidate_model)
334
+ except GraderConfigError as exc:
335
+ raise GraderRuntimeError(str(exc)) from exc
336
+ v = run_judge(self.deps.ask, self.cfg, out)
337
+ if v.passed:
338
+ reason = "meets every criterion"
339
+ else:
340
+ quote = f' "{v.evidence[:120]}"' if v.evidence else ""
341
+ reason = f"{v.failed_criterion}:{quote}"
342
+ if not v.evidence_found:
343
+ reason += " [evidence not found in output]"
344
+ return Grade(
345
+ score=v.score,
346
+ verdict="pass" if v.passed else "fail",
347
+ reason=reason,
348
+ details=v.details(self.cfg.judge_model()),
349
+ )
350
+
351
+
352
+ @register("judge", uses_model=True)
353
+ def judge(arg: Any, deps: GraderDeps) -> Grader:
354
+ """LLM judge against a rubric. Blinded, evidence-citing, never judges its own model."""
355
+ return _JudgeGrader(parse_config(arg), deps)
diffscore/labeling.py ADDED
@@ -0,0 +1,167 @@
1
+ """Your own pass/fail on outputs: the gold set the judge is measured against.
2
+
3
+ A label belongs to an *output*, not to a run. The same answer to the same case
4
+ reappears in every later run that hits the cache, so labels are matched on
5
+ (case, output text) and one label covers all of those runs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from dataclasses import dataclass
12
+ from typing import Literal
13
+
14
+ from sqlalchemy import select
15
+ from sqlalchemy.orm import Session, selectinload
16
+
17
+ from diffscore.db import Case, HumanLabel, Result, Run
18
+
19
+ LabelVerdict = Literal["pass", "fail"]
20
+
21
+
22
+ class LabelError(ValueError):
23
+ pass
24
+
25
+
26
+ def input_text(case: Case) -> str:
27
+ """The case input as the user wrote it in the suite file."""
28
+ data = case.input
29
+ if set(data) == {"input"} and isinstance(data["input"], str):
30
+ return data["input"]
31
+ return json.dumps(data, ensure_ascii=False, indent=2)
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class LabelItem:
36
+ result_id: int
37
+ case_key: str
38
+ input: str
39
+ output: str
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class LabeledOutput:
44
+ case_id: int
45
+ case_key: str
46
+ output: str
47
+ verdict: LabelVerdict
48
+ model: str # the model that produced the output (for the self-preference check)
49
+
50
+
51
+ def _existing(
52
+ session: Session, suite_id: int, grader: str | None
53
+ ) -> dict[tuple[int, str], HumanLabel]:
54
+ """(case_id, output) -> the newest label for it, from any run of the suite."""
55
+ stmt = (
56
+ select(HumanLabel)
57
+ .join(HumanLabel.result)
58
+ .join(Result.run)
59
+ .where(Run.suite_id == suite_id)
60
+ .options(selectinload(HumanLabel.result))
61
+ .order_by(HumanLabel.id)
62
+ )
63
+ stmt = stmt.where(
64
+ HumanLabel.grader_name.is_(None) if grader is None else HumanLabel.grader_name == grader
65
+ )
66
+ index: dict[tuple[int, str], HumanLabel] = {}
67
+ for label in session.scalars(stmt):
68
+ index[(label.result.case_id, label.result.output or "")] = label
69
+ return index
70
+
71
+
72
+ def label_queue(
73
+ session: Session, run_id: int, grader: str | None, *, relabel: bool = False
74
+ ) -> list[LabelItem]:
75
+ """Outputs of a run still waiting for your verdict, in case order."""
76
+ run = session.scalars(
77
+ select(Run)
78
+ .options(selectinload(Run.results).selectinload(Result.case))
79
+ .where(Run.id == run_id)
80
+ ).first()
81
+ if run is None:
82
+ raise LabelError(f"no run with id {run_id}")
83
+ done = {} if relabel else _existing(session, run.suite_id, grader)
84
+ items = []
85
+ for r in sorted(run.results, key=lambda r: r.id):
86
+ if r.output is None or (r.case_id, r.output) in done:
87
+ continue
88
+ items.append(LabelItem(r.id, r.case.key, input_text(r.case), r.output))
89
+ return items
90
+
91
+
92
+ def save_label(
93
+ session: Session,
94
+ result_id: int,
95
+ grader: str | None,
96
+ verdict: LabelVerdict,
97
+ note: str | None = None,
98
+ ) -> None:
99
+ if verdict not in ("pass", "fail"):
100
+ raise LabelError(f"a label is pass or fail, not {verdict!r}")
101
+ label = session.scalars(
102
+ select(HumanLabel).where(
103
+ HumanLabel.result_id == result_id,
104
+ HumanLabel.grader_name.is_(None)
105
+ if grader is None
106
+ else HumanLabel.grader_name == grader,
107
+ )
108
+ ).first()
109
+ if label is None:
110
+ label = HumanLabel(result_id=result_id, grader_name=grader)
111
+ session.add(label)
112
+ label.verdict = verdict
113
+ label.note = note or None
114
+ session.commit()
115
+
116
+
117
+ def labeled_outputs(session: Session, suite_id: int, grader: str | None) -> list[LabeledOutput]:
118
+ """Every distinct labelled output of the suite, newest label winning."""
119
+ index = _existing(session, suite_id, grader)
120
+ if not index:
121
+ return []
122
+ result_ids = [label.result_id for label in index.values()]
123
+ results = {
124
+ r.id: r
125
+ for r in session.scalars(
126
+ select(Result)
127
+ .options(selectinload(Result.case), selectinload(Result.run))
128
+ .where(Result.id.in_(result_ids))
129
+ )
130
+ }
131
+ out = []
132
+ for (case_id, output), label in sorted(index.items(), key=lambda kv: kv[1].id):
133
+ r = results[label.result_id]
134
+ verdict: LabelVerdict = "pass" if label.verdict == "pass" else "fail"
135
+ out.append(LabeledOutput(case_id, r.case.key, output, verdict, r.run.model))
136
+ return out
137
+
138
+
139
+ def judges_in_run(session: Session, run_id: int) -> list[str]:
140
+ """Display names of the judge graders a run's cases were configured with."""
141
+ from diffscore.suite import GraderSpec
142
+
143
+ names: list[str] = []
144
+ cases = session.scalars(
145
+ select(Case).join(Result, Result.case_id == Case.id).where(Result.run_id == run_id)
146
+ )
147
+ for case in cases:
148
+ for g in case.graders:
149
+ if g.get("name") == "judge":
150
+ name = GraderSpec(name="judge", arg=g.get("arg")).display_name
151
+ if name not in names:
152
+ names.append(name)
153
+ return names
154
+
155
+
156
+ def rubric_lines(session: Session, run_id: int, grader: str) -> list[str]:
157
+ """The rubric a labeller should judge against, so both judge the same thing."""
158
+ from diffscore.suite import GraderSpec
159
+
160
+ case = session.scalars(
161
+ select(Case).join(Result, Result.case_id == Case.id).where(Result.run_id == run_id)
162
+ ).first()
163
+ for g in case.graders if case else []:
164
+ spec = GraderSpec(name=g["name"], arg=g.get("arg"))
165
+ if spec.display_name == grader and isinstance(spec.arg, dict):
166
+ return [f"{c['name']}: {c['description']}" for c in spec.arg.get("rubric", [])]
167
+ return []