AI Hints
Home›Fine-Tuning LLMs Tutorial›Decoding, Instruct Models and Chat Templates
Fine-Tuning LLMs · Lesson 18 of 120

Chat Templates

How a conversation becomes text.

⏱ 2 min read▶ Video at 28:36🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

A chat is a list of messages, from different speakers. But a model only reads one long string of tokens. So how does a conversation become one piece of text? With a chat template.

  • A chat is a list of messages
  • A model reads one string
  • The chat template joins them

Messages and roles

We write a conversation as a list of messages. Each message has a role, and some content. The system role sets the rules, like who the assistant is. The user role is the person asking. And the assistant role is the model's reply.

keyvalue
systemthe rules and the persona
userthe person asking
assistantthe model's reply
Each messagerole + content

See the template

Here's a short conversation. A system message, and a user question. Apply chat template turns it into text. Tokenize equals false gives us text, not IDs, so we can read it. Add generation prompt adds the start of the assistant's turn. Run it. Each message is wrapped in i m start and i m end tokens, with its role. And it ends with the assistant's turn, open, ready for the model to write.

app.pypython
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
messages = [{"role": "system", "content": "You help customers of Riverside Books."},
            {"role": "user", "content": "Is Dune in stock?"}]
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
print(text)
Output
<|im_start|>system
You help customers of Riverside Books.<|im_end|>
<|im_start|>user
Is Dune in stock?<|im_end|>
<|im_start|>assistant

Why this matters for fine-tuning

Here's the key point. A model was trained with one exact template. If you use a different one, it gets confused. So when we fine-tune, we always format our examples with the model's own chat template. Luckily, the tokenizer does this for us.

keyvalue
Each modelhas its own template
Wrong templateconfuses the model
Fine-tuninguse the model's template
Easyapply_chat_template()

Summary

Let's recap. A chat is a list of messages, with roles. The chat template turns them into one string, with special tokens. And we must always use the model's own template. Next, how much memory a model needs.

Key takeaways
  • system, user, assistant
  • apply_chat_template()
  • Always the model's own
Next up: Parameters and Memory — how big is a model?