Instruction Tuning: Teaching Models to Follow Orders
A pretrained model has read the internet; it has never been asked to do a job. Instruction tuning is the bridge: a supervised stage that shows the model thousands of examples of a request paired with the response a good assistant would give. The weights barely move relative to pretraining, yet behavior changes completely â from continuation to compliance. This lesson covers what the data must look like, how the loss should be computed, how to run a small loop without overfitting, and how to tell whether the result actually improved.
From Continuer to Assistant
During pretraining the model learned that text is followed by more text of the same kind, so it will happily continue a conversation, then start a new unrelated one, then emit a system prompt it saw in training data. Instruction tuning replaces that distribution with a narrower one: given an instruction, produce the answer. It teaches the structure of helpful responses â directness, format, refusal when the request is impossible â and it teaches the model to treat the beginning of the prompt as authoritative rather than as text to imitate.
The stage is deliberately cheap relative to pretraining: learning rates around 2e-5, one to three epochs, and thousands to hundreds of thousands of examples. Two risks live at that scale. Too many epochs on too few examples produces a parrot that memorizes responses and forgets everything else, a form of catastrophic forgetting. Too little data leaves the model still halfway between continuation and compliance, visible as answers that start well and then drift into a second topic.
Anatomy of a Training Example
An effective record has an instruction, optional context, and a response, plus metadata that lets you audit the source later. The instruction should be self-contained and imperative, the context should contain everything the response depends on, and the response should be the output you want at inference â same tone, same format, same level of detail. If you want citations in production, cite in the training data. Models do not invent formatting rules you never demonstrated.
Diversity of task types matters more than raw count. Mix summarization, extraction, classification, rewriting, coding, math, and multi-turn dialogue, and include refusals and clarifying questions so those behaviors exist in the tuned model. Balance your categories deliberately: a dataset that is 80 percent translation will pull the model toward translating everything, including questions you meant it to answer.
import json
def make_example(instruction, context, response, source, tags):
return {
"instruction": instruction.strip(),
"context": context.strip(),
"response": response.strip(),
"source": source,
"tags": tags,
"validated": True,
}
def render(example, chat_template=True):
if chat_template:
return [
{"role": "system", "content": "You are a precise assistant."},
{"role": "user", "content": example["instruction"] if not example["context"]
else f"{example['instruction']}\n\nContext:\n{example['context']}"},
{"role": "assistant", "content": example["response"]},
]
prompt = f"### Instruction:\n{example['instruction']}\n\n"
if example["context"]:
prompt += f"### Context:\n{example['context']}\n\n"
return prompt + f"### Response:\n{example['response']}"
dataset = [
make_example(
"Summarize the incident report in three bullets.",
"API returned 502 for 12 minutes after deploy 41.",
"Deploy 41 introduced a null upstream; rolled back in 12 minutes.",
"incident-41", ["summarize", "sre"]),
make_example("Classify the ticket as bug, question, or request.",
"Where can I change my billing email?", "question", "support-102",
["classify"]),
]
print(json.dumps(render(dataset[0], chat_template=False), indent=2)[:400])
Strip out anything you would not want the model to imitate â internal identifiers, apologies, visible chain-of-thought dumps â because the loss teaches it to reproduce exactly that text.
Format, Masking, and the Details That Decide Quality
Formatting choices are not cosmetic. Using the model's native chat template at training time means the same token patterns appear at inference, which removes a whole category of mismatch. Loss masking decides what the model is graded on: if you include the prompt tokens in the loss, the model spends capacity predicting your instructions rather than its answers, and the format starts leaking into output.
| Training detail | Common default | Why it matters |
|---|---|---|
| Chat template | Model's official tokenizer template | Inference consistency, role tokens handled correctly |
| Loss masking | Response tokens only | Grades answers instead of prompts |
| Sequence length | 1024 to 4096 tokens | Long enough for context, short enough for throughput |
| Learning rate | 1e-5 to 3e-5 with warmup | Higher rates forget general capabilities fast |
| Epochs | One to three | More epochs means memorization and drift |
| Packing | Concatenate short examples | Better throughput; keep document boundaries |
| Validation | Held-out examples plus a general benchmark | Catches overfitting and capability loss together |
Track a general benchmark alongside your task metric. If task accuracy climbs while general capability falls, you are trading breadth for a narrow imitation â lower the learning rate, add replay data, or stop earlier.
A Minimal Loop You Can Trust
The loop below is intentionally small: render each example, mask the prompt, compute cross-entropy on the response, step the optimizer, and evaluate on a held-out set each epoch. Everything else â distributed training, mixed precision, gradient accumulation â is an optimization you add after this works.
import torch
from torch.utils.data import DataLoader
from transformers import AutoModelForCausalLM, AutoTokenizer
def prepare(example, tok, max_len=1024):
messages = render(example, chat_template=True)
ids = tok.apply_chat_template(messages, add_generation_prompt=False,
return_tensors="pt")
prompt_ids = tok.apply_chat_template(messages[:-1], add_generation_prompt=True)
labels = ids.clone()
labels[0, : prompt_ids.shape[-1]] = -100
if ids.shape[-1] == max_len:
labels[0, : ids.shape[-1] - max_len] = -100
return ids[0], labels[0]
def train(model, tok, records, epochs=2, lr=2e-5):
optimizer = torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=lr)
model.train()
for epoch in range(epochs):
total, steps = 0.0, 0
for record in records:
ids, labels = prepare(record, tok)
out = model(input_ids=ids.unsqueeze(0), labels=labels.unsqueeze(0))
out.loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
optimizer.zero_grad()
total += float(out.loss)
steps += 1
if steps >= 50:
break
print(f"epoch {epoch + 1}: loss {total / max(steps, 1):.4f}")
return model
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
train(model, tok, dataset)
Print the masked and unmasked token sequences once for a real example. Off-by-one errors in masking are invisible in the loss curve and obvious in that printout.
Where the Data Comes From
Hand-written examples give the highest quality per token but scale slowly. Public datasets such as Alpaca, Dolly, OpenAssistant, and FLAN mixtures offer breadth immediately and vary widely in noise. Distillation â generating responses with a stronger model and filtering them â scales cheaply and transfers style, at the price of inheriting the teacher's blind spots. Production logs converted into examples capture your real traffic distribution, but they require careful de-identification and curation, because users write messy, ambiguous, occasionally unsafe prompts.
Whatever the source, dedupe near-identical records, split train and validation by source rather than at random to prevent leakage, and keep a provenance field on every example. When a regression appears after a future run, provenance is how you find which batch introduced it.
Proving It Improved
Three views of evaluation keep you honest. Task accuracy on held-out examples of the same distribution tells you whether the tuning worked. Format validity â does the response parse, stay in schema, and end properly â tells you whether it will integrate. General capability checks on a small unrelated benchmark tell you what you gave up. Pair those with a handful of human preferences against the untuned model, since automatic scores often miss tone and usefulness.
Resist the temptation to evaluate on the prompts you trained on. Memorization looks exactly like competence there, and the gap only appears on fresh phrasing from a different author. Keep a small set of fresh examples written by someone who never saw the training data, and treat that set as the only honest scorecard before you ship.
â ī¸Validate the template first
Best Practices
- Use the model's official chat template and mask prompt tokens out of the loss
- Mix task types and include refusals so behavior is present, not hoped for
- Early-stop against a held-out set while watching a general benchmark for forgetting
- Dedupe and split by source to keep validation honest
- Record provenance for every example so regressions can be traced to a batch
Key Takeaways
- Instruction tuning changes behavior by shifting the target distribution, not by adding knowledge
- Examples must demonstrate the exact format and tone you expect in production
- Loss masking on response tokens is the difference between answering and echoing
- Overfitting shows up as rising task scores alongside falling general capability
- Evaluate held-out tasks, format validity, and general skills together before shipping