Instruction Tuning and Supervised Fine-Tuning (SFT)
A pretrained language model continues text; it does not follow instructions. Supervised fine-tuning (SFT), or instruction tuning, trains it on examples of instructions paired with good responses, formatted with a chat template of system, user and assistant turns. The model then learns to answer, follow formats and act as an assistant (InstructGPT, FLAN, Alpaca, LIMA). Key practical choices are the data (quality and diversity beat volume), the template, packing, and computing the loss only on response tokens, so the model is not trained to imitate prompts. This page covers SFT data sources, templates, loss masking, packing and evaluation. In the exercises you build a chat template, prompt masks and packed sequences, then instruction-tune a one-block Transformer on 300 examples. An instruction token says whether to copy the prompt or copy it plus one. With the loss on response tokens only, response accuracy reached 0.93. With the loss on all tokens, the same budget reached only 0.51, learning to copy but not to obey the instruction. Without the instruction token, accuracy was 0.51, as expected for an ambiguous task.
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.
Teaching a model to follow instructions
A model trained only to continue text might answer “Write a haiku about rockets” by continuing with more instructions. Instruction tuning shows it many examples of instructions with good answers, so it learns the pattern “when asked, respond helpfully in the requested form”. A trick that matters: only grade the model on the answers, not on repeating the questions. The demo shows the causal mask the model uses while learning.
LLM lab
Row i shows what token i may attend to: itself and earlier tokens only (36 of 64 pairs). This is what lets one forward pass train on every next-token prediction at once.
Why engineers care
SFT is how a general model becomes a procedure assistant that answers in the required format (step lists, checklists, JSON) and refuses out-of-scope requests.
📝 Quick check (Level 0)
0/3 answered
1. SFT trains on…
2. In SFT the loss is usually computed on…
3. A chat template marks…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.
By hand
Data: human-written demonstrations (InstructGPT), converted academic tasks (FLAN, T0), model-generated instructions (Self-Instruct, Alpaca), curated small sets (LIMA: about 1000 examples) and conversation logs (with consent). Deduplicate and filter for quality.
Template: role markers and end-of-turn tokens, for example <|user|> … <|end|> <|assistant|> …. Use exactly the template the model was trained with at inference.
Loss masking: labels −100 on system and user tokens, so only the assistant’s tokens are trained. With a 400-token prompt and a 100-token answer, only 20% of tokens carry loss.
Packing: concatenate examples into full-length sequences (with attention masks between them if needed) instead of padding.
Scale: SFT sets are small (thousands to a few million examples, often under 10⁹ tokens), so 1–3 epochs at a low learning rate.
Evaluation: instruction-following benchmarks (IFEval), human or LLM-judge preference (F14-3), and checks that pretraining knowledge survives.
📝 Quick check (Level 1)
0/3 answered
1. Fraction of tokens trained with a 400-token prompt and 100-token answer:
2. LIMA used about…
3. Labels of prompt tokens are set to…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.
SFT in code
Exercise 1.
Render a conversation with a chat template.
Build label masks that ignore prompt tokens.
Pack examples into fixed-length sequences.
Practice.
TRL’s SFTTrainer handles chat templates (tokenizer.apply_chat_template), assistant-only loss and packing.
Keep a held-out set of instructions; read many outputs yourself.
Mix task-specific data with general instruction data to keep the model broadly useful.
Make sure the end-of-turn token is trained, or the model will not stop generating.
Render a chat template, build prompt-masked labels and pack examples.
📝 Quick check (Level 2)
0/3 answered
1. Hugging Face method that applies a model's chat format:
2. If the end-of-turn token is not trained, the model…
3. General instruction data is mixed in to…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.
Theory
Why mask the prompt. Prompt tokens are given at inference time, so predicting them is not part of the task. Training on them spends capacity and gradient on imitating users (and, in exercise 2, on predicting random tokens), diluting the signal from the response. Results in the literature are mixed for large models with long training; with a small budget, masking clearly focuses learning.
What SFT changes. The superficial alignment hypothesis (LIMA) holds that knowledge comes from pretraining, while SFT mainly teaches format, style and when to use which ability. This is why a small, high-quality, diverse set can beat a large noisy one.
Limits. SFT imitates demonstrations, including their errors, and cannot teach the model to prefer better over worse answers when both are plausible. Preference-based alignment (F7) addresses that.
📝 Quick check (Level 3)
0/3 answered
1. Prompt tokens at inference are…
2. The superficial alignment hypothesis says SFT mainly teaches…
3. SFT cannot directly teach…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.
Does computing the loss only on responses make instruction tuning more efficient?
History.
J. Wei et al., “Finetuned language models are zero-shot learners” (ICLR 2022), FLAN.
L. Ouyang et al., “Training language models to follow instructions with human feedback” (NeurIPS 2022), InstructGPT.
R. Taori et al., “Alpaca” (2023); C. Zhou et al., “LIMA: less is more for alignment” (NeurIPS 2023).
Exercise 2.
Examples: [instruction] prompt (7 random tokens) [SEP] response (7 tokens). Instruction “copy” means the response repeats the prompt; “shift” means each prompt token plus 1 (mod 10).
Model: the one-block Transformer from F6-1, trained from scratch on 300 examples for 300 Adam steps.
Variants:
loss on response tokens only;
loss on all tokens;
no instruction token (task ambiguous).
Metric: greedy response-token accuracy on 1000 new examples.
variant
response accuracy
loss on responses only
0.927
loss on all tokens
0.510
no instruction token
0.508
Masking the prompt makes the budget count: the model learns both the copying and the instruction-dependent shift.
With loss on all tokens it learns only half the task: in the same steps it learned to copy, but not to obey the shift instruction (about 0.5 = right on copy examples). Gradient on the random prompt tokens is pure noise.
Without the instruction, nothing can disambiguate the task, and accuracy is about 0.5 whatever the training.
Seeds: seeds 1 and 2 gave 0.714 and 0.924 with masking, against 0.505 and 0.516 without. With masking the run in seed 1 had not yet fully learned the shift, so masking speeds learning without guaranteeing it.
🐍 Exercise 2 (research): does computing the loss only on responses make instruction tuning more efficient?
Instruction-tune a small Transformer with the loss on response tokens only, on all tokens, and without the instruction token; compare response accuracy.
SFT in AI, robotics and aerospace
Procedure assistants: teaching formats such as checklists, numbered steps and structured fault reports.
Robot instruction following: the same recipe fine-tunes vision-language-action models on (instruction, demonstration) pairs.
Design lesson: train on what the model must produce, with clean, diverse demonstrations.
References
J. Wei et al. (2022). “Finetuned language models are zero-shot learners.” Proc. ICLR.
L. Ouyang et al. (2022). “Training language models to follow instructions with human feedback.” NeurIPS.
C. Zhou et al. (2023). “LIMA: less is more for alignment.” NeurIPS.
Z. Shi et al. (2024). “Instruction tuning with loss over instructions.” arXiv:2405.14394.
300 examples, 300 steps: response-only loss 0.93 accuracy vs 0.51 with loss on all tokens.
Practice
Show:
Level 0
Problem 1Level 0
Fraction of tokens with loss for a 400-token prompt and 100-token answer?
0.2.
Problem 2Level 0
Training examples in exercise 2?
300.
Problem 3Level 0
Approximate size of the LIMA dataset?
1000.
Level 1
Problem 4Level 1
SFT tokens for 10,000 examples of 600 tokens?
6000000.
Problem 5Level 1
Packing efficiency of lengths 100, 300, 200, 400 padded to 1000?
0.25.
Problem 6Level 1
Response tokens per example in exercise 2?
7.
Problem 7Level 1
Accuracy expected if only the copy instruction is learned and tasks are balanced?
0.5.
Level 2
Problem 8Level 2
Response accuracy with response-only loss?
0.927.
Problem 9Level 2
Response accuracy with loss on all tokens?
0.51.
Problem 10Level 2
Response accuracy without the instruction token?
0.508.
Problem 11Level 2
Training steps?
300.
Problem 12Level 2
Response-only accuracy, seed 1?
0.714.
Problem 13Level 2
Instructions in exercise 2?
2.
Level 3
Problem 14Level 3
Explain why the no-instruction model could not beat 0.5.
Without the instruction token, copy and shift examples have identical inputs (a random prompt and SEP) but different correct responses, each half the time. Any model’s best guess is right on only one of the two tasks for each input, so at most about 0.5 of response tokens can be correct. ∎
Problem 15Level 3
Explain why loss on all tokens slowed learning.
Prompt tokens are random, so their prediction loss stays at about ln 10 and their gradients are noise. They are 8 of 15 targets, so most of each update pushes in random directions, and the useful signal from the 7 response tokens is diluted. In 300 steps the model learned only the easier copying part. ∎
Problem 16Level 3
Compare SFT with continued pretraining for a domain assistant.
Continued pretraining on domain text teaches knowledge and vocabulary but not how to answer. SFT on domain instruction–response pairs teaches behaviour and format, drawing on knowledge already present. Assistants usually need both: continued pretraining if the domain is far from general text, then SFT. ∎
Problem 17Level 3
Advise on building an SFT set for a maintenance assistant.
Collect a few thousand high-quality question–answer pairs from engineers and manuals, covering common tasks and refusal cases; deduplicate; use the model’s chat template with assistant-only loss; mix in general instruction data; hold out a test set; and review outputs with domain experts. ∎
Level 4
Problem 18Level 4
Response-only accuracy, seed 2?
0.924.
Problem 19Level 4
Loss-on-all-tokens accuracy, seed 1?
0.505.
Problem 20Level 4
Prompt length in exercise 2?
7.
Coding practice
🐍 Code 1 (Level 0): trained fraction
response / total.
🐍 Code 2 (Level 0): SFT tokens
examples · length.
🐍 Code 3 (Level 0): packing efficiency
Σ lengths / (n · max).
🐍 Code 4 (Level 0): instruction dedup
Normalise and drop repeats.
🐍 Code 5 (Level 0): LIMA budget
About 1000 examples.
Topic test
A timed test drawn at random from this topic's question bank. Each attempt gets new questions. For a longer test across the whole chapter, see the chapter test, or mix topics in the question bag.
Instruction Tuning and Supervised Fine-Tuning (SFT): topic test
10 questions, drawn at random from a bank of 21. Every attempt is different.
⏱ Time limit: 15 minutes. The test submits itself when time runs out.
Levels covered: 0, 1, 2, 3, 4. No hints or solutions until you submit.