🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Instruction Tuning: Teaching Models to Follow Orders

đŸŸĸ Free Lesson

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.

python
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 detailCommon defaultWhy it matters
Chat templateModel's official tokenizer templateInference consistency, role tokens handled correctly
Loss maskingResponse tokens onlyGrades answers instead of prompts
Sequence length1024 to 4096 tokensLong enough for context, short enough for throughput
Learning rate1e-5 to 3e-5 with warmupHigher rates forget general capabilities fast
EpochsOne to threeMore epochs means memorization and drift
PackingConcatenate short examplesBetter throughput; keep document boundaries
ValidationHeld-out examples plus a general benchmarkCatches 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.

python
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

Before a long run, tokenize one example with your exact chat template and confirm the response tokens are the only ones left in the labels. A wrong template wastes the whole run, not just a few steps.

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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement