margin-referee 0.1.2__tar.gz → 0.1.3__tar.gz
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.
- margin_referee-0.1.3/PKG-INFO +134 -0
- margin_referee-0.1.3/README.md +119 -0
- margin_referee-0.1.3/margin_referee/__init__.py +2 -0
- margin_referee-0.1.3/margin_referee/cases.py +379 -0
- margin_referee-0.1.3/margin_referee/cli.py +211 -0
- margin_referee-0.1.3/margin_referee/experiments.py +181 -0
- margin_referee-0.1.3/margin_referee/hurdle.py +158 -0
- margin_referee-0.1.3/margin_referee/receipt.py +178 -0
- margin_referee-0.1.3/margin_referee/replay.py +290 -0
- margin_referee-0.1.3/margin_referee.egg-info/PKG-INFO +134 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/margin_referee.egg-info/SOURCES.txt +7 -0
- margin_referee-0.1.3/margin_referee.egg-info/requires.txt +6 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/pyproject.toml +4 -2
- margin_referee-0.1.3/tests/test_experiments.py +104 -0
- margin_referee-0.1.3/tests/test_hurdle.py +95 -0
- margin_referee-0.1.3/tests/test_receipt.py +114 -0
- margin_referee-0.1.3/tests/test_receipt_spec.py +36 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/tests/test_referee.py +51 -0
- margin_referee-0.1.2/PKG-INFO +0 -67
- margin_referee-0.1.2/README.md +0 -54
- margin_referee-0.1.2/margin_referee/__init__.py +0 -2
- margin_referee-0.1.2/margin_referee/cases.py +0 -214
- margin_referee-0.1.2/margin_referee/cli.py +0 -87
- margin_referee-0.1.2/margin_referee/replay.py +0 -152
- margin_referee-0.1.2/margin_referee.egg-info/PKG-INFO +0 -67
- margin_referee-0.1.2/margin_referee.egg-info/requires.txt +0 -3
- {margin_referee-0.1.2 → margin_referee-0.1.3}/LICENSE +0 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/margin_referee/endpoints.py +0 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/margin_referee/stats.py +0 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/margin_referee.egg-info/dependency_links.txt +0 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/margin_referee.egg-info/entry_points.txt +0 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/margin_referee.egg-info/top_level.txt +0 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/setup.cfg +0 -0
- {margin_referee-0.1.2 → margin_referee-0.1.3}/tests/test_cases.py +0 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: margin-referee
|
|
3
|
+
Version: 0.1.3
|
|
4
|
+
Summary: Can you ship this AI change? A verdict on a model, prompt, tool or host change from your own eval cases, with a receipt anyone can verify.
|
|
5
|
+
License: MIT
|
|
6
|
+
Keywords: llm,evals,model-selection,agents,promptfoo,langfuse,braintrust
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
12
|
+
Provides-Extra: verify
|
|
13
|
+
Requires-Dist: cryptography>=42; extra == "verify"
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# margin-referee
|
|
17
|
+
|
|
18
|
+
Can you ship this change? Ask your own eval set.
|
|
19
|
+
|
|
20
|
+
`margin-referee` tests a change on the cases you already have (a promptfoo results file, a
|
|
21
|
+
Braintrust, LangSmith or Langfuse dataset export, or JSONL): a new model, a new system prompt, or
|
|
22
|
+
the same model on another endpoint. It runs what you use today and the candidate, grades both with
|
|
23
|
+
each case's own check, and answers promote (ship it), a refusal (don't), or hold (not enough cases
|
|
24
|
+
to tell). What the change does to cost is one line of the answer. No account, no backend, no
|
|
25
|
+
telemetry.
|
|
26
|
+
|
|
27
|
+
Published on PyPI (https://pypi.org/project/margin-referee/) and GitHub
|
|
28
|
+
(https://github.com/trymargin/margin-referee).
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
pip install margin-referee
|
|
32
|
+
margin-referee fit cases.jsonl
|
|
33
|
+
OPENROUTER_API_KEY=... margin-referee replay cases.jsonl \
|
|
34
|
+
--baseline openai/gpt-4.1 --candidate openai/gpt-6-luna --cap 1
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Why another eval tool
|
|
38
|
+
|
|
39
|
+
Because "the candidate scored higher on our evals" is how most bad switches start. Three things
|
|
40
|
+
make it unreliable, and this tool corrects for each:
|
|
41
|
+
|
|
42
|
+
- **Small sets lie.** The verdict is a paired test on the cases both models ran. Only the cases
|
|
43
|
+
they disagree on carry evidence, and a clean sweep on 20 cases proves nothing. `fit` tells you,
|
|
44
|
+
for free and before anything runs, how many cases you need: about 100 against a current model
|
|
45
|
+
that passes everything, and more as its pass rate falls.
|
|
46
|
+
- **The best of several looks better than it is.** Try four models on the same cases and keep the
|
|
47
|
+
winner, and you have mostly found noise. The bar rises with every candidate you try on
|
|
48
|
+
overlapping cases (remembered in `~/.margin-referee/ledger.json`), so renaming or trimming the
|
|
49
|
+
cases does not reset it. To confirm a winner, replay it alone on cases none of them saw.
|
|
50
|
+
- **Half-graded cases flatter the candidate.** A case with a check this tool cannot run (an LLM
|
|
51
|
+
rubric, say) is left out and counted, never half-graded. An answer cut off by the output limit,
|
|
52
|
+
or a call that errored, is unanswered, not a fail, and any unanswered case blocks a promotion.
|
|
53
|
+
|
|
54
|
+
## What `replay` also does
|
|
55
|
+
|
|
56
|
+
- **It stops paying once the answer is clear.** From 40 cases on, the replay stops as soon as the
|
|
57
|
+
answer is already `do_not_ship`: even the reading most favourable to the candidate misses the
|
|
58
|
+
bar. Each look is held to a stricter test (Bonferroni across the planned looks), so looking often
|
|
59
|
+
cannot manufacture a loss. It never stops early for ship; `stopped_early` says when it stopped,
|
|
60
|
+
and `--no-early-stop` runs every case. (Borrowed from VERDICT, `verdict-gate`.)
|
|
61
|
+
- **Reliability, with `--repeats 3`** (1 to 5). Each case runs that many times per side and passes
|
|
62
|
+
only if every run passed (pass^k); the paired test reads that strict result. `reliability` gives
|
|
63
|
+
pass@1 and pass^k per side, the cases that flipped between runs, and an estimate of the repeats
|
|
64
|
+
needed to see a 1-point gap. Spend scales with the repeats.
|
|
65
|
+
- **Traffic weights.** Give a case a `weight` (or `metadata.weight`: its share of traffic, or a
|
|
66
|
+
count) and `weighted` reports the same cases weighted by traffic, including the share of traffic
|
|
67
|
+
on the cases that got worse. It is a weighting of the same cases, not a new test: the decision
|
|
68
|
+
stays on the unweighted paired test.
|
|
69
|
+
|
|
70
|
+
## A second opinion on a comparison you already ran
|
|
71
|
+
|
|
72
|
+
Ran the baseline and a cheaper model as two Braintrust experiments (by hand, or with Loop)?
|
|
73
|
+
`check` reads both, pairs the cases, and gives the same verdict, without calling a model:
|
|
74
|
+
|
|
75
|
+
```
|
|
76
|
+
margin-referee check baseline.jsonl candidate.jsonl --scorer correct
|
|
77
|
+
BRAINTRUST_API_KEY=... margin-referee check bt:<baseline id> bt:<candidate id> --scorer correct
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
A pass is the named score at or above `--threshold` (default 1.0, full credit only). Pass
|
|
81
|
+
`--candidates N` when several models were tried on the same cases. A case one experiment lacks
|
|
82
|
+
blocks the promotion. With no `metrics.estimated_cost` in the exports, it says whether quality
|
|
83
|
+
held but claims no saving. Exit code 0 means promote.
|
|
84
|
+
|
|
85
|
+
## The verdict on a Hurdle suite
|
|
86
|
+
|
|
87
|
+
Ran a [Hurdle](https://github.com/togethercomputer/hurdle) suite with and without a skill, or on
|
|
88
|
+
two models? `hurdle` reads the runs it saved and says whether the difference is real:
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
margin-referee hurdle .hurdle --compare condition --baseline baseline --candidate with-skill
|
|
92
|
+
margin-referee hurdle .hurdle --compare model --baseline <model now> --candidate <model to try>
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
A task passes only if every repeat passed, and `repeats_passed` shows each side's count. A run
|
|
96
|
+
Hurdle marked incomplete or unknown leaves its task unanswered, which blocks a promotion.
|
|
97
|
+
|
|
98
|
+
## A receipt for the verdict
|
|
99
|
+
|
|
100
|
+
`replay`, `check` and `hurdle` take `--receipt out.json`. It writes the verdict as an
|
|
101
|
+
[in-toto Statement](https://github.com/in-toto/attestation) in a DSSE envelope: the decision, the
|
|
102
|
+
bar, the paired counts and gap, how many candidates were tried, cost per case, each segment, and a
|
|
103
|
+
list of what the record does not show. A receipt you write this way is **unsigned** and says
|
|
104
|
+
`assuranceLevel: self-run`. It is your own claim in a format someone else can read.
|
|
105
|
+
|
|
106
|
+
A receipt Margin's hosted service issues is signed with Ed25519. Check one with:
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
pip install 'margin-referee[verify]'
|
|
110
|
+
margin-referee verify receipt.json --key-url https://trymargin.io/.well-known/margin-receipt-key
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Exit 0 means the holder of that key signed it and nobody edited it since. It is a signed record,
|
|
114
|
+
not a certification: it does not show the grader is right, that the cases cover production, or
|
|
115
|
+
what a person decided to ship.
|
|
116
|
+
|
|
117
|
+
## What it runs on
|
|
118
|
+
|
|
119
|
+
- **OpenRouter**, with your own key: any model it serves.
|
|
120
|
+
- **A model in your own account**, with `--candidate-endpoint` or `--baseline-endpoint` and a
|
|
121
|
+
JSON object: `bedrock` (region, model, a Bedrock API key), `vertex_ai` (project, region, model,
|
|
122
|
+
access token), `azure_openai` (resource, deployment, key) or `openai_compatible` (base URL,
|
|
123
|
+
model, key: a fine-tune, vLLM, a self-hosted model). Your credential is used for that run only,
|
|
124
|
+
and you give your own per-token price, so a negotiated discount counts.
|
|
125
|
+
- **A prompt change**: `--candidate-system` replays the candidate with a new system prompt. Each
|
|
126
|
+
prompt you try counts as a candidate.
|
|
127
|
+
|
|
128
|
+
## What it does not do
|
|
129
|
+
|
|
130
|
+
It does not open the pull request, watch the change after you merge it, keep the history across
|
|
131
|
+
your team, or let your agents call it with a spend limit. That is
|
|
132
|
+
[Margin](https://trymargin.io), which runs this same test.
|
|
133
|
+
|
|
134
|
+
MIT licensed.
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# margin-referee
|
|
2
|
+
|
|
3
|
+
Can you ship this change? Ask your own eval set.
|
|
4
|
+
|
|
5
|
+
`margin-referee` tests a change on the cases you already have (a promptfoo results file, a
|
|
6
|
+
Braintrust, LangSmith or Langfuse dataset export, or JSONL): a new model, a new system prompt, or
|
|
7
|
+
the same model on another endpoint. It runs what you use today and the candidate, grades both with
|
|
8
|
+
each case's own check, and answers promote (ship it), a refusal (don't), or hold (not enough cases
|
|
9
|
+
to tell). What the change does to cost is one line of the answer. No account, no backend, no
|
|
10
|
+
telemetry.
|
|
11
|
+
|
|
12
|
+
Published on PyPI (https://pypi.org/project/margin-referee/) and GitHub
|
|
13
|
+
(https://github.com/trymargin/margin-referee).
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
pip install margin-referee
|
|
17
|
+
margin-referee fit cases.jsonl
|
|
18
|
+
OPENROUTER_API_KEY=... margin-referee replay cases.jsonl \
|
|
19
|
+
--baseline openai/gpt-4.1 --candidate openai/gpt-6-luna --cap 1
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Why another eval tool
|
|
23
|
+
|
|
24
|
+
Because "the candidate scored higher on our evals" is how most bad switches start. Three things
|
|
25
|
+
make it unreliable, and this tool corrects for each:
|
|
26
|
+
|
|
27
|
+
- **Small sets lie.** The verdict is a paired test on the cases both models ran. Only the cases
|
|
28
|
+
they disagree on carry evidence, and a clean sweep on 20 cases proves nothing. `fit` tells you,
|
|
29
|
+
for free and before anything runs, how many cases you need: about 100 against a current model
|
|
30
|
+
that passes everything, and more as its pass rate falls.
|
|
31
|
+
- **The best of several looks better than it is.** Try four models on the same cases and keep the
|
|
32
|
+
winner, and you have mostly found noise. The bar rises with every candidate you try on
|
|
33
|
+
overlapping cases (remembered in `~/.margin-referee/ledger.json`), so renaming or trimming the
|
|
34
|
+
cases does not reset it. To confirm a winner, replay it alone on cases none of them saw.
|
|
35
|
+
- **Half-graded cases flatter the candidate.** A case with a check this tool cannot run (an LLM
|
|
36
|
+
rubric, say) is left out and counted, never half-graded. An answer cut off by the output limit,
|
|
37
|
+
or a call that errored, is unanswered, not a fail, and any unanswered case blocks a promotion.
|
|
38
|
+
|
|
39
|
+
## What `replay` also does
|
|
40
|
+
|
|
41
|
+
- **It stops paying once the answer is clear.** From 40 cases on, the replay stops as soon as the
|
|
42
|
+
answer is already `do_not_ship`: even the reading most favourable to the candidate misses the
|
|
43
|
+
bar. Each look is held to a stricter test (Bonferroni across the planned looks), so looking often
|
|
44
|
+
cannot manufacture a loss. It never stops early for ship; `stopped_early` says when it stopped,
|
|
45
|
+
and `--no-early-stop` runs every case. (Borrowed from VERDICT, `verdict-gate`.)
|
|
46
|
+
- **Reliability, with `--repeats 3`** (1 to 5). Each case runs that many times per side and passes
|
|
47
|
+
only if every run passed (pass^k); the paired test reads that strict result. `reliability` gives
|
|
48
|
+
pass@1 and pass^k per side, the cases that flipped between runs, and an estimate of the repeats
|
|
49
|
+
needed to see a 1-point gap. Spend scales with the repeats.
|
|
50
|
+
- **Traffic weights.** Give a case a `weight` (or `metadata.weight`: its share of traffic, or a
|
|
51
|
+
count) and `weighted` reports the same cases weighted by traffic, including the share of traffic
|
|
52
|
+
on the cases that got worse. It is a weighting of the same cases, not a new test: the decision
|
|
53
|
+
stays on the unweighted paired test.
|
|
54
|
+
|
|
55
|
+
## A second opinion on a comparison you already ran
|
|
56
|
+
|
|
57
|
+
Ran the baseline and a cheaper model as two Braintrust experiments (by hand, or with Loop)?
|
|
58
|
+
`check` reads both, pairs the cases, and gives the same verdict, without calling a model:
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
margin-referee check baseline.jsonl candidate.jsonl --scorer correct
|
|
62
|
+
BRAINTRUST_API_KEY=... margin-referee check bt:<baseline id> bt:<candidate id> --scorer correct
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
A pass is the named score at or above `--threshold` (default 1.0, full credit only). Pass
|
|
66
|
+
`--candidates N` when several models were tried on the same cases. A case one experiment lacks
|
|
67
|
+
blocks the promotion. With no `metrics.estimated_cost` in the exports, it says whether quality
|
|
68
|
+
held but claims no saving. Exit code 0 means promote.
|
|
69
|
+
|
|
70
|
+
## The verdict on a Hurdle suite
|
|
71
|
+
|
|
72
|
+
Ran a [Hurdle](https://github.com/togethercomputer/hurdle) suite with and without a skill, or on
|
|
73
|
+
two models? `hurdle` reads the runs it saved and says whether the difference is real:
|
|
74
|
+
|
|
75
|
+
```
|
|
76
|
+
margin-referee hurdle .hurdle --compare condition --baseline baseline --candidate with-skill
|
|
77
|
+
margin-referee hurdle .hurdle --compare model --baseline <model now> --candidate <model to try>
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
A task passes only if every repeat passed, and `repeats_passed` shows each side's count. A run
|
|
81
|
+
Hurdle marked incomplete or unknown leaves its task unanswered, which blocks a promotion.
|
|
82
|
+
|
|
83
|
+
## A receipt for the verdict
|
|
84
|
+
|
|
85
|
+
`replay`, `check` and `hurdle` take `--receipt out.json`. It writes the verdict as an
|
|
86
|
+
[in-toto Statement](https://github.com/in-toto/attestation) in a DSSE envelope: the decision, the
|
|
87
|
+
bar, the paired counts and gap, how many candidates were tried, cost per case, each segment, and a
|
|
88
|
+
list of what the record does not show. A receipt you write this way is **unsigned** and says
|
|
89
|
+
`assuranceLevel: self-run`. It is your own claim in a format someone else can read.
|
|
90
|
+
|
|
91
|
+
A receipt Margin's hosted service issues is signed with Ed25519. Check one with:
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
pip install 'margin-referee[verify]'
|
|
95
|
+
margin-referee verify receipt.json --key-url https://trymargin.io/.well-known/margin-receipt-key
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Exit 0 means the holder of that key signed it and nobody edited it since. It is a signed record,
|
|
99
|
+
not a certification: it does not show the grader is right, that the cases cover production, or
|
|
100
|
+
what a person decided to ship.
|
|
101
|
+
|
|
102
|
+
## What it runs on
|
|
103
|
+
|
|
104
|
+
- **OpenRouter**, with your own key: any model it serves.
|
|
105
|
+
- **A model in your own account**, with `--candidate-endpoint` or `--baseline-endpoint` and a
|
|
106
|
+
JSON object: `bedrock` (region, model, a Bedrock API key), `vertex_ai` (project, region, model,
|
|
107
|
+
access token), `azure_openai` (resource, deployment, key) or `openai_compatible` (base URL,
|
|
108
|
+
model, key: a fine-tune, vLLM, a self-hosted model). Your credential is used for that run only,
|
|
109
|
+
and you give your own per-token price, so a negotiated discount counts.
|
|
110
|
+
- **A prompt change**: `--candidate-system` replays the candidate with a new system prompt. Each
|
|
111
|
+
prompt you try counts as a candidate.
|
|
112
|
+
|
|
113
|
+
## What it does not do
|
|
114
|
+
|
|
115
|
+
It does not open the pull request, watch the change after you merge it, keep the history across
|
|
116
|
+
your team, or let your agents call it with a spend limit. That is
|
|
117
|
+
[Margin](https://trymargin.io), which runs this same test.
|
|
118
|
+
|
|
119
|
+
MIT licensed.
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""Read an eval export into cases, and grade an answer with the case's own checks.
|
|
2
|
+
|
|
3
|
+
Copied verbatim from Margin's hosted product (src/margin/dataset_replay.py); a test in the
|
|
4
|
+
product repo fails if the two ever differ.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass, field, replace
|
|
12
|
+
from typing import Iterable, Optional
|
|
13
|
+
|
|
14
|
+
#: A free-text expected answer longer than this is a judgement, not a label: never compared exactly.
|
|
15
|
+
LABEL_MAX_CHARS = 80
|
|
16
|
+
CHECKS = ("equals", "icontains", "contains", "regex", "is-json", "json-field", "json-match")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Case:
|
|
21
|
+
id: str
|
|
22
|
+
messages: list
|
|
23
|
+
check: str
|
|
24
|
+
value: str = ""
|
|
25
|
+
#: The production call's structured-output request, replayed as it was (OpenAI shape).
|
|
26
|
+
response_format: Optional[dict] = None
|
|
27
|
+
#: The production call's own output limit, when the export carries one.
|
|
28
|
+
max_tokens: Optional[int] = None
|
|
29
|
+
#: Further ``(check, value)`` pairs the case must also pass (a promptfoo case's other asserts).
|
|
30
|
+
also: tuple = ()
|
|
31
|
+
#: The slice of traffic the case belongs to (``segment``, or ``metadata.segment`` /
|
|
32
|
+
#: ``metadata.category``), so a change that ties overall but loses one slice is caught.
|
|
33
|
+
segment: str = ""
|
|
34
|
+
#: The case's share of real traffic (a share or a count; ``weight`` or ``metadata.weight``).
|
|
35
|
+
#: It weights the report only: the decision stays on the unweighted paired test.
|
|
36
|
+
weight: Optional[float] = None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Parsed:
|
|
41
|
+
cases: list = field(default_factory=list)
|
|
42
|
+
#: ``(case id, why it cannot be graded here)`` for every case left out.
|
|
43
|
+
ungraded: list = field(default_factory=list)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _messages(x) -> Optional[list]:
|
|
47
|
+
"""The OpenAI chat messages a dataset row means, or None when it names none."""
|
|
48
|
+
if isinstance(x, list) and x and all(isinstance(m, dict) and "role" in m for m in x):
|
|
49
|
+
return x
|
|
50
|
+
if isinstance(x, str) and x.strip():
|
|
51
|
+
try:
|
|
52
|
+
return _messages(json.loads(x))
|
|
53
|
+
except ValueError:
|
|
54
|
+
return [{"role": "user", "content": x}]
|
|
55
|
+
if isinstance(x, dict):
|
|
56
|
+
for k in ("messages", "input", "question", "prompt", "query"):
|
|
57
|
+
if k in x and (m := _messages(x[k])) is not None:
|
|
58
|
+
return m
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _label(expected) -> Optional[str]:
|
|
63
|
+
"""A dataset's expected answer, when it is short enough to be a label rather than prose."""
|
|
64
|
+
if isinstance(expected, dict):
|
|
65
|
+
vals = [v for v in expected.values() if isinstance(v, (str, int, float, bool))]
|
|
66
|
+
expected = vals[0] if len(vals) == 1 else None
|
|
67
|
+
if isinstance(expected, (int, float, bool)):
|
|
68
|
+
expected = str(expected)
|
|
69
|
+
if isinstance(expected, str) and 0 < len(expected.strip()) <= LABEL_MAX_CHARS:
|
|
70
|
+
return expected.strip()
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _segment(row) -> str:
|
|
75
|
+
"""The case's segment label, from the row or its metadata; empty when it has none."""
|
|
76
|
+
if not isinstance(row, dict):
|
|
77
|
+
return ""
|
|
78
|
+
meta = row.get("metadata") if isinstance(row.get("metadata"), dict) else {}
|
|
79
|
+
for v in (row.get("segment"), meta.get("segment"), meta.get("category")):
|
|
80
|
+
if isinstance(v, (str, int)) and str(v).strip():
|
|
81
|
+
return str(v).strip()[:64]
|
|
82
|
+
return ""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _weight(row) -> Optional[float]:
|
|
86
|
+
"""The case's traffic weight, from the row or its metadata; None when it has none or it is
|
|
87
|
+
not a positive, finite number (a weight is never guessed)."""
|
|
88
|
+
if not isinstance(row, dict):
|
|
89
|
+
return None
|
|
90
|
+
meta = row.get("metadata") if isinstance(row.get("metadata"), dict) else {}
|
|
91
|
+
for v in (row.get("weight"), meta.get("weight")):
|
|
92
|
+
if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 < v < float("inf"):
|
|
93
|
+
return float(v)
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _row(i: int, row: dict, out: Parsed) -> None:
|
|
98
|
+
cid = str(row.get("id") or row.get("case_id") or f"case-{i}")
|
|
99
|
+
msgs = _messages(row.get("messages") or row.get("input") or row.get("inputs"))
|
|
100
|
+
if msgs is None:
|
|
101
|
+
out.ungraded.append((cid, "no input messages"))
|
|
102
|
+
return
|
|
103
|
+
check = row.get("check")
|
|
104
|
+
if check is not None:
|
|
105
|
+
if check not in CHECKS:
|
|
106
|
+
out.ungraded.append((cid, f"check {check!r} is not deterministic"))
|
|
107
|
+
return
|
|
108
|
+
if check == "regex" and _bad_regex(str(row.get("expected", row.get("value", "")))):
|
|
109
|
+
out.ungraded.append((cid, "its regex does not compile"))
|
|
110
|
+
return
|
|
111
|
+
out.cases.append(Case(cid, msgs, check, str(row.get("expected", row.get("value", ""))),
|
|
112
|
+
row.get("response_format"), row.get("max_tokens"),
|
|
113
|
+
segment=_segment(row), weight=_weight(row)))
|
|
114
|
+
return
|
|
115
|
+
keys = ("expected", "expectedOutput", "expected_output", "outputs", "output")
|
|
116
|
+
expected = next((row[k] for k in keys if row.get(k) is not None), None)
|
|
117
|
+
if isinstance(expected, dict) and len(expected) > 1 and all(
|
|
118
|
+
isinstance(v, (str, int, float, bool)) for v in expected.values()):
|
|
119
|
+
# MAR-2313: a structured answer (several fields) is graded on every field, not left out
|
|
120
|
+
out.cases.append(Case(cid, msgs, "json-match", json.dumps(expected),
|
|
121
|
+
row.get("response_format"), row.get("max_tokens"),
|
|
122
|
+
segment=_segment(row), weight=_weight(row)))
|
|
123
|
+
return
|
|
124
|
+
label = _label(expected)
|
|
125
|
+
if label is None:
|
|
126
|
+
out.ungraded.append((cid, "expected answer is free text, which needs a judge"))
|
|
127
|
+
return
|
|
128
|
+
out.cases.append(Case(cid, msgs, "equals", label, segment=_segment(row), weight=_weight(row)))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _promptfoo(doc: dict, out: Parsed) -> None:
|
|
132
|
+
rows = (doc.get("results") or {}).get("results") or []
|
|
133
|
+
for i, r in enumerate(rows):
|
|
134
|
+
cid = str((r.get("testCase") or {}).get("description") or r.get("id") or f"case-{i}")
|
|
135
|
+
msgs = _messages((r.get("prompt") or {}).get("raw"))
|
|
136
|
+
every = (r.get("testCase") or {}).get("assert") or []
|
|
137
|
+
asserts = [a for a in every if a.get("type") in CHECKS]
|
|
138
|
+
judged = sorted({str(a.get("type")) for a in every if a.get("type") not in CHECKS})
|
|
139
|
+
if msgs is None:
|
|
140
|
+
out.ungraded.append((cid, "no rendered prompt"))
|
|
141
|
+
elif judged and asserts:
|
|
142
|
+
# MAR-2313: grading only the deterministic half would pass answers the suite fails
|
|
143
|
+
out.ungraded.append((cid, f"it also asserts {', '.join(judged)}, which this replay "
|
|
144
|
+
"cannot grade, so passing the rest would not be a pass"))
|
|
145
|
+
elif not asserts:
|
|
146
|
+
out.ungraded.append((cid, "no deterministic assertion (equals, contains, regex...)"))
|
|
147
|
+
elif any(a["type"] == "regex" and _bad_regex(str(a.get("value", ""))) for a in asserts):
|
|
148
|
+
out.ungraded.append((cid, "its regex does not compile"))
|
|
149
|
+
else:
|
|
150
|
+
a, rest = asserts[0], asserts[1:]
|
|
151
|
+
tc = r.get("testCase") or {}
|
|
152
|
+
out.cases.append(Case(cid, msgs, a["type"], str(a.get("value", "")),
|
|
153
|
+
also=tuple((b["type"], str(b.get("value", ""))) for b in rest),
|
|
154
|
+
segment=_segment({**(tc.get("vars") or {}),
|
|
155
|
+
"metadata": tc.get("metadata")}),
|
|
156
|
+
# only metadata: a prompt variable named weight is not traffic
|
|
157
|
+
weight=_weight({"metadata": tc.get("metadata")})))
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _bad_regex(pattern: str) -> bool:
|
|
161
|
+
try:
|
|
162
|
+
re.compile(pattern)
|
|
163
|
+
return False
|
|
164
|
+
except re.error:
|
|
165
|
+
return True
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def parse(text: str) -> Parsed:
|
|
169
|
+
"""Cases from a promptfoo results file, a JSON array, or JSONL (Braintrust, LangSmith, ours)."""
|
|
170
|
+
out = Parsed()
|
|
171
|
+
text = text.strip()
|
|
172
|
+
try:
|
|
173
|
+
doc = json.loads(text)
|
|
174
|
+
except ValueError:
|
|
175
|
+
doc = None
|
|
176
|
+
if isinstance(doc, dict) and "results" in doc:
|
|
177
|
+
_promptfoo(doc, out)
|
|
178
|
+
return _unique_ids(out)
|
|
179
|
+
rows: Iterable = doc if isinstance(doc, list) else (
|
|
180
|
+
[doc] if isinstance(doc, dict) else _lines(text))
|
|
181
|
+
for i, row in enumerate(rows):
|
|
182
|
+
if isinstance(row, dict):
|
|
183
|
+
_row(i, row, out)
|
|
184
|
+
else:
|
|
185
|
+
out.ungraded.append((f"case-{i}", "not a JSON object"))
|
|
186
|
+
return _unique_ids(out)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _unique_ids(out: Parsed) -> Parsed:
|
|
190
|
+
"""Cases pair by id, so a repeated id (a promptfoo description used twice, say) would pair
|
|
191
|
+
one case's answers with another's. Repeats get ``#2``, ``#3``; the first keeps its name."""
|
|
192
|
+
taken, cases = {c.id for c in out.cases}, []
|
|
193
|
+
used: set[str] = set()
|
|
194
|
+
for c in out.cases:
|
|
195
|
+
name, n = c.id, 1
|
|
196
|
+
# a rename never takes a name already used, or one a later case carries as its own
|
|
197
|
+
while name in used or (name != c.id and name in taken):
|
|
198
|
+
n += 1
|
|
199
|
+
name = f"{c.id}#{n}"
|
|
200
|
+
used.add(name)
|
|
201
|
+
cases.append(c if name == c.id else replace(c, id=name))
|
|
202
|
+
out.cases = cases
|
|
203
|
+
return out
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _lines(text: str):
|
|
207
|
+
for line in text.splitlines():
|
|
208
|
+
if line.strip():
|
|
209
|
+
try:
|
|
210
|
+
yield json.loads(line)
|
|
211
|
+
except ValueError:
|
|
212
|
+
yield None
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def grade(output: str, case: Case) -> bool:
|
|
216
|
+
"""Pass only when the answer passes the case's check and every one in ``also``."""
|
|
217
|
+
return all(_check(output, c, v) for c, v in ((case.check, case.value), *case.also))
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _check(output: str, check: str, want: str) -> bool:
|
|
221
|
+
out = (output or "").strip()
|
|
222
|
+
if check == "equals":
|
|
223
|
+
return out.lower().strip(" .\"'") == want.lower().strip(" .\"'")
|
|
224
|
+
if check == "contains":
|
|
225
|
+
return want in out
|
|
226
|
+
if check == "icontains":
|
|
227
|
+
return want.lower() in out.lower()
|
|
228
|
+
if check == "regex":
|
|
229
|
+
return re.search(want, out) is not None
|
|
230
|
+
if check == "json-field": # value is "field=expected": one field of a JSON answer
|
|
231
|
+
name, _, want = want.partition("=")
|
|
232
|
+
try:
|
|
233
|
+
got = json.loads(out).get(name)
|
|
234
|
+
except (ValueError, AttributeError):
|
|
235
|
+
return False
|
|
236
|
+
return str(got).strip().lower() == want.strip().lower()
|
|
237
|
+
if check == "is-json":
|
|
238
|
+
try:
|
|
239
|
+
json.loads(out)
|
|
240
|
+
return True
|
|
241
|
+
except ValueError:
|
|
242
|
+
return False
|
|
243
|
+
if check == "json-match": # value is a JSON object: every field must match
|
|
244
|
+
try:
|
|
245
|
+
got, wanted = json.loads(out), json.loads(want)
|
|
246
|
+
return all(str(got.get(k)).strip().lower() == str(v).strip().lower()
|
|
247
|
+
for k, v in wanted.items())
|
|
248
|
+
except (ValueError, AttributeError):
|
|
249
|
+
return False
|
|
250
|
+
raise ValueError(check)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
#: Early stopping looks only once this many cases have an answer from both sides.
|
|
254
|
+
MIN_EARLY_STOP_CASES = 40
|
|
255
|
+
#: One-sided 95%, the confidence the ``runs_needed`` estimate is stated at.
|
|
256
|
+
RUNS_NEEDED_Z = 1.645
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def planned_looks(total: int, batch: int) -> int:
|
|
260
|
+
"""How many times a replay of ``total`` cases, run ``batch`` at a time, may look at its
|
|
261
|
+
own result: the family the early-stop test is corrected for."""
|
|
262
|
+
return max(1, math.ceil(total / max(1, batch)))
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def stop_early(pairs: list, total: int, looks: int, bound, candidates: int = 1,
|
|
266
|
+
unanswered: int = 0) -> Optional[dict]:
|
|
267
|
+
"""Stop spending when the answer is already ``do_not_ship``: even the bound most favourable
|
|
268
|
+
to the candidate misses the bar on the cases so far (borrowed from VERDICT, ``verdict-gate``).
|
|
269
|
+
|
|
270
|
+
``bound(ps, family)`` is the paired test at a z corrected for ``family`` looks; the family is
|
|
271
|
+
every planned look times every candidate tried (Bonferroni), so looking often cannot
|
|
272
|
+
manufacture a loss. ⛔ It never stops for ship: a pass needs every case. It also never stops
|
|
273
|
+
with a case unanswered, because that case may be one the candidate would have passed."""
|
|
274
|
+
n = len(pairs)
|
|
275
|
+
if n < MIN_EARLY_STOP_CASES or n >= total or unanswered:
|
|
276
|
+
return None
|
|
277
|
+
pb = bound([(b, c) for _, b, c in pairs], max(1, candidates) * max(1, looks))
|
|
278
|
+
if pb is None or (2 * pb.shortfall - pb.upper) <= pb.margin:
|
|
279
|
+
return None
|
|
280
|
+
return {"after_cases": n, "of_cases": total, "looks": looks,
|
|
281
|
+
"reason": f"after {n} of {total} cases even the reading most favourable to the "
|
|
282
|
+
"candidate was past what the bar allows"}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def runs_needed(flip_baseline: float, flip_candidate: float, cases: int,
|
|
286
|
+
gap: float = 0.01, z: float = RUNS_NEEDED_Z) -> dict:
|
|
287
|
+
"""An ESTIMATE of how many repeats per case would show a ``gap`` (1 point) between the two
|
|
288
|
+
pass rates through run-to-run noise alone.
|
|
289
|
+
|
|
290
|
+
A flip rate ``q`` (two runs of one case disagree) means a per-run variance of ``q / 2`` for
|
|
291
|
+
that case. The gap between the two sides' mean pass rates over ``cases`` cases and ``r``
|
|
292
|
+
repeats then has a run-noise standard error of ``sqrt((q_b + q_c) / 2 / (cases * r))``;
|
|
293
|
+
``r`` is the smallest count that puts ``z`` of those inside ``gap``:
|
|
294
|
+
|
|
295
|
+
r = ceil(z^2 * (q_b + q_c) / 2 / (cases * gap^2))
|
|
296
|
+
|
|
297
|
+
It covers run-to-run noise only, not which cases were sampled, so it is a floor."""
|
|
298
|
+
r = z * z * (flip_baseline + flip_candidate) / 2 / (max(1, cases) * gap * gap)
|
|
299
|
+
return {"repeats": max(1, math.ceil(r)), "for_gap_points": round(100 * gap, 2),
|
|
300
|
+
"estimate": True,
|
|
301
|
+
"note": "an estimate from the measured flip rates: repeats per case needed for "
|
|
302
|
+
"run-to-run noise alone to be smaller than the gap; it does not cover which "
|
|
303
|
+
"cases were sampled"}
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def reliability_terms(runs: dict, k: int) -> Optional[dict]:
|
|
307
|
+
"""With ``k`` repeats: per side ``pass_at_1`` (the mean over every run) and ``pass_pow_k``
|
|
308
|
+
(the share of cases that passed ALL k runs, the rule the verdict is judged on), and the cases
|
|
309
|
+
whose result flipped between repeats. ``runs`` is ``{case id: {side: [scores]}}``. None with
|
|
310
|
+
one run: one run cannot show a flip."""
|
|
311
|
+
if k < 2 or not runs:
|
|
312
|
+
return None
|
|
313
|
+
out: dict = {"repeats": k, "rule": f"a case passes only if all {k} runs passed (pass^{k}); "
|
|
314
|
+
"the paired test uses that strict result"}
|
|
315
|
+
rate = {}
|
|
316
|
+
for side in ("baseline", "candidate"):
|
|
317
|
+
per = {cid: [float(x) for x in r[side]] for cid, r in runs.items()}
|
|
318
|
+
flipped = sorted(c for c, s in per.items() if 0 < sum(s) < len(s))
|
|
319
|
+
# the share of repeat pairs of one case that disagree, averaged over cases
|
|
320
|
+
rate[side] = sum(sum(s) * (len(s) - sum(s)) / (len(s) * (len(s) - 1) / 2)
|
|
321
|
+
for s in per.values() if len(s) > 1) / len(per)
|
|
322
|
+
out[side] = {"pass_at_1": round(sum(sum(s) / len(s) for s in per.values()) / len(per), 4),
|
|
323
|
+
"pass_pow_k": round(sum(1 for s in per.values() if min(s) >= 1) / len(per),
|
|
324
|
+
4),
|
|
325
|
+
"flipped": len(flipped), "flipped_cases": flipped[:10],
|
|
326
|
+
"flip_rate": round(rate[side], 4)}
|
|
327
|
+
out["runs_needed"] = runs_needed(rate["baseline"], rate["candidate"], len(runs))
|
|
328
|
+
return out
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def weighted_terms(pairs: list, weight_of: dict) -> Optional[dict]:
|
|
332
|
+
"""The same paired cases, weighted by the traffic each carries: the weighted pass rate on
|
|
333
|
+
each side and the share of traffic on cases that got worse. ⛔ A weighting of the same cases,
|
|
334
|
+
not a new test: the decision stays on the unweighted paired test. None when no case has a
|
|
335
|
+
weight; a case without one is left out of the weighting and counted."""
|
|
336
|
+
ws = [(weight_of[cid], b, c) for cid, b, c in pairs if weight_of.get(cid)]
|
|
337
|
+
total = sum(w for w, _, _ in ws)
|
|
338
|
+
if not ws or total <= 0:
|
|
339
|
+
return None
|
|
340
|
+
worse = sum(w for w, b, c in ws if b > c) / total
|
|
341
|
+
return {"cases": len(ws), "unweighted_cases": len(pairs) - len(ws),
|
|
342
|
+
"baseline_pass_rate": round(sum(w * b for w, b, _ in ws) / total, 4),
|
|
343
|
+
"candidate_pass_rate": round(sum(w * c for w, _, c in ws) / total, 4),
|
|
344
|
+
"worse_traffic_share": round(worse, 4),
|
|
345
|
+
"better_traffic_share": round(sum(w for w, b, c in ws if c > b) / total, 4),
|
|
346
|
+
"summary": (f"the change breaks cases covering {worse:.1%} of your traffic" if worse
|
|
347
|
+
else "no weighted case got worse"),
|
|
348
|
+
"note": "the same cases weighted by the traffic share you gave each one, not a new "
|
|
349
|
+
"test: the decision is made on the unweighted paired test"}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def apply_extras(v: dict, early: Optional[dict], k: int, reliability: Optional[dict],
|
|
353
|
+
weighted: Optional[dict]) -> dict:
|
|
354
|
+
"""Put the early stop, the reliability block and the traffic weighting on a verdict.
|
|
355
|
+
|
|
356
|
+
⛔ A replay stopped early is a deliberate stop on ``do_not_ship`` and nothing else: if the
|
|
357
|
+
verdict it reaches is anything else (more candidates were tried than the stop was corrected
|
|
358
|
+
for), it is ``not_enough_evidence``. It never ships and never promotes."""
|
|
359
|
+
v.update(stopped_early=early, reliability=reliability, weighted=weighted)
|
|
360
|
+
if early:
|
|
361
|
+
left = early["of_cases"] - early["after_cases"]
|
|
362
|
+
v["promoted"] = False
|
|
363
|
+
if v["decision"] != "do_not_ship":
|
|
364
|
+
v["decision"], v["quality"] = "not_enough_evidence", "unclear"
|
|
365
|
+
v["why"] = (f"the replay stopped early after {early['after_cases']} of "
|
|
366
|
+
f"{early['of_cases']} cases, but with {k} models tried on these cases "
|
|
367
|
+
"that stop is not proven; run it again with early stopping off")
|
|
368
|
+
elif v["quality"] == "worse":
|
|
369
|
+
v["why"] = (f"stopped after {early['after_cases']} of {early['of_cases']} cases: even "
|
|
370
|
+
"the reading most favourable to the candidate is past what the bar "
|
|
371
|
+
f"allows, so the remaining {left} cases were not run because the answer "
|
|
372
|
+
"was already clear")
|
|
373
|
+
else: # a loss proven in one segment (``apply_segments``): its reason stands
|
|
374
|
+
v["why"] += (f"; the replay stopped early after {early['after_cases']} of "
|
|
375
|
+
f"{early['of_cases']} cases")
|
|
376
|
+
if weighted and weighted["worse_traffic_share"] > 0:
|
|
377
|
+
v["why"] += (f"; {weighted['summary']} (a weighting of the same cases; the decision is "
|
|
378
|
+
"on the unweighted paired test)")
|
|
379
|
+
return v
|