I once spent an afternoon debugging a prompt that was fine at 11am and garbage at 2pm. The model hadn't changed and neither had the data. The diff turned out to be one character: I had "cleaned up" a template so it ended with Answer: instead of Answer:.
One trailing space. Outputs started with double spaces, odd capitalization, stray newlines, and wrong answers I couldn't explain. Deleting the space fixed all of it.
That's the trailing space problem, and the fix has a name: token healing. It comes straight out of how BPE tokenizers work, and once you see the mechanism you'll start spotting it in eval harnesses, code completion, and assistant prefill.
TL;DR
- BPE tokenizers glue the space to the front of the next word:
" Paris"is one token, not" "+"Paris". - A prompt ending in a space tokenizes that space as a lone token. During training, the model almost never saw a lone space followed by a word token, because the tokenizer always merged them.
- So a trailing space puts the model off-distribution on its very first generated token. Expect double spaces, weird casing, or plain wrong answers.
- Fix: strip trailing whitespace from prompts and put the space in the expected output, or use token healing: back up one token and constrain the first generated token to start with the text you removed.
- The same bug hits logprob scoring (
"positive"vs" positive"), code completion that ends mid-indent, and URLs that end inhttp:.
Why does a trailing space break an LLM prompt?
A trailing space breaks an LLM prompt because the tokenizer turns it into a standalone space token, and the model was trained on text where that space was almost always fused onto the following word. The model now has to continue from a token sequence it has rarely seen.
Here's the normal case with a GPT-style BPE tokenizer (GPT-2, cl100k_base, and Llama 3's tokenizer all behave this way):
"The capital of France is"
-> ["The", " capital", " of", " France", " is"]
next token: " Paris"
Every word after the first carries its leading space. That's what the merges learned, because " Paris" shows up in text constantly, so it earned its own vocabulary slot.
Now add the space:
"The capital of France is "
-> ["The", " capital", " of", " France", " is", " "]
next token: ???
The model has two bad options:
- Emit
" Paris"anyway. Now your output readsis Pariswith a double space. - Emit
"Paris"without the space. That's a different token, and in training it almost never followed a lone" "token, because any time the raw text containedis Paris, the tokenizer produced" is"," Paris". The pair[" ", "Paris"]basically doesn't exist in the training data.
Either way you've moved probability mass somewhere the model is unsure about. On a frontier model the damage can be small. On a base model or a small local model, it's often visible in a few samples.
What exactly is "off-distribution" here?
Off-distribution means the input token sequence is one the model saw rarely or never during training, so its next-token probabilities are poorly calibrated. The text you typed is perfectly normal English. The token sequence is not.
This is the part that trips people up. You think in characters. The model thinks in token IDs. Two strings that look identical to you can produce sequences that look wildly different to the model, and the tokenizer's greedy merging makes some sequences effectively impossible in training data.
GPT-2's vocabulary has 50,257 tokens. cl100k_base has roughly 100k. Llama 3 has 128,256. Bigger vocabularies mean more multi-character merges, and every merge creates new "this split never happens" holes in the space of sequences.
Where does this bug show up in production?
It shows up anywhere you hand the model a raw string boundary instead of a chat-template boundary. Chat APIs mostly hide it, because the template ends with a fixed assistant header and the model starts fresh. These four places don't hide it.
1. Completion-style prompts on base models
Anything like Q: ... A:, Label:, JSON:, or Translation: with a space at the end. Base models and small fine-tunes are the most sensitive. This was my afternoon.
2. URLs and other merged punctuation
The classic public example comes from the Guidance library's writeup on prompt boundaries. End a prompt with http: and ask for the rest of a URL. In common BPE vocabularies :// is a single token, so the model has rarely seen : followed by //. It tends to produce something other than the obvious //, because the path it would normally take starts with a token you already half-consumed.
The same shape appears with <a href=", """, ->, ==, and any other high-frequency punctuation cluster that got its own token.
3. Code completion that ends mid-indent
Code tokenizers have tokens for runs of whitespace. If your editor sends a prompt ending in def foo():\n (four spaces of indent), you've split a whitespace run that the model normally sees as one unit, plus whatever comes after it. The completion can come back with the wrong indentation level or a strange first token. A lot of code-completion tooling handles this by trimming the prompt back to the last newline and letting the model generate the indentation itself.
4. Logprob scoring for classification and evals
This one silently corrupts numbers instead of text. Say you classify by comparing log-probabilities:
# wrong: these tokens almost never follow "Sentiment:" in real text
score(context="Sentiment:", continuation="positive")
score(context="Sentiment:", continuation="negative")
# right: the space belongs to the continuation
score(context="Sentiment:", continuation=" positive")
score(context="Sentiment:", continuation=" negative")
Scoring "positive" with no leading space measures how likely the model is to produce a rare token variant. You still get a winner, so nothing crashes. You just get a worse classifier and a benchmark number that understates the model.
Eval harnesses learned this the hard way. EleutherAI's lm-evaluation-harness, for example, has a target_delimiter setting that defaults to a single space, and it tokenizes context and continuation together before splitting them, so the boundary matches what the model saw in training.
Does this affect Claude or GPT chat APIs?
Mostly no for normal chat, because the chat template controls the boundary. It matters when you prefill. If you start the assistant turn yourself ({"role": "assistant", "content": "Answer: "}), you've recreated the raw-string boundary. Anthropic's Messages API refuses this outright: it rejects a final assistant prefill that ends in trailing whitespace. I read that error as a polite version of this whole post.
If your provider doesn't reject it, nothing warns you. Strip it yourself.
How does token healing work?
Token healing removes the last token (or last few) from the prompt, then constrains the first generated token so its text must start with what was removed. The model gets to pick the natural token for the boundary instead of being forced to continue from an awkward split.
For "The capital of France is ":
- Tokens end in
" is"," ". Remove" ". - Allowed first tokens: anything whose text starts with
" ", which includes" Paris". - The model picks
" Paris", a sequence it has seen a million times.
For http:, you'd remove ":" and allow only tokens starting with ":", which lets the model pick "://".
Here's a minimal version with Hugging Face transformers. It's a sketch, not a library, but it's the whole idea:
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL)
# decode every token id once, up front
VOCAB_TEXT = [tok.decode([i]) for i in range(len(tok))]
ALL_IDS = list(range(len(tok)))
def heal(prompt: str):
ids = tok.encode(prompt, add_special_tokens=False)
removed = tok.decode(ids[-1:])
healed = ids[:-1]
allowed = [i for i, t in enumerate(VOCAB_TEXT) if t.startswith(removed)]
return healed, allowed
prompt_ids, allowed = heal("The capital of France is ")
n = len(prompt_ids)
def first_token_only(batch_id, input_ids):
# constrain step 1, free after that
return allowed if input_ids.shape[-1] == n else ALL_IDS
out = model.generate(
input_ids=torch.tensor([prompt_ids]),
prefix_allowed_tokens_fn=first_token_only,
max_new_tokens=20,
)
Two caveats. Backing up a single token isn't always enough. Robust implementations back up several tokens and use a prefix trie over the vocabulary. And the output now includes the text you removed, so strip that prefix before you show it to anyone. Guidance does all of this for you, which is the main reason I'd reach for it before writing my own.
What should you actually do?
Most teams never need real token healing. They need three habits:
-
Strip trailing whitespace from every prompt. One
.rstrip()in the template renderer, plus a test that fails if a template ends in a space or tab. -
Put the space in the output, not the input. Score
" positive", stop on"\n", and expect the model to produce the leading space itself. -
Never end a prompt mid-token on purpose. Don't end on
http:, half an indent, or the first quote of a string. End on a clean boundary like a newline, or use token healing if you can't.
And when output quality changes after a "harmless" template edit, diff the token IDs, not the strings. tok.encode(old) vs tok.encode(new) will show you the problem in seconds.
So why does a trailing space break your LLM prompt?
A trailing space breaks an LLM prompt because BPE tokenizers attach spaces to the beginning of the next word, so your space becomes a standalone token that almost never appeared before a word token in training. The model's first generated token then comes from an off-distribution context, which shows up as double spaces, odd formatting, or wrong answers, and as quietly wrong logprob scores in evals. Strip trailing whitespace and let the model generate the space itself. When you must end on a partial token, use token healing: remove the last token and constrain the first generated token to start with the removed text.
Written by the developer behind Preterview, an interview prep platform.
Top comments (0)