Train a WEPR detector from answers that are already judged#

You start with the whole training set already in hand: answers the model under test generated, and a verdict on each. This notebook turns that pair into a fitted detector.

A detector is trained for one model — it scores how uncertain that model was while it generated — so the responses must come from the model you want to detect hallucinations in, carrying their top_logprobs. The wider context is in the guide’s Training a detector.

It walks that training set through the package end to end: reading the two batch files, running the three pipeline steps by hand, fitting, cross-validating, and saving the result.

The sample files are synthetic: real questions, with the responses and their log-probabilities generated rather than sampled from a model.

Needs / cost: nothing external: no network, no API key, no GPU. Every cell runs on the committed fixtures in seconds.

Section

What it does

Cost

The inputs

Read the two batch files, pair them by custom_id

none, both files ship beside this notebook

The three steps

Parse, entropy, classify, run by hand

seconds

Fit

Fit on a stratified split, report ROC-AUC on the holdout

seconds

What the fit weighs

The fitted coefficient per rank

seconds

How well does this fit generalise?

Five folds over every response

seconds

Which k should this be fitted at?

A grid over k

seconds

Is it worth labelling more answers?

The learning curve

seconds

Choosing the final estimator

Regularise, then tune the threshold

seconds

Per-token scores

Score each token of a held-out answer

seconds

Save it, and load it back

.skops out, from_pretrained in

seconds

Hide code cell source

import subprocess  # ruff: ignore[suspicious-subprocess-import]
import sys
import urllib.request

# Colab starts from a runtime with neither the package nor the files that sit beside
# this notebook in the repository. Everywhere else -- a clone synced with
# `uv sync --group notebooks`, the docs build, the test suite -- both are already there,
# so this cell does nothing and there is nothing for a reader to uncomment.
ON_COLAB = "google.colab" in sys.modules

PACKAGES = [
    "artefactual",
    "matplotlib",
]

FETCH = [
    "https://raw.githubusercontent.com/artefactory/artefactual/main/docs/examples/responses_sample.jsonl",
    "https://raw.githubusercontent.com/artefactory/artefactual/main/docs/examples/judgments_sample.jsonl",
]

if ON_COLAB:
    subprocess.run([sys.executable, "-m", "pip", "install", "-q", *PACKAGES], check=True)  # ruff: ignore[subprocess-without-shell-equals-true]
    for url in FETCH:
        urllib.request.urlretrieve(url, url.rsplit("/", 1)[-1])  # ruff: ignore[suspicious-url-open-usage]

try:
    from myst_nb import glue
except ImportError:
    # Only the documentation build has MyST-NB, and only it renders what `glue` records.
    # Running this notebook anywhere else -- Colab, a clone, the test suite -- must not
    # need a Sphinx extension installed, so the calls below become no-ops.
    def glue(*_args, **_kwargs):
        return None

The inputs#

RESPONSES holds what the model under test generated, one OpenAI Batch line per request, each carrying top_logprobs per token — that distribution is the only thing the detector reads. JUDGMENTS holds a verdict on each of those responses, keyed by the same custom_id, from an LLM judge, a human pass, or matching against a gold answer.

read_batch reads the lines, read_judgment reads the verdict inside one. A failed request carries no completion and failure says why: two of the hundred lines are timeouts, leaving 98 responses. 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.

from pathlib import Path

from artefactual.preprocessing import index_by_custom_id, read_batch, read_judgment, read_message

# Responses generated by the model this detector is being built for, one OpenAI Batch line
# each, carrying `top_logprobs` per token. This is the file to swap for your own run.
RESPONSES = Path("responses_sample.jsonl")
# A verdict on each of those responses, keyed by the same `custom_id`.
JUDGMENTS = Path("judgments_sample.jsonl")
K = 15  # candidates per token; a detector scores the k it was fit at
SEED = 42

# `read_batch` validates each line into `BatchRequestOutput` and refuses a repeated
# `custom_id`, which would otherwise pair a response with another question's verdict.
lines = read_batch(RESPONSES)
for row in lines:
    if row.failure:
        print(f"dropped {row.custom_id}: {row.failure}")

generated = index_by_custom_id(lines)
# `read_judgment` returns True when the judge said the response was CORRECT, the opposite
# of the class the detector predicts.
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]
labels = [label for _, label in labelled]
print(f"{len(generated)} responses, {len(labelled)} judged, {sum(labels)} hallucinations")
dropped dpql_4760: error {'code': 'rate_limit_exceeded', 'message': 'request timed out'}
dropped sq-47: error {'code': 'rate_limit_exceeded', 'message': 'request timed out'}
98 responses, 98 judged, 46 hallucinations

The three steps#

A detector is a scikit-learn Pipeline, and running its steps separately shows what each one contributes.

The endpoint returns, at every token position, the k most likely candidates, each with a rank (see How it works).

LogProbParser turns the batch lines into (responses, tokens, ranks) — it opens the Batch envelope itself, so the lines go in as they were read. The array is NaN-padded, because responses differ in length: here the longest is 4 tokens, and every token carries all 15 ranks.

entropy_contributions converts each log-probability to s_kj = -p·ln(p), same shape, one contribution per candidate. EntropyTransformer then reduces the rank axis: the wepr reduction keeps a mean and a max per rank, so k=15 becomes 30 features per response, one coefficient each for the classifier to weight.

from artefactual import WEPR, LogProbParser, make_detector
from artefactual.scoring import EntropyTransformer, WEPRPooling

logprobs = LogProbParser(k=K).transform(responses)  # (responses, tokens, ranks), NaN-padded
s_kj = EntropyTransformer.entropy_contributions(logprobs)  # -p*ln(p) per candidate, peaking at p=1/e
features = EntropyTransformer(pooling=WEPRPooling()).transform(logprobs)

logprobs.shape, s_kj.shape, features.shape
((98, 4, 15), (98, 4, 15), (98, 30))

Fit#

make_detector(k=K) is the pipeline unfitted, so fit takes the batch lines directly and there is no feature extraction to write. The split is stratified and happens first, so what is reported describes responses the detector never saw.

ROC-AUC scores the ranking: whether hallucinations sort above grounded answers. The classification report scores the decisions at a 0.5 cut, where recall on the hallucination row is the fraction caught and precision is how many of the flags were right. Only the AUC carries over to a different threshold.

import numpy as np
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.model_selection import train_test_split

y = np.array(labels)
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)
scores = detector.predict_proba(x_test)[:, 1]

# Glued, so the paragraph below quotes this run's value.
glue("auc", roc_auc_score(y_test, scores), display=False)
glue("held_out", len(y_test), display=False)

print(f"fitted on {len(y_train)}, holding out {len(y_test)}")
print(f"ROC-AUC: {roc_auc_score(y_test, scores):.2f}\n")
print(classification_report(y_test, scores >= 0.5, target_names=["grounded", "hallucination"], zero_division=0))
fitted on 73, holding out 25
ROC-AUC: 1.00

               precision    recall  f1-score   support

     grounded       1.00      1.00      1.00        13
hallucination       1.00      1.00      1.00        12

     accuracy                           1.00        25
    macro avg       1.00      1.00      1.00        25
 weighted avg       1.00      1.00      1.00        25

On the 25 held-out responses this fit reaches a ROC-AUC of 1.00. The sample is synthetic and small, so read it as the shape of the workflow rather than as a result.

What the fit weighs#

A fitted make_detector pipeline slices. detector[0] is the parser and detector[-1] the WEPR classifier, whose pipeline_ holds the entropy step and the logistic regression. The entropy step on the parser’s output produces exactly the features the three steps above built by hand.

detector[-1].pipeline_[-1] is the logistic regression, and its 30 coefficients are 2k: a weight per rank for the mean of the entropy contributions, and a weight per rank for the max. Plotted against the rank, they say which part of the distribution this detector reads — weight lands across the whole axis rather than on rank 0. The magnitudes are large because the default classifier is unregularised; Choosing the final estimator is about that.

Hide code cell source

import matplotlib.pyplot as plt

# The by-hand steps and the pipeline compute the same features.
assert np.allclose(detector[-1].pipeline_[:-1].transform(detector[0].transform(responses)), features, equal_nan=True)

mean_weights, max_weights = detector[-1].pipeline_[-1].coef_[0].reshape(2, K)
ranks = np.arange(K)

axes = plt.subplot()
axes.bar(ranks - 0.2, mean_weights, width=0.4, label="mean over ranks")
axes.bar(ranks + 0.2, max_weights, width=0.4, label="max over ranks")
axes.set(xlabel="rank", ylabel="coefficient")
axes.legend()
# Returns None, so the figure is the cell's only output -- an object repr above it is noise.
axes.grid(axis="y", linewidth=0.3)
../_images/6bcf3a38b1320e3d12c0f1c9df172c1968c9c05890017a45b86fb7be9adb31a6.png

How well does this fit generalise?#

Every sklearn.model_selection tool works on the detector, so the holdout above is not the only reading available. Five folds over all 98 responses report a spread as well as a mean, so the holdout score above can be read against it: a single 25-answer split can sit well inside that spread or outside it, which is what one split this small is worth.

from sklearn.model_selection import StratifiedKFold, cross_val_score

folds = StratifiedKFold(5, shuffle=True, random_state=SEED)

auc = cross_val_score(make_detector(k=K), responses, y, cv=folds, scoring="roc_auc")
print(f"5-fold ROC-AUC: {auc.mean():.2f} +/- {auc.std():.2f}   {np.round(auc, 2)}")
5-fold ROC-AUC: 1.00 +/- 0.00   [1. 1. 1. 1. 1.]

Which k should this be fitted at? (advanced)#

Tuning needs a pipeline, so this section uses make_pipeline: LogProbParser’s k is searchable as logprobparser__k, and the pipeline is refitted at each width, so the comparison is legitimate. Tune a detector you train, never a published one: its weights are frozen. Read the scores across k before choosing: a score that keeps rising with k says the signal lives in the deeper ranks, not just the top one, while one that flattens early says the extra ranks add little.

This search chooses the k to fit at. It is not a knob to turn afterwards: WEPR fits one coefficient per rank, so a detector’s coefficients are the width it was trained at, and it refuses any other. Search once, fit at the winner, and load at that same value forever after. Every published detector was fitted at 15.

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline

search = GridSearchCV(
    make_pipeline(LogProbParser(), WEPR(estimator=LogisticRegression())),
    {"logprobparser__k": [5, 10, 15]},
    cv=folds,
    scoring="roc_auc",
)
search.fit(responses, y)
for k, mean in zip(search.cv_results_["param_logprobparser__k"], search.cv_results_["mean_test_score"], strict=True):
    print(f"  k={k:>2}: {mean:.2f}")
  k= 5: 1.00
  k=10: 1.00
  k=15: 1.00

Is it worth labelling more answers?#

LearningCurveDisplay answers the question that decides that: the 5-fold AUC at 20, 40, 60, 80 and 98 responses. A curve still climbing at the right edge says more labels are worth buying; one that has flattened says the next hundred buy nothing.

Hide code cell source

from sklearn.model_selection import LearningCurveDisplay

learning_curve = LearningCurveDisplay.from_estimator(
    make_detector(k=K),
    responses,
    y,
    cv=folds,
    scoring="roc_auc",
    train_sizes=np.linspace(0.2, 1.0, 5),
    score_name="ROC-AUC",
    std_display_style="fill_between",
)
../_images/f74c784e6c97e65ebf593eeb205e1146010b066d977487f586238aeda1440ddd.png

Choosing the final estimator#

estimator= takes any scikit-learn estimator. The default is the unregularised logistic regression the shipped detectors were fitted with, and on data this separable it saturates: almost every score lands on 0 or 1, which leaves a precision-recall curve with almost no points on it and no threshold to choose between.

Regularising is one keyword, and it spreads the scores back out — same features, same split, a curve you can actually pick an operating point from. PrecisionRecallDisplay draws both on one axes, where the saturation is the shape of the curve rather than a count of thresholds.

Then pick the threshold with TunedThresholdClassifierCV: it cross-validates the cut on the training set alone, so the operating point is not chosen on the rows it is then reported against. It wraps the detector, so predict uses the tuned cut while predict_proba still returns the detector’s own scores. The threshold is a number, not part of the .skops weights — it travels with the detector, not inside it.

Hide code cell source

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import PrecisionRecallDisplay, precision_recall_curve

parser = LogProbParser(k=K)
train_logprobs, test_logprobs = parser.transform(x_train), parser.transform(x_test)

curves = None
for label, estimator in (("C=inf (default)", None), ("C=1.0", LogisticRegression(C=1.0, max_iter=1000))):
    fitted = WEPR(estimator=estimator).fit(train_logprobs, y_train)
    probabilities = fitted.predict_proba(test_logprobs)[:, 1]
    decided = np.mean((probabilities < 0.01) | (probabilities > 0.99))
    thresholds = precision_recall_curve(y_test, probabilities)[2]
    print(
        f"{label:>15}: AUC {roc_auc_score(y_test, probabilities):.2f}, "
        f"{decided:.0%} of scores at the rails, {len(thresholds)} distinct thresholds"
    )
    # The first call makes the axes, the second draws onto it: `curves.ax_` is how a
    # Display hands its axes to the next one, with no figure to manage by hand.
    curves = PrecisionRecallDisplay.from_predictions(
        y_test, probabilities, name=label, ax=None if curves is None else curves.ax_
    )
C=inf (default): AUC 1.00, 100% of scores at the rails, 25 distinct thresholds
          C=1.0: AUC 1.00, 0% of scores at the rails, 25 distinct thresholds
../_images/189f58c9fa3810276a5d60485bb3610fc9b85f4c21b93ab22cc6e915cf99ff9c.png
from sklearn.model_selection import TunedThresholdClassifierCV

# Tuned on the training rows only, by cross-validation, and reported on the held-out ones.
tuned = TunedThresholdClassifierCV(
    WEPR(estimator=LogisticRegression(C=1.0, max_iter=1000)),
    scoring="f1",
    cv=folds,
).fit(train_logprobs, y_train)

print(f"threshold {tuned.best_threshold_:.2f} rather than 0.5, {tuned.best_score_:.2f} F1 in cross-validation")
print(
    classification_report(
        y_test, tuned.predict(test_logprobs), target_names=["grounded", "hallucination"], zero_division=0
    )
)
threshold 0.39 rather than 0.5, 1.00 F1 in cross-validation
               precision    recall  f1-score   support

     grounded       1.00      1.00      1.00        13
hallucination       1.00      1.00      1.00        12

     accuracy                           1.00        25
    macro avg       1.00      1.00      1.00        25
 weighted avg       1.00      1.00      1.00        25

Per-token scores#

predict_token_proba scores every token position instead of pooling the response into one number, which locates where a response drifts. Padded positions stay NaN rather than being scored as real tokens.

These sample responses are at most four tokens long, so there is little to see.

Hide code cell source

per_token = detector[-1].predict_token_proba(detector[0].transform(x_test[:3]))  # (responses, tokens, 1)

for row, scores_per_token in zip(x_test[:3], per_token, strict=True):
    tokens = [t["token"] for t in row.completion["choices"][0]["logprobs"]["content"]]
    scored = " ".join(f"{token.strip()}={score:.2f}" for token, (score,) in zip(tokens, scores_per_token, strict=False))
    print(f"P={detector.predict_proba(row)[0, 1]:.2f}  {scored}")
P=1.00  Jóhanna=1.00 Sigurðardóttir=1.00
P=1.00  Antonio=1.00 Garcia=1.00 Padilla=1.00
P=1.00  Ball-and-socket=1.00 joints=1.00

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.

The rows scored below are held-out ones.

path = detector[-1].save_pretrained("wepr-trained.skops")
reloaded = WEPR.from_pretrained(path)
print(f"{path}, reloaded")

# Held-out answers: the rows the fit never saw.
for row, label in list(zip(x_test, y_test, strict=True))[:5]:
    said = (read_message(row.completion) or "").strip()
    print(
        f"[{'hallucination' if label else 'grounded    '}] P={reloaded.predict_proba(parser.transform(row))[0, 1]:.3f}  {said[:40]!r}"
    )

# The width is part of the weights, so a mismatch is refused rather than mis-shaped.
try:
    reloaded.predict_proba(LogProbParser(k=K - 1).transform(x_test[:1]))
except ValueError as error:
    print(f"\nscoring at k={K - 1} -> ValueError: {error}")
wepr-trained.skops, reloaded
[hallucination] P=1.000  'Jóhanna Sigurðardóttir'
[hallucination] P=1.000  'Antonio Garcia Padilla'
[hallucination] P=1.000  'Ball-and-socket joints'
[grounded    ] P=0.000  'Alfred Lord Tennyson'
[grounded    ] P=0.001  'Nicaragua'

scoring at k=14 -> ValueError: X has 28 features, but LogisticRegression is expecting 30 features as input.

Where to go next#

  • epr is the same call with one word changed: it pools every candidate into a single feature instead of 2k, which is the one to reach for when there is too little labelled data to fit wepr’s coefficients. EntropyTransformer(pooling=...) also takes a Pooling subclass or a callable (s_kj, axis) -> features, so the two shipped poolings are not the only ones.

  • scripts/train_detector.py reads these same two files and reports bootstrap confidence intervals around the AUC, which a holdout this size needs.

  • predict_proba and predict_token_proba are the whole scoring surface; a fitted detector is an ordinary estimator from here on.