4.3.11 · D4Pretraining & Fine-Tuning LLMs

Exercises — Supervised fine-tuning (SFT)

2,469 words11 min readBack to topic

Two facts we reuse constantly, stated in plain words first:


L1 — Recognition

Exercise 1.1 (L1)

Which loss function does SFT minimize, and how does it differ from the loss used during pretraining?

Recall Solution

What loss: the next-token cross-entropy (equivalently, the average negative log-likelihood of the correct next token), exactly as in Cross-entropy loss and Autoregressive language modeling. The difference: not the loss formula. Two things change:

  1. Data — curated (prompt, response) demonstrations instead of raw internet text.
  2. Loss mask — only response tokens contribute to the loss; prompt tokens are masked out. Everything else (the forward pass, the backprop, the cross-entropy) is identical.

Exercise 1.2 (L1)

In the chat-templated example <|user|> Hi <|assistant|> Hello! <|eos|>, which tokens get mask ?

Recall Solution

Mask for everything up to and including <|assistant|> (that is the prompt, given input). Mask for the answer tokens and <|eos|> — so here Hello, !, and <|eos|>. Why include <|eos|>? So the model learns when to stop talking — a real assistant skill. See Chat templates & special tokens.

Exercise 1.3 (L1)

True or false: "SFT is a form of imitation learning (behavioral cloning)." Justify in one sentence.

Recall Solution

True. We show the model demonstrations of the desired output and train it to reproduce them; copying a demonstrated policy is exactly behavioral cloning.


L2 — Application

Exercise 2.1 (L2)

A model answers a one-token response. It assigns probability to the correct token. Compute the per-token loss .

Recall Solution

. Sanity check: is a "meh" probability, so the loss is well above but not huge. If were , loss would be ; if , loss .

Exercise 2.2 (L2)

Prompt = ["Name","a","color","?"]. Response = ["Blue","<eos>"]. The model predicts:

Compute the masked average SFT loss.

Recall Solution

Step 1 — mask. Prompt tokens get ; only "Blue" and "" count. So . Step 2 — per-token NLL. Step 3 — average. Why divide by 2? So a long answer isn't automatically penalized more than a short one — we average per response token.

Exercise 2.3 (L2)

Same setup as 2.2, but a bug leaves the mask ON for all tokens (prompt included). The prompt-token probabilities the model assigned were each (four prompt tokens). Recompute the "loss" the buggy code reports.

Recall Solution

Now (4 prompt + 2 answer). Prompt contribution: . Answer contribution: . Interpretation: the loss is now dominated by how well the model predicts the user's own question — a skill we never wanted to teach. Compare to the correct : the signal about the answer has been drowned out.

Figure — Supervised fine-tuning (SFT)

L3 — Analysis

Exercise 3.1 (L3)

Explain, using the loss formula, why masking the prompt matters. What concretely goes wrong if we don't?

Recall Solution

Unmasked, the loss includes terms for predicting prompt tokens. Gradient descent then pushes the model to become a good question predictor, spending capacity on user input we already have. Two concrete harms:

  1. Diluted signal — as Exercise 2.3 showed numerically, prompt terms can dominate the average and swamp the answer-learning signal.
  2. Wasted capacity / worse answers — the model optimizes something irrelevant to the task, which can degrade answer quality. The mask zeroes out those prompt terms so only answer-generation is rewarded.

Exercise 3.2 (L3)

Two responses to the same prompt have masked losses and . Convert each to the model's average per-token probability of the correct token, and explain what the gap means.

Recall Solution

Loss , so the geometric-mean per-token probability is .

  • Meaning: on the first response the model was already assigning ~82% average probability to the right tokens (nearly imitating it), while on the second only ~45% — much more to learn. Lower loss ⇔ closer to reproducing the demonstration.

Exercise 3.3 (L3)

A student claims: "After SFT the model knows new facts it didn't before." Refute or support, and say what SFT actually changed.

Recall Solution

Mostly refute. SFT teaches format and behavior — responding rather than autocompleting, tone, instruction-following, stopping at <|eos|>. The bulk of factual knowledge comes from pretraining. Why it looks like new knowledge: the model appears smarter because it now surfaces what it already knew in a helpful format. Danger: trying to cram fresh facts through a small SFT set often produces hallucination — the model learns the style of confidently stating facts without the underlying knowledge to back specific ones.


L4 — Synthesis

Exercise 4.1 (L4)

You have 2,000 hand-checked demonstrations and 200,000 scraped noisy Q&A pairs. Using "SFT = imitation," argue which you'd fine-tune on, and predict the failure mode of the wrong choice.

Recall Solution

Choose the 2,000 clean demos (LIMA-style reasoning). Argument: the loss rewards matching whatever you show — good or bad. Noisy data teaches noisy behavior: hallucinated facts, sloppy formatting, inconsistent tone. The model becomes an excellent imitator of garbage. Failure mode of the big noisy set: the model's average behavior regresses to the noisy demonstrations; more tokens ≠ better if those tokens encode bad behavior. The 20% that matters here is data quality, not quantity. (This is the intuition behind Instruction Tuning datasets being carefully curated.)

Exercise 4.2 (L4)

Order these three stages and justify: SFT, pretraining, preference optimization (RLHF / Direct Preference Optimization (DPO)). Why can't you swap SFT and pretraining?

Recall Solution

Order: pretraining → SFT → preference optimization.

  • Pretraining first: builds the raw language/world model from massive text; without it there's nothing to imitate with.
  • SFT next: converts the autocomplete into an instruction-follower via demonstrations.
  • Preference optimization last: refines which good answers to prefer using ranked comparisons — it assumes the model already produces reasonable candidates (which SFT gave it). Can't swap SFT/pretraining: SFT is continued training on a pretrained model; a from-scratch model has no linguistic competence to clone behavior onto, so a few thousand demos couldn't teach language and behavior at once.

Exercise 4.3 (L4)

Your SFT machine runs out of memory doing full fine-tuning. Name a technique from the connections that fits, and state in one sentence why it uses less memory — without changing the SFT loss.

Recall Solution

Use LoRA / PEFT. It freezes the base weights and trains only small low-rank adapter matrices, so the optimizer stores gradients/states for a tiny fraction of parameters — the loss (masked cross-entropy) is unchanged, only which parameters receive updates differs.


L5 — Mastery

Exercise 5.1 (L5)

Derive, from the chain rule, why the sequence log-probability equals a sum of per-token log-probs, and connect this to why per-token cross-entropy is the natural loss. Then compute the total masked loss for a 3-token answer with per-token correct-probabilities .

Recall Solution

Derivation. A response has joint conditional probability factorizable by the chain rule of probability: Taking (monotonic, so it doesn't move the maximizer) turns the product into a sum: Flipping sign gives a quantity to minimize; each term is precisely the per-token Cross-entropy loss between the one-hot true token and the model's predicted distribution. So minimizing sequence NLL = summing per-token cross-entropies — the loss is forced by the autoregressive factorization, not chosen arbitrarily. Compute. Each token: . Average over 3 response tokens: . (Here the average equals the per-token value because all three are equal — a useful check.)

Exercise 5.2 (L5)

Two runs on the same single-answer batch report losses (correctly masked) and (mask accidentally left off, so it also averaged over 3 prompt tokens whose probabilities were each). Was model B actually better at the answer? Reconstruct B's true answer-only loss (answer is 1 token).

Recall Solution

B's reported loss mixes prompt terms. With 3 prompt tokens at : each contributes . Let the single answer token contribute . B averages over tokens: This is impossible — a per-token NLL can't be negative. So a reported cannot arise from those prompt probabilities: the unmasked average would be dominated by the large prompt terms ( from the prompt alone). The lesson: an unmasked loss is not comparable to a masked one — B's number is measuring a different quantity, and here the arithmetic even flags the mismatch. Never compare masked vs unmasked losses across runs.

Exercise 5.3 (L5)

Design a one-paragraph SFT recipe for turning a base model into a polite coding assistant. Reference at least four connected concepts and state, for each, the why.

Recall Solution

Start from a strong base checkpoint (knowledge lives in pretraining, so pick one already fluent in code). Curate a small, high-quality demonstration set of (coding question → clean, correct, well-formatted answer) — quality bounds imitation quality (Instruction Tuning). Wrap every example in a consistent chat template so the model learns role boundaries and where answers begin/end, and mask everything up to <|assistant|>, keep <|eos|> masked-in so it learns to stop. Train with the standard masked next-token cross-entropy (unchanged from autoregressive pretraining); if memory is tight, use LoRA / PEFT to update only small adapters. Then, and only then, refine tone and correctness preferences with RLHF or Direct Preference Optimization (DPO), because those need a competent SFT policy to rank. The whole SFT phase is imitation — Demonstrate, Mask, Mimic.


Recall One-line self-test recap

SFT loss = masked next-token cross-entropy ::: average over response tokens only Perfect-prediction per-token loss ::: (because ) Two things that differ from pretraining ::: the data and the loss mask Why average, not sum ::: so loss doesn't scale with answer length