Instruction tuning (SFT)¶
Supervised fine-tuning takes a model that continues documents and shows it a few thousand to a few hundred thousand examples of a prompt followed by an ideal answer, training with the ordinary next-token loss on the answer tokens only. It is cheap, fast and surprisingly powerful, because it mostly teaches the model a format for knowledge it already has. Its limit is the same as its strength: it can only imitate.
10,000 ft
A base model trained on internet text treats "What is the capital of France?" as the start of a document, and may well continue it with three more quiz questions. Instruction tuning (also called supervised fine-tuning, SFT) is the first post-training step that fixes this. It descends from multi-task NLP: FLAN (Wei et al., 2021) and T0 (Sanh et al., 2021) showed that phrasing many tasks as natural-language instructions made models better at unseen instructions; InstructGPT (Ouyang et al., 2022) made human-written demonstrations the first stage of the RLHF recipe. Every later stage of this track (reward models, PPO, DPO) starts from an SFT model and uses it as the reference to stay close to. The loss is exactly the language-modelling objective; everything interesting is in the data, the template and the mask.
2,000 ft
Collect (prompt, ideal response) pairs. Render each through a chat template that marks who is speaking with special tokens and ends each turn with an end-of-turn token. Tokenise, and build a loss mask that is 1 on the assistant's tokens and 0 on everything else. Train the pre-trained model with next-token cross-entropy, averaged over the masked-in tokens only, for one to a few epochs at a small learning rate. The model learns the format (answer, then stop), the register (helpful, direct) and the policy for edge cases (clarify, refuse, admit ignorance) that the demonstrations show.
Ground level¶
What a base model does with a question¶
Pre-training maximises the probability of internet text. On the internet, a line that reads "Q: What is the boiling point of water?" is followed by an answer, by another question (a quiz), by "asked 3 years ago" (a forum), or by nothing useful at all. The base model assigns probability to all of these continuations in proportion to how often they occur. Prompt engineering for base models (GPT-3's few-shot prompts) worked by writing the start of a document in which the desired answer was the most likely continuation.
So the knowledge is there; the behaviour is not pinned down. Instruction tuning pins it down: after SFT, the most likely continuation of a user turn is an assistant turn that answers it and then ends.
The objective: next-token loss on the answer¶
Write a training example as a prompt \(x\) (system message, user turns, earlier assistant turns) and a target response \(y = (y_1, \dots, y_T)\). SFT minimises the negative log-likelihood of the response given the prompt:
This is the pre-training loss with two changes: the data is curated demonstrations rather than web text, and the prompt tokens contribute no loss. The model still reads the prompt (it is in the context, so it shapes every prediction), but it is not trained to produce it.
Chat templates: turning a conversation into one token stream¶
A transformer sees one sequence of tokens. A conversation has structure: a system message, alternating user and assistant turns, sometimes tool calls and tool results. A chat template serialises that structure with special tokens. Schematically:
The exact tokens differ by model family, and they matter in three ways:
- They are the interface. At inference time the serving stack must render conversations
with exactly the template used in training. A mismatched template (wrong role token, a
missing newline) is a common and silent cause of degraded quality. Hugging Face stores each
model's template with its tokenizer (chat templating docs)
so
apply_chat_templatereproduces it. - The end-of-turn token is how the model learns to stop. If the response is not followed by an end-of-turn token that is in the loss, the model never learns to emit it and will ramble into an imagined next user turn. LIMA added a dedicated end-of-turn token rather than reuse the pre-trained end-of-sequence token, to avoid "conflation with any other meaning that the pretrained model may have imbued" in it (Zhou et al., 2023). A related bug: if the end-of-sequence token doubles as the padding token, masking the padding also masks the real end token, and the model never learns to stop (Huang et al., 2024, detail 3).
- Role tokens carry the system's authority structure. Because system, user and tool text are marked differently, the model can learn that a system instruction outranks a user request and that text inside a tool result is data, not instructions. That distinction is the basis of defences against prompt injection.
Loss masking¶
cross_entropy skips. Note the off-by-one: the position holding the assistant role token is trained, because its target is the first answer token.Why mask the prompt? Three reasons, in decreasing order of importance:
- You want an assistant, not a user simulator. Training on user turns teaches the model to produce user turns. With long prompts (documents to summarise, retrieved passages, tool outputs) most tokens in the batch would be prompt, and most of the gradient would go into predicting text the model will never be asked to write.
- Prompts are often not text you would want imitated: pasted logs, typos, adversarial requests in a safety dataset.
- It keeps the loss interpretable: the number you watch is the model's surprise at the answer.
Masking is the default in most SFT libraries, but not universal. Some recipes train on the whole sequence and report little difference on short prompts. With long-context data the difference is large. Test it rather than assume.
Where the data comes from¶
Human-written demonstrations. InstructGPT's SFT set had about 13k training prompts (from the API and written by labellers), with responses written by a team of about 40 contractors (Ouyang et al., 2022). Meta's Llama 2 team started from public instruction data, then found that "fewer but higher-quality examples from our own vendor-based annotation efforts" improved results notably, and stopped at 27,540 annotations (Touvron et al., 2023). They also found that outputs sampled from the resulting SFT model were often competitive with human-written answers, and moved annotation effort to preference labels instead. That observation is the economic case for the next two pages: once the model writes as well as your annotators, it is cheaper to have people compare answers than write them.
Reformatted NLP tasks. FLAN took a 137B model and instruction-tuned it on over 60 NLP datasets, each rendered through ten hand-written templates, and evaluated on held-out task clusters; it beat zero-shot 175B GPT-3 on 20 of 25 datasets (Wei et al., 2021). Super-NaturalInstructions collected 1,600+ tasks with declarative instructions (Wang et al., 2022). The Flan 2022 collection scaled to 1.8K tasks and added chain-of-thought data; Flan-PaLM 540B gained 9.4 points on average over PaLM 540B, using about 0.2% of the pre-training compute (1.4B fine-tuning tokens against 780B pre-training tokens) (Chung et al., 2022). Task collections teach breadth and robustness to phrasing; on their own they produce terse, benchmark-shaped answers rather than conversational ones.
Model-generated data. Self-Instruct bootstrapped from 175 seed tasks: GPT-3 generated new instructions and answers, filtered for quality and diversity, about 52k instructions in all, and fine-tuning GPT-3 on them gave a 33% absolute improvement on Super-NaturalInstructions (Wang et al., 2022). Stanford's Alpaca applied the same recipe with OpenAI's text-davinci-003 to fine-tune LLaMA 7B on 52K demonstrations; the data cost under USD 500 and the training run three hours on eight 80 GB A100s (Stanford CRFM, 2023). Alpaca started the wave of open chat models distilled from closed ones; distillation and synthetic data covers it properly.
Curated mixtures. Modern open recipes build per-skill subsets (maths, code, instruction following with constraints, safety, multilingual, tool use), check each subset's effect on a skill-specific evaluation, decontaminate against benchmarks, and keep what helps. Tülu 3's final SFT mixture has 939,344 prompts (Lambert et al., 2024).
How much data do you need?¶
Two results bracket the answer.
LIMA: less is more for alignment. Zhou et al. fine-tuned LLaMA 65B on exactly 1,000 carefully curated prompts and responses (about 750,000 tokens), with no preference learning. In a human study, LIMA's answers were equivalent to or preferred over GPT-4's in 43% of cases, 58% against Bard and 65% against DaVinci003, which had been trained with human feedback (Zhou et al., 2023). They stated the superficial alignment hypothesis: "A model's knowledge and capabilities are learnt almost entirely during pretraining, while alignment teaches it which subdistribution of formats should be used when interacting with users."
The false promise of imitation. Gudibande et al. fine-tuned models from 1.5B to 13B on 0.3M to 150M tokens of ChatGPT outputs. Crowd workers rated the imitators as competitive with ChatGPT, but targeted evaluations showed they closed "little to none of the gap" on tasks not heavily represented in the imitation data: the models had learned ChatGPT's style but not its factuality (Gudibande et al., 2023).
Both results say the same thing from opposite sides. SFT moves a model a short distance in behaviour space: from "continue the document" to "answer in this format". That takes very little data, if the data is clean and diverse. It does not create knowledge or reasoning the base model lacks, and when it appears to, check whether the evaluators were fooled by style. In practice, published recipes use tens of thousands (Llama 2) to about a million (Tülu 3) examples, because they cover many skills, languages and edge cases, not because one skill needs that many.
SFT on facts the model does not know teaches it to make things up
If a demonstration answers a question whose answer the base model does not know, the only way for the model to lower its loss is to learn to produce confident answers without knowing. Gekhman et al. measured this in closed-book QA: fine-tuning examples with new knowledge are learned much more slowly than ones consistent with what the model knows, and "as the examples with new knowledge are eventually learned, they linearly increase the model's tendency to hallucinate" (Gekhman et al., 2024). John Schulman made the same argument in his 2023 Berkeley talk (linked below): "even if you clone on a hundred percent correct answers, you're teaching the model to hallucinate", because "the correct target has to actually depend on what knowledge is in the network" (transcript). Good demonstration sets include "I don't know" and clarifying questions where they are the honest response, and leave knowledge acquisition to pre-training (or to retrieval).
What SFT can and cannot do¶
SFT is maximum likelihood on demonstrations, so its optimum is to reproduce the demonstrators' distribution of answers, including their mistakes. If 10% of your answers to a type of question are confidently wrong, an SFT model trained to convergence will be confidently wrong about 10% of the time on that type. Build it, below, shows this exactly. Three consequences shape the rest of the track:
- The ceiling is the demonstrator. SFT cannot produce answers better on average than the data it imitates. Preference learning can, because it only needs people to recognise the better of two answers, which is easier than writing the best one.
- SFT has no negative signal. It is told what to say, never what not to say. A model can only learn "this answer is worse than that one" from comparisons or rewards.
- It trains on someone else's text, not the model's own. At inference time the model conditions on its own earlier tokens; during SFT it always conditions on the demonstrator's. Small early deviations put it in states it never trained on (the exposure bias of sequence models). RL methods train on the model's own samples and do not have this mismatch.
Multi-turn and system prompts¶
Multi-turn examples are rendered as one sequence with every assistant turn in the loss (or only the last, to avoid weighting long conversations heavily). System prompts are trained the same way: a dataset where the system message sets a persona or a constraint, and the assistant turns obey it. Llama 2 found that models forgot system-style instructions after a few turns and introduced Ghost Attention, a data trick: attach the instruction to every user turn when sampling training dialogues, then drop it from all but the first turn when training, so the model learns to keep obeying an instruction it can only see at the start (Touvron et al., 2023, section 3.3).
History¶
Instruction tuning came from two directions that met in 2022.
The multi-task direction asked whether one model trained on many tasks, each described in words, could do new tasks from their descriptions alone. Natural Instructions and then Super-NaturalInstructions collected tasks with instructions; FLAN (Google, September 2021) and T0 (BigScience, October 2021) showed that instruction tuning on dozens of datasets improved zero-shot performance on held-out task types. FLAN also found that "the benefits of instruction tuning emerge only with sufficient model scale": for its 8B and smaller models, instruction tuning hurt held-out performance. The Flan 2022 collection (Chung et al.) scaled this to 1.8K tasks and showed chain-of-thought data was necessary to keep reasoning abilities.
The alignment direction came from OpenAI's work on learning from human feedback. In InstructGPT (March 2022), SFT on labeller demonstrations was the first of three stages, and its role was specifically to give RL a good starting point. InstructGPT's SFT models "overfit on validation loss after 1 epoch", yet training for 16 epochs improved both reward model score and human preference ratings, an early sign that validation loss is the wrong thing to watch.
After ChatGPT (November 2022), the open community needed SFT data fast. Self-Instruct (December 2022) and Alpaca (March 2023) showed that a strong model could write it; LIMA (May 2023) showed that a little, very good data went a long way; Llama 2-Chat (July 2023) and the AI2 Tülu series (2023–2024) turned SFT into a careful, measured data-mixing discipline.
In practice¶
| Setting | Typical choice | Evidence |
|---|---|---|
| Learning rate (full fine-tune) | about 1e-6 to 2e-5, lower for bigger models | Tülu 3: 5e-6 for 8B, 2e-6 for 70B; LIMA: 1e-5 decaying to 1e-6 |
| Epochs | 1–3 for large mixtures; more for tiny sets | Tülu 3: 2 epochs; InstructGPT: 16; LIMA: 15 on 1,000 examples |
| Effective batch | tens to a few hundred sequences | Tülu 3: 128; LIMA: 32 |
| Max length | as long as your data needs | Tülu 3: 4,096 tokens |
| Schedule | linear warm-up, then linear or cosine decay | InstructGPT: cosine decay |
| Model selection | held-out generations judged by people, a reward model or an LLM judge | LIMA: "perplexity does not correlate with generation quality" |
Practical details that cost people days:
- Loss aggregation. Averaging the loss over all tokens in a batch weights every token equally; averaging within each sequence first weights every example equally. With gradient accumulation or several GPUs, many frameworks silently mixed the two. Tülu 3 traced a performance gap to exactly this and switched to a summed loss, retuning the learning rate to 5e-6 (Lambert et al., 2024, section 4.3.2). The numbers in Build it show how large the difference is when lengths vary.
- Packing. Concatenating short examples into one long sequence wastes no compute on padding. Use attention masks that stop one example attending to the previous one, or at least an end-of-turn token between them; otherwise the model learns spurious dependencies between unrelated examples.
- Template drift. Train and serve with the identical template; add a unit test that renders a conversation with the tokenizer's template and compares token ids.
- Forgetting. A narrow SFT set can degrade general abilities (maths, multilinguality, coding). Mixing in a share of general instruction data is the standard defence; see merging and continual learning.
- Noisy embeddings (NEFTune). Adding uniform noise to the input embeddings during SFT, scaled by \(\alpha/\sqrt{Ld}\) for sequence length \(L\) and width \(d\), raised LLaMA-2-7B trained on Alpaca from 29.79% to 64.69% on AlpacaEval (Jain et al., 2023). Gains on stronger data mixtures are smaller; it is a cheap knob, not a fix for bad data.
- Parameter-efficient training. Most people fine-tune with adapters rather than all weights. LoRA and QLoRA explains the trade-offs.
How this shows up in Jarvis
Jarvis, Finny's assistant over a financial-planning engine, follows the code-computes, model-explains split: every number comes from the engine, and the model routes requests and explains results. That split is what keeps SFT-style tuning (or few-shot prompting, its inference-time cousin) safe for a product like this: demonstrations teach the format of an explanation and when to call a tool, never facts about a user's money that the model would otherwise have to invent. See the Jarvis case study.
Common misconceptions¶
- "Fine-tuning teaches the model new facts." It can, slowly and unreliably, and at the cost of more hallucination (the pitfall above). Knowledge comes from pre-training or retrieval; SFT teaches behaviour.
- "Lower validation loss means a better assistant." InstructGPT and LIMA both found the opposite past the first epoch. Judge generations.
- "More SFT data is always better." Llama 2 improved by setting aside millions of third-party examples in favour of tens of thousands of better ones.
- "SFT and RLHF do the same thing." SFT imitates a fixed distribution; RLHF optimises the model's own distribution against a judge, with negative signal. They are complements: SFT makes RL start from somewhere sensible.
First principles¶
Why does such a small intervention change behaviour so much? Look at it as a change of distribution. SFT minimises cross-entropy to the demonstration distribution \(p_{\text{demo}}(y\mid x)\), which (see information theory) is the same as minimising the forward KL divergence
Three properties follow.
- The distance travelled is small when the base model already puts mass on good answers. The base model assigns some probability to "an assistant-style answer" because such text exists on the web. SFT only has to move that mass from a small fraction to most of the distribution. In logit terms it is a shift of a few nats on a handful of decisions (start answering, use this register, stop), which a few thousand examples pin down. This is the superficial alignment hypothesis expressed as an information budget.
- Forward KL is mode-covering. It penalises the model heavily for putting low probability on anything the demonstrators do, and lightly for putting probability on things they never do. So SFT models are spread across all the styles in the data, including the bad ones. Preference optimisation, which uses the reverse direction through its KL-regularised objective, is mode-seeking: it concentrates on the best-rated answers.
- It is imitation, so the optimum is the demonstrator. Maximum likelihood is consistent: with enough data and capacity, \(\pi_\theta \to p_{\text{demo}}\). Nothing in the objective asks for better than that.
What would break if you changed it? Drop the mask and the optimum becomes the joint distribution of prompts and answers: the model also learns to imitate users. Drop the end-of-turn token from the loss and the model never learns to stop. Train only on the single best answer per prompt, chosen by a judge, and you get rejection-sampling fine-tuning (or expert iteration), which edges SFT towards optimisation: Llama 2 used it before PPO (Touvron et al., 2023).
The maths¶
Notation: a batch of \(B\) sequences; sequence \(b\) has tokens \(s^{(b)}_1, \dots, s^{(b)}_{N_b}\) and mask \(m^{(b)}_t \in \{0, 1\}\), equal to 1 when token \(s^{(b)}_t\) belongs to an assistant turn. Logits \(\mathbf{z}^{(b)}_t \in \mathbb{R}^{V}\) at position \(t\) predict token \(t+1\).
Token-mean SFT loss (every trained token weighted equally):
Sequence-mean SFT loss (every example weighted equally): with \(n_b = \sum_t m^{(b)}_{t+1}\) trained tokens in sequence \(b\),
Under \(\mathcal{L}_{\text{seq}}\) one token of an \(n_b\)-token answer gets weight \(1/(B\,n_b)\), so a token in an 8-token answer counts \(400/8 = 50\) times as much as a token in a 400-token answer. Under \(\mathcal{L}_{\text{tok}}\) they count equally, and the long answer gets 98% of the gradient. Neither is wrong; they encode different beliefs about what matters. What is wrong is switching between them by accident when you change the number of GPUs or accumulation steps.
Gradient with respect to the logits. For a trained position, the softmax cross-entropy gradient is \(\partial \ell_t / \partial \mathbf{z}_t = \operatorname{softmax}(\mathbf{z}_t) - \mathbf{e}_{s_{t+1}}\), bounded in each coordinate by 1 (derived in information theory). Masked positions get exactly zero gradient on their own logits, but their hidden states still receive gradient through attention from later, trained positions; the prompt representation is trained to be useful for answering.
Derivation: SFT is MLE is forward-KL minimisation
For one prompt \(x\), the expected SFT loss is
by adding and subtracting \(\log p_{\text{demo}}(y\mid x)\) inside the expectation. The entropy term does not depend on \(\theta\), so minimising the loss minimises the KL. The sequence log-probability factorises by the chain rule, \(\log \pi_\theta(y\mid x) = \sum_t \log \pi_\theta(y_t\mid x, y_{<t})\), which is why the per-token loss above is exactly the sequence-level negative log-likelihood. Since \(\mathrm{KL}\ge 0\) with equality iff the distributions match, the population optimum is \(\pi_\theta = p_{\text{demo}}\) wherever the model family can represent it.
NEFTune, for completeness: given input embeddings \(X \in \mathbb{R}^{L\times d}\), train on \(X + \frac{\alpha}{\sqrt{Ld}}\,\varepsilon\) with \(\varepsilon_{ij} \sim \mathrm{Uniform}(-1, 1)\), and use clean embeddings at inference. The paper uses \(\alpha \in \{5, 10, 15\}\).
Build it¶
First, the mask and the two aggregation rules, with real numbers (NumPy):
import numpy as np
rng = np.random.default_rng(0)
# A chat example rendered with a template, then tokenised (toy ids). Labels are -100 on
# everything the model should NOT learn to produce: system, user turn, template tokens.
tokens = ["<|user|>", "What", "is", "2+2", "?", "<|assistant|>", "4", ".", "<|end|>"]
learn = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1], dtype=bool) # assistant tokens + end-of-turn
V, T = 50, len(tokens)
logits = rng.normal(size=(T, V)) # stand-in for the model's outputs
targets = rng.integers(0, V, size=T) # next-token ids (shifted labels)
def token_nll(logits, targets):
z = logits - logits.max(-1, keepdims=True)
logp = z - np.log(np.exp(z).sum(-1, keepdims=True))
return -logp[np.arange(len(targets)), targets]
nll = token_nll(logits, targets)
print("per-token NLL:", nll.round(2))
print(f"unmasked mean {nll.mean():.3f} masked mean (SFT loss) {nll[learn].mean():.3f}"
f" tokens trained on: {learn.sum()} of {T}")
# Loss aggregation: one short and one long response in the same optimiser step.
short = rng.uniform(1.0, 3.0, size=8) # per-token losses of an 8-token answer
long_ = rng.uniform(1.0, 3.0, size=400) # per-token losses of a 400-token answer
tok_mean = np.concatenate([short, long_]).mean() # all tokens in one batch
seq_mean = (short.mean() + long_.mean()) / 2 # each sequence averaged, then averaged
w_tok = len(short) / (len(short) + len(long_))
print(f"token-mean loss {tok_mean:.3f} (short answer's share of gradient {w_tok:.1%})")
print(f"sequence-mean loss {seq_mean:.3f} (short answer's share of gradient 50.0%)")
print(f"per-token weight, sequence-mean: short {1/(2*8):.4f} vs long {1/(2*400):.5f}"
f" -> ratio {400/8:.0f}x")
per-token NLL: [2.98 4.19 4.46 5.06 6.41 1.99 3.78 5.82 6.05]
unmasked mean 4.525 masked mean (SFT loss) 5.214 tokens trained on: 3 of 9
token-mean loss 1.990 (short answer's share of gradient 2.0%)
sequence-mean loss 1.882 (short answer's share of gradient 50.0%)
per-token weight, sequence-mean: short 0.0625 vs long 0.00125 -> ratio 50x
Second, the imitation ceiling. One prompt, four kinds of answer the demonstrators wrote in different proportions, and gradient descent on the SFT loss (NumPy):
import numpy as np
rng = np.random.default_rng(1)
# One prompt, four kinds of answer the demonstrators wrote, with a quality score for each.
styles = ["correct+concise", "correct+rambling", "wrong+confident", "refuses"]
quality = np.array([1.0, 0.6, -1.0, -0.3])
demo_p = np.array([0.55, 0.30, 0.10, 0.05]) # how often demonstrators wrote each
demos = rng.choice(4, size=2000, p=demo_p) # the SFT dataset for this prompt
theta = np.zeros(4) # policy logits, start uniform
for step in range(500): # SFT = gradient descent on mean NLL
pi = np.exp(theta - theta.max()); pi /= pi.sum()
grad = pi - np.bincount(demos, minlength=4) / len(demos) # d(mean NLL)/d(theta)
theta -= 1.0 * grad
pi = np.exp(theta - theta.max()); pi /= pi.sum()
for s, p, q in zip(styles, pi, demo_p):
print(f"{s:17s} learned {p:.3f} demonstrators {q:.2f}")
print(f"expected quality: SFT policy {pi @ quality:+.3f}, demonstrators {demo_p @ quality:+.3f},"
f" best single answer {quality.max():+.1f}")
correct+concise learned 0.551 demonstrators 0.55
correct+rambling learned 0.300 demonstrators 0.30
wrong+confident learned 0.093 demonstrators 0.10
refuses learned 0.056 demonstrators 0.05
expected quality: SFT policy +0.622, demonstrators +0.615, best single answer +1.0
The model learns the empirical frequencies of its 2,000 samples (0.093 rather than 0.10 is sampling noise in the dataset, not an optimisation error), and its expected quality equals the demonstrators'. Nothing in the loss knows that "wrong+confident" is bad. The reward model and RLHF pages run the same toy and push the policy towards the best answer.
Finally, the shape of a real SFT step in PyTorch (standard code; not run here). With Hugging Face models you can instead set masked label positions to −100 and let the model compute the loss:
import torch.nn.functional as F
def sft_loss(logits, input_ids, loss_mask):
"""logits (B, T, V); input_ids (B, T); loss_mask (B, T) = 1 on assistant tokens."""
logits = logits[:, :-1] # position t predicts token t+1
targets = input_ids[:, 1:]
mask = loss_mask[:, 1:].float()
nll = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1),
reduction="none")
return (nll * mask.reshape(-1)).sum() / mask.sum() # token-mean over trained tokens
Things to try
- Render one conversation through two different models' chat templates with
tokenizer.apply_chat_template(..., tokenize=False)and compare them. Which tokens would your mask need to cover in each? - In the imitation toy, set the "wrong+confident" share to 0.3. What happens to expected quality? Then train only on the most frequent answer per prompt (a crude rejection sampling) and compare.
- Fine-tune a small open model (0.5B–1.5B) with LoRA on 1,000 examples, with and without the prompt mask, using TRL's SFTTrainer. Ask both models a question and look at what they generate after their answer.
- Train the same model for 1, 3 and 10 epochs. Plot validation loss, then judge 30 generations from each blind. Do the two rankings agree?
Check yourself¶
Why is the end-of-turn token included in the loss mask, and what happens if it is not?
The model learns to stop only by being trained to predict the end-of-turn token after a complete answer. If that token is masked out (or is the same id as the padding token and gets masked with the padding), the model never receives gradient to emit it, so at inference it keeps generating: usually a hallucinated next user turn.
LIMA reached strong quality with 1,000 examples. Why do production recipes use tens of thousands to a million?
LIMA tested general conversational quality on one model and one style. Production models must cover many skills (code, maths, tool calls, multilingual, safety behaviour, long context, formats) and edge cases, each of which needs its own examples, and must not regress on any of them. The per-skill requirement may be small; the union is large.
Your SFT model's validation loss rises after epoch 1, but a judge prefers the epoch-3 checkpoint. Which do you ship and why?
Usually epoch 3, after checking on more held-out generations. Validation loss measures how well the model predicts the reference answer token by token. Further epochs make the model more confident in the demonstrated style, which raises loss on references that word things differently while improving the generations. InstructGPT and LIMA both report this effect. Confirm the judge is not just rewarding length.
With sequence-mean aggregation, a batch has one 10-token and one 1,000-token answer. How much more does one token of the short answer weigh than one token of the long answer? And with token-mean?
Sequence-mean: each sequence gets weight ½, split over its tokens, so a short-answer token weighs \(1/20\) and a long-answer token \(1/2000\): 100 times more. Token-mean: all 1,010 tokens weigh \(1/1010\) each, equally, so the short answer gets about 1% of the gradient.
Why does SFT on answers the base model does not know increase hallucination?
To lower the loss on a fact it cannot retrieve, the model must learn to emit a confident, specific answer from a context in which it has no supporting knowledge. That is the behaviour "answer confidently regardless of knowledge", and it generalises to other questions. Gekhman et al. found hallucination rises roughly linearly as such examples are fitted.
Hard: SFT minimises forward KL to the demonstrators. Explain why that makes SFT a poor final stage when demonstrators sometimes err, and what objective fixes it.
Forward KL is mode-covering: the optimum reproduces every behaviour in the data in proportion, including errors, and penalises the model for assigning low probability to any demonstrated behaviour. To prefer the good modes you need a signal that ranks behaviours: a reward or comparisons, optimised with a reverse-KL-regularised objective, \(\max_\pi \mathbb{E}_\pi[r] - \beta\,\mathrm{KL}(\pi\|\pi_{\text{SFT}})\), whose solution re-weights the SFT distribution towards high-reward answers. That is RLHF, or DPO.
Hard: the hidden states at masked prompt positions get no direct loss. Do the weights that compute them still learn from the prompt? Explain.
Yes. Masked positions contribute no loss on their own predictions, but trained positions attend to them, so the gradient of the answer tokens' loss flows back through attention into the prompt positions' keys, values and all earlier layers. The model learns to represent prompts in a way that helps answering; it just is not trained to predict prompt tokens.
Go deeper¶
Papers
- Finetuned Language Models Are Zero-Shot Learners — Wei et al., 2021. FLAN. Read the held-out-cluster evaluation design and the scale ablation in section 4.
- Multitask Prompted Training Enables Zero-Shot Task Generalization — Sanh et al., 2021. T0: the same idea with crowd-sourced prompt templates.
- Scaling Instruction-Finetuned Language Models — Chung et al., 2022. Flan 2022: 1.8K tasks, chain-of-thought data, and what scales.
- Training language models to follow instructions with human feedback — Ouyang et al., 2022. Section 3.5 and Appendix C.1 for SFT; the rest for the stages that follow.
- Self-Instruct — Wang et al., 2022. The generate-filter loop behind most synthetic SFT data.
- LIMA: Less Is More for Alignment — Zhou et al., 2023. The superficial alignment hypothesis and how the 1,000 examples were chosen.
- The False Promise of Imitating Proprietary LLMs — Gudibande et al., 2023. Why style fools raters; read with LIMA.
- Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations? — Gekhman et al., 2024. The controlled experiment behind the pitfall above.
- Tülu 3 — Lambert et al., 2024. Section 4: building an SFT mixture skill by skill, and the loss-aggregation bug.
- NEFTune: Noisy Embeddings Improve Instruction Finetuning — Jain et al., 2023. A two-line trick and an honest discussion of why it might work.
Videos and lectures
- Instruction finetuning and RLHF lecture (NYU CSCI 2590) — Hyung Won Chung. A Flan author on what instruction tuning does and why RLHF comes next.
- John Schulman: Reinforcement Learning from Human Feedback: Progress and Challenges — UC Berkeley EECS. The behaviour-cloning-causes-hallucination argument, from an InstructGPT author.
- State of GPT — Andrej Karpathy, Microsoft Build 2023. The base → SFT → RM → RL pipeline at the right altitude, with base-model examples.
Articles and docs
- Alpaca: A Strong, Replicable Instruction-Following Model — Stanford CRFM, 2023. The cheap-distillation recipe and its stated limitations.
- Chat templates — Hugging Face docs. How templates are stored and applied, and generation prompts.
Courses and books
- Supervised Fine-Tuning (LLM Course, chapter 11) — Hugging Face. Hands-on SFT with chat templates and TRL.
- Reinforcement Learning from Human Feedback — Nathan Lambert. The instruction-tuning chapter places SFT in the full pipeline.
Code
- huggingface/trl — SFTTrainer, with chat-template handling and completion-only loss.
- allenai/open-instruct — The Tülu training code: SFT, DPO and RLVR at scale.
Where this leads¶
- Reward models and preference data: the signal SFT lacks, "this answer is better than that one".
- Parameter-efficient fine-tuning: LoRA and QLoRA: how to run SFT on one GPU.
- Distillation and synthetic data: where most SFT data now comes from.
- Project: fine-tune a model with LoRA: do it end to end.