Repository navigation
Expand file tree
/
Copy pathoff_on.py
More file actions
317 lines (283 loc) · 15.5 KB
/
Copy pathoff_on.py
File metadata and controls
317 lines (283 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""Verifier OFF vs ON — the project's headline experiment (design.md).
Every other number this benchmark reports is a *level*, and a level is explainable by the
corpus, the model, the question set, or the grader — the grader prompt alone moved 18 of
40 grades once, with no change to the agent. A delta measured with everything else held
constant is the only causal claim available, which is why this is the Week 2 gate.
The experiment: identical questions, corpus, prompts, grader and retrieval mode. The only
difference is `VERIFIER_ENABLED`, which decides whether the Gate ever sees a confidence
score and therefore whether it can force a retry or escalate. What we are measuring is
whether that intervention changes how faithful the shipped answer is.
## The measurement trap this file exists to avoid
With the verifier off, nothing is checked at runtime, so that arm's citations carry no
verdicts. The obvious move — reuse the ON arm's runtime verdicts and post-hoc only the OFF
arm — is wrong. Any difference in *how* the two arms were checked then shows up as an
intervention effect that is really a measurement artefact.
So neither arm's runtime verdicts are used. Both are re-verified here, offline, by the
same code path, with the same claim/mention partition and the same misattribution rule.
Judge calls are cached on (claim, source), so re-checking the ON arm is mostly free.
Usage: uv run python -m bench.off_on --off <results.json> --on <results.json>
"""
import argparse
import json
from pathlib import Path
from typing import Any
from agent.nodes.verifier import SWEEP_CANDIDATES
from agent.nodes.verifier import claim_context as verifier_claim_context
from app.concurrency import map_parallel
from app.db import connect
from app.settings import get_settings
from verify.claims import is_substantive_claim
from verify.grounding import check as grounding_check
from verify.judge import get_judge
from verify.verdict import verify_citation
def claim_context(answer: str, claim: str) -> str | None:
"""The sentence a claim was lifted from, found by locating it in the answer.
`agent/nodes/verifier.py` does this from the citation's stored offsets. Results files
keep only {claim, chunk_id}, so here the claim is located by search — which is exactly
as good whenever the claim appears once, and declines to guess when it does not.
"""
if not answer or not claim.strip():
return None
start = answer.find(claim)
if start < 0 or answer.find(claim, start + 1) >= 0:
# Absent, or ambiguous: several occurrences mean several possible subjects, and a
# wrong one is worse than none.
return None
return verifier_claim_context(answer, start, start + len(claim))
def chunk_texts(chunk_ids: list[int]) -> dict[int, tuple[str, str]]:
"""chunk_id -> (source_id, title + text). Read straight from the corpus.
The results files store `chunk_id` on every citation, so the source a claim pointed at
is recoverable without re-running retrieval — which also means the OFF arm can be
checked against exactly what it cited, not an approximation of it.
"""
if not chunk_ids:
return {}
with connect() as conn:
rows = conn.execute(
"""SELECT c.id, p.source || ':' || p.external_id, p.title, c.text
FROM chunks c JOIN papers p ON p.id = c.paper_id WHERE c.id = ANY(%s)""",
(chunk_ids,),
).fetchall()
return {int(cid): (src, f"{title}\n\n{text}") for cid, src, title, text in rows}
def paper_texts(source_ids: list[str], visible: set[int] | None = None) -> dict[str, list[str]]:
"""source_id -> the chunks of that paper the model was actually shown.
`visible` is the run's retrieved chunk ids. Without it this returned every chunk of the
paper in the database, including paragraphs never retrieved — so a claim the model
produced from its own training could match something it was never given and be recorded
as a misfiled citation rather than an unsupported one.
Misattribution has to mean the evidence was in the context and the citation pointed at
the wrong part of it. A claim true only in the world is still one the reader cannot
check from what they were shown, and filing it under citation hygiene understates it.
`None` means the results file predates `retrieved_chunk_ids` and cannot support the
distinction; the caller warns rather than silently reverting to the looser rule.
"""
if not source_ids:
return {}
with connect() as conn:
rows = conn.execute(
"""SELECT p.source || ':' || p.external_id, c.id, p.title, c.text
FROM chunks c JOIN papers p ON p.id = c.paper_id
WHERE p.source || ':' || p.external_id = ANY(%s)""",
(source_ids,),
).fetchall()
out: dict[str, list[str]] = {}
for src, chunk_id, title, text in rows:
if visible is not None and int(chunk_id) not in visible:
continue
out.setdefault(src, []).append(f"{title}\n\n{text}")
return out
def verify_arm(records: list[dict[str, Any]], label: str) -> dict[str, Any]:
"""Re-check every citation in an arm, identically to the other arm."""
# Each claim carries the answer it came from, so the sentence the span was lifted out of
# is recoverable here. Without it this re-check judges bare fragments — "70 billion
# parameters per token." with no subject — and the judge supplies one from the source's
# topic and refutes its own invention. The runtime verifier was fixed for that; this file
# produces the number the README quotes and was still running the unfixed call.
#
# Recovered by searching the answer text rather than by stored offsets, because the
# harness records only {claim, chunk_id}. Recovering it means every already-committed
# run can be re-checked correctly, not just runs from here on.
citations = [
(r["id"], c, claim_context(r.get("answer") or "", c["claim"]))
for r in records
for c in (r.get("citations") or [])
if is_substantive_claim(c["claim"])
]
sources = chunk_texts(sorted({c["chunk_id"] for _, c, _ in citations}))
# Restricted to what each run actually retrieved. Records written before the harness
# stored this cannot make the distinction, and saying so beats quietly using the looser
# rule that inflates misattribution at fabrication's expense.
visible: set[int] | None = set()
for record in records:
retrieved = record.get("retrieved_chunk_ids")
if retrieved is None:
visible = None
break
assert visible is not None
visible.update(int(chunk_id) for chunk_id in retrieved)
if visible is None:
print(
f" {label}: WARNING — this run predates `retrieved_chunk_ids`, so the "
"misattribution sweep searches every chunk of a paper including ones the model "
"was never shown. Misattribution is overstated and fabrication understated.",
flush=True,
)
papers = paper_texts(sorted({src for src, _ in sources.values()}), visible)
def check(item: tuple[str, dict[str, Any], str | None]) -> dict[str, Any]:
_, citation, context = item
source = sources.get(citation["chunk_id"])
if source is None:
return {"verdict": "unsupported", "misattributed": False}
result = verify_citation(citation["claim"], source[1], context)
misattributed = False
if result.judge.verdict == "unsupported":
# Supported somewhere else in the same paper: a misfiled reference rather than
# an invented fact. Deterministic and free, and it must be applied to both arms
# or the delta measures the rule instead of the intervention.
# Lexical shortlists, the judge decides — identical to the runtime sweep in
# agent/nodes/verifier.py. Requiring a lexical "supported" here missed claims
# the paper states in wording the lexical check only scores `partial`, and
# counted them as fabrications. Both arms go through this same code, so the
# rule cannot differ between them.
scored = sorted(
(
(grounding_check(citation["claim"], other).score, other)
for other in papers.get(source[0], [])
if other != source[1]
and grounding_check(citation["claim"], other).verdict
in ("supported", "partial")
),
key=lambda pair: -pair[0],
)
misattributed = any(
get_judge().judge(citation["claim"], other, context).verdict == "supported"
for _, other in scored[:SWEEP_CANDIDATES]
)
return {"verdict": result.judge.verdict, "misattributed": misattributed}
print(f" {label}: re-checking {len(citations)} substantive claims", flush=True)
verdicts = map_parallel(check, citations, max_workers=get_settings().max_parallel_requests)
# The same numbers again, one row per distinct claim rather than per citation.
#
# The headline rate pools over citations, so a claim the model attached to four chunks
# of one paper counts four times. Measured on the slice, that alone turned six
# fabricated claims into eleven fabricated citations — and it means the headline delta
# is only an intervention effect if the two arms attach citations at the same rate.
# Reported beside the per-citation rate rather than replacing it: "how many of the
# agent's claims were invented" and "how many of its citations do not hold up" are both
# worth knowing, and they are not the same question.
#
# A claim counts as fabricated when nothing backs it: no citation came back
# `supported`, and it was not found elsewhere in the paper either. If one of four
# citations holds, the agent did not invent the claim — it attached three references
# sloppily, which is what misattribution already measures.
#
# Note which way each metric leans, because neither is neutral. The per-citation rate
# punishes the arm that cites more; this one rewards it, since more citations mean more
# chances that one holds. The two therefore bracket the truth rather than either being
# the answer, and both are reported.
by_claim: dict[tuple[str, str], list[dict[str, Any]]] = {}
for (question_id, citation, _), verdict in zip(citations, verdicts, strict=True):
by_claim.setdefault((question_id, citation["claim"].strip().lower()), []).append(verdict)
claims = len(by_claim)
unbacked = {
key
for key, vs in by_claim.items()
if not any(v["verdict"] == "supported" or v["misattributed"] for v in vs)
}
fabricated_claims = len(unbacked)
# The same count restricted to answers the Gate passed — what a user is actually shown
# as confident. An escalated answer is handed over flagged, with its unsupported claims
# named, so counting those as fabrications scores the system's correct behaviour as a
# failure. Measured: 3 of the on arm's 5 unbacked claims sit in one escalated answer,
# so the unrestricted number says verification made fabrication worse when what
# happened is that the Gate caught a bad revision and refused to stand behind it.
escalated_ids = {r["id"] for r in records if r["gate_decision"] == "escalate"}
presented = {key for key in by_claim if key[0] not in escalated_ids}
fabricated_presented = len(unbacked & presented)
checked = len(verdicts)
fabricated = sum(
1 for v in verdicts if v["verdict"] == "unsupported" and not v["misattributed"]
)
misattributed = sum(1 for v in verdicts if v["misattributed"])
partial = sum(1 for v in verdicts if v["verdict"] == "partial")
grades = [r["grade"] for r in records if r.get("answerable", True)]
return {
"questions": len(records),
"claims_checked": checked,
"fabricated": fabricated,
"misattributed": misattributed,
"partial": partial,
"hallucinated_citation_rate": round(fabricated / checked, 4) if checked else None,
"distinct_claims": claims,
"citations_per_claim": round(checked / claims, 3) if claims else None,
"fabricated_claims": fabricated_claims,
"fabricated_claim_rate": round(fabricated_claims / claims, 4) if claims else None,
"claims_presented": len(presented),
"fabricated_claims_presented": fabricated_presented,
"fabricated_claim_rate_presented": round(fabricated_presented / len(presented), 4)
if presented
else None,
"misattribution_rate": round(misattributed / checked, 4) if checked else None,
"accuracy": round(grades.count("correct") / len(grades), 4) if grades else None,
"incorrect_rate": round(grades.count("incorrect") / len(grades), 4) if grades else None,
"escalated": sum(1 for r in records if r["gate_decision"] == "escalate"),
"retries": sum(1 for r in records if r["gate_attempts"] > 0),
}
def main() -> None:
parser = argparse.ArgumentParser(prog="off-on")
parser.add_argument("--off", required=True)
parser.add_argument("--on", required=True)
parser.add_argument("--out", default="bench/results/verifier-off-on.json")
args = parser.parse_args()
off = json.loads(Path(args.off).read_text())
on = json.loads(Path(args.on).read_text())
shared = sorted({r["id"] for r in off["records"]} & {r["id"] for r in on["records"]})
print(f"{len(shared)} questions answered by both arms\n")
off_records = [r for r in off["records"] if r["id"] in shared]
on_records = [r for r in on["records"] if r["id"] in shared]
result = {
"questions": len(shared),
"off_run": off["bench_run_id"],
"on_run": on["bench_run_id"],
"off": verify_arm(off_records, "verifier off"),
"on": verify_arm(on_records, "verifier on "),
}
o, n = result["off"], result["on"]
for key in (
"hallucinated_citation_rate",
"fabricated_claim_rate",
"fabricated_claim_rate_presented",
"misattribution_rate",
"accuracy",
"incorrect_rate",
):
if o[key] is not None and n[key] is not None:
result.setdefault("delta", {})[key] = round(n[key] - o[key], 4)
Path(args.out).write_text(json.dumps(result, indent=2) + "\n")
print(f"\n{'':<28}{'OFF':>10}{'ON':>10}{'delta':>10}")
for key in (
"hallucinated_citation_rate",
"fabricated_claim_rate",
"fabricated_claim_rate_presented",
"misattribution_rate",
"accuracy",
"incorrect_rate",
):
d = result.get("delta", {}).get(key)
print(f" {key:<26}{o[key]!s:>10}{n[key]!s:>10}{d!s:>10}")
print(f" {'claims checked':<26}{o['claims_checked']:>10}{n['claims_checked']:>10}")
print(f" {'distinct claims':<26}{o['distinct_claims']:>10}{n['distinct_claims']:>10}")
print(
f" {'citations per claim':<26}{o['citations_per_claim']:>10}{n['citations_per_claim']:>10}"
)
print(f" {'fabricated claims':<26}{o['fabricated_claims']:>10}{n['fabricated_claims']:>10}")
print(
f" {' of those, presented':<26}"
f"{o['fabricated_claims_presented']:>10}{n['fabricated_claims_presented']:>10}"
f" (excludes escalated answers)"
)
print(f" {'escalated':<26}{o['escalated']:>10}{n['escalated']:>10}")
print(f" {'retries issued':<26}{o['retries']:>10}{n['retries']:>10}")
print(f"\nwritten to {args.out}")
if __name__ == "__main__":
main()