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
- Builds on
- 44 concepts →
- Quiz
- 4 questions ↓
Read first
Fine-TuningThis leads to
RLHF and Preference OptimizationThe full path from zero — 44 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- NumPy and Array Thinking
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- Training, Validation and Test Sets
- The Perceptron
- Logistic Regression
- Overfitting and the Bias–Variance Tradeoff
- Regularization: L1 and L2
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Dropout and Regularizing Neural Networks
- PyTorch
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Optimizers: SGD, Momentum and Adam
- LSTMs and GRUs
- Residual Connections
- Training Neural Networks in Practice
- Sequence-to-Sequence Models
- Transfer Learning
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- Pretraining Large Language Models
- Fine-Tuning
- 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:
- Treat the input as a request and respond to it, rather than continuing it.
- Answer in the expected style: helpful, on-topic, the right length, formatted sensibly.
- Know where your turn ends: emit an end-of-turn marker and stop.
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.
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|>systemand 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
- Preference tuning. SFT teaches the model to imitate good answers. RLHF and DPO then teach it to prefer better answers over worse ones, which improves helpfulness and safety beyond what demonstrations alone achieve.
- Reasoning models add training on long, verified chains of thought: Reasoning Models and Test-Time Compute.
- Tool use and structured output are taught the same way, with extra roles and formats in the template: Tool Use and Function Calling, Structured Output and JSON.
- Prompting builds on the conventions here: Prompt Engineering.
- Doing it yourself: Fine-Tuning an Open Model in Practice and LoRA and Parameter-Efficient Fine-Tuning.
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
- Change
renderso that it also trains on the system message. How many trained tokens are there now? Why is this usually a bad idea?- Rewrite
renderto produce the Llama 3 format shown above. Which token now marks the end of a turn?- 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|>.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Hugging Face LLM Course
Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.
Training language models to follow instructions with human feedback
InstructGPT: the RLHF recipe that turned GPT-3 into an assistant, and the precursor of ChatGPT.
Finetuned Language Models Are Zero-Shot Learners (FLAN)
Instruction tuning on more than 60 NLP tasks phrased as instructions makes a model much better at following instructions for tasks it never saw.
LIMA: Less Is More for Alignment
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.
Self-Instruct: Aligning Language Models with Self-Generated Instructions
Uses a language model to write its own instruction-following training data from a small seed set, the trick behind many cheap open chat models.
TRL documentation
Transformer Reinforcement Learning: trainers for supervised fine-tuning (SFT), reward modelling, PPO, DPO and GRPO on Hugging Face models.
Hugging Face Documentation
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