Simple Algorithm
Deep Learning · Emergence · 26 min

Instruction Tuning & Its Data

How a few thousand demonstrations change a base model, and which data matters.

Fine-tune a 65-billion-parameter base model on 1,000 carefully chosen examples, about 750,000 tokens, and people judge its answers equivalent to or better than GPT-4's in 43% of comparisons. Fine-tune open models on up to 150 million tokens of ChatGPT's answers, and crowdworkers rate about 70% of their outputs as good as ChatGPT's, yet targeted benchmarks show they closed little or none of the gap in capability. Instruction tuning changes how a model answers far more easily than what it can do. This lesson follows the evidence from multitask instruction tuning to curated, synthetic and imitated chat data, and asks which properties of the data matter.

What you’ll learn

  • Describe multitask instruction tuning (FLAN, T0, Super-NaturalInstructions, Flan-PaLM) and what scaling the number of tasks, the model and chain-of-thought data each did.
  • Prove that supervised fine-tuning minimizes the forward KL divergence from the demonstration distribution, token by token on the data's own prefixes, and use it to explain why imitation copies style more readily than capability.
  • State the superficial alignment hypothesis and weigh the evidence for it (LIMA, token-distribution shifts) and against it.
  • Explain packing, loss masking and loss normalization, count the tokens that carry loss, and describe how fine-tuning can erode earlier skills and safety behavior.

Instructions as a multitask curriculum

Instruction tuning began as multitask learning. Take many supervised NLP datasets, rewrite every example as a natural-language instruction with hand-written templates, fine-tune, and test on task types held out entirely. Four studies set out what this does:

StudyModel and dataMain findings
FLAN (Wei et al., 2022)137B decoder-only model; 62 datasets in 12 task clusters, 10 templates per datasetzero-shot FLAN beat zero-shot 175B GPT-3 on 20 of 25 datasets; each evaluation cluster was held out of training
T0 (Sanh et al., 2022)11B encoder–decoder; 2,073 prompts for 177 datasetsmatched or beat GPT-3 on 9 of 11 held-out datasets at about one sixteenth the size; more prompts per dataset raised the median and cut the variance across prompt wordings
Super-NaturalInstructions (Wang et al., 2022)1,616 tasks of 76 types with expert-written definitionsheld-out performance grew log-linearly with the number of training tasks (up to 757) and saturated at 64 examples per task
Flan-PaLM (Chung et al., 2024)1,836 tasks from 473 datasets; models of 8B to 540B parametersgains of 9.4 to 15.5 points on held-out benchmarks, most of them reached by 282 tasks; tuning cost 0.2% of pretraining compute
Breadth of tasks matters far more than depth: performance tracks the number of distinct tasks and prompt wordings, while extra examples of a task stop helping quickly.

The ablations are as informative as the headlines:

  • Instructions themselves matter. Fine-tuned on the same data as bare input–output pairs, or with only the dataset's name prepended, FLAN's model averaged 37.3% and about 47% on four held-out clusters, against 55.2% with natural-language instructions.
  • Scale gates the benefit. For models of 8 billion parameters and smaller, FLAN's instruction tuning hurt held-out tasks; the authors' hypothesis is that learning the roughly 40 training tasks used up the small models' capacity.
  • Nothing to gain where the task is already language modeling. On sentence-completion tasks such as commonsense reasoning, FLAN beat its base model on only three of seven.
  • Tuning can remove abilities. Fine-tuning Flan-PaLM on non-chain-of-thought data alone substantially degraded its step-by-step reasoning; adding nine datasets with written-out reasoning kept it.
Check your understanding

FLAN's authors instruction-tuned models from 422 million to 137 billion parameters and evaluated on held-out task clusters. What did they find for the models of 8 billion parameters and below?

  1. The largest relative gains, because small models have the most to learn
  2. No effect either way
  3. Gains on held-out tasks only when the templates were removed
  4. Worse performance on held-out tasks than without instruction tuning
Show the answer

D. Worse performance on held-out tasks than without instruction tuning

Instruction tuning helped the two models near 100 billion parameters substantially and hurt the 8-billion-parameter and smaller ones on held-out clusters. One explanation is capacity: the small models spent it fitting the training tasks rather than learning to follow instructions in general. Later work with more tasks and better recipes (Flan-T5, for example) did improve small models, so the threshold depends on the recipe.

What maximum likelihood on demonstrations optimizes

The SFT loss of Fine-Tuning & Aligning Large Models is maximum likelihood on responses. Its population version has an exact information-theoretic meaning, and the meaning explains much of what the experiments find.

DerivationProof, and three consequences
  1. −log⁡πθ(y∣x)=log⁡pdemo(y∣x)πθ(y∣x)−log⁡pdemo(y∣x) → Ey∼pdemo  DKL+H-\log\pi_{\boldsymbol\theta}(y\mid x)=\log\frac{p_{\text{demo}}(y\mid x)}{\pi_{\boldsymbol\theta}(y\mid x)}-\log p_{\text{demo}}(y\mid x)\ \xrightarrow{\ \E_{y\sim p_{\text{demo}}}\ }\ \KL+H

    Add and subtract log⁡pdemo\log p_{\text{demo}} inside the expectation. The entropy term does not depend on θ\boldsymbol\theta, so minimizing the expected SFT loss is minimizing the KL:

  2. E[∑tlog⁡pdemo(yt∣x,y<t)πθ(yt∣x,y<t)]=∑tEy<t∼pdemo[DKL(pdemo(⋅∣x,y<t) ∥ πθ(⋅∣x,y<t))]■\E\Big[\sum_t\log\frac{p_{\text{demo}}(y_t\mid x,y_{<t})}{\pi_{\boldsymbol\theta}(y_t\mid x,y_{<t})}\Big]=\sum_t\E_{y_{<t}\sim p_{\text{demo}}}\Big[\KL\big(p_{\text{demo}}(\cdot\mid x,y_{<t})\,\big\|\,\pi_{\boldsymbol\theta}(\cdot\mid x,y_{<t})\big)\Big]\quad\blacksquare

    Both distributions factor over tokens (treat responses as padded with end-of-sequence tokens to a common length), so the log-ratio is a sum. Take each term's expectation first over yty_t given the prefix, then over the prefix:

  3. Mode covering. The forward KL is infinite wherever πθ\pi_{\boldsymbol\theta} gives zero probability to something the demonstrations do, so the model must spread mass over all of their behavior, quirks and mistakes included. Reinforcement learning with a KL penalty and on-policy distillation use the reverse direction, which is mode-seeking.

  4. Only the demonstrations' prefixes count. The loss never evaluates the model on prefixes it would generate itself. Small per-token errors can carry it to prefixes no demonstration resembles, where nothing constrains it: exposure bias, whose T2ϵT^2\epsilon worst case is stated and explained in Training Recurrent Networks.

  5. Imitation is distillation. If the demonstrations are a stronger model's outputs, SFT is sequence-level knowledge distillation (Kim & Rush, 2016): the student fits the teacher's output distribution, but only as far as its own knowledge and capacity allow (Knowledge Distillation).

Gudibande et al. (2024) tested imitation directly. They fine-tuned base models of 1.5 to 13 billion parameters on 0.3 to 150 million tokens of ChatGPT's outputs. Crowdworkers rated about 70% of the best imitation model's outputs as equal to or better than ChatGPT's. Targeted benchmarks disagreed: the imitation models closed little or none of the gap between their base model and ChatGPT on tasks not heavily represented in the imitation data, and broad imitation data did not improve factual question answering at all, while imitation data aimed at those questions did. The models had learned ChatGPT's confident, well-organized style without its knowledge, and raters without domain expertise missed the errors. The authors' conclusion: a better base model is the higher-leverage improvement.

Think first Why might fine-tuning on a strong model's answers make a weaker model hallucinate more than before?

The student learns to produce the teacher's kind of answer, specific and confident, for any question, including ones whose facts it never learned. The format transfers; the knowledge behind it does not. Ghosh et al. (2024) report that instruction tuning on open datasets did not add knowledge, that LoRA tuning mostly changed how responses begin and their style tokens, and that full-parameter tuning increased hallucination, partly by borrowing tokens from similar training examples.

How little data? The superficial alignment hypothesis

Zhou et al. (2023) fine-tuned the 65-billion-parameter LLaMA on 1,000 examples: 750 questions and answers selected from community forums for quality and diversity, and 250 written by the authors in a uniform helpful style. With no preference learning at all, LIMA's answers were judged equivalent to or better than GPT-4's in 43% of comparisons, Bard's in 58% and those of text-davinci-003, an RLHF-trained model, in 65%. They proposed the superficial alignment hypothesis: a model's knowledge and capabilities are learned almost entirely in pretraining, and alignment teaches it which subdistribution of formats to use with users.

Their ablations, on a 7-billion-parameter model graded by an LLM, pointed the same way. More diverse prompts (Stack Exchange against the more uniform wikiHow) helped; quality-filtered responses scored 0.5 points higher on a six-point scale than unfiltered ones; doubling the number of examples, without more diversity, did not help. The model held coherent multi-turn conversations with no dialogue in its training data, though it failed to follow the prompt within three exchanges in 6 of 10 test conversations, and 30 added dialogue examples improved it markedly.

Base → aligned (7B)Same top tokenBase rank 2–3Base rank > 3
Llama-2 → Llama-2-chat (SFT + RLHF)77.7%14.5%7.8%
Llama-2 → Vicuna-7b-v1.5 (SFT)82.4%12.8%4.8%
Mistral → Mistral-Instruct (SFT)82.2%12.5%5.2%
Token-distribution shift (Lin et al., 2024): the aligned model decodes an answer greedily, and each of its tokens is ranked under the base model given the same prefix. The positions that shift are mostly stylistic ("However", "cannot", "Here", "Thank"), safety disclaimers and the first few tokens; knowledge-bearing tokens usually sit where the base model already ranked them first. With three fixed stylistic examples and a system prompt, untuned base models matched SFT- and RLHF-tuned models on the authors' evaluation set.
Check your understanding

Lin et al. (2024) ranked each token of an aligned model's answer under its base model. What did most positions show?

  1. The aligned model's token was usually ranked first by the base model too; the shifts were mostly stylistic tokens, disclaimers and early positions
  2. The aligned model's tokens were usually ranked low by the base model, showing that alignment rewrites most of the answer
  3. The shifted tokens were mainly facts and numbers that alignment had corrected
  4. Base and aligned models never agreed on the first token
Show the answer

A. The aligned model's token was usually ranked first by the base model too; the shifts were mostly stylistic tokens, disclaimers and early positions

About 78 to 82% of positions shared the top token and only about 5 to 8% fell outside the base model's top three. Those were mostly discourse markers ("However", "Here"), refusals and disclaimers, concentrated early in the answer, which is why a few in-context examples of the right style could stand in for tuning on their evaluation.

Synthetic, imitated and filtered data

Human demonstrations are slow to write, so most open instruction data is generated. Self-Instruct (Wang et al., 2023) bootstrapped GPT-3 from 175 seed tasks into a large synthetic instruction set, with filters against invalid and near-duplicate items, and improved GPT-3 by 33 points on Super-NaturalInstructions, on par with InstructGPT-001 (Synthetic Data & Model Collapse has the details). Alpaca (Taori et al., 2023) fine-tuned the 7-billion-parameter LLaMA on 52,000 demonstrations generated the same way by text-davinci-003, and started a wave of open models trained on stronger models' outputs.

Two careful studies then asked which of that data helps. AlpaGasus (Chen et al., 2024) had ChatGPT rate Alpaca's 52,000 examples and kept the 9,000 best: the smaller set trained a better model, 5.7 times faster. Tülu (Wang et al., 2023) trained models of 6.7 to 65 billion parameters on 12 open instruction datasets and found that different datasets unlocked different skills, that no single dataset or mixture was best everywhere, and that preference-based evaluations, by models or by people, failed to show capability differences that benchmarks exposed.

Property of the dataEvidence that it mattersCaveat
Diversity of promptsmore task clusters (FLAN) and prompt wordings (T0); Stack Exchange beat the more uniform wikiHow (LIMA)hard to measure, and confounded with the data's source
Quality of responsesfiltered responses scored 0.5 higher on a six-point scale (LIMA); 9,000 well-rated examples beat 52,000 (AlpaGasus)"quality" judged by an LLM inherits that LLM's preferences
Quantitysaturates early: held-out tasks gained little beyond 64 examples per task (Super-NaturalInstructions); doubling the examples did not improve response quality (LIMA)keeps paying for reasoning-heavy skills, as a power law (Raghavendra et al., 2024)
Coverage of the target skillimitation helped only where the imitation data covered the task (Gudibande et al.); chain-of-thought data kept reasoning (Flan-PaLM)skills absent from the mixture can degrade
The base modelimitation could not substitute for a stronger base model; the best open model in each of Tülu's evaluations reached on average 87% of ChatGPT's scoresets the ceiling for everything above
A summary of the evidence as of the mid-2020s. Most comparisons use models of 7 to 65 billion parameters and fixed evaluation suites, so their conclusions may shift with scale and with how models are judged.

Packing, masking and what fine-tuning costs

SFT examples range from a few tokens to thousands, and padding a batch to its longest example wastes compute. Packing concatenates examples into fixed-length rows. With an ordinary causal mask, each token could then attend to the unrelated examples earlier in its row; a block-diagonal mask and positions that restart with each example keep the examples independent:

python
def pack(examples, eos_id):
    """examples: list of (prompt_ids, response_ids). Returns one packed row."""
    ids, labels, doc, pos = [], [], [], []
    for k, (prompt, response) in enumerate(examples):
        seq = prompt + response + [eos_id]
        ids += seq
        labels += [-100] * len(prompt) + response + [eos_id]  # loss on the response only
        doc += [k] * len(seq)                                  # which example each token is from
        pos += list(range(len(seq)))                           # positions restart per example
    ids, labels, doc, pos = map(torch.tensor, (ids, labels, doc, pos))
    causal = torch.tril(torch.ones(len(ids), len(ids), dtype=torch.bool))
    attn_mask = causal & (doc[:, None] == doc[None, :])        # attend only within one example
    return ids, labels, pos, attn_mask

The boolean mask can be passed as attn_mask to F.scaled_dot_product_attention, where True means "may attend". Attention kernels for variable-length sequences achieve the same without materializing the T×TT\times T mask.

Which tokens, weighted how. Averaging the loss over all response tokens in a batch gives example ii, with nin_i response tokens and mean per-token gradient gˉi\bar{\mathbf g}_i, the weight ni/∑jnjn_i/\sum_jn_j; averaging within each example first gives every example the weight 1/B1/B:

gtoken=∑ini∑jnj gˉiversusgexample=1B∑igˉi.\mathbf g_{\text{token}}=\sum_i\frac{n_i}{\sum_jn_j}\,\bar{\mathbf g}_i\qquad\text{versus}\qquad\mathbf g_{\text{example}}=\frac1B\sum_i\bar{\mathbf g}_i.

The first favors long responses, the second short ones, and gradient accumulation that averages each micro-batch separately silently gives yet another weighting. Masking is itself a choice: training on the instruction tokens as well helped when instructions were long and responses short, or when there were few examples, apparently by reducing overfitting (Shi et al., 2024).

Predict before you look

A dataset has 100,000 single-turn conversations. Each has 120 tokens of system prompt and template, a 380-token user message and a 250-token reply (end-of-turn token included). With the prompt masked, what percentage of all tokens carries loss?

Show the answer

33 %

250/(120+380+250)=1/3250/(120+380+250)=1/3: 25 million of 75 million tokens. The model still processes all 75 million (forward and backward), so compute scales with the full length while the learning signal comes from a third of it, one reason long-prompt data can benefit from some loss on the instructions.

What fine-tuning costs. Any update can erode what earlier training built (Catastrophic Forgetting & Continual Learning). InstructGPT's RLHF lowered accuracy on several public NLP benchmarks, the "alignment tax" (Fine-Tuning & Aligning Large Models). Safety behavior is fragile in the same way: Qi et al. (2024) removed GPT-3.5 Turbo's safety guardrails through a public fine-tuning API with 10 adversarially designed examples, at a cost under 0.20 US dollars, and found that fine-tuning on ordinary, benign datasets also degraded safety, to a lesser extent.

Key takeaways

  • Multitask instruction tuning generalizes to held-out task types; what scales it is the number of distinct tasks and prompt wordings, not examples per task (Super-NaturalInstructions saturated at 64 per task; Flan-PaLM's gains came mostly by 282 tasks).
  • SFT minimizes DKL(pdemo∥πθ)\KL(p_{\text{demo}}\|\pi_{\boldsymbol\theta}), a sum of next-token divergences on the demonstrations' prefixes: it is mode-covering, never tests the model on its own prefixes, and with a teacher's outputs it is sequence-level distillation.
  • Small curated sets go far for format and persona (LIMA's 1,000 examples; only about 5 to 8% of tokens shift between base and aligned models), but objective skills keep improving with more data, and fine-tuning can remove skills it does not train.
  • Imitating a stronger model copies its style more than its capability; quality, diversity and coverage of the target skill matter more than raw quantity.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Supervised fine-tuning minimizes E[−log⁡πθ(y∣x)]\E\big[-\log\pi_{\boldsymbol\theta}(y\mid x)\big] on demonstrations. Which statement is exact?

  1. It minimizes DKL(πθ ∥ pdemo)\KL(\pi_{\boldsymbol\theta}\,\|\,p_{\text{demo}}) over the model's own samples
  2. It minimizes DKL(pdemo ∥ πθ)\KL(p_{\text{demo}}\,\|\,\pi_{\boldsymbol\theta}), a sum of next-token divergences on the demonstrations' prefixes, up to a constant entropy
  3. It maximizes the reward the demonstrations would receive
  4. It minimizes the number of tokens the model gets wrong when generating freely
Show the answer

B. It minimizes DKL(pdemo ∥ πθ)\KL(p_{\text{demo}}\,\|\,\pi_{\boldsymbol\theta}), a sum of next-token divergences on the demonstrations' prefixes, up to a constant entropy

E[−log⁡πθ]=DKL(pdemo∥πθ)+H(pdemo)\E[-\log\pi_{\boldsymbol\theta}]=\KL(p_{\text{demo}}\|\pi_{\boldsymbol\theta})+H(p_{\text{demo}}), and the chain rule splits the KL over prefixes drawn from the demonstrations. The model is never scored on prefixes it generates itself, which is the root of exposure bias.

Question 2

Which finding most directly challenges the superficial alignment hypothesis?

  1. LIMA matched strong assistants in human preference with 1,000 examples
  2. Aligned and base models share the top-ranked token at most positions
  3. On math, coding and multi-hop benchmarks, post-training performance kept improving as a power law in the number of fine-tuning examples
  4. Three in-context examples let a base model imitate an assistant's style
Show the answer

C. On math, coding and multi-hop benchmarks, post-training performance kept improving as a power law in the number of fine-tuning examples

If post-training only selected a format, a handful of examples would saturate objective benchmarks. Raghavendra et al. (2024) found that it did not for reasoning-heavy tasks: style aligned quickly, but scores kept climbing with more data.

Question 3

Imitation models trained on ChatGPT's outputs were rated highly by crowdworkers yet closed little of the gap on targeted benchmarks. What explains the discrepancy, according to Gudibande et al.?

  1. The crowdworkers were shown ChatGPT's answers by mistake
  2. The benchmarks were contaminated
  3. Imitation data cannot be used for fine-tuning
  4. The models copied ChatGPT's confident, well-structured style but not its factual knowledge, and non-expert raters missed the errors
Show the answer

D. The models copied ChatGPT's confident, well-structured style but not its factual knowledge, and non-expert raters missed the errors

Style is learned from a modest amount of data; knowledge and capability come mostly from the base model. Imitation helped on tasks heavily represented in the imitation data and little elsewhere, so the authors argued that better base models are the higher-leverage path.

Question 4

Flan-PaLM was instruction-tuned on a large mixture without any chain-of-thought examples. What happened to its step-by-step reasoning, and what fixed it?

  1. It improved, since any instruction tuning helps reasoning
  2. It degraded substantially; adding nine datasets with written-out reasoning preserved it
  3. It was unaffected; reasoning depends only on pretraining
  4. It degraded, and nothing short of retraining from scratch restored it
Show the answer

B. It degraded substantially; adding nine datasets with written-out reasoning preserved it

Fine-tuning shifts the model toward the formats it sees. Training only on short direct answers taught it to skip reasoning; mixing in nine chain-of-thought datasets kept the ability and improved held-out reasoning benchmarks without hurting the others.

Further reading

  • J. Wei et al., "Finetuned language models are zero-shot learners," ICLR (2022).
  • H. W. Chung et al., "Scaling instruction-finetuned language models," Journal of Machine Learning Research 25 (2024).
  • C. Zhou et al., "LIMA: Less is more for alignment," NeurIPS (2023).
  • A. Gudibande, E. Wallace, C. Snell, X. Geng, H. Liu, P. Abbeel, S. Levine & D. Song, "The false promise of imitating proprietary language models," ICLR (2024).
  • B. Y. Lin et al., "The unlocking spell on base LLMs: Rethinking alignment via in-context learning," ICLR (2024).