◆ AI All-in-One

Level 3 In-Depth AI · Transformers and Language Models

Instruction Tuning and Chat Models

How a raw text predictor becomes an assistant that follows instructions and holds a conversation. Instruction datasets, chat templates, system prompts and the special tokens that mark who is speaking.

Level
●●●●● Easy
Reading
10 min
To learn it well
45 minutes to read, an hour to practise
↗ Plan a path here

Read first

Fine-Tuning

This leads to

RLHF and Preference Optimization
The full path from zero — 44 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Tensors and Shapes
  15. NumPy and Array Thinking
  16. Language Modeling and Next-Token Prediction
  17. Supervised Learning
  18. Linear Regression
  19. Training, Validation and Test Sets
  20. The Perceptron
  21. Logistic Regression
  22. Overfitting and the Bias–Variance Tradeoff
  23. Regularization: L1 and L2
  24. Neural Networks
  25. Recurrent Neural Networks
  26. Backpropagation
  27. Activation Functions
  28. Dropout and Regularizing Neural Networks
  29. PyTorch
  30. Vanishing and Exploding Gradients
  31. Normalization Layers: BatchNorm and LayerNorm
  32. Optimizers: SGD, Momentum and Adam
  33. LSTMs and GRUs
  34. Residual Connections
  35. Training Neural Networks in Practice
  36. Sequence-to-Sequence Models
  37. Transfer Learning
  38. Attention
  39. Self-Attention and Multi-Head Attention
  40. Positional Encodings
  41. The Transformer
  42. GPT and Decoder-Only Models
  43. Pretraining Large Language Models
  44. Fine-Tuning
  45. Instruction Tuning and Chat Models

Read them roughly in this order. See it on the concept map →

Why it matters

A base model is trained to continue text. Give one the prompt "Write a haiku about autumn." and it might continue with "Write a haiku about winter. Write a haiku about spring.", because on the web, a line like that is often part of a list of writing exercises. The model knows perfectly well what a haiku is. It just isn't trying to help you; it is trying to predict what text comes next.

Instruction tuning is the supervised fine-tuning step that fixes this. The model is trained on thousands to millions of examples of an instruction followed by a good response, laid out in a fixed conversation format. Afterwards it treats your text as a request and its own output as the reply. The result is called an instruct model or chat model: Llama 3 8B Instruct instead of Llama 3 8B, the model inside ChatGPT instead of the raw GPT.

Every assistant you have used went through this step, usually followed by preference training (RLHF and Preference Optimization). Even when you only call an API, you are using its conventions: the system prompt, the alternating user and assistant turns, and the hidden special tokens that separate them. Understanding them explains why models sometimes run on past the end of their answer, why the system prompt has extra weight, and why prompt injection (Prompt Injection and LLM Security) is hard to stop.

The intuition

Think of a brilliant new employee who has read everything in the library but has never had a job. They know the material, but they don't know the format of work: someone asks a question, you answer it, you stop, you don't wander off. A week of shadowing, watching hundreds of examples of "request → good reply", teaches them the job. It doesn't teach them chemistry.

That is instruction tuning. The knowledge comes from pretraining. The instruction-tuning data teaches three habits:

  1. Treat the input as a request and respond to it, rather than continuing it.
  2. Answer in the expected style: helpful, on-topic, the right length, formatted sensibly.
  3. Know where your turn ends: emit an end-of-turn marker and stop.
Base model trained only to continue text Instruction-tuned model base model + SFT on chat examples Write a haiku about autumn. Write a haiku about autumn. Write a haiku about winter. Write a haiku about spring. Write a limerick about a cat. 25 creative writing prompts for your classroom … Red leaves drift and fall, the cold wind hums through bare trees, the year exhales slow. <|im_end|> ← stops here continues the page the prompt seems to come from: a list of writing exercises, not an answer treats the prompt as a request, answers it, then emits the end-of-turn token
Fig. 1 The same prompt sent to a base model and an instruction-tuned model. The base model continues the text as if it were a web page; the instruct model answers it and stops.

Key idea Instruction tuning is supervised fine-tuning on (instruction, response) pairs written in a fixed chat format. It changes the model's behaviour (answer, then stop) far more than its knowledge.

How it works

Instruction datasets

An instruction-tuning example is a short conversation. In its simplest form:

  • Instruction: "Summarise this paragraph in one sentence: …"
  • Response: "The paragraph argues that …"

Datasets have come from four main sources:

  • Existing NLP datasets, rewritten as instructions. Google's FLAN (2021) took more than 60 datasets (translation, sentiment, question answering…) and wrote templates such as "Is the sentiment of this review positive or negative?". Training on many tasks phrased as instructions made the model better at unseen tasks too, which is the key finding: instruction following generalises.
  • Human-written demonstrations. OpenAI paid contractors to write ideal answers to real user prompts for InstructGPT (about 13,000 prompts in the SFT set). Databricks' Dolly 15k (2023) was written by its employees and released openly.
  • Model-generated data. Self-Instruct (2022) had a model write new instructions and answers from a small seed set. Stanford's Alpaca (March 2023) used this idea to generate 52,000 examples with an OpenAI model and fine-tuned LLaMA 7B on them, for a reported total cost of under $600. Distilling a strong model's answers into a weaker one became the cheapest way to build chat models (Knowledge Distillation and Small Models, Synthetic Data).
  • Real conversations. Logged chats, with consent and filtering, give realistic multi-turn data.

Quality beats quantity. The LIMA paper (2023) got a strong assistant from just 1,000 hand-picked examples. Modern open recipes typically mix a few hundred thousand to a few million examples covering chat, coding, maths, safety refusals and tool calls.

Chat templates

A language model sees only a single stream of tokens. To represent a multi-turn conversation, an exchange of several messages between a user and the assistant, we flatten it into one sequence using a chat template: a fixed text layout with special tokens, reserved vocabulary entries that never occur in normal text and mark structure.

Here is a conversation in ChatML, the format popularised by OpenAI and used, for example, by the Qwen models:

<|im_start|>system
You are a concise assistant.<|im_end|>
<|im_start|>user
Capital of France?<|im_end|>
<|im_start|>assistant
Paris.<|im_end|>

<|im_start|> and <|im_end|> ("input message start/end") are single special tokens, not strings of characters. Each message has a role: system, user or assistant (and, in newer templates, tool for the results of tool calls). Llama 3 uses different tokens for the same idea:

<|begin_of_text|><|start_header_id|>system<|end_header_id|>

You are a concise assistant.<|eot_id|><|start_header_id|>user<|end_header_id|>

Capital of France?<|eot_id|><|start_header_id|>assistant<|end_header_id|>

Paris.<|eot_id|>

Every model family has its own template, and a model only works properly with the one it was trained on. That is why libraries store the template with the tokenizer.

The system prompt

The system prompt is a message at the start of the conversation, in the system role, that sets the model's persona, rules and context: "You are a support agent for Acme. Answer only questions about Acme products." Nothing magical makes it binding. The model obeys it because instruction tuning (and later preference training) included many examples where the system message set rules and the assistant followed them, even when a user message pushed the other way. Developers write the system prompt and users usually don't see it.

Training: which tokens count

Training uses the ordinary next-token loss with loss masking: only the assistant's tokens are scored. The model reads the system and user messages but is not trained to produce them.

One conversation = one token sequence. Loss only on the assistant's tokens. <|im_start|> system You are a concise assistant . <|im_end|> context only <|im_start|> user Capital of France ? <|im_end|> context only <|im_start|> assistant Paris . <|im_end|> trained <|im_start|> user And of Italy ? <|im_end|> context only <|im_start|> assistant Rome . <|im_end|> trained label = −100 (ignored by the loss) label = the token itself (cross-entropy loss) Training on <|im_end|> teaches the model to end its turn. Newline tokens are omitted here for space.
Fig. 2 A two-turn conversation rendered as one token sequence. All tokens are fed to the model, but only the assistant's replies, including their end-of-turn tokens, contribute to the loss.

Note the end-of-turn token <|im_end|> is trained. That is how the model learns to stop. When serving, the inference code watches for that token and ends the reply as soon as it appears. If the template is wrong, the model never sees its stop signal and keeps generating, often inventing a fake next user turn.

A worked example: counting the signal

In the two-turn conversation in the code below, the rendered sequence has 43 tokens (using a simple stand-in tokenizer). Only 8 are trained: Paris . <|im_end|> \n Rome . <|im_end|> \n. So more than 80% of the sequence is context. This is normal for chat data, and it is why people measure instruction datasets in examples and in trained tokens rather than raw tokens. It is also why long system prompts are cheap to train with: they cost compute but add no loss terms.

At inference time

When you call a chat API with a list of messages, the provider applies the template, appends the header for a new assistant turn (<|im_start|>assistant\n), and lets the model generate until it emits the end-of-turn token. Open-model libraries do the same with one call, tokenizer.apply_chat_template(messages, add_generation_prompt=True).

In code

This plain-Python example renders a conversation with a ChatML-style template and builds the training labels, using -100 (PyTorch's "ignore" index for cross-entropy) for every token that should not be learned.

import re
IGNORE = -100

def render(messages):
    """Return (text_piece, is_trained) pairs in template order."""
    pieces = []
    for m in messages:
        pieces.append((f"<|im_start|>{m['role']}\n", False))       # header: never trained
        trained = m["role"] == "assistant"
        pieces.append((m["content"] + "<|im_end|>\n", trained))    # reply + end-of-turn
    return pieces

def tokenize(text):    # stand-in for a real tokenizer: special tokens, words, punctuation
    return re.findall(r"<\|[a-z_]+\|>|\w+|[^\w\s]|\n", text)

chat = [
    {"role": "system", "content": "You are a concise assistant."},
    {"role": "user", "content": "Capital of France?"},
    {"role": "assistant", "content": "Paris."},
    {"role": "user", "content": "And of Italy?"},
    {"role": "assistant", "content": "Rome."},
]

vocab, input_ids, labels = {}, [], []
for text, trained in render(chat):
    for tok in tokenize(text):
        tid = vocab.setdefault(tok, len(vocab))
        input_ids.append(tid)
        labels.append(tid if trained else IGNORE)

print(f"{len(input_ids)} tokens, {sum(l != IGNORE for l in labels)} trained on")
inv = {i: t for t, i in vocab.items()}
print("trained tokens:", [inv[l] for l in labels if l != IGNORE])

# 43 tokens, 8 trained on
# trained tokens: ['Paris', '.', '<|im_end|>', '\n', 'Rome', '.', '<|im_end|>', '\n']

With a real model, the tokenizer already knows its template. This needs a download, so it is not run here:

from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
messages = [{"role": "system", "content": "You are a concise assistant."},
            {"role": "user", "content": "Capital of France?"}]
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
print(text)   # the ChatML text above, ending with "<|im_start|>assistant\n"

TRL's SFTTrainer (Fine-Tuning) applies the template and, with the right option set (assistant_only_loss=True in recent versions), builds the mask for you.

Common pitfalls

  • Wrong or missing template. Prompting an instruct model with raw text, or a base model with a chat template, gives poor results. Always use the template the model was trained with, via apply_chat_template.
  • The model never stops. Usually the end-of-turn token was masked out during training, or the serving code is watching for a different stop token.
  • Training on the prompt. Forgetting the mask wastes capacity and can make the model echo user-style text.
  • Doubling special tokens. Some tokenizers add a beginning-of-sequence token automatically, and some templates include it too. Two <|begin_of_text|> tokens is a classic silent bug.
  • Data that teaches the wrong style. If half your responses start with "Certainly!", your model will too. Read samples of your dataset before training.
  • Expecting new knowledge. Instruction tuning on a few thousand examples won't teach facts reliably. See Retrieval-Augmented Generation.

Watch out Special tokens are part of the security model. If user-supplied text can contain the literal characters <|im_start|>system and your pipeline turns them into the real special token, a user can forge a system message. Tokenize user input so that special-token strings stay ordinary text.

Where it leads

A bit of history

The idea of training one model on many tasks described in natural language grew through 2021. Google's FLAN ("Finetuned Language Models Are Zero-Shot Learners", September 2021) and the BigScience project's T0 showed that instruction tuning improved zero-shot performance on held-out tasks. In early 2022, OpenAI's InstructGPT paper combined supervised demonstrations with RLHF and found that labelers preferred outputs of the 1.3-billion-parameter InstructGPT model over those of the 175-billion-parameter GPT-3. ChatGPT, launched in November 2022, was built with a similar recipe applied to conversations.

In 2023 the open community caught up quickly. Stanford's Alpaca, Vicuna (trained on conversations users shared from ChatGPT), Databricks' Dolly, and the volunteer-built OpenAssistant dataset showed that a good base model plus a modest instruction set produced a usable chat model. Chat templates, at first an undocumented detail of each model, were standardised in Hugging Face's apply_chat_template in late 2023.

Try it

  1. Change render so that it also trains on the system message. How many trained tokens are there now? Why is this usually a bad idea?
  2. Rewrite render to produce the Llama 3 format shown above. Which token now marks the end of a turn?
  3. Take an open instruct model (or any chat API) and send the same request with and without a system prompt. Record how the answer's length and tone change.

Hint for 2: each message becomes a header (<|start_header_id|>role<|end_header_id|> plus two newlines), then the content, then <|eot_id|>.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You prompt a base model with "Write a haiku about autumn." and it replies "Write a haiku about winter. Write a haiku about spring." What would fix this?

  2. Your fine-tuned chat model never stops and starts inventing a fake next user turn. What is the most likely cause?

  3. Why does a model generally follow its system prompt even when a user pushes the other way?

  4. Your pipeline converts the literal text <|im_start|>system in user input into the real special token. What is the risk?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face LLM Course

Hugging Face · Intermediate · Free

Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.

Paper

LIMA: Less Is More for Alignment

Zhou et al. (Meta) · 2023 · Intermediate · Free

Fine-tunes a 65B base model on just 1,000 carefully chosen examples and gets a strong assistant, evidence that most knowledge comes from pretraining.

Docs

TRL documentation

Hugging Face · Intermediate · Free

Transformer Reinforcement Learning: trainers for supervised fine-tuning (SFT), reward modelling, PPO, DPO and GRPO on Hugging Face models.

Docs

Hugging Face Documentation

Hugging Face · Intermediate · Free

Documentation for transformers, datasets, diffusers, PEFT, TRL and the rest of the ecosystem.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/instruction-tuning.md