Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Logprob | The natural log of the probability the model gave a token. Servers return them on request. |
| Top-k logprobs | The k most likely tokens at a position and their logprobs. Servers return these, not the whole vocabulary. |
| Teacher forcing | Feeding a fixed text to the model and reading its predictions at every position, instead of letting it generate. |
| Prompt logprobs | Logprobs for the tokens of the input, which a server computes during prefill. This is how you teacher-force through an API. |
| KL divergence | KL(P‖Q) = Σ P(t)·(log P(t) − log Q(t)): how much distribution Q differs from P, in nats. 0 means identical. |
| Golden file | Stored outputs of the reference build, checked into the repository, that later builds are compared with. |
| Silent data corruption (SDC) | A hardware fault that produces wrong numbers without any error being raised. |
1. What is it?#
A regression test that compares the probability distributions two builds of a serving stack produce, position by position, on a fixed set of texts. Instead of asking “is the answer right?” (28.d) it asks “does the candidate predict what the reference predicts, at every token?”
It is the most sensitive and cheapest quality test an inference team has:
- Sensitive: it sees differences far too small to change a benchmark score, and tells you where they are (which positions, which context lengths, which kinds of text).
- Cheap: it is prefill only. Scoring a million tokens of fixed text takes minutes, where generating and grading the same amount takes hours.
- Low noise: no sampling and no cascading divergence (28.a). The same text goes into both.
It is the “L3, within tolerance” rung of 28.a, and the numerical level of the validation ladder in 13.b. This lesson shows how to build it from what an OpenAI-compatible server returns, which statistics to compute, and how to set thresholds from data rather than folklore.
Facts checked on 13 November 2026.
2. Why does it matter?#
Because the bugs that matter most produce small, local changes in distributions:
- a kernel that is wrong only beyond some context length or for one tail-tile shape (28.b);
- a KV-cache quantization that is fine for short prompts and drifts on long ones (13.h);
- a single faulty GPU in a fleet computing wrong numbers silently (Meta’s “Silent Data Corruptions at Scale”, 2021, documents such faults in production CPUs; accelerators are not immune);
- an approximate operation that misbehaves on a few inputs (the approximate top-k bug in Anthropic’s September 2025 postmortem).
A benchmark run averages these away. A per-position KL comparison sliced by position and by data type points straight at them. And because it is fast, you can run it on every engine bump, every config change, and continuously against production.
3. Simple analogy#
Tuning two pianos to each other. You could ask a panel to listen to a concerto on each and vote on which sounds better (an eval). Or you could play every key on both and measure the pitch difference with a tuner. The tuner finds the one key that is a quarter-tone flat; the panel probably does not, unless the concerto happens to use it a lot.
4. Tiny example: a KL check from top-k logprobs#
Servers return only the top k logprobs per position (vLLM’s limit is 20 by default,
--max-logprobs). The program shows how much you can conclude from that. It builds synthetic
reference logits for 400 teacher-forced positions over a 2,000-token vocabulary, then three
candidates: an A/A rerun with tiny noise, an “FP8” candidate with small noise everywhere, and a
candidate with a bug that adds large errors from position 300 onwards (think: a long-context kernel
bug). The noise levels are illustrative, not measurements of real FP8.
For each, it computes from the top-20 lists only: a bucketed KL (explained in section 5), top-1 agreement, top-1 flips where the reference was confident (margin above 1 nat), and the mean absolute change in the logprob of the reference’s top token. The last column is the true KL over the full vocabulary, which a server would not give you, shown for comparison.
// klcheck.go — a logprob/KL regression check, computed only from what an
// OpenAI-compatible server returns: the top-k logprobs at each teacher-forced position.
package main
import (
"fmt"
"math"
"math/rand"
"sort"
)
const (
vocab = 2000
positions = 400
topK = 20 // logprobs requested per position
confident = 1.0 // nats: a top-1 flip above this reference margin is suspicious
)
type topk map[int]float64 // token id -> logprob, as returned by the server
func logSoftmax(z []float64) []float64 {
m := math.Inf(-1)
for _, v := range z {
m = max(m, v)
}
s := 0.0
for _, v := range z {
s += math.Exp(v - m)
}
out := make([]float64, len(z))
for i, v := range z {
out[i] = v - m - math.Log(s)
}
return out
}
func top(lp []float64, k int) topk {
idx := make([]int, len(lp))
for i := range idx {
idx[i] = i
}
sort.Slice(idx, func(a, b int) bool { return lp[idx[a]] > lp[idx[b]] })
t := topk{}
for _, i := range idx[:k] {
t[i] = lp[i]
}
return t
}
func argmax(t topk) (best int, margin float64) {
first, second := math.Inf(-1), math.Inf(-1)
for tok, v := range t {
if v > first {
first, second, best = v, first, tok
} else if v > second {
second = v
}
}
return best, first - second
}
// bucketKL is KL(ref || cand) over the tokens present in BOTH top-k lists plus one
// "everything else" bucket. Merging tokens can only lower KL, so this is a lower bound.
func bucketKL(ref, cand topk) float64 {
kl, pRest, qRest := 0.0, 1.0, 1.0
for tok, lp := range ref {
lq, ok := cand[tok]
if !ok {
continue
}
p := math.Exp(lp)
kl += p * (lp - lq)
pRest -= p
qRest -= math.Exp(lq)
}
if pRest > 1e-12 && qRest > 1e-12 {
kl += pRest * math.Log(pRest/qRest)
}
return max(kl, 0)
}
type stats struct{ meanKL, p99KL, maxKL, top1, confFlips, meanAbsDLP, trueMeanKL float64 }
// compare plays a reference and a candidate server on the same tokens (teacher forcing).
// noise(pos) is the size of the candidate's logit error at that position.
func compare(rng *rand.Rand, ref [][]float64, noise func(pos int) float64) stats {
var kls []float64
var s stats
for pos, z := range ref {
zc := make([]float64, vocab)
for i := range z {
zc[i] = z[i] + noise(pos)*rng.NormFloat64()
}
lp, lq := logSoftmax(z), logSoftmax(zc)
full := 0.0
for i := range lp {
full += math.Exp(lp[i]) * (lp[i] - lq[i])
}
s.trueMeanKL += full / positions
tr, tc := top(lp, topK), top(lq, topK)
kl := bucketKL(tr, tc)
kls = append(kls, kl)
s.meanKL += kl / positions
a, margin := argmax(tr)
b, _ := argmax(tc)
if a == b {
s.top1 += 1.0 / positions
} else if margin > confident {
s.confFlips++
}
// The logprob of the token the reference would emit, which the candidate also
// reports when scoring the same text (prompt logprobs).
s.meanAbsDLP += math.Abs(lp[a]-lq[a]) / positions
}
sort.Float64s(kls)
s.p99KL, s.maxKL = kls[len(kls)*99/100], kls[len(kls)-1]
return s
}
func main() {
rng := rand.New(rand.NewSource(3))
ref := make([][]float64, positions) // reference logits for each teacher-forced position
for p := range ref {
ref[p] = make([]float64, vocab)
for i := range ref[p] {
ref[p][i] = 2 * rng.NormFloat64()
}
ref[p][rng.Intn(vocab)] += 14 * rng.Float64() // some positions confident, some open
}
runs := []struct {
name string
noise func(int) float64
}{
{"A/A (same build, other batch)", func(int) float64 { return 0.003 }},
{"FP8 candidate", func(int) float64 { return 0.04 }},
{"bug after position 300", func(p int) float64 {
if p >= 300 {
return 1.5
}
return 0.04
}},
}
fmt.Println("run mean KL p99 KL max KL top-1 conf.flips mean|dLP| full-vocab KL")
for _, r := range runs {
s := compare(rng, ref, r.noise)
fmt.Printf("%-30s %8.5f %8.5f %9.5f %5.1f%% %10.0f %9.4f %13.5f\n", r.name,
s.meanKL, s.p99KL, s.maxKL, 100*s.top1, s.confFlips, s.meanAbsDLP, s.trueMeanKL)
}
}Output:
run mean KL p99 KL max KL top-1 conf.flips mean|dLP| full-vocab KL
A/A (same build, other batch) 0.00000 0.00001 0.00001 99.7% 0 0.0016 0.00000
FP8 candidate 0.00025 0.00109 0.00141 98.0% 0 0.0228 0.00062
bug after position 300 0.04734 0.66626 1.49556 84.2% 9 0.2845 0.21181What it shows:
- The three cases are separated by orders of magnitude on every statistic, from top-20 data alone. The A/A row is the noise floor; anything near it is “no change”.
- The bucketed KL is a lower bound (0.00025 against a true 0.00062; 0.047 against 0.21). It is reliable for detecting change and comparing builds, not for reporting the absolute KL.
- The tail shows a local bug more clearly than the mean. The bug’s mean KL is about 190 times the FP8 candidate’s, and that ratio shrinks as the corpus grows with healthy text; its p99 and max are 600 to 1,000 times larger, and 9 top-1 flips happened where the reference was confident. 28.a: a confident flip is not numerics.
- Top-1 agreement alone is a weak signal (98% versus 84%): near-ties flip in the healthy candidate too.
5. Technical explanation#
Getting the numbers out of a server#
Teacher forcing through an API means asking for logprobs of the prompt. In vLLM (v0.32.0), the
completions endpoint accepts a prompt_logprobs field (and echo: true with logprobs maps to
it):
curl -s localhost:8000/v1/completions -H 'Content-Type: application/json' -d '{
"model": "my-model",
"prompt": [128000, 791, 6864, 315, 9822, 374, 12366, 13],
"max_tokens": 1,
"temperature": 0,
"prompt_logprobs": 20
}'- Send token ids, not text, so both builds score exactly the same tokens. If the candidate has a different tokenizer or template, that is a separate test (28.f); do not let it leak into this one.
- Know what the logprobs mean. vLLM’s default
--logprobs-modeisraw_logprobs: values from the model’s output before any logits processors, penalties or temperature. The other modes areprocessed_logprobs,raw_logitsandprocessed_logits. Compare like with like, and use the processed mode deliberately if you are testing the sampler pipeline (18.e). - Prompt logprobs bypass the prefix cache in vLLM V1 (the prefill is recomputed for such requests), so this test does not exercise the cached-prefix path. Test that path separately, with generated-token logprobs on requests that hit the cache.
--max-logprobscaps k (default 20). Raise it on test deployments if you want larger top-k lists.
The statistics#
STATISTIC COMPUTED FROM CATCHES
mean KL (bucketed) top-k of both overall drift
p99 and max KL, with position top-k of both local bugs: one position range, one text type
top-1 agreement top-k of both coarse change; weak alone
confident flips top-1 + reference margin defects (28.a); should be 0 versus reference
Δ logprob of the reference token prompt logprob of the perplexity change; bias (sign of the mean)
actual next token
same-top-p, Δp, RMS Δp as above llama.cpp's perplexity tool reports theseReport every statistic sliced: by position bucket (0–1k, 1k–8k, 8k–32k, beyond), by data type (chat, code, multilingual, tool-call JSON, reasoning trace), and by GPU host. A regression that lives in one slice is invisible in the total.
The Δ logprob of the actual next token has a useful property: its mean over a corpus is exactly the change in log-perplexity. Its sign tells you direction (negative: the candidate finds the text less likely), which KL, being always positive, does not.
KL from top-k lists, correctly#
You do not have the full distributions, so construct a partition you can compute exactly:
S = tokens in BOTH the reference's and the candidate's top-k lists
p_t,q_t = their probabilities (exact, from the returned logprobs)
p_rest = 1 − Σ_{t∈S} p_t q_rest = 1 − Σ_{t∈S} q_t
KL_bucket = Σ_{t∈S} p_t·log(p_t/q_t) + p_rest·log(p_rest/q_rest)Merging outcomes into buckets can only lose information, so KL_bucket ≤ KL_true (the
data-processing inequality). That gives you a sound test: if the bucketed KL is above the
threshold, the true KL is too. Common shortcuts are not sound: dropping the “rest” term, or
filling a token missing from one list with that list’s lowest logprob, can understate or overstate
the KL in ways you cannot bound.
Use KL(reference ‖ candidate): it weights the error by how likely the reference thinks each
token is, which is what matters when the reference defines correct behaviour. When you can export
full logits (offline, from the engine or a debugging hook), compute the exact KL; llama.cpp’s
llama-perplexity does this with --kl-divergence-base (save the reference logits) and
--kl-divergence (compare a quantized model against them).
Setting thresholds from the noise floor#
There is no universal “good KL”. It depends on the model, the text, the context length and the reference. Derive thresholds:
1. Run the reference build twice under different load (different batch composition).
That A/A comparison is your noise floor for every statistic and slice.
2. For a change that should be numerically neutral (kernel refactor, TP layout):
pass if each statistic is within a small multiple (e.g. 2–3×) of the A/A value.
3. For a change that is lossy by design (quantization):
record its values once, after it passes the task and behaviour evals of 28.d,
and use them as the budget for future builds of the same configuration.
4. Hard rules regardless of budget:
confident flips = 0 (versus the same-precision reference); no NaN or inf;
no slice with p99 KL more than 10× the overall p99.13.b’s rules of thumb (mean KL below 0.01, top-1 agreement above 99% for a quantized model against BF16) are a reasonable first gate when you have no history. Your own A/A numbers replace them as soon as you have them.
The corpus#
WHAT WHY
the reference's own greedy outputs positions the model actually visits when serving
for a few thousand real prompts
human-written text and code positions where the model is less certain
long documents at your maximum long-context kernels, KV quantization, RoPE scaling
served context
tool-call and JSON transcripts structured output, where one token decides validity
reasoning traces long generations, the place quantization damage concentrates
every language you serve rare-token paths, tokenizer edge casesStore the corpus as token ids together with the reference’s top-k logprobs: these are the golden files. Regenerate them deliberately (new model revision, new reference) and never silently.
6. Under the hood: why teacher forcing removes the cascade#
In free generation, the first differing token changes every later input, so two runs drift apart
for reasons unrelated to any new difference (28.a). With teacher forcing, the input at position
i is the same fixed token for both builds, so the comparison at position i measures only how
the two builds compute P(next | same prefix). Each position is an independent measurement of the
same thing, and 1,000,000 positions give 1,000,000 measurements.
There is one subtlety. The KV cache at position i was built by each build from the same tokens,
but with each build’s own arithmetic. Errors in early layers’ keys and values therefore do
accumulate along the sequence. That is not a flaw; it is exactly the long-context error you want
to see, which is why slicing by position is so informative. A KL that grows steadily with position
is the signature of KV-cache precision or a long-context kernel problem.
7. Performance implications#
- Prefill only, so cheap. At prefill rates of tens of thousands of tokens per second per GPU, a 1-million-token corpus is scored in under a minute of GPU time per build. Run it on every change.
- Prompt logprobs cost memory. The engine materializes a distribution for every prompt position; vLLM’s Model Runner V2 chunks this to limit peaks (18.e). Use moderate prompt lengths per request, or give the test deployment headroom.
- Golden files are small: token ids plus 20 (id, logprob) pairs per position, a few hundred bytes per position before compression.
8. Production implications#
- CI gate. Every engine version bump, kernel library upgrade, config change and quantization re-export runs the KL suite against the golden files. Fail on hard rules; flag on budgets.
- Production probe. A small fixed set (say 50 sequences) scored every few minutes on every replica, compared with golden. It catches what CI cannot: a wrong config on one deployment, traffic routed to the wrong model or revision (the first Anthropic incident), a node with a faulty GPU. Alert per replica and per host, not on the fleet average.
- Per-host comparisons find hardware faults. When one host’s KL is far above its siblings' running the same build, drain it and run the vendor’s diagnostics (for NVIDIA, DCGM’s diagnostic levels, 21.l).
- Keep golden files per (model revision, reference build) and record which reference each threshold came from.
- Do not expose logprob probes to users as a quality guarantee. They measure closeness to your reference, not answer quality; that is 28.d’s job.
9. Common mistakes#
- Comparing free-running generations instead of teacher-forced positions.
- Sending text instead of token ids, so a tokenizer change pollutes the comparison.
- Comparing raw logprobs from one build with processed logprobs from the other.
- Computing KL from top-k lists without a “rest” bucket, or patching missing tokens, so the number has no defined relationship to the true KL.
- Reporting only the mean. Local bugs live in p99, max and slices.
- Copying thresholds from someone else’s model. Derive them from your A/A noise floor.
- Testing only short sequences. Long-context and KV-precision errors grow with position.
- Alerting on the fleet average, which hides one bad replica among a hundred.
10. Hands-on exercise#
- Run
klcheck.go. Add per-position slices (0–299 and 300–399) to the output. How much bigger is the bug’s KL in the second slice than the overall mean suggested? - Change
topKto 5 and then to 100. How does the bucketed KL’s gap to the full-vocabulary KL change? At what k is it within 10% for the FP8 case? - Replace the “rest” bucket with the shortcut “skip tokens missing from either list”. Show a case where it reports a smaller KL than the A/A run although the candidate is worse.
- Against a real server: score 200 sequences of 2,000 tokens with
prompt_logprobs: 20on two identical deployments (A/A), then on an FP8 deployment. Build the table of section 5, sliced by position. - Turn it into a probe: a script that scores 20 golden sequences against every replica behind a load balancer and reports the worst replica’s p99 KL.
11. Interview questions#
- Why is a teacher-forced logprob comparison more sensitive and cheaper than running a benchmark?
- A server returns only the top-20 logprobs. How do you compute a KL divergence you can trust?
- Which direction of KL do you use, and why?
- How do you set the pass threshold for a KL regression test?
- Mean KL is unchanged after an upgrade but users report worse long-document answers. What do you look at?
- How would you use logprob probes to find a faulty GPU in a fleet?
- What can a logprob regression test not tell you?
12. Further reading#
Checked on 13 November 2026.
- vLLM v0.32.0 docs, V1 guide (logprobs modes; prompt logprobs and prefix caching)
- llama.cpp
llama-perplexityREADME (KL divergence statistics) - Dutta et al., “Accuracy is Not All You Need” (arXiv 2407.09141): KL and flips as metrics
- Dixit et al., “Silent Data Corruptions at Scale” (arXiv 2102.11245)
- Anthropic, “A postmortem of three recent issues” (17 September 2025)
- Validation ladder: 13.b. Sampler pipeline and logprobs in vLLM: 18.e. Paired task evaluation: 28.d.