Pidoku

Debugging Quality Incidents: Templates, Tokenizers, Sampling

Module 28 Lesson 28.f 1h 15m Difficulty 4/5

Prerequisites 12.b, 12.o, 18.e, 18.i, 28.a, 28.e


Before you start: words you need#

WordPlain meaning
Quality incidentUsers get worse answers, with no crash and no error rate change.
Chat templateThe Jinja program that turns a list of messages into the exact text and special tokens a chat model was trained on (12.b).
Generation promptThe assistant header a template appends at the end, so the model knows it is its turn to speak.
BOS / EOSSpecial “beginning of sequence” and “end of sequence” tokens.
Stop tokenA token that ends generation when the model produces it.
Sampling parametersTemperature, top-k, top-p, min-p, penalties and seed: the settings that turn logits into a chosen token (12.o).
BisectFind the cause by halving the search space repeatedly: which version, which host, which setting.

1. What is it?#

The practice of going from “the model got worse” to a root cause, quickly. Most quality incidents in inference are not in the model’s weights or in floating-point numerics. They are in the layer around the model: how the prompt is built and tokenized, how output is sampled, stopped, detokenized and parsed, and which server a request reaches.

This lesson gives a symptom-to-cause table, a triage procedure that splits “input side” from “model side” from “output side” in a few steps, and the specific failure modes of templates, tokenizers and samplers that recur across engines and model releases.

Facts checked on 13 November 2026.


2. Why does it matter?#

Because these incidents are frequent, quiet and expensive:

  • Shortly after Llama 3’s release (April 2024), many deployments let the model run past the end of its answer. The chat template ends each turn with <|eot_id|>, but configurations listed only <|end_of_text|> as the end-of-sequence token; the fix, made in the model repository’s generation_config.json and copied by many derivatives, was to add token 128009 (<|eot_id|>).
  • Gemma (March 2024): Unsloth found that fine-tuning without the BOS token gave much worse loss, and that several public implementations had numerical deviations (28.b).
  • gpt-oss (2025): OpenAI’s verification guide warns providers that a prompt not in the harmony format “can have cascading generation issues”, and supplies a compatibility test.
  • Anthropic (August–September 2025): three bugs, one of them in routing and one in token selection, degraded answers for weeks because each bug showed different symptoms on different platforms at different rates, which looked like random, inconsistent degradation.

The common thread: the weights were fine, the server returned 200, and finding the cause took far longer than fixing it. Speed of diagnosis is the skill.


3. Simple analogy#

A restaurant complaint: “the soup tastes wrong.” The recipe (the weights) has not changed. Was the order taken wrong (the prompt)? Was it a different kitchen (routing)? Did the cook use the wrong salt (sampling settings)? Was it served cold (output handling)? A good manager does not start by rewriting the recipe. They taste what left the kitchen, then check the order slip.


4. Tiny example: lint what the model actually sees#

The single most useful debugging artefact is the rendered prompt as token ids, exactly as the server built it. Most template bugs are visible in it at a glance, if you know what to look for. This program checks four requests against a Llama-3-style template: the correct one, and three real bug patterns.

Go
// promptlint.go — check what the model will actually see, not what the client sent.
// Input: the rendered prompt as the server's tokenizer split it (special tokens shown
// by name), plus the request's stop-token set. Llama-3-style markers for the example.
package main

import (
	"fmt"
	"strings"
)

const (
	bos    = "<|begin_of_text|>"
	eot    = "<|eot_id|>"
	header = "<|start_header_id|>assistant<|end_header_id|>\n\n"
)

type request struct {
	name   string
	tokens []string // the rendered prompt, one entry per token; special tokens by name
	stops  []string // tokens that end generation for this request
}

func lint(r request) []string {
	var problems []string
	n := 0
	for _, t := range r.tokens {
		if t == bos {
			n++
		}
	}
	switch {
	case n == 0:
		problems = append(problems, "no BOS token: the model never saw a prompt start like this in training")
	case n > 1:
		problems = append(problems, fmt.Sprintf("%d BOS tokens: template added one and the tokenizer added another", n))
	}
	prompt := strings.Join(r.tokens, "")
	switch {
	case strings.HasSuffix(prompt, header):
	case strings.HasSuffix(prompt, strings.TrimRight(header, "\n")):
		problems = append(problems, "generation prompt lacks the blank line the template puts after the header")
	default:
		problems = append(problems, "no assistant generation prompt at the end: the model may continue the user's turn")
	}
	stop := false
	for _, s := range r.stops {
		stop = stop || s == eot
	}
	if !stop {
		problems = append(problems, "end-of-turn token "+eot+" is not a stop token: output will run on past the answer")
	}
	return problems
}

func main() {
	user := []string{"<|start_header_id|>", "user", "<|end_header_id|>", "\n\n", "Hi", eot}
	gen := []string{"<|start_header_id|>", "assistant", "<|end_header_id|>", "\n\n"}
	cat := func(parts ...[]string) []string {
		var out []string
		for _, p := range parts {
			out = append(out, p...)
		}
		return out
	}
	reqs := []request{
		{"correct", cat([]string{bos}, user, gen), []string{eot}},
		{"text rendered, then tokenized again", cat([]string{bos, bos}, user, gen), []string{eot}},
		{"add_generation_prompt forgotten", cat([]string{bos}, user), []string{eot}},
		{"hand-built prompt, old EOS config", cat([]string{bos}, user, gen[:3]), []string{"<|end_of_text|>"}},
	}
	for _, r := range reqs {
		p := lint(r)
		fmt.Printf("%-36s %d problem(s)\n", r.name, len(p))
		for _, s := range p {
			fmt.Println("   -", s)
		}
	}
}

Output:

correct                              0 problem(s)
text rendered, then tokenized again  1 problem(s)
   - 2 BOS tokens: template added one and the tokenizer added another
add_generation_prompt forgotten      1 problem(s)
   - no assistant generation prompt at the end: the model may continue the user's turn
hand-built prompt, old EOS config    2 problem(s)
   - generation prompt lacks the blank line the template puts after the header
   - end-of-turn token <|eot_id|> is not a stop token: output will run on past the answer

Each of these produces fluent text and no error:

  • Two BOS tokens happen when code renders the template to text (which already contains the BOS) and then tokenizes that text with default settings, which adds another. The effect varies by model, from barely measurable to clearly worse; the input simply is not one the model was trained on. llama.cpp warns about it explicitly.
  • No generation prompt (add_generation_prompt=False in apply_chat_template) leaves the prompt ending inside the user’s turn. The model may continue the user’s message or invent the header itself.
  • The missing stop token makes output run past the answer, often into an imaginary next user turn: the Llama 3 pattern above.

Engines apply the model’s template on the chat endpoint, so these bugs usually come from clients that use the completions endpoint with hand-built prompts, from overridden templates (--chat-template), or from an evaluation or RL harness that builds prompts itself.


5. Technical explanation#

Symptom to likely cause#

SYMPTOM                                         FIRST SUSPECTS
Output runs on, invents "User:" turns           stop/EOS tokens; generation prompt missing; template
Model repeats or continues the question         generation prompt missing; wrong role tokens
Slightly worse everywhere, nothing obvious      template mismatch (old/overridden), double or missing BOS,
                                                default system prompt changed, quantization (28.d)
Repetition loops                                greedy on a model that forbids it (Qwen3 thinking mode:
                                                "DO NOT use greedy decoding"); penalties not applied;
                                                low-bit quantization on long outputs
Odd characters, foreign script mid-answer       sampler bug (Anthropic's top-k), kernel corruption, wrong
                                                tokenizer revision; "�" alone = detokenization split (12.b)
Reasoning leaks into the answer, or is missing  reasoning parser vs template mismatch; enable_thinking flag (18.i)
Tool calls malformed or never triggered         tool parser and template disagree; structured-output backend (18.i)
Only long prompts are bad                       RoPE scaling config, silent truncation, KV quantization,
                                                long-context kernel (28.e slice by position)
Only some users, or intermittently              routing to the wrong model or config, one bad replica or host,
                                                sticky sessions keep hitting it (Anthropic's first bug)
Started after an engine upgrade, model same     changed defaults: sampling defaults, template handling,
                                                tokenizer library, kernel backend

Triage in five steps#

flowchart TD
  R["1. Reproduce: exact request,<br/>all sampling params, seed,<br/>deterministic pool (28.c)"] --> T["2. Capture the rendered<br/>prompt as token ids"]
  T --> D{"Token ids equal to the<br/>reference rendering?"}
  D -->|"no"| IN["INPUT SIDE<br/>template, tokenizer, BOS,<br/>system prompt, truncation"]
  D -->|"yes"| L{"3. Teacher-forced logprobs<br/>match the reference? (28.e)"}
  L -->|"no"| MD["MODEL SIDE<br/>weights, config, kernels,<br/>quantization, one bad host"]
  L -->|"yes"| OUT["OUTPUT SIDE<br/>sampling params, stop tokens,<br/>detokenization, parsers"]
  MD --> B["4. Bisect: replica, host,<br/>GPU type, version, config, time"]
  IN --> F["5. Fix, add a regression test,<br/>write the postmortem"]
  OUT --> F
  B --> F
  class R,T neutral
  class D,L queue
  class IN,OUT,MD warn
  class B,F compute

The key move is step 3. If the server’s logprobs on the same token ids match the reference, the weights, kernels and configuration are fine, and the bug is in what goes in or what comes out. That one comparison eliminates half the system.

Step 1, reproduce. Get the full request: messages, tools, every sampling parameter, the seed if any, the model name and revision the router chose, the replica that served it. Replay it on a deterministic deployment (28.c). If a sampled request has no seed, replay it many times and look at the distribution of outcomes, not one sample.

Step 2, see the prompt. vLLM’s server has a POST /tokenize endpoint that accepts chat messages with add_generation_prompt and can return the token strings (return_token_strs), so you can see exactly what the server’s template and tokenizer produce. Compare with the model author’s rendering:

Python
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("org/model", revision="<pinned revision>")
ids = tok.apply_chat_template(messages, tools=tools, add_generation_prompt=True, tokenize=True)
print(tok.convert_ids_to_tokens(ids))   # diff this against the server's /tokenize output

Tokenize inside apply_chat_template (tokenize=True), as here. Rendering to text and then calling the tokenizer with default settings is the classic double-BOS path.

Step 3, model side or not. Send the server the reference token ids with prompt_logprobs and compare with golden logprobs (28.e). Do it per replica if the problem is intermittent.

Step 4, bisect. By replica and host (a hardware fault or a wrong config on one node), by GPU type (kernel selection differs), by engine version, by configuration flag, and by time: correlate the first reports with every deploy, config change, routing or load-balancer change. Anthropic’s postmortem notes that it did not immediately connect a jump in reports with a load balancing change that had increased affected traffic.

Step 5, close the loop. Every incident adds a test: a template golden file, a stop-token check, a logprob probe, a canary guard (23.g).

Templates#

FAILURE                                   PREVENTION
template in tokenizer_config.json and a   pin model AND tokenizer revision; record a hash of the
separate chat_template.jinja disagree,    template actually used at server start; alert on change
or the model repo updated its template
server started with --chat-template      treat overrides as code: reviewed, versioned, tested
pointing at an old or generic file        against the author's rendering
template features not passed through      test with tools, multi-turn, system prompt, images, and
(tools, documents, enable_thinking)       reasoning on and off; not just "Hi"
harness builds prompts by hand            use the server's chat endpoint, or apply_chat_template
                                          with the pinned tokenizer, never string concatenation
format-specific protocols (harmony)       run the author's compatibility suite (gpt-oss) before launch

A useful habit: a template golden test. For a dozen representative conversations (plain, multi-turn, with tools, with tool results, with reasoning on and off), store the expected token ids. Run it on every model, tokenizer, template or engine change.

Tokenizers#

FAILURE                                   PREVENTION
tokenizer revision differs from weights   pin both; verify vocab size and special-token ids at startup
special tokens added twice or not at all  check BOS count in the golden test
add_special_tokens default differs        set it explicitly in every code path that tokenizes
between code paths
incremental detokenization splits a       use the engine's detokenizer; test multilingual and emoji
multi-byte character ("�")                output with streaming on (12.b)
stop strings that span token boundaries   test stop strings in streaming and non-streaming mode

Sampling#

The sampling pipeline (12.o, and vLLM’s order in 18.e) is code, and code has bugs and defaults:

FAILURE                                   PREVENTION
defaults come from the model's            know that vLLM (v0.32.0) loads sampling defaults from the
generation_config.json, not the engine    model's generation_config.json by default
                                          (--generation-config auto; "vllm" uses engine defaults);
                                          a model revision can change your defaults
client parameter silently ignored         echo the effective parameters in logs; test each
(unsupported field, wrong name)           parameter changes the output distribution
order of temperature / top-k / top-p /    a sampler change is a distribution change: run the
min-p / penalties differs                 sampled distribution test of 28.d
approximate top-k or top-p for speed      test that it never drops the most likely token
                                          (Anthropic's third bug); compare with exact in FP32
penalties applied to prompt tokens or not engines differ; pin behaviour with a test
temperature 0 for a model whose card      follow the model card's recommended settings, per mode
forbids greedy

6. Under the hood: why these bugs are quiet#

A language model is robust. Given a prompt in slightly the wrong format, it still produces fluent text, because fluent text is what it does best. It just does the task a bit worse, on some inputs, and recovers from many isolated mistakes; Anthropic’s postmortem names exactly this as a reason its evaluations missed the problem.

So quality bugs produce small average effects with a long tail: most requests look normal, a few are badly wrong. Averaged metrics (benchmark score, mean output length) move a little and inside their noise. That is why the methods of this module look at distributions and tails: confident flips (28.a), paired flips (28.d), p99 KL and slices (28.e), and here, a direct look at the exact token ids. And it is why time correlation with changes matters so much: the signal in user reports is weak, so line it up with what changed.


7. Performance implications#

  • Diagnosis needs the tools ready before the incident: a deterministic deployment, the /tokenize comparison, golden logprobs and per-replica probes. Building them during an incident multiplies its length.
  • Sampling and output checks are cheap. Logging the effective sampling parameters, stop reason and output length per request costs almost nothing and answers half the questions in the symptom table.
  • Fast paths trade exactness for speed (approximate top-k, fused samplers). Keep a test that compares them with the exact path, because their failures look like model quality problems.

8. Production implications#

  • Log, per request: model name and revision, the replica and host, template hash, effective sampling parameters, prompt and output token counts, finish reason, and whether structured output or tool parsing succeeded. Without these, steps 1 and 4 are guesswork.
  • Quality canaries on every replica: the logprob probe of 28.e plus a few fixed prompts with checked properties (stops correctly, valid JSON, no unexpected script).
  • Alert on distribution shifts: finish-reason “length” share, mean output length, tool-call validity, refusal rate, and the share of characters outside the expected scripts (23.g’s tier-2 guards).
  • Make it easy for users to report, with the request id attached, and route those reports to someone who can replay them.
  • Write postmortems that include the detection gap: how long between the change and the first report, and between the report and the cause. That gap is what the next test should shrink.

9. Common mistakes#

  1. Starting with the weights or the kernels. Check the prompt token ids and the sampling parameters first; they are cheaper and more often the cause.
  2. Reproducing with a “similar” request. Use the exact request, including every parameter and the seed.
  3. Rendering the template to text and tokenizing again. Double BOS.
  4. Overriding the chat template and forgetting it when the model repository updates its own.
  5. Assuming engine defaults for sampling when the model’s generation_config.json supplies them.
  6. Looking at fleet-wide averages for an intermittent problem that lives on one replica.
  7. Not correlating reports with changes in time, including routing and load-balancer changes.
  8. Fixing without adding a test. The same class of bug returns with the next model.

10. Hands-on exercise#

  1. Run promptlint.go. Extend it to check that the token before the generation prompt is the end-of-turn token, and that a system message, if present, comes first.
  2. With a real model, render a conversation with apply_chat_template(tokenize=True) and with “render to text, then tok(text)”. Compare token ids. Then score both with prompt logprobs and compare the logprob of the assistant’s reference answer.
  3. Start vLLM with a model whose generation_config.json sets temperature and top-p. Send a request with no sampling parameters and measure output diversity. Restart with --generation-config vllm and repeat. Write down what changed.
  4. Build a template golden test for a model you serve: 12 conversations covering tools, multi-turn and reasoning on and off, token ids stored, checked against the server’s /tokenize.
  5. Write a one-page runbook for “users say the model got worse”, following section 5’s five steps, with the exact commands for your stack.

11. Interview questions#

  1. Users say the model “got dumber” this week, with no errors in the dashboards. Walk through your investigation.
  2. How do you decide whether a quality problem is in the input, the model or the output side?
  3. Give three ways a chat template can be wrong without raising an error.
  4. Why does a double BOS token happen, and how do you prevent it?
  5. An engine upgrade changed output style although the model did not change. What could cause that?
  6. The problem affects only some requests, intermittently. What do you suspect and how do you bisect?
  7. What would you log per request so the next quality incident takes hours, not weeks?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in