Foundations to Frontier
Tests
F. NLP and Large Language Models › F6 Fine-Tuning and Adaptation

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.

Level 0: Foundation

★☆☆☆☆ 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. 1. SFT trains on…
  2. 2. In SFT the loss is usually computed on…
  3. 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. 1. Fraction of tokens trained with a 400-token prompt and 100-token answer:
  2. 2. LIMA used about…
  3. 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.
from trl import SFTTrainer, SFTConfig
cfg = SFTConfig(output_dir="sft", learning_rate=2e-5, num_train_epochs=2, packing=True,
                assistant_only_loss=True, max_length=2048)
SFTTrainer(model="meta-llama/Llama-3.2-1B", train_dataset=ds_chat, args=cfg).train()   # ds_chat: {"messages": [...]}
🐍 Exercise 1: templates, masks and packing
Render a chat template, build prompt-masked labels and pack examples.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Hugging Face method that applies a model's chat format:
  2. 2. If the end-of-turn token is not trained, the model…
  3. 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. 1. Prompt tokens at inference are…
  2. 2. The superficial alignment hypothesis says SFT mainly teaches…
  3. 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

  1. J. Wei et al. (2022). “Finetuned language models are zero-shot learners.” Proc. ICLR.
  2. L. Ouyang et al. (2022). “Training language models to follow instructions with human feedback.” NeurIPS.
  3. C. Zhou et al. (2023). “LIMA: less is more for alignment.” NeurIPS.
  4. Z. Shi et al. (2024). “Instruction tuning with loss over instructions.” arXiv:2405.14394.