margin-referee 0.1.0__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.0/LICENSE +21 -0
- margin_referee-0.1.0/PKG-INFO +64 -0
- margin_referee-0.1.0/README.md +51 -0
- margin_referee-0.1.0/margin_referee/__init__.py +2 -0
- margin_referee-0.1.0/margin_referee/cases.py +196 -0
- margin_referee-0.1.0/margin_referee/cli.py +87 -0
- margin_referee-0.1.0/margin_referee/endpoints.py +198 -0
- margin_referee-0.1.0/margin_referee/replay.py +147 -0
- margin_referee-0.1.0/margin_referee/stats.py +119 -0
- margin_referee-0.1.0/margin_referee.egg-info/PKG-INFO +64 -0
- margin_referee-0.1.0/margin_referee.egg-info/SOURCES.txt +16 -0
- margin_referee-0.1.0/margin_referee.egg-info/dependency_links.txt +1 -0
- margin_referee-0.1.0/margin_referee.egg-info/entry_points.txt +2 -0
- margin_referee-0.1.0/margin_referee.egg-info/requires.txt +3 -0
- margin_referee-0.1.0/margin_referee.egg-info/top_level.txt +1 -0
- margin_referee-0.1.0/pyproject.toml +23 -0
- margin_referee-0.1.0/setup.cfg +4 -0
- margin_referee-0.1.0/tests/test_referee.py +73 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Margin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: margin-referee
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Should you switch models? Replay your own eval set on a candidate and get a verdict that holds up.
|
|
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
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# margin-referee
|
|
15
|
+
|
|
16
|
+
Should you switch models? Ask your own eval set.
|
|
17
|
+
|
|
18
|
+
`margin-referee` replays the cases you already have (a promptfoo results file, a Braintrust,
|
|
19
|
+
LangSmith or Langfuse dataset export, or JSONL) on the model you run today and on a candidate,
|
|
20
|
+
grades both with each case's own check, and tells you whether the candidate holds up and costs
|
|
21
|
+
less. No account, no backend, no telemetry.
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
pip install margin-referee
|
|
25
|
+
margin-referee fit cases.jsonl
|
|
26
|
+
OPENROUTER_API_KEY=... margin-referee replay cases.jsonl \
|
|
27
|
+
--baseline openai/gpt-4.1 --candidate openai/gpt-6-luna --cap 1
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Why another eval tool
|
|
31
|
+
|
|
32
|
+
Because "the candidate scored higher on our evals" is how most bad switches start. Three things
|
|
33
|
+
make it unreliable, and this tool corrects for each:
|
|
34
|
+
|
|
35
|
+
- **Small sets lie.** The verdict is a paired test on the cases both models ran. Only the cases
|
|
36
|
+
they disagree on carry evidence, and a clean sweep on 20 cases proves nothing. `fit` tells you,
|
|
37
|
+
for free and before anything runs, how many cases you need: about 100 against a current model
|
|
38
|
+
that passes everything, and more as its pass rate falls.
|
|
39
|
+
- **The best of several looks better than it is.** Try four models on the same cases and keep the
|
|
40
|
+
winner, and you have mostly found noise. The bar rises with every candidate you try on
|
|
41
|
+
overlapping cases (remembered in `~/.margin-referee/ledger.json`), so renaming or trimming the
|
|
42
|
+
cases does not reset it. To confirm a winner, replay it alone on cases none of them saw.
|
|
43
|
+
- **Half-graded cases flatter the candidate.** A case with a check this tool cannot run (an LLM
|
|
44
|
+
rubric, say) is left out and counted, never half-graded. An answer cut off by the output limit,
|
|
45
|
+
or a call that errored, is unanswered, not a fail, and any unanswered case blocks a promotion.
|
|
46
|
+
|
|
47
|
+
## What it runs on
|
|
48
|
+
|
|
49
|
+
- **OpenRouter**, with your own key: any model it serves.
|
|
50
|
+
- **A model in your own account**, with `--candidate-endpoint` or `--baseline-endpoint` and a
|
|
51
|
+
JSON object: `bedrock` (region, model, a Bedrock API key), `vertex_ai` (project, region, model,
|
|
52
|
+
access token), `azure_openai` (resource, deployment, key) or `openai_compatible` (base URL,
|
|
53
|
+
model, key: a fine-tune, vLLM, a self-hosted model). Your credential is used for that run only,
|
|
54
|
+
and you give your own per-token price, so a negotiated discount counts.
|
|
55
|
+
- **A prompt change**: `--candidate-system` replays the candidate with a new system prompt. Each
|
|
56
|
+
prompt you try counts as a candidate.
|
|
57
|
+
|
|
58
|
+
## What it does not do
|
|
59
|
+
|
|
60
|
+
It does not open the pull request, watch the change after you merge it, keep the history across
|
|
61
|
+
your team, or let your agents call it with a spend limit. That is
|
|
62
|
+
[Margin](https://trymargin.io), which runs this same test.
|
|
63
|
+
|
|
64
|
+
MIT licensed.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# margin-referee
|
|
2
|
+
|
|
3
|
+
Should you switch models? Ask your own eval set.
|
|
4
|
+
|
|
5
|
+
`margin-referee` replays the cases you already have (a promptfoo results file, a Braintrust,
|
|
6
|
+
LangSmith or Langfuse dataset export, or JSONL) on the model you run today and on a candidate,
|
|
7
|
+
grades both with each case's own check, and tells you whether the candidate holds up and costs
|
|
8
|
+
less. No account, no backend, no telemetry.
|
|
9
|
+
|
|
10
|
+
```
|
|
11
|
+
pip install margin-referee
|
|
12
|
+
margin-referee fit cases.jsonl
|
|
13
|
+
OPENROUTER_API_KEY=... margin-referee replay cases.jsonl \
|
|
14
|
+
--baseline openai/gpt-4.1 --candidate openai/gpt-6-luna --cap 1
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Why another eval tool
|
|
18
|
+
|
|
19
|
+
Because "the candidate scored higher on our evals" is how most bad switches start. Three things
|
|
20
|
+
make it unreliable, and this tool corrects for each:
|
|
21
|
+
|
|
22
|
+
- **Small sets lie.** The verdict is a paired test on the cases both models ran. Only the cases
|
|
23
|
+
they disagree on carry evidence, and a clean sweep on 20 cases proves nothing. `fit` tells you,
|
|
24
|
+
for free and before anything runs, how many cases you need: about 100 against a current model
|
|
25
|
+
that passes everything, and more as its pass rate falls.
|
|
26
|
+
- **The best of several looks better than it is.** Try four models on the same cases and keep the
|
|
27
|
+
winner, and you have mostly found noise. The bar rises with every candidate you try on
|
|
28
|
+
overlapping cases (remembered in `~/.margin-referee/ledger.json`), so renaming or trimming the
|
|
29
|
+
cases does not reset it. To confirm a winner, replay it alone on cases none of them saw.
|
|
30
|
+
- **Half-graded cases flatter the candidate.** A case with a check this tool cannot run (an LLM
|
|
31
|
+
rubric, say) is left out and counted, never half-graded. An answer cut off by the output limit,
|
|
32
|
+
or a call that errored, is unanswered, not a fail, and any unanswered case blocks a promotion.
|
|
33
|
+
|
|
34
|
+
## What it runs on
|
|
35
|
+
|
|
36
|
+
- **OpenRouter**, with your own key: any model it serves.
|
|
37
|
+
- **A model in your own account**, with `--candidate-endpoint` or `--baseline-endpoint` and a
|
|
38
|
+
JSON object: `bedrock` (region, model, a Bedrock API key), `vertex_ai` (project, region, model,
|
|
39
|
+
access token), `azure_openai` (resource, deployment, key) or `openai_compatible` (base URL,
|
|
40
|
+
model, key: a fine-tune, vLLM, a self-hosted model). Your credential is used for that run only,
|
|
41
|
+
and you give your own per-token price, so a negotiated discount counts.
|
|
42
|
+
- **A prompt change**: `--candidate-system` replays the candidate with a new system prompt. Each
|
|
43
|
+
prompt you try counts as a candidate.
|
|
44
|
+
|
|
45
|
+
## What it does not do
|
|
46
|
+
|
|
47
|
+
It does not open the pull request, watch the change after you merge it, keep the history across
|
|
48
|
+
your team, or let your agents call it with a spend limit. That is
|
|
49
|
+
[Margin](https://trymargin.io), which runs this same test.
|
|
50
|
+
|
|
51
|
+
MIT licensed.
|
|
@@ -0,0 +1,196 @@
|
|
|
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 re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Iterable, Optional
|
|
12
|
+
|
|
13
|
+
#: A free-text expected answer longer than this is a judgement, not a label: never compared exactly.
|
|
14
|
+
LABEL_MAX_CHARS = 80
|
|
15
|
+
CHECKS = ("equals", "icontains", "contains", "regex", "is-json", "json-field", "json-match")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Case:
|
|
20
|
+
id: str
|
|
21
|
+
messages: list
|
|
22
|
+
check: str
|
|
23
|
+
value: str = ""
|
|
24
|
+
#: The production call's structured-output request, replayed as it was (OpenAI shape).
|
|
25
|
+
response_format: Optional[dict] = None
|
|
26
|
+
#: The production call's own output limit, when the export carries one.
|
|
27
|
+
max_tokens: Optional[int] = None
|
|
28
|
+
#: Further ``(check, value)`` pairs the case must also pass (a promptfoo case's other asserts).
|
|
29
|
+
also: tuple = ()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class Parsed:
|
|
34
|
+
cases: list = field(default_factory=list)
|
|
35
|
+
#: ``(case id, why it cannot be graded here)`` for every case left out.
|
|
36
|
+
ungraded: list = field(default_factory=list)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _messages(x) -> Optional[list]:
|
|
40
|
+
"""The OpenAI chat messages a dataset row means, or None when it names none."""
|
|
41
|
+
if isinstance(x, list) and x and all(isinstance(m, dict) and "role" in m for m in x):
|
|
42
|
+
return x
|
|
43
|
+
if isinstance(x, str) and x.strip():
|
|
44
|
+
try:
|
|
45
|
+
return _messages(json.loads(x))
|
|
46
|
+
except ValueError:
|
|
47
|
+
return [{"role": "user", "content": x}]
|
|
48
|
+
if isinstance(x, dict):
|
|
49
|
+
for k in ("messages", "input", "question", "prompt", "query"):
|
|
50
|
+
if k in x and (m := _messages(x[k])) is not None:
|
|
51
|
+
return m
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _label(expected) -> Optional[str]:
|
|
56
|
+
"""A dataset's expected answer, when it is short enough to be a label rather than prose."""
|
|
57
|
+
if isinstance(expected, dict):
|
|
58
|
+
vals = [v for v in expected.values() if isinstance(v, (str, int, float, bool))]
|
|
59
|
+
expected = vals[0] if len(vals) == 1 else None
|
|
60
|
+
if isinstance(expected, (int, float, bool)):
|
|
61
|
+
expected = str(expected)
|
|
62
|
+
if isinstance(expected, str) and 0 < len(expected.strip()) <= LABEL_MAX_CHARS:
|
|
63
|
+
return expected.strip()
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _row(i: int, row: dict, out: Parsed) -> None:
|
|
68
|
+
cid = str(row.get("id") or row.get("case_id") or f"case-{i}")
|
|
69
|
+
msgs = _messages(row.get("messages") or row.get("input") or row.get("inputs"))
|
|
70
|
+
if msgs is None:
|
|
71
|
+
out.ungraded.append((cid, "no input messages"))
|
|
72
|
+
return
|
|
73
|
+
check = row.get("check")
|
|
74
|
+
if check is not None:
|
|
75
|
+
if check not in CHECKS:
|
|
76
|
+
out.ungraded.append((cid, f"check {check!r} is not deterministic"))
|
|
77
|
+
return
|
|
78
|
+
if check == "regex" and _bad_regex(str(row.get("expected", row.get("value", "")))):
|
|
79
|
+
out.ungraded.append((cid, "its regex does not compile"))
|
|
80
|
+
return
|
|
81
|
+
out.cases.append(Case(cid, msgs, check, str(row.get("expected", row.get("value", ""))),
|
|
82
|
+
row.get("response_format"), row.get("max_tokens")))
|
|
83
|
+
return
|
|
84
|
+
keys = ("expected", "expectedOutput", "expected_output", "outputs", "output")
|
|
85
|
+
expected = next((row[k] for k in keys if row.get(k) is not None), None)
|
|
86
|
+
if isinstance(expected, dict) and len(expected) > 1 and all(
|
|
87
|
+
isinstance(v, (str, int, float, bool)) for v in expected.values()):
|
|
88
|
+
# MAR-2313: a structured answer (several fields) is graded on every field, not left out
|
|
89
|
+
out.cases.append(Case(cid, msgs, "json-match", json.dumps(expected),
|
|
90
|
+
row.get("response_format"), row.get("max_tokens")))
|
|
91
|
+
return
|
|
92
|
+
label = _label(expected)
|
|
93
|
+
if label is None:
|
|
94
|
+
out.ungraded.append((cid, "expected answer is free text, which needs a judge"))
|
|
95
|
+
return
|
|
96
|
+
out.cases.append(Case(cid, msgs, "equals", label))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _promptfoo(doc: dict, out: Parsed) -> None:
|
|
100
|
+
rows = (doc.get("results") or {}).get("results") or []
|
|
101
|
+
for i, r in enumerate(rows):
|
|
102
|
+
cid = str((r.get("testCase") or {}).get("description") or r.get("id") or f"case-{i}")
|
|
103
|
+
msgs = _messages((r.get("prompt") or {}).get("raw"))
|
|
104
|
+
every = (r.get("testCase") or {}).get("assert") or []
|
|
105
|
+
asserts = [a for a in every if a.get("type") in CHECKS]
|
|
106
|
+
judged = sorted({str(a.get("type")) for a in every if a.get("type") not in CHECKS})
|
|
107
|
+
if msgs is None:
|
|
108
|
+
out.ungraded.append((cid, "no rendered prompt"))
|
|
109
|
+
elif judged and asserts:
|
|
110
|
+
# MAR-2313: grading only the deterministic half would pass answers the suite fails
|
|
111
|
+
out.ungraded.append((cid, f"it also asserts {', '.join(judged)}, which this replay "
|
|
112
|
+
"cannot grade, so passing the rest would not be a pass"))
|
|
113
|
+
elif not asserts:
|
|
114
|
+
out.ungraded.append((cid, "no deterministic assertion (equals, contains, regex...)"))
|
|
115
|
+
elif any(a["type"] == "regex" and _bad_regex(str(a.get("value", ""))) for a in asserts):
|
|
116
|
+
out.ungraded.append((cid, "its regex does not compile"))
|
|
117
|
+
else:
|
|
118
|
+
a, rest = asserts[0], asserts[1:]
|
|
119
|
+
out.cases.append(Case(cid, msgs, a["type"], str(a.get("value", "")),
|
|
120
|
+
also=tuple((b["type"], str(b.get("value", ""))) for b in rest)))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _bad_regex(pattern: str) -> bool:
|
|
124
|
+
try:
|
|
125
|
+
re.compile(pattern)
|
|
126
|
+
return False
|
|
127
|
+
except re.error:
|
|
128
|
+
return True
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def parse(text: str) -> Parsed:
|
|
132
|
+
"""Cases from a promptfoo results file, a JSON array, or JSONL (Braintrust, LangSmith, ours)."""
|
|
133
|
+
out = Parsed()
|
|
134
|
+
text = text.strip()
|
|
135
|
+
try:
|
|
136
|
+
doc = json.loads(text)
|
|
137
|
+
except ValueError:
|
|
138
|
+
doc = None
|
|
139
|
+
if isinstance(doc, dict) and "results" in doc:
|
|
140
|
+
_promptfoo(doc, out)
|
|
141
|
+
return out
|
|
142
|
+
rows: Iterable = doc if isinstance(doc, list) else (
|
|
143
|
+
[doc] if isinstance(doc, dict) else _lines(text))
|
|
144
|
+
for i, row in enumerate(rows):
|
|
145
|
+
if isinstance(row, dict):
|
|
146
|
+
_row(i, row, out)
|
|
147
|
+
else:
|
|
148
|
+
out.ungraded.append((f"case-{i}", "not a JSON object"))
|
|
149
|
+
return out
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _lines(text: str):
|
|
153
|
+
for line in text.splitlines():
|
|
154
|
+
if line.strip():
|
|
155
|
+
try:
|
|
156
|
+
yield json.loads(line)
|
|
157
|
+
except ValueError:
|
|
158
|
+
yield None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def grade(output: str, case: Case) -> bool:
|
|
162
|
+
"""Pass only when the answer passes the case's check and every one in ``also``."""
|
|
163
|
+
return all(_check(output, c, v) for c, v in ((case.check, case.value), *case.also))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _check(output: str, check: str, want: str) -> bool:
|
|
167
|
+
out = (output or "").strip()
|
|
168
|
+
if check == "equals":
|
|
169
|
+
return out.lower().strip(" .\"'") == want.lower().strip(" .\"'")
|
|
170
|
+
if check == "contains":
|
|
171
|
+
return want in out
|
|
172
|
+
if check == "icontains":
|
|
173
|
+
return want.lower() in out.lower()
|
|
174
|
+
if check == "regex":
|
|
175
|
+
return re.search(want, out) is not None
|
|
176
|
+
if check == "json-field": # value is "field=expected": one field of a JSON answer
|
|
177
|
+
name, _, want = want.partition("=")
|
|
178
|
+
try:
|
|
179
|
+
got = json.loads(out).get(name)
|
|
180
|
+
except (ValueError, AttributeError):
|
|
181
|
+
return False
|
|
182
|
+
return str(got).strip().lower() == want.strip().lower()
|
|
183
|
+
if check == "is-json":
|
|
184
|
+
try:
|
|
185
|
+
json.loads(out)
|
|
186
|
+
return True
|
|
187
|
+
except ValueError:
|
|
188
|
+
return False
|
|
189
|
+
if check == "json-match": # value is a JSON object: every field must match
|
|
190
|
+
try:
|
|
191
|
+
got, wanted = json.loads(out), json.loads(want)
|
|
192
|
+
return all(str(got.get(k)).strip().lower() == str(v).strip().lower()
|
|
193
|
+
for k, v in wanted.items())
|
|
194
|
+
except (ValueError, AttributeError):
|
|
195
|
+
return False
|
|
196
|
+
raise ValueError(check)
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""margin-referee: should you switch models? Ask your own eval set.
|
|
2
|
+
|
|
3
|
+
margin-referee fit results.json
|
|
4
|
+
margin-referee replay cases.jsonl --baseline openai/gpt-4.1 \
|
|
5
|
+
--candidate openai/gpt-6-luna --cap 1
|
|
6
|
+
|
|
7
|
+
``fit`` is free and offline. ``replay`` calls models through OpenRouter with your own key
|
|
8
|
+
(``OPENROUTER_API_KEY``), or a model in your own account with ``--candidate-endpoint`` /
|
|
9
|
+
``--baseline-endpoint`` (a JSON object: Bedrock, Vertex AI, Azure OpenAI or any
|
|
10
|
+
OpenAI-compatible endpoint, with your per-token price).
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import pathlib
|
|
19
|
+
import sys
|
|
20
|
+
|
|
21
|
+
from margin_referee import cases as cases_mod
|
|
22
|
+
from margin_referee import endpoints, replay, stats
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _fit(a) -> int:
|
|
26
|
+
parsed = cases_mod.parse(pathlib.Path(a.file).read_text())
|
|
27
|
+
n = len(parsed.cases)
|
|
28
|
+
need = stats.smallest_suite(a.baseline_rate, candidates=a.candidates)
|
|
29
|
+
out = {"graded": n, "ungraded": len(parsed.ungraded), "needed": need,
|
|
30
|
+
"ready": n >= need,
|
|
31
|
+
"losses_absorbed": stats.losses_absorbed(n, a.baseline_rate, a.candidates),
|
|
32
|
+
"ungraded_examples": parsed.ungraded[:5]}
|
|
33
|
+
print(json.dumps(out, indent=1))
|
|
34
|
+
return 0 if out["ready"] else 2
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _endpoint(raw, model: str):
|
|
38
|
+
if raw:
|
|
39
|
+
return endpoints.parse(json.loads(raw))
|
|
40
|
+
key = os.environ.get("OPENROUTER_API_KEY", "")
|
|
41
|
+
if not key:
|
|
42
|
+
raise SystemExit("set OPENROUTER_API_KEY, or pass an endpoint for a model in your account")
|
|
43
|
+
return endpoints.parse({"kind": "openrouter", "model": model, "api_key": key})
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _replay(a) -> int:
|
|
47
|
+
parsed = cases_mod.parse(pathlib.Path(a.file).read_text())
|
|
48
|
+
if not parsed.cases:
|
|
49
|
+
print(json.dumps({"error": "no case can be graded", "ungraded": parsed.ungraded[:5]}))
|
|
50
|
+
return 2
|
|
51
|
+
base = _endpoint(a.baseline_endpoint, a.baseline)
|
|
52
|
+
cand = _endpoint(a.candidate_endpoint, a.candidate)
|
|
53
|
+
res = replay.run(parsed.cases, endpoints.chat_for(base), endpoints.chat_for(cand),
|
|
54
|
+
cap_usd=a.cap, candidate_system=a.candidate_system)
|
|
55
|
+
prompt = a.candidate_system
|
|
56
|
+
label = cand.label + ("+system:" + hashlib.sha256(prompt.encode()).hexdigest()[:10]
|
|
57
|
+
if prompt else "")
|
|
58
|
+
tried = replay.record_and_count(parsed.cases, base.label, label)
|
|
59
|
+
v = replay.verdict(res, tried)
|
|
60
|
+
v.update(baseline=base.label, candidate=label, ungraded=len(parsed.ungraded),
|
|
61
|
+
baseline_endpoint=endpoints.describe(base),
|
|
62
|
+
candidate_endpoint=endpoints.describe(cand))
|
|
63
|
+
print(json.dumps(v, indent=1))
|
|
64
|
+
return 0 if v["promoted"] else 1
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def main(argv=None) -> int:
|
|
68
|
+
ap = argparse.ArgumentParser(prog="margin-referee", description=__doc__.splitlines()[0])
|
|
69
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
70
|
+
f = sub.add_parser("fit", help="is this eval set big enough to prove a switch? (free)")
|
|
71
|
+
f.add_argument("file")
|
|
72
|
+
f.add_argument("--baseline-rate", type=float, default=stats.DEFAULT_BASELINE_RATE)
|
|
73
|
+
f.add_argument("--candidates", type=int, default=1)
|
|
74
|
+
r = sub.add_parser("replay", help="run both models on the cases and get the verdict")
|
|
75
|
+
r.add_argument("file")
|
|
76
|
+
r.add_argument("--baseline", default="")
|
|
77
|
+
r.add_argument("--candidate", default="")
|
|
78
|
+
r.add_argument("--cap", type=float, required=True, help="the most this replay may spend, USD")
|
|
79
|
+
r.add_argument("--candidate-system", help="test a prompt change: the candidate's system prompt")
|
|
80
|
+
r.add_argument("--candidate-endpoint", help="JSON: a model in your own account")
|
|
81
|
+
r.add_argument("--baseline-endpoint", help="JSON: a model in your own account")
|
|
82
|
+
a = ap.parse_args(argv)
|
|
83
|
+
return _fit(a) if a.cmd == "fit" else _replay(a)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
sys.exit(main())
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""A model endpoint for the replay: OpenRouter, or a model in your OWN account (Bedrock, Vertex AI,
|
|
2
|
+
Azure OpenAI, any OpenAI-compatible endpoint). Ported from Margin's hosted product.
|
|
3
|
+
|
|
4
|
+
⛔ THE CREDENTIAL IS NEVER STORED OR LOGGED. It lives in this object for the replay and is gone
|
|
5
|
+
with it; ``__repr__`` hides it, and an HTTP error carries the endpoint's status and body, never
|
|
6
|
+
the request headers.
|
|
7
|
+
⛔ THE PRICE IS THE CUSTOMER'S, AND IT IS REQUIRED. Their own account is billed at their own rate
|
|
8
|
+
(including any negotiated discount), which Margin cannot know. An unpriced candidate would read as
|
|
9
|
+
free and win on cost, so ``parse`` refuses one rather than guessing.
|
|
10
|
+
⛔ A CUSTOM URL IS HTTPS AND PUBLIC. Margin's servers make the call, so a URL that resolves to a
|
|
11
|
+
private, loopback or link-local address is refused (no reaching into our own network).
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import ipaddress
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import socket
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.parse
|
|
21
|
+
import urllib.request
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from types import SimpleNamespace
|
|
24
|
+
from typing import Optional
|
|
25
|
+
|
|
26
|
+
KINDS = ("openrouter", "openai_compatible", "azure_openai", "vertex_ai", "bedrock")
|
|
27
|
+
OPENROUTER = "https://openrouter.ai/api/v1/chat/completions"
|
|
28
|
+
_NAME = re.compile(r"^[A-Za-z0-9._:/@-]{1,200}$")
|
|
29
|
+
_SLUG = re.compile(r"^[a-z0-9-]{1,63}$")
|
|
30
|
+
TIMEOUT_S = 120
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class EndpointError(ValueError):
|
|
34
|
+
"""The endpoint description cannot be used; the message says why."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class Endpoint:
|
|
39
|
+
kind: str
|
|
40
|
+
url: str
|
|
41
|
+
model: str
|
|
42
|
+
input_per_mtok: float
|
|
43
|
+
output_per_mtok: float
|
|
44
|
+
headers: dict = field(repr=False)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def label(self) -> str:
|
|
48
|
+
"""What the verdict and the best-of-N count call this candidate."""
|
|
49
|
+
return f"{self.kind}:{self.model}"
|
|
50
|
+
|
|
51
|
+
def __repr__(self) -> str: # never the credential
|
|
52
|
+
return f"Endpoint({self.label!r}, {self.url!r})"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _need(d: dict, key: str, pattern: re.Pattern = _NAME) -> str:
|
|
56
|
+
v = d.get(key)
|
|
57
|
+
if not isinstance(v, str) or not pattern.match(v.strip()):
|
|
58
|
+
raise EndpointError(f"candidate_endpoint.{key} is missing or not a plain name")
|
|
59
|
+
return v.strip()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _secret(d: dict, key: str) -> str:
|
|
63
|
+
v = d.get(key)
|
|
64
|
+
if not isinstance(v, str) or not v.strip() or len(v) > 8192:
|
|
65
|
+
raise EndpointError(f"candidate_endpoint.{key} is required (it is used for this replay "
|
|
66
|
+
"only and never stored)")
|
|
67
|
+
return v.strip()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _public_https(url: str) -> str:
|
|
71
|
+
u = urllib.parse.urlparse(url)
|
|
72
|
+
if u.scheme != "https" or not u.hostname:
|
|
73
|
+
raise EndpointError("candidate_endpoint.base_url must be an https URL")
|
|
74
|
+
try:
|
|
75
|
+
addrs = {a[4][0] for a in socket.getaddrinfo(u.hostname, u.port or 443)}
|
|
76
|
+
except OSError:
|
|
77
|
+
raise EndpointError(f"candidate_endpoint.base_url: {u.hostname} does not resolve")
|
|
78
|
+
for a in addrs:
|
|
79
|
+
ip = ipaddress.ip_address(a.split("%")[0])
|
|
80
|
+
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved \
|
|
81
|
+
or ip.is_multicast or ip.is_unspecified:
|
|
82
|
+
raise EndpointError("candidate_endpoint.base_url resolves to a private address, "
|
|
83
|
+
"which Margin will not call")
|
|
84
|
+
return url.rstrip("/")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def parse(d: object) -> Endpoint:
|
|
88
|
+
"""An ``Endpoint`` from the tool's ``candidate_endpoint`` object, or ``EndpointError``."""
|
|
89
|
+
if not isinstance(d, dict):
|
|
90
|
+
raise EndpointError("candidate_endpoint is an object")
|
|
91
|
+
kind = d.get("kind")
|
|
92
|
+
if kind not in KINDS:
|
|
93
|
+
raise EndpointError(f"candidate_endpoint.kind is one of {', '.join(KINDS)}")
|
|
94
|
+
if kind == "openrouter": # billed cost comes back on every answer, so no price is needed
|
|
95
|
+
return Endpoint(kind, OPENROUTER, _need(d, "model"), -1.0, -1.0,
|
|
96
|
+
{"Authorization": "Bearer " + _secret(d, "api_key")})
|
|
97
|
+
price = d.get("price") or {}
|
|
98
|
+
try:
|
|
99
|
+
pin, pout = float(price["input_per_mtok"]), float(price["output_per_mtok"])
|
|
100
|
+
except (KeyError, TypeError, ValueError):
|
|
101
|
+
raise EndpointError("candidate_endpoint.price needs input_per_mtok and output_per_mtok "
|
|
102
|
+
"(USD per million tokens, your own rate): an unpriced candidate "
|
|
103
|
+
"would read as free")
|
|
104
|
+
if not (0 <= pin < 1000 and 0 <= pout < 1000):
|
|
105
|
+
raise EndpointError("candidate_endpoint.price is USD per million tokens, 0 to 1000")
|
|
106
|
+
if kind == "openai_compatible":
|
|
107
|
+
raw = d.get("base_url")
|
|
108
|
+
url = _public_https(raw.strip() if isinstance(raw, str) and len(raw) < 300 else "")
|
|
109
|
+
url, model = url + "/chat/completions", _need(d, "model")
|
|
110
|
+
headers = {"Authorization": "Bearer " + _secret(d, "api_key")}
|
|
111
|
+
elif kind == "azure_openai":
|
|
112
|
+
res = _need(d, "resource", _SLUG)
|
|
113
|
+
model = _need(d, "deployment")
|
|
114
|
+
ver = _need(d, "api_version") if d.get("api_version") else "2024-10-21"
|
|
115
|
+
url = (f"https://{res}.openai.azure.com/openai/deployments/"
|
|
116
|
+
f"{urllib.parse.quote(model, safe='')}/chat/completions?api-version={ver}")
|
|
117
|
+
headers = {"api-key": _secret(d, "api_key")}
|
|
118
|
+
elif kind == "vertex_ai":
|
|
119
|
+
project, region, model = _need(d, "project", _SLUG), _need(d, "region", _SLUG), \
|
|
120
|
+
_need(d, "model")
|
|
121
|
+
url = (f"https://{region}-aiplatform.googleapis.com/v1/projects/{project}/locations/"
|
|
122
|
+
f"{region}/endpoints/openapi/chat/completions")
|
|
123
|
+
headers = {"Authorization": "Bearer " + _secret(d, "access_token")}
|
|
124
|
+
else: # bedrock: the Converse API with a Bedrock API key (no request signing needed)
|
|
125
|
+
region, model = _need(d, "region", _SLUG), _need(d, "model")
|
|
126
|
+
url = (f"https://bedrock-runtime.{region}.amazonaws.com/model/"
|
|
127
|
+
f"{urllib.parse.quote(model, safe='')}/converse")
|
|
128
|
+
headers = {"Authorization": "Bearer " + _secret(d, "api_key")}
|
|
129
|
+
return Endpoint(kind, url, model, pin, pout, headers)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _post(url: str, headers: dict, body: dict) -> dict:
|
|
133
|
+
req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST",
|
|
134
|
+
headers={"content-type": "application/json", **headers})
|
|
135
|
+
try:
|
|
136
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT_S) as r:
|
|
137
|
+
return json.load(r)
|
|
138
|
+
except urllib.error.HTTPError as e: # the endpoint's answer, never our request headers
|
|
139
|
+
raise RuntimeError(f"HTTP {e.code} from the endpoint: {e.read()[:300]!r}") from None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _bedrock_body(messages: list, max_tokens: int, temperature: float) -> dict:
|
|
143
|
+
system = [{"text": m["content"]} for m in messages if m.get("role") == "system"]
|
|
144
|
+
msgs = [{"role": m["role"], "content": [{"text": str(m.get("content") or "")}]}
|
|
145
|
+
for m in messages if m.get("role") in ("user", "assistant")]
|
|
146
|
+
config = {"maxTokens": max_tokens, "temperature": temperature}
|
|
147
|
+
body = {"messages": msgs, "inferenceConfig": config}
|
|
148
|
+
return {**body, "system": system} if system else body
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def chat_for(ep: Endpoint):
|
|
152
|
+
"""A ``chat`` callable shaped like ``providers.openrouter.chat`` for the replay. The OpenRouter
|
|
153
|
+
routing policy kwargs are accepted and ignored: the call goes to the customer's own account."""
|
|
154
|
+
def chat(messages, *, model=None, temperature=0.0, max_tokens=1024, response_format=None,
|
|
155
|
+
**_policy):
|
|
156
|
+
if ep.kind == "bedrock":
|
|
157
|
+
d = _post(ep.url, ep.headers, _bedrock_body(messages, max_tokens, temperature))
|
|
158
|
+
text = "".join(c.get("text", "") for c in
|
|
159
|
+
((d.get("output") or {}).get("message") or {}).get("content") or [])
|
|
160
|
+
u = d.get("usage") or {}
|
|
161
|
+
tin, tout = int(u.get("inputTokens") or 0), int(u.get("outputTokens") or 0)
|
|
162
|
+
finish = "length" if d.get("stopReason") == "max_tokens" else "stop"
|
|
163
|
+
else:
|
|
164
|
+
body = {"model": ep.model, "messages": messages, "temperature": temperature,
|
|
165
|
+
"max_tokens": max_tokens}
|
|
166
|
+
if response_format:
|
|
167
|
+
body["response_format"] = response_format
|
|
168
|
+
if ep.kind == "openrouter":
|
|
169
|
+
body["usage"] = {"include": True}
|
|
170
|
+
d = _post(ep.url, ep.headers, body)
|
|
171
|
+
choice = (d.get("choices") or [{}])[0]
|
|
172
|
+
text = ((choice.get("message") or {}).get("content")) or ""
|
|
173
|
+
u = d.get("usage") or {}
|
|
174
|
+
tin, tout = int(u.get("prompt_tokens") or 0), int(u.get("completion_tokens") or 0)
|
|
175
|
+
finish = choice.get("finish_reason") or "stop"
|
|
176
|
+
if not (tin or tout):
|
|
177
|
+
raise RuntimeError("the endpoint reported no token usage, so the call cannot be "
|
|
178
|
+
"priced")
|
|
179
|
+
if ep.kind == "openrouter":
|
|
180
|
+
if u.get("cost") is None:
|
|
181
|
+
raise RuntimeError("OpenRouter returned no billed cost for this call")
|
|
182
|
+
cost = float(u["cost"])
|
|
183
|
+
else:
|
|
184
|
+
cost = (tin * ep.input_per_mtok + tout * ep.output_per_mtok) / 1e6
|
|
185
|
+
return SimpleNamespace(text=text, cost_usd=cost, finish_reason=finish, input_tokens=tin,
|
|
186
|
+
output_tokens=tout, cache_read_tokens=0, model=ep.label)
|
|
187
|
+
return chat
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def describe(ep: Optional[Endpoint]) -> Optional[dict]:
|
|
191
|
+
"""What a verdict may say about the endpoint (never the credential)."""
|
|
192
|
+
if ep is None:
|
|
193
|
+
return None
|
|
194
|
+
if ep.kind == "openrouter":
|
|
195
|
+
return {"kind": ep.kind, "model": ep.model, "price_source": "OpenRouter's billed cost"}
|
|
196
|
+
return {"kind": ep.kind, "model": ep.model, "host": urllib.parse.urlparse(ep.url).hostname,
|
|
197
|
+
"price_per_mtok": {"input": ep.input_per_mtok, "output": ep.output_per_mtok},
|
|
198
|
+
"price_source": "the rate you supplied for your own account"}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Run both models on every case, grade each answer with the case's own check, and decide.
|
|
2
|
+
|
|
3
|
+
A case either side could not answer (an error, or an answer cut off by the output limit) is left
|
|
4
|
+
out and counted, never graded as a fail, and a replay with any such case promotes nothing: a
|
|
5
|
+
verdict on the survivors would grade the candidate only on what it finished.
|
|
6
|
+
|
|
7
|
+
Every candidate tried against the same baseline on overlapping cases is remembered in a local
|
|
8
|
+
ledger (``~/.margin-referee/ledger.json``), so the bar rises with each one and renaming or
|
|
9
|
+
trimming the cases does not reset it. A fresh set no candidate ran on is judged as one candidate:
|
|
10
|
+
that is how a winner is confirmed on held-out cases.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import pathlib
|
|
18
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from typing import Callable, Optional
|
|
21
|
+
|
|
22
|
+
from margin_referee import stats
|
|
23
|
+
from margin_referee.cases import Case, grade
|
|
24
|
+
|
|
25
|
+
LEDGER = pathlib.Path(os.environ.get("MARGIN_REFEREE_LEDGER",
|
|
26
|
+
pathlib.Path.home() / ".margin-referee" / "ledger.json"))
|
|
27
|
+
OVERLAP = 0.1
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Result:
|
|
32
|
+
pairs: list = field(default_factory=list) # (case id, baseline score, candidate score)
|
|
33
|
+
cost: dict = field(default_factory=lambda: {"baseline": 0.0, "candidate": 0.0})
|
|
34
|
+
unanswered: list = field(default_factory=list) # (case id, side, why)
|
|
35
|
+
stopped: str = ""
|
|
36
|
+
spend_usd: float = 0.0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def with_system(messages: list, system: Optional[str]) -> list:
|
|
40
|
+
if system is None:
|
|
41
|
+
return messages
|
|
42
|
+
rest = messages[1:] if messages and messages[0].get("role") == "system" else messages
|
|
43
|
+
return [{"role": "system", "content": system}, *rest]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _one(case: Case, side: str, chat: Callable, system: Optional[str], max_tokens: int):
|
|
47
|
+
msgs = with_system(case.messages, system) if side == "candidate" else case.messages
|
|
48
|
+
try:
|
|
49
|
+
r = chat(msgs, max_tokens=case.max_tokens or max_tokens,
|
|
50
|
+
response_format=case.response_format)
|
|
51
|
+
except Exception as exc: # noqa: BLE001 - an unanswered call is a missing pair, named
|
|
52
|
+
return None, 0.0, f"{type(exc).__name__}: {exc}"[:200]
|
|
53
|
+
if r.finish_reason == "length":
|
|
54
|
+
return None, r.cost_usd, "cut off by the output limit"
|
|
55
|
+
try:
|
|
56
|
+
return (1.0 if grade(r.text, case) else 0.0), r.cost_usd, None
|
|
57
|
+
except Exception as exc: # noqa: BLE001 - a check that cannot run grades nothing
|
|
58
|
+
return None, r.cost_usd, f"check failed: {type(exc).__name__}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def run(cases: list, baseline_chat: Callable, candidate_chat: Callable, *, cap_usd: float,
|
|
62
|
+
candidate_system: Optional[str] = None, max_tokens: int = 8192,
|
|
63
|
+
workers: int = 8) -> Result:
|
|
64
|
+
"""Both sides on every case until the next batch could cross ``cap_usd``."""
|
|
65
|
+
out, worst, i = Result(), 0.0, 0
|
|
66
|
+
|
|
67
|
+
def pair(case):
|
|
68
|
+
b = _one(case, "baseline", baseline_chat, None, max_tokens)
|
|
69
|
+
c = _one(case, "candidate", candidate_chat, candidate_system, max_tokens)
|
|
70
|
+
return case, b, c
|
|
71
|
+
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
|
|
72
|
+
while i < len(cases):
|
|
73
|
+
room = cap_usd - out.spend_usd
|
|
74
|
+
size = workers if worst == 0 else min(workers, int(room // worst))
|
|
75
|
+
if size < 1 or room <= 0:
|
|
76
|
+
out.stopped = f"stopped at the ${cap_usd:.2f} cap after {i} cases"
|
|
77
|
+
break
|
|
78
|
+
batch = cases[i:i + (1 if worst == 0 else size)]
|
|
79
|
+
for case, (bs, bc, be), (cs, cc, cerr) in pool.map(pair, batch):
|
|
80
|
+
spent = bc + cc
|
|
81
|
+
out.spend_usd += spent
|
|
82
|
+
worst = max(worst, spent)
|
|
83
|
+
if be or cerr:
|
|
84
|
+
out.unanswered.append((case.id, "baseline" if be else "candidate",
|
|
85
|
+
be or cerr))
|
|
86
|
+
continue
|
|
87
|
+
out.cost["baseline"] += bc
|
|
88
|
+
out.cost["candidate"] += cc
|
|
89
|
+
out.pairs.append((case.id, bs, cs))
|
|
90
|
+
i += len(batch)
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def case_fps(cases: list) -> set:
|
|
95
|
+
return {hashlib.sha256(json.dumps([c.messages, c.check, c.value], sort_keys=True)
|
|
96
|
+
.encode()).hexdigest()[:12] for c in cases}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def record_and_count(cases: list, baseline: str, candidate: str,
|
|
100
|
+
ledger: pathlib.Path = LEDGER) -> int:
|
|
101
|
+
"""Remember this candidate and return how many distinct candidates were tried against
|
|
102
|
+
``baseline`` on these cases or a set sharing ``OVERLAP`` of them (this one included)."""
|
|
103
|
+
mine = case_fps(cases)
|
|
104
|
+
try:
|
|
105
|
+
rows = json.loads(ledger.read_text())
|
|
106
|
+
except (OSError, ValueError):
|
|
107
|
+
rows = []
|
|
108
|
+
need = max(1, int(OVERLAP * len(mine)))
|
|
109
|
+
tried = {r["candidate"] for r in rows if r.get("baseline") == baseline
|
|
110
|
+
and len(mine & set(r.get("cases", []))) >= need}
|
|
111
|
+
rows.append({"baseline": baseline, "candidate": candidate, "cases": sorted(mine)})
|
|
112
|
+
ledger.parent.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
ledger.write_text(json.dumps(rows))
|
|
114
|
+
return len(tried | {candidate})
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def verdict(res: Result, candidates: int = 1) -> dict:
|
|
118
|
+
"""Promoted only when the paired test clears the bar for ``candidates`` tried, the candidate
|
|
119
|
+
costs less per case, and every case got a gradable answer from both sides."""
|
|
120
|
+
n = len(res.pairs)
|
|
121
|
+
k = max(1, candidates)
|
|
122
|
+
pb = stats.paired_bound([(b, c) for _, b, c in res.pairs], z=stats.family_z(k))
|
|
123
|
+
cost = {s: (v / n if n else None) for s, v in res.cost.items()}
|
|
124
|
+
cheaper = n > 0 and cost["candidate"] < cost["baseline"]
|
|
125
|
+
complete = not res.unanswered and not res.stopped
|
|
126
|
+
promoted = bool(pb and pb.supported and cheaper and complete)
|
|
127
|
+
if promoted:
|
|
128
|
+
why = "the candidate held the pass rate at the bar and costs less per case"
|
|
129
|
+
elif pb is None:
|
|
130
|
+
why = "no case ran on both models"
|
|
131
|
+
elif not complete:
|
|
132
|
+
why = (f"{len(res.unanswered)} case(s) got no gradable answer" if res.unanswered
|
|
133
|
+
else res.stopped) + ", so the comparison is incomplete"
|
|
134
|
+
elif not pb.supported:
|
|
135
|
+
why = (f"with {k} models tried on these {n} cases it needs about "
|
|
136
|
+
f"{stats.gate_floor(k)}; confirm it alone on fresh cases" if n < stats.gate_floor(k)
|
|
137
|
+
else f"the quality bound is {pb.upper:.1%} behind, the bar allows {pb.margin:.1%}")
|
|
138
|
+
else:
|
|
139
|
+
why = "the candidate costs more per case: an upgrade, not a saving"
|
|
140
|
+
return {"cases": n, "baseline_passed": int(sum(b for _, b, _ in res.pairs)),
|
|
141
|
+
"candidate_passed": int(sum(c for _, _, c in res.pairs)),
|
|
142
|
+
"baseline_cost_per_case": cost["baseline"],
|
|
143
|
+
"candidate_cost_per_case": cost["candidate"],
|
|
144
|
+
"candidates_tried": k, "cases_needed": stats.gate_floor(k),
|
|
145
|
+
"lost": pb.baseline_only if pb else 0, "won": pb.candidate_only if pb else 0,
|
|
146
|
+
"promoted": promoted, "why": why, "unanswered": len(res.unanswered),
|
|
147
|
+
"stopped": res.stopped, "spend_usd": round(res.spend_usd, 6)}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""The switch gate's statistics: a paired comparison with a best-of-N correction.
|
|
2
|
+
|
|
3
|
+
Ported from Margin's hosted product (``src/margin/autoroute.py`` and ``src/margin/fit_check.py``);
|
|
4
|
+
a test in the product repo runs both on the same inputs and fails if they ever disagree.
|
|
5
|
+
|
|
6
|
+
The question it answers: could the candidate be WORSE than the model you run today by more than
|
|
7
|
+
the bar allows (3% of your current pass rate), given the cases both ran? Cases both passed, or
|
|
8
|
+
both failed, say nothing about the gap; only the cases they disagree on do (McNemar). Two floors
|
|
9
|
+
keep a small panel from clearing on almost nothing: the half-width never falls below the
|
|
10
|
+
"rule of three" (3/n), and the panel must be at least as large as an all-passing absolute test
|
|
11
|
+
would need. Trying several candidates and keeping the best raises the bar (Bonferroni), because
|
|
12
|
+
the best of several looks better than it is.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import math
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from functools import lru_cache
|
|
19
|
+
from statistics import NormalDist
|
|
20
|
+
from typing import Iterable, Optional
|
|
21
|
+
|
|
22
|
+
#: The bar: the candidate must hold at least 97% of the current model's pass rate.
|
|
23
|
+
PARITY_THRESHOLD = 0.97
|
|
24
|
+
#: One-sided 95% normal quantile.
|
|
25
|
+
EVIDENCE_Z = 1.645
|
|
26
|
+
_ZERO_EVENT_BOUND = 3.0
|
|
27
|
+
DEFAULT_BASELINE_RATE = 0.9
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def family_z(candidates: int, base_z: float = EVIDENCE_Z) -> float:
|
|
31
|
+
"""The z that holds 95% confidence across ``candidates`` tried (Bonferroni)."""
|
|
32
|
+
if candidates < 1:
|
|
33
|
+
raise ValueError(f"candidates must be >= 1, got {candidates}")
|
|
34
|
+
if candidates == 1:
|
|
35
|
+
return base_z
|
|
36
|
+
norm = NormalDist()
|
|
37
|
+
return norm.inv_cdf(1.0 - (1.0 - norm.cdf(base_z)) / candidates)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def trials_needed(threshold: float = PARITY_THRESHOLD, z: float = EVIDENCE_Z) -> int:
|
|
41
|
+
"""Fewest all-passing trials whose Wilson lower bound clears ``threshold`` (88 at 0.97)."""
|
|
42
|
+
if not 0.0 <= threshold < 1.0:
|
|
43
|
+
raise ValueError(f"threshold must be in [0, 1), got {threshold}")
|
|
44
|
+
return math.ceil(z * z * threshold / (1.0 - threshold))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class Paired:
|
|
49
|
+
paired: int
|
|
50
|
+
ties: int
|
|
51
|
+
baseline_only: int
|
|
52
|
+
candidate_only: int
|
|
53
|
+
shortfall: float
|
|
54
|
+
upper: float
|
|
55
|
+
margin: float
|
|
56
|
+
supported: bool
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def paired_bound(pairs: Iterable[tuple[float, float]], *, threshold: float = PARITY_THRESHOLD,
|
|
60
|
+
z: float = EVIDENCE_Z) -> Optional[Paired]:
|
|
61
|
+
"""``pairs`` is one ``(baseline_score, candidate_score)`` per case, each in [0, 1]. None when
|
|
62
|
+
there are no pairs: no evidence, no claim."""
|
|
63
|
+
ties = baseline_only = candidate_only = 0
|
|
64
|
+
baseline_passes = 0.0
|
|
65
|
+
for b, c in pairs:
|
|
66
|
+
baseline_passes += b
|
|
67
|
+
if b > c:
|
|
68
|
+
baseline_only += 1
|
|
69
|
+
elif c > b:
|
|
70
|
+
candidate_only += 1
|
|
71
|
+
else:
|
|
72
|
+
ties += 1
|
|
73
|
+
paired = ties + baseline_only + candidate_only
|
|
74
|
+
if paired == 0:
|
|
75
|
+
return None
|
|
76
|
+
discordant = baseline_only + candidate_only
|
|
77
|
+
shortfall = (baseline_only - candidate_only) / paired
|
|
78
|
+
half = max(z * (discordant ** 0.5) / paired, _ZERO_EVENT_BOUND / paired)
|
|
79
|
+
margin = (baseline_passes / paired) * (1.0 - threshold)
|
|
80
|
+
upper = shortfall + half
|
|
81
|
+
return Paired(paired, ties, baseline_only, candidate_only, shortfall, upper, margin,
|
|
82
|
+
paired >= trials_needed(threshold, z) and upper <= margin)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def losses_absorbed(n: int, baseline_rate: float = DEFAULT_BASELINE_RATE,
|
|
86
|
+
candidates: int = 1) -> Optional[int]:
|
|
87
|
+
"""The most cases a candidate may lose (and win none) on an ``n``-case suite and still
|
|
88
|
+
clear the bar; None when even a clean sweep cannot."""
|
|
89
|
+
passes = round(n * baseline_rate)
|
|
90
|
+
z = family_z(max(1, candidates))
|
|
91
|
+
best = None
|
|
92
|
+
for k in range(0, passes + 1):
|
|
93
|
+
pairs = [(1.0 if i < passes else 0.0, 0.0 if i < k else (1.0 if i < passes else 0.0))
|
|
94
|
+
for i in range(n)]
|
|
95
|
+
pb = paired_bound(pairs, z=z)
|
|
96
|
+
if pb is None or not pb.supported:
|
|
97
|
+
break
|
|
98
|
+
best = k
|
|
99
|
+
return best
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@lru_cache(maxsize=64)
|
|
103
|
+
def smallest_suite(baseline_rate: float = DEFAULT_BASELINE_RATE, limit: int = 2000,
|
|
104
|
+
candidates: int = 1) -> int:
|
|
105
|
+
"""The fewest cases that can prove a switch at this current pass rate, with no
|
|
106
|
+
disagreement (100 against a perfect current model, 111 against one passing 90%)."""
|
|
107
|
+
lo, hi = trials_needed(), limit
|
|
108
|
+
while lo < hi:
|
|
109
|
+
mid = (lo + hi) // 2
|
|
110
|
+
if losses_absorbed(mid, baseline_rate, candidates) is None:
|
|
111
|
+
lo = mid + 1
|
|
112
|
+
else:
|
|
113
|
+
hi = mid
|
|
114
|
+
return lo
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def gate_floor(candidates: int = 1) -> int:
|
|
118
|
+
"""Cases needed to prove a switch when ``candidates`` models were tried on the same cases."""
|
|
119
|
+
return max(trials_needed(z=family_z(candidates)), smallest_suite(1.0, candidates=candidates))
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: margin-referee
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Should you switch models? Replay your own eval set on a candidate and get a verdict that holds up.
|
|
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
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# margin-referee
|
|
15
|
+
|
|
16
|
+
Should you switch models? Ask your own eval set.
|
|
17
|
+
|
|
18
|
+
`margin-referee` replays the cases you already have (a promptfoo results file, a Braintrust,
|
|
19
|
+
LangSmith or Langfuse dataset export, or JSONL) on the model you run today and on a candidate,
|
|
20
|
+
grades both with each case's own check, and tells you whether the candidate holds up and costs
|
|
21
|
+
less. No account, no backend, no telemetry.
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
pip install margin-referee
|
|
25
|
+
margin-referee fit cases.jsonl
|
|
26
|
+
OPENROUTER_API_KEY=... margin-referee replay cases.jsonl \
|
|
27
|
+
--baseline openai/gpt-4.1 --candidate openai/gpt-6-luna --cap 1
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Why another eval tool
|
|
31
|
+
|
|
32
|
+
Because "the candidate scored higher on our evals" is how most bad switches start. Three things
|
|
33
|
+
make it unreliable, and this tool corrects for each:
|
|
34
|
+
|
|
35
|
+
- **Small sets lie.** The verdict is a paired test on the cases both models ran. Only the cases
|
|
36
|
+
they disagree on carry evidence, and a clean sweep on 20 cases proves nothing. `fit` tells you,
|
|
37
|
+
for free and before anything runs, how many cases you need: about 100 against a current model
|
|
38
|
+
that passes everything, and more as its pass rate falls.
|
|
39
|
+
- **The best of several looks better than it is.** Try four models on the same cases and keep the
|
|
40
|
+
winner, and you have mostly found noise. The bar rises with every candidate you try on
|
|
41
|
+
overlapping cases (remembered in `~/.margin-referee/ledger.json`), so renaming or trimming the
|
|
42
|
+
cases does not reset it. To confirm a winner, replay it alone on cases none of them saw.
|
|
43
|
+
- **Half-graded cases flatter the candidate.** A case with a check this tool cannot run (an LLM
|
|
44
|
+
rubric, say) is left out and counted, never half-graded. An answer cut off by the output limit,
|
|
45
|
+
or a call that errored, is unanswered, not a fail, and any unanswered case blocks a promotion.
|
|
46
|
+
|
|
47
|
+
## What it runs on
|
|
48
|
+
|
|
49
|
+
- **OpenRouter**, with your own key: any model it serves.
|
|
50
|
+
- **A model in your own account**, with `--candidate-endpoint` or `--baseline-endpoint` and a
|
|
51
|
+
JSON object: `bedrock` (region, model, a Bedrock API key), `vertex_ai` (project, region, model,
|
|
52
|
+
access token), `azure_openai` (resource, deployment, key) or `openai_compatible` (base URL,
|
|
53
|
+
model, key: a fine-tune, vLLM, a self-hosted model). Your credential is used for that run only,
|
|
54
|
+
and you give your own per-token price, so a negotiated discount counts.
|
|
55
|
+
- **A prompt change**: `--candidate-system` replays the candidate with a new system prompt. Each
|
|
56
|
+
prompt you try counts as a candidate.
|
|
57
|
+
|
|
58
|
+
## What it does not do
|
|
59
|
+
|
|
60
|
+
It does not open the pull request, watch the change after you merge it, keep the history across
|
|
61
|
+
your team, or let your agents call it with a spend limit. That is
|
|
62
|
+
[Margin](https://trymargin.io), which runs this same test.
|
|
63
|
+
|
|
64
|
+
MIT licensed.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
margin_referee/__init__.py
|
|
5
|
+
margin_referee/cases.py
|
|
6
|
+
margin_referee/cli.py
|
|
7
|
+
margin_referee/endpoints.py
|
|
8
|
+
margin_referee/replay.py
|
|
9
|
+
margin_referee/stats.py
|
|
10
|
+
margin_referee.egg-info/PKG-INFO
|
|
11
|
+
margin_referee.egg-info/SOURCES.txt
|
|
12
|
+
margin_referee.egg-info/dependency_links.txt
|
|
13
|
+
margin_referee.egg-info/entry_points.txt
|
|
14
|
+
margin_referee.egg-info/requires.txt
|
|
15
|
+
margin_referee.egg-info/top_level.txt
|
|
16
|
+
tests/test_referee.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
margin_referee
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "margin-referee"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Should you switch models? Replay your own eval set on a candidate and get a verdict that holds up."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
keywords = ["llm", "evals", "model-selection", "agents", "promptfoo", "langfuse", "braintrust"]
|
|
13
|
+
# Zero runtime dependencies on purpose: it runs anywhere Python does.
|
|
14
|
+
dependencies = []
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
dev = ["pytest>=7"]
|
|
18
|
+
|
|
19
|
+
[project.scripts]
|
|
20
|
+
margin-referee = "margin_referee.cli:main"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools]
|
|
23
|
+
packages = ["margin_referee"]
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""margin-referee, offline: the floors, the paired test, best-of-N, the ledger and the CLI."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from types import SimpleNamespace
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from margin_referee import cli, endpoints, replay, stats
|
|
10
|
+
from margin_referee.cases import Case
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_the_floors_are_the_gates():
|
|
14
|
+
assert stats.trials_needed() == 88
|
|
15
|
+
assert [stats.gate_floor(k) for k in (1, 2, 3, 4)] == [100, 125, 147, 163]
|
|
16
|
+
assert stats.smallest_suite(1.0) == 100 and stats.smallest_suite(0.9) == 111
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_a_small_clean_sweep_does_not_promote():
|
|
20
|
+
assert not stats.paired_bound([(1.0, 1.0)] * 20).supported
|
|
21
|
+
assert stats.paired_bound([(1.0, 1.0)] * 120).supported
|
|
22
|
+
assert stats.paired_bound([]) is None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _fake(scores, cost):
|
|
26
|
+
it = iter(scores)
|
|
27
|
+
|
|
28
|
+
def chat(messages, **_):
|
|
29
|
+
return SimpleNamespace(text="yes" if next(it) else "no", cost_usd=cost,
|
|
30
|
+
finish_reason="stop")
|
|
31
|
+
return chat
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _cases(n, start=0):
|
|
35
|
+
return [Case(f"c{i}", [{"role": "user", "content": f"q{i}"}], "equals", "yes")
|
|
36
|
+
for i in range(start, start + n)]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_the_best_of_several_must_clear_a_higher_bar(tmp_path):
|
|
40
|
+
cases = _cases(120)
|
|
41
|
+
res = replay.run(cases, _fake([1] * 120, 0.01), _fake([1] * 120, 0.001), cap_usd=10,
|
|
42
|
+
workers=1)
|
|
43
|
+
assert replay.verdict(res, 1)["promoted"]
|
|
44
|
+
assert not replay.verdict(res, 4)["promoted"] # 120 < 163 for best of 4
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_an_unanswered_case_promotes_nothing():
|
|
48
|
+
def broken(messages, **_):
|
|
49
|
+
raise TimeoutError("slow")
|
|
50
|
+
res = replay.run(_cases(120), _fake([1] * 120, 0.01), broken, cap_usd=10, workers=1)
|
|
51
|
+
v = replay.verdict(res)
|
|
52
|
+
assert not v["promoted"] and v["unanswered"] == 120
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_renaming_cases_does_not_reset_the_count_but_fresh_cases_do(tmp_path):
|
|
56
|
+
ledger = tmp_path / "ledger.json"
|
|
57
|
+
assert replay.record_and_count(_cases(150), "b", "m1", ledger) == 1
|
|
58
|
+
renamed = [Case("x" + c.id, c.messages, c.check, c.value) for c in _cases(150)]
|
|
59
|
+
assert replay.record_and_count(renamed, "b", "m2", ledger) == 2
|
|
60
|
+
assert replay.record_and_count(_cases(200, start=1000), "b", "m3", ledger) == 1
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_an_unpriced_endpoint_is_refused():
|
|
64
|
+
with pytest.raises(endpoints.EndpointError, match="price"):
|
|
65
|
+
endpoints.parse({"kind": "bedrock", "region": "us-east-1", "model": "m", "api_key": "k"})
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_fit_reports_ready_or_not(tmp_path, capsys):
|
|
69
|
+
f = tmp_path / "cases.jsonl"
|
|
70
|
+
f.write_text("\n".join(json.dumps({"input": f"q{i}", "expected": "yes"}) for i in range(50)))
|
|
71
|
+
assert cli.main(["fit", str(f)]) == 2
|
|
72
|
+
out = json.loads(capsys.readouterr().out)
|
|
73
|
+
assert out["graded"] == 50 and out["needed"] == 111 and not out["ready"]
|