All courses

Supervised fine-tuning on demonstrations

Fine-tune a base model on (prompt, ideal response) pairs, computing the loss only on response tokens. Explain why a small, high-quality set mainly teaches format and persona rather than new knowledge.

Builds on: Base models continue documents, Shifted targets and parallel training, The LLM training loop

▶ Watch this lesson Start the whole course

What the animation says

From continuer to assistant

A base model only continues documents. Hand it a question, and it may just write more questions. An assistant answers in a steady voice, follows a format, and stops at the right point. To get there, labs write maybe ten to a hundred thousand examples, after pretraining on trillions of tokens. Each example is a prompt and an ideal reply, glued into one document with a fixed layout: User, then Assistant. We train with the usual next-token loop. But which predictions should the model be graded on?

Only the reply is graded

Only the reply counts. Here is our tiny document: User, hi, Assistant, Hello, exclamation mark, end. Six tokens. Each position predicts the next one, so positions one to five have a target. The end token belongs to the reply. It teaches the model when to stop. A position is scored when its target is a reply token. Watch the target column, not the input. Your turn: drag the divider so only the scored positions sit below it.

Masked loss, by hand

So the mask is zero, zero, one, one, one. The model gives each true next token a probability: point one, point zero five, point five, point eight, point nine. Each position's loss is minus the log of that probability. Confident and right means a small loss. Average only the three scored positions: about point six nine, point two two and point one one. That's roughly point three four. Now remove the mask and average all five positions. What happens to the loss?

The mask in PyTorch

It nearly quadruples, to about one point two six. Without the mask, guessing the user's words dominates. In code, the mask is one line. Shift the tokens left to get the targets, as usual. Then this line sets the prompt targets to minus one hundred. Cross entropy skips every target equal to that ignore index and averages over the reply tokens only. Gradients still flow back through attention into the prompt. So the model learns to use the prompt, just never to predict it.

Why so few examples work

So supervised fine-tuning is plain next-token loss on demonstrations, with the prompt masked out. Why do so few examples change behaviour so much? Style, format and persona show up in every single example. Thousands of repeats push them hard. A new fact appears once or twice. That's too little signal to store it reliably. So fine-tuning mostly changes how the model answers, not what it knows. The knowledge came from pretraining.

From document-continuer to assistant

A base model only continues documents. An assistant answers in a steady voice, follows a format and stops at the right point. Labs get there with perhaps 10k–100k written examples, after pretraining on trillions of tokens. How do you train on (prompt, ideal response) pairs? And why do so few examples change behavior so much while adding little new knowledge?

Same loop, but only the reply is graded

Glue each pair into one document with a fixed layout, e.g. `User: … Assistant: …`. Then run the usual training loop with teacher forcing. One change: **only response tokens are scored**. The model reads the prompt as context, but it is never trained to predict the user's words. Pretraining already stored facts and skills. The demos mainly teach *which kind of document to continue*: an assistant's reply.

The masked next-token loss

$$\mathcal{L} = -\frac{1}{\sum_t m_t}\sum_{t=1}^{T-1} m_t \log p_\theta(x_{t+1}\mid x_{\le t})$$ $m_t=1$ if the target $x_{t+1}$ is a response token, else $0$. The sums run over all sequences in the batch. Shifted targets, causal mask, forward and backward are unchanged. Response losses still backpropagate through attention into prompt positions, so the model learns to *use* the prompt.

Masked vs unmasked loss, by hand

Tokens: `User:` `hi` `Assistant:` `Hello` `!` `<end>` (T=6). `<end>` teaches the model when to stop. Positions 1–5 predict $x_2…x_6$. Only $x_4…x_6$ are response tokens, so $m=[0,0,1,1,1]$. The model's probabilities on the true targets are 0.1, 0.05, 0.5, 0.8, 0.9. - **Masked:** $(0.6931+0.2231+0.1054)/3 = 1.0216/3 \approx 0.341$ nats. - **Unmasked:** add $2.3026+2.9957$, giving $6.3199/5\approx1.264$. Without the mask, guessing the user's words dominates the loss.

Loss masking in PyTorch

The one SFT-specific line sets prompt targets to `-100`. `cross_entropy` then skips those positions and averages over response tokens only. The rest of the training loop is unchanged.
import torch, torch.nn.functional as F
V = 10
ids = torch.tensor([[3, 7, 1, 4, 9, 2]])   # [B=1, T=6]; first 3 = prompt
prompt_len = 3
inputs, targets = ids[:, :-1], ids[:, 1:].clone()  # shift left
targets[:, :prompt_len - 1] = -100  # targets x2..x3 are prompt: no loss
logits = torch.randn(1, 5, V, requires_grad=True)  # stand-in for model(inputs)
loss = F.cross_entropy(logits.reshape(-1, V), targets.reshape(-1),
                       ignore_index=-100)  # mean over response tokens only
loss.backward()
print(loss.item())

Remember

SFT is next-token cross-entropy on demonstration documents, with a loss mask so only response tokens count. Style, format and persona recur in *every* example, so a small clean set shifts them strongly. Each new fact appears only once or twice, which is too little signal to store it reliably. So SFT mostly changes *how* the model answers, not *what it knows*.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.