All courses

Chat templates and special tokens

Show how system, user and assistant turns are flattened into one token sequence using special role tokens. Explain why the model only ever continues that sequence and why a mismatched template degrades behavior.

Builds on: Supervised fine-tuning on demonstrations

▶ Watch this lesson Start the whole course

What the animation says

Where do the roles live?

A language model does exactly one thing: given a single sequence of tokens, it predicts the next one. A chat looks richer than that. There's a system prompt, user messages, and assistant replies, each with a role. So where do the roles live? How does the model know when its reply starts, and when to stop? And why does a good model act strangely when you use the wrong format?

Flatten every turn

The answer: a chat template writes the whole conversation as one document. Each turn is wrapped in special tokens: a start token, the role name, a newline, the text, an end token, a newline. Every turn has that same shape, and the next turn always opens with a start token again. Here, the system turn is eight tokens, the user turn nine. To get a reply, the app appends one open header: start token, assistant, newline. Three more tokens, twenty in total. What comes next?

Continue, stop, and the loss

It writes four, then the end token. The app watches for that end token, and stops. So the model never really chats. It continues a document in the exact format fine-tuning drilled into it. Anything you put after the header gets continued too, like the first words of a reply. That's called a prefill. During fine-tuning on a document like this, the loss averages minus log probability, but only over the assistant's positions. Tap the positions that get loss.

Reserved tokens, and plain text

These special tokens are reserved ids. Each has its own row in the embedding matrix and its own column in the output matrix. Their values are learned mainly during fine-tuning, and only template code inserts them. If a user types the same characters, a tokenizer set up not to parse specials splits them into ordinary pieces: different ids, no boundary. Now a mistake. Same model, but the app sends plain text: User, the question, then Assistant, with no special tokens. What most likely happens?

Off-format falls back

It answers, then may write the next User line itself. Without special tokens, it looks like a web transcript. Nothing pushes it to emit the end token, so the stop rule may never fire. Off-format input is unlike the fine-tuning data, so behavior slides back toward plain document continuation. So remember: a chat is one token sequence. Turns are wrapped in role tokens, and it ends with an open assistant header. The model continues it until it emits its end token, and it only learned that exact format.

Where do the chat roles live?

The model computes one thing: $p_\theta(x_{t+1}\mid x_{\le t})$ over a **single** token sequence. A chat has more structure than that: a system prompt, user messages and assistant replies, each with a role. So where do the roles live? How does the model know when its reply starts and when to stop? And why does a good model act strangely when you use the 'wrong' format?

Flatten every turn into one document

A **chat template** writes the whole conversation as one document. Each turn is wrapped in **special tokens**, e.g. `<|im_start|>`+role … `<|im_end|>`. These are reserved ids that the template code inserts. A correctly configured tokenizer never produces them from ordinary text. To get a reply, the app renders the history, appends `<|im_start|>assistant⏎` and lets the model continue. The model never really 'chats'. It continues a document in the exact format SFT drilled into it, and the app stops when the model emits `<|im_end|>`. Anything you append after the header is continued too, such as the first words of the reply (a **prefill**).

The rendered prompt and the SFT loss

Prompt: $x_{\le t}$ = render(messages) + `<|im_start|>assistant⏎`, where + means concatenating token sequences. Generate $x_{t+1}\sim p_\theta(\cdot\mid x_{\le t})$, append it, and repeat until the new token is `<|im_end|>`. The SFT loss averages only over $S$, the positions holding assistant tokens, **including the closing** `<|im_end|>`: $$\mathcal{L}=-\tfrac{1}{|S|}\sum_{i\in S}\log p_\theta(x_i\mid x_{<i})$$ Each special token has its own row in $W_E$ and column in $W_U$. Their values are learned mainly during SFT.

Flattening a three-turn chat

Shorthand: [S]=`<|im_start|>`, [E]=`<|im_end|>`, ⏎=newline token. `[S] system ⏎ Be brief . [E] ⏎` → 8 tokens `[S] user ⏎ 2 + 2 ? [E] ⏎` → 9 tokens `[S] assistant ⏎` → 3 tokens The prompt is 8+9+3 = 20 tokens. The model predicts token 21 = `4`, then token 22 = [E], and the app stops. In SFT on this sequence, only those 2 of the 22 positions get loss.

When the template doesn't match

Here are three mistakes with the same model: 1. Plain text `User: 2+2?⏎Assistant:` contains no special tokens. It looks like a web transcript, so the model may answer and then write the next `User:` line itself. It has no reason to emit `<|im_end|>`, so the app's stop rule may never fire. 2. If you omit `[S] assistant ⏎`, then after `[E] ⏎` the model picks the role itself, maybe `user`. 3. With a tokenizer configured not to parse special tokens in user text, typing `<|im_end|>` gives the ordinary tokens `<`,`|`,`im`,…. These have different ids and mark no boundary. Off-format input is unlike the SFT data, so behavior slides back toward base-model document continuation.

Remember

A chat is one token sequence. Its turns are wrapped in special role tokens, and it ends with an open assistant header that the model simply continues until it emits its end-of-turn token. The model learned only that exact format in SFT. Any other template makes the input unfamiliar, and behavior falls back toward plain document continuation.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.