Train a WEPR detector from an endpoint alone: generate, judge, fit#
You start with an endpoint and nothing else. This notebook builds the whole training set
for the model that endpoint serves — it asks your questions, keeps the top_logprobs
behind each response, has a judge grade them — then fits a WEPR detector and saves it.
A detector is trained for one generator model, on answers that model produced plus a verdict on each from a judge, which should be a different model: a model that grades its own answers teaches the detector its own self-agreement rather than its hallucinations. The wider context is in the guide’s Training a detector.
Four sections. The first costs no requests and is still the expensive one: a gold answer per question is written by someone. The two that do spend requests write their results to disk, so a refit never pays for them twice.
Needs / cost: an endpoint that returns top_logprobs and its key (see Prerequisites); N generation requests and N judge requests, written to disk so a refit never pays twice. The fit itself takes seconds.
Section |
What it does |
Cost |
|---|---|---|
Bring the questions |
Your questions, each with a gold answer |
the work: writing the gold answers |
Generate the responses |
One request each, keeping |
N requests to |
Judge the responses |
One request each, against the gold answer |
N requests to |
Fit and evaluate |
Fit, evaluate, save |
seconds |
Both written files are the OpenAI Batch output shape — one JSON object per line wrapping
a completion under custom_id — which is what the Batch API returns and what
scripts/train_detector.py reads, so nothing downstream needs a conversion.
Prerequisites#
Variable |
What it is |
|---|---|
|
Any OpenAI-compatible endpoint returning |
|
Its key |
|
The model being scored — the detector belongs to it, and the id has to be one your endpoint serves |
|
Optional. The endpoint that grades the answers; defaults to |
|
Optional. Its key; defaults to |
|
Optional. The model that grades; defaults to |
Generation and judging are two different jobs and this notebook keeps them apart. The
generator must return top_logprobs, which usually means a self-hosted endpoint; the judge
only has to follow the reply format, and reads no log-probabilities at all. Leave the
JUDGE_* variables unset and both run against the same endpoint, which is the cheapest
setup and the one whose labels are worth doubting: a model that is confidently wrong grades
its own wrong answer as correct, and that verdict becomes the training label.
The endpoint must return at least K candidates per token. top_logprobs is commonly capped at
20, so K = 15 fits; an endpoint that caps lower is refused by name when the responses are
generated, rather than training on narrower data.
This notebook is not executed when the documentation is built, so the numbers you see are the ones your own run produces.
Configuration#
Every knob in one place. MODEL has no default: a model id only means something to the
endpoint serving it, and a wrong one fails on every generation request rather than here.
K is how many candidates per token the endpoint is asked for (candidate and rank are
defined in How it works). The rule for K is in Using a detector.
import getpass
import json
import os
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from jinja2 import Template
# No default: a model id only means something to the endpoint serving it.
MODEL = os.environ["OPENAI_MODEL"]
# The OpenAI client reads its key from the environment.
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("OPENAI_API_KEY: ")
# The judge is a second model. The verdict becomes the label -- `y = int(not verdict)` --
# and a model grading its own answers would correlate the label with its own confidence.
# The generator has to serve `top_logprobs`; the judge needs no log-probabilities. Each
# JUDGE_* falls back to its generator counterpart, so a single-endpoint run works with
# nothing new set.
JUDGE_MODEL = os.environ.get("JUDGE_MODEL", MODEL)
JUDGE_BASE_URL = os.environ.get("JUDGE_BASE_URL", os.environ.get("OPENAI_BASE_URL"))
JUDGE_API_KEY = os.environ.get("JUDGE_API_KEY", os.environ["OPENAI_API_KEY"])
# Candidates kept per token -- the tokens the model considered, most likely first, one per
# rank. Part of the feature definition, not a batch size: WEPR fits one coefficient per
# rank, so a detector is only ever used at the k it was fitted at. Every
# published detector uses 15.
K = 15
# The API caps it at 20, and an endpoint asked for more rejects every generation request --
# which arrives as "no answers were generated" three cells later, pointing at the wrong
# thing.
assert 1 <= K <= 20, "top_logprobs must be between 1 and 20"
SEED = 42
WORKERS = 8
RESPONSES = Path("responses.jsonl")
JUDGMENTS = Path("judgments.jsonl")
Both prompts are the paper’s, rendered with jinja as the originals are: the reply format
the judge demands is itself a JSON object, and jinja passes a bare { through where
str.format would read it as a field, as it would a question containing one. The judge
prompt is long; the cell below is collapsed, and the Judge the responses section prints it
rendered against a real answer, which is the form worth reading.
The two request helpers#
Both request sections do the same two things: one chat completion per item, and a file of
replies written as they arrive. ask and run below are that shape, factored out so the
cells that use them show the request being made and nothing else.
run writes each reply the moment it lands rather than after the pool finishes. ask
returns the API’s failures instead of raising them, but the SDK does not wrap every
transport pathology — a 502 whose HTML body arrives under a JSON content type raises
JSONDecodeError inside the worker — and that would come out of pool.map and discard
every reply already paid for. Writing as they arrive means the file holds what was produced
up to the failure.
Both files it writes are the OpenAI Batch output shape, so scripts/train_detector.py
reads them without knowing what produced them — this notebook, a Batch job, or an offline
runner.
Bring the questions#
This is the cell to replace. questions_sample.json sits beside this notebook: a
hundred rows, half TriviaQA and half SimpleQA, there so the notebook runs end to end out of the
box. The detector
you actually want is trained on the questions your users ask, because it learns how your
model behaves on the traffic it will meet. The paper measured that gap: its numbers drop
10-20 points when a TriviaQA-trained detector is pointed at WebQuestions.
Two fields per question, plus two optional ones: question is asked, short_answer is what
a correct response has to agree with, answer_aliases lists other wordings the judge should
also accept, and question_id names the row if the file already carries one.
Two properties decide whether a question set works. Responses must be short enough for a judge to grade, and the model must get enough of them wrong that both classes appear. A hundred is the working size; at twenty-five a capable model often gets nothing wrong, and the run spends the requests before refusing to fit.
For a set at the paper’s scale, scripts/ecir/build_questions.sh draws one from the Hub in
these same fields – ./build_questions.sh mixed 100 > questions.json rebuilds the pack that
ships here (mixed takes an even count and splits it between the two sets), triviaqa 500 or
simpleqa 500 draw a single set, and webquestions gives the out-of-domain set – and QUESTIONS_FILE below becomes Path("questions.json").
question_id is what travels: it becomes custom_id on the responses and the verdicts, and
that is what every later join pairs on. A duplicate would pair an answer with another
question’s gold answer – a wrong label rather than an error – so a file that names its own
rows is checked for collisions, and a file that does not gets ids from position, which
cannot collide.
QUESTIONS_FILE = Path("questions_sample.json")
questions = [
{
"question_id": entry.get("question_id") or f"q{position:03d}",
"question": entry["question"],
"short_answer": entry["short_answer"],
"answer_aliases": entry.get("answer_aliases") or [],
}
for position, entry in enumerate(json.loads(QUESTIONS_FILE.read_text(encoding="utf-8")))
]
repeated = [qid for qid, seen in Counter(q["question_id"] for q in questions).items() if seen > 1]
assert not repeated, (
f"{len(repeated)} question_id(s) appear more than once, e.g. {repeated[0]!r}. Every "
f"later join pairs on this id, so a duplicate would grade one answer against another question."
)
incomplete = [q for q in questions if not q["question"] or not q["short_answer"]]
assert not incomplete, (
f"{len(incomplete)} question(s) are missing `question` or `short_answer`, e.g. "
f"{incomplete[0]}. Both are needed: one is asked, the other is what the judge grades against."
)
print(f"{len(questions)} questions")
print(json.dumps(questions[0], indent=2, ensure_ascii=False))
Generate the responses, keeping the log-probabilities#
One request per question, WORKERS at a time, with logprobs=True and top_logprobs=K.
That distribution is the entire input to the detector; the response text is only ever read
to judge it.
run writes responses.jsonl as the replies arrive; generate only says what to ask for.
The sampling parameters are the paper’s.
The cell after it runs LogProbParser over what came back. That is the pipeline’s own first
step, and it is where an endpoint that accepted logprobs=True and ignored it, or that
capped the candidates below K, is refused by name — before the judge spends another N requests
judging responses that cannot be trained on.
def generate(question):
return ask(
GENERATE.render(query=question["question"]),
logprobs=True,
top_logprobs=K,
temperature=1.0,
top_p=1.0,
# The paper also samples with top_k=50. OpenAI's API has no such parameter, so
# only a self-hosted server can be asked for it, through `extra_body`.
max_completion_tokens=200,
)
generated = run(generate, [(question["question_id"], question) for question in questions], RESPONSES)
ok = [(q, r) for q, r in zip(questions, generated, strict=True) if not isinstance(r, Exception)]
print(f"wrote {RESPONSES}, {len(ok)}/{len(generated)} generated")
for question, result in zip(questions, generated, strict=True):
if isinstance(result, Exception):
print(f" failed: {question['question_id']}: {result}")
from artefactual.preprocessing import LogProbParser
# Nothing came back at all -- almost always OPENAI_BASE_URL, the key, or a model name the
# endpoint does not serve. Checked before indexing, because the errors above say what
# happened and a bare IndexError here would not.
assert ok, (
"no responses were generated. Check OPENAI_BASE_URL, OPENAI_API_KEY and OPENAI_MODEL -- "
"the generator's three, not the JUDGE_* ones, which are not used until the next section, "
"and read the per-request errors above: an endpoint that rejects `top_logprobs`, "
"`temperature` or `max_completion_tokens` fails every request the same way."
)
# The pipeline's own first step. It owns the rank axis, so it refuses a response carrying no
# log-probabilities or fewer than K candidates on any token, and says which, by name.
logprobs = LogProbParser(k=K).transform([completion for _, completion in ok])
logprobs.shape
Judge the responses#
A second request per response, at temperature=0, asking the model to compare what it said
against the gold answer and reply with {"judgment": true|false, "explanation": "..."}.
The reply is written to disk whole, so each verdict keeps the sentence explaining it.
read_judgment turns that reply into the label. Judges wrap the object in prose or a
Markdown fence often enough that a bare json.loads is unsafe, and a stringified "false"
must not be taken for a verdict — bool("false") is True, which would mark every wrong
response correct.
The class balance is printed with the count. All-correct means the questions were too easy for this model, all-wrong usually means it is not answering in the short form the judge expects.
from artefactual.preprocessing import read_judgment
def judge(pair):
"""The judge's reply, kept whole: the verdict is derived from it, not instead of it."""
question, completion = pair
return ask(
render_judge(question, completion),
api=judge_client,
model=JUDGE_MODEL,
temperature=0,
max_completion_tokens=200,
)
verdicts = run(judge, [(question["question_id"], (question, completion)) for question, completion in ok], JUDGMENTS)
# `read_judgment` returns True when the judge said the response was CORRECT, the opposite of
# the class the detector predicts, so the label is its negation. It reads the fenced and
# prose-wrapped replies a model actually returns, and answers None for a reply -- or a failed
# request -- carrying no verdict at all.
judgments = [
(question, completion, int(not verdict))
for (question, completion), reply in zip(ok, verdicts, strict=True)
if not isinstance(reply, Exception) and (verdict := read_judgment(reply)) is not None
]
assert judgments, (
"no verdict could be read from any reply. The judge answers in JSON; a model that "
"cannot hold that format needs a different one, or a larger max_completion_tokens."
)
dropped = len(verdicts) - len(judgments)
hallucinated = sum(flag for _, _, flag in judgments)
print(f"wrote {JUDGMENTS}, {len(verdicts)} replies" + (f", {dropped} failed or unreadable" if dropped else ""))
print(f" {len(judgments)} labelled, {hallucinated} hallucinations ({hallucinated / len(judgments):.0%})")
# A reply cut off at `max_completion_tokens` is invalid JSON, so it lands in `dropped` with
# nothing saying why. The judge answers in JSON *and* explains itself, so this is the cap
# that runs out first.
truncated = sum(1 for v in verdicts if not isinstance(v, Exception) and v.choices[0].finish_reason == "length")
if truncated:
print(f" {truncated} reply(ies) hit max_completion_tokens; raise it and rerun this cell")
for question, completion, flag in judgments[:2]:
said = (completion.choices[0].message.content or "").strip()
print(f" [{'hallucination' if flag else 'grounded'}] said {said[:40]!r} (gold: {question['short_answer']!r})")
Fit and evaluate#
This step reads the two files back rather than using what is still in memory, so a refit at
another k costs no requests. read_batch is the reader, so a file written by anything
else parses the same way.
make_detector(k=K) is the unfitted pipeline, which takes the batch lines directly: the
parser opens the envelope itself, so there is no feature extraction to write.
ROC-AUC scores the ranking — whether hallucinations sort above grounded responses —
which is what matters if you triage by score. The classification report scores the
decisions at a 0.5 cut, where recall on the hallucination row is the fraction actually
caught. Only the AUC carries over to another threshold, so pick one from the held-out scores
rather than assuming 0.5.
import numpy as np
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.model_selection import train_test_split
from artefactual import WEPR, LogProbParser, make_detector
from artefactual.preprocessing import index_by_custom_id, read_batch, read_judgment, read_message
# Read back from disk, as a fresh kernel would. `read_batch` validates
# each line and refuses a repeated `custom_id`, which would pair a response with another
# question's verdict.
generated = index_by_custom_id(read_batch(RESPONSES))
labelled = [
(generated[row.custom_id], int(not verdict))
for row in read_batch(JUDGMENTS)
if row.custom_id in generated and (verdict := read_judgment(row.completion)) is not None
]
responses = [row for row, _ in labelled]
y = np.array([label for _, label in labelled])
print(f"read {len(responses)} labelled responses back from {RESPONSES.name} and {JUDGMENTS.name}")
x_train, x_test, y_train, y_test = train_test_split(responses, y, test_size=0.25, stratify=y, random_state=SEED)
detector = make_detector(k=K).fit(x_train, y_train)
print(f"fitted on {len(y_train)}, holding out {len(y_test)}")
scores = detector.predict_proba(x_test)[:, 1]
print(f"\nROC-AUC: {roc_auc_score(y_test, scores):.2f}")
print(classification_report(y_test, scores >= 0.5, target_names=["grounded", "hallucination"], zero_division=0))
Audit the labels the judge produced#
A detector fitted on mislabelled rows inherits them. The judge says whether the answer
matches the gold one; the label is the negation of that, so a mismatch is hallucination,
the class the detector is fitted to predict. Both columns below are on that axis.
cross_val_predict gives every response a score from a fold that did not contain it. The
rows where the detector is most confident and disagrees with the label are the ones to read
first, printed with the question, the gold answer and the judge’s own explanation.
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from artefactual.preprocessing import Judgment
# What each verdict was made against, and the sentence the judge gave for it.
asked = {question["question_id"]: question for question in questions}
judged = read_batch(JUDGMENTS)
explanations = {
row.custom_id: judgment.explanation
for row, judgment in zip(judged, Judgment.from_batch(judged), strict=True)
if judgment is not None
}
folds = StratifiedKFold(5, shuffle=True, random_state=SEED)
# Out-of-fold: every score comes from a detector that never saw that response.
out_of_fold = cross_val_predict(make_detector(k=K), responses, y, cv=folds, method="predict_proba")[:, 1]
scored = zip(out_of_fold, y, responses, strict=True)
disagreements = sorted(scored, key=lambda row: abs(row[0] - row[1]), reverse=True)[:5]
print("the five rows the detector disagrees with the label about most:\n")
for score, label, row in disagreements:
question = asked[row.custom_id]
# `label` is the judge's verdict already negated, so both columns say hallucination.
print(f" labelled {'hallucination' if label else 'grounded'}, detector P(hallucination)={score:.3f}")
print(f" Q {question['question']}")
print(f" said {(read_message(row.completion) or '').strip()!r}")
print(f" gold {question['short_answer']!r}")
print(f" why {explanations.get(row.custom_id, '')!r}\n")
Save it, and load it back#
.skops rather than a pickle. from_pretrained takes a .skops file, a directory holding
model.skops, or a Hugging Face repository id — the shipped detectors are loaded that
way, and yours is too once you push its model.skops to a repository of your own.
The width is part of the weights, not a runtime option: the coefficients were fitted at one rank
count and mean nothing at another, so scoring arrays of a different k raises rather than
mis-shaping the score.
path = detector[-1].save_pretrained("wepr-generated.skops")
reloaded = WEPR.from_pretrained(path)
parser = LogProbParser(k=K)
# Held-out responses: the rows the fit above never saw.
for row, label in list(zip(x_test, y_test, strict=True))[:5]:
said = (read_message(row.completion) or "")[:40]
print(
f"[{'hallucination' if label else 'grounded '}] P={reloaded.predict_proba(parser.transform(row))[0, 1]:.3f} {said!r}"
)
Where to go next#
Refit without regenerating. The two files are the expensive part: a different
k,eprinstead ofwepr, or relabelled verdicts all reuse them, and none of it costs another request.Feed the CLI instead. This run’s two Batch files go straight into the
train_detector.pyscript in the repository, which also reports the bootstrap confidence intervals the fit above does not — worth having, because a holdout this size cannot pin a score down on its own.More questions. The generation is the cost and the fit is seconds, so point
QUESTIONS_FILEat a longer set rather than economising on labels.At thousands of questions, stop making one request per response. Batch submission takes a JSONL of requests and returns the JSONL these files already are, at roughly half the price: OpenAI’s Batch API if your provider hosts one, or an offline batch runner against a self-hosted server. Only the two generating cells change – what they write, and everything after them, stays as it is.
Your own questions. Only the questions cell changes, and it is a list. Training data should resemble the traffic being scored: the paper’s numbers drop 10-20 points when a TriviaQA-trained detector meets WebQuestions.