Chapter 01 · Foundations

Supervised fine-tuning & the data engine

SFT is maximum likelihood on someone else's trajectories. Everything interesting about it — what it teaches, what it breaks, why distillation beats RL for small models — follows from that one sentence.

⏱ 75 min8 interactivesPrereq: cross-entropy, softmax, a bit of RL vocabulary
In one breath
  • SFT minimizes forward KL from the demonstration distribution to the model, using teacher forcing. That makes it off-policy imitation (behavior cloning): the model is never trained on the prefixes it will produce itself.
  • Most practical SFT bugs live in the plumbing: chat template, end-of-turn token, loss masks, packing masks and how you average the loss. Each one silently changes which tokens the model learns from, and how hard.
  • Data quality and diversity beat volume for format (LIMA); volume still buys skills (Tülu 3, OpenThoughts). Synthetic data is now the default; collapse is a risk of replacing real data, not of using synthetic data.
  • Distillation is SFT with a better target: teacher logits carry far more signal than one sampled token, and on-policy distillation (student samples, teacher grades every token) fixes exposure bias while keeping dense supervision. For small models it beats RL at roughly a tenth of the compute in the reported cases.
  • Rejection-sampling fine-tuning (STaR, ReST, expert iteration) is RL with a binary reward and no negative gradient: cheap, stable, and diversity-collapsing. Context distillation, Anthropic's 2021 trick, turns a prompt into weights and lives on in deliberative alignment and on-policy self-distillation.
  • "SFT memorizes, RL generalizes" is a useful slogan with real caveats: much of the gap is data design, and the deeper story is about how far each method moves the model from where it started.

§1The objective: conditional maximum likelihood

Take a pretrained model that continues documents. Show it examples of the documents you wish it would write, and raise their probability. That is all SFT is, and almost every subtlety comes from the word "examples".

A dataset $\mathcal{D}$ holds pairs $(x, y)$: a context $x$ (system prompt, conversation so far) and a target response $y = (y_1,\dots,y_T)$. The model $\pit$ factorizes the response autoregressively. SFT minimizes the negative log-likelihood of the targets, but only on the tokens you choose to train on, selected by a binary mask $m_t$:

$$\mathcal{L}_{\text{SFT}}(\theta) \;=\; -\,\htmlClass{t-data}{\E_{(x,y)\sim\mathcal{D}}}\Bigg[\frac{1}{\htmlClass{t-norm}{Z}}\sum_{t=1}^{T} \htmlClass{t-mask}{m_t}\,\log \pit\big(y_t \,\big|\, x,\, \htmlClass{t-prefix}{y_{\lt t}}\big)\Bigg]$$
  • Data distribution: responses come from humans or a teacher model, never from $\pit$ itself. This is what makes SFT off-policy.
  • Ground-truth prefix: teacher forcing. Token $t$ is predicted from the dataset's previous tokens, not the model's.
  • Loss mask: 1 on tokens you want to learn (usually assistant content plus its end token), 0 on prompts and padding.
  • Normalizer: number of loss tokens in the sequence, in the batch, or 1 (sum). This innocent choice re-weights long versus short answers (§2).

Two equivalent readings matter for the rest of the guide. First, since $\E_{y\sim p}[-\log q(y)] = H(p) + \KL(p\,\|\,q)$ and the entropy of the data does not depend on $\theta$, minimizing the expected NLL is minimizing

$$\E_{x}\Big[\KL\big(p_{\text{data}}(\cdot\mid x)\,\big\|\,\pit(\cdot\mid x)\big)\Big],$$

the forward KL from the data to the model. Forward KL punishes the model for putting low probability anywhere the data puts mass, so it is mode-covering. Keep this in your pocket until §4.

Second, SFT is behavior cloning. Treat the context plus partial response as a state $s_t = (x, y_{\lt t})$, the next token as an action $a_t = y_t$, and appending as a deterministic transition. A dataset of demonstrations is a dataset of expert state-action pairs, and cross-entropy on them is the textbook behavior-cloning loss. The RL chapters (02, 06) will use exactly this MDP; the difference is only whose trajectories you learn from.

Analogy · tracing paper

SFT is learning to draw by tracing over a master's drawings. Every stroke you practice starts exactly where the master's previous stroke ended. You get very good at continuing correct partial drawings. Nobody ever shows you what to do after your own wobbly line, because in tracing your line is always erased and replaced by the master's.

Where it breaks: a tracer learns nothing about the master's intent, while an LLM does learn generalizable structure from demonstrations (that is why SFT works at all). The analogy is about the state distribution, not about understanding.

Teacher forcing and exposure bias

Teacher forcing makes training embarrassingly parallel: one forward pass computes the loss at every position, because every prefix is known in advance. The price is a mismatch. At training time the prefix $y_{\lt t}$ comes from the data. At inference time it comes from the model. If the model makes a mistake the data never contains, it is now in a state it was never trained on. This is exposure bias.

Imitation learning makes this quantitative. Let $\varepsilon$ be the per-step error rate of the cloned policy on the expert's state distribution (roughly what your validation loss measures). In the worst case, once the policy leaves the expert's states it never recovers and pays a cost of 1 on every remaining step. The probability of having left by step $t$ is at most $t\varepsilon$ (union bound), so

$$\text{expected cost} \;\le\; \sum_{t=1}^{T} t\,\varepsilon \;\approx\; \tfrac{1}{2}\,T^2\varepsilon \qquad\text{versus}\qquad T\varepsilon \text{ under teacher forcing.}$$

This is the classical $O(T^2\varepsilon)$ behavior-cloning bound (Ross & Bagnell; restated for language generation by Arora et al., 2022 as $T\varepsilon \le \mathcal{R}(\pi_{\text{BC}}) \le T^2\varepsilon$). Methods that train on the learner's own states, such as DAgger, bring it back to linear. Play with the toy below: the blue dashed line is what your loss curve "sees"; the clay line is what users experience.

A two-state Markov model of generation: on the data manifold the model errs with rate ε and leaves it; off the manifold every step is a mistake until it recovers. Push T up with recovery at 0 and watch the clay curve bend away from εT: quadratic at first, then one mistake per token once almost every rollout has left the manifold. Then raise self-recovery: the gap shrinks to linear. The green curve is a policy trained on its own states, which learned to recover. A toy, not a measurement.

So is exposure bias the reason LLMs hallucinate and loop? The evidence is mixed, and the disagreement is itself worth understanding. He et al. (2019) fed models ground-truth versus self-generated prefixes and found the distortion "is limited, and does not seem to be incremental", attributing it to a self-recovery ability of language models (one intuition: a model pretrained on messy text has seen many recoveries from small errors, so its own slips rarely push it off the manifold). Arora et al. (2022) measured error accumulation directly and argued it is real and that perplexity fails to capture it. Both can be true: the self-recovery slider in the widget is exactly the quantity they disagree about, and it is plausibly larger for big pretrained models than for small task-specific ones (an intuition, not a measured result).

A subtler failure is that teacher forcing can make the task easier than it really is. Bachmann & Nagarajan (2024) built a path-finding task where, given the true prefix of the answer, later tokens are trivially predictable, so the model learns a "Clever Hans" shortcut that uses the revealed prefix and never learns to plan the first token. At inference there is no revealed prefix and the model fails. The models were trained to perfect training accuracy, yet failed on held-out graphs drawn from the same distribution: the loss curve gave no warning.

Key idea · why this chapter is the first RL chapter

SFT trains on $d_{\text{data}}(s)$; deployment happens on $d_{\pit}(s)$. Every method later in this guide that samples from the model during training (rejection sampling, on-policy distillation, PPO, GRPO) exists partly to close that gap. When someone says "on-policy", translate it as "trained on the states it will actually visit".

SFT is a (badly weighted) policy gradient

Here is a derivation worth working through by hand. For a single demonstration $y^*$, write the SFT gradient as an expectation under the model's own distribution:

$$\nabla_\theta \log \pit(y^*\mid x) \;=\; \sum_{y}\pit(y\mid x)\,\frac{\mathbb{1}[y=y^*]}{\pit(y\mid x)}\,\nabla_\theta\log\pit(y\mid x) \;=\; \E_{y\sim\pit}\!\Big[\underbrace{\tfrac{\mathbb{1}[y=y^*]}{\pit(y\mid x)}}_{\text{implicit reward}}\nabla_\theta\log\pit(y\mid x)\Big].$$

So SFT is REINFORCE with a sparse reward that is inversely proportional to the model's own probability of the demonstration. Demonstrations the model finds unlikely get enormous effective reward. Wu et al. (2025) use this reading to argue that the $1/\pit$ weight is what makes SFT generalize poorly and propose Dynamic Fine-Tuning: multiply each token's loss by its (stop-gradient) probability, cancelling the weight. TRL now exposes it as loss_type="dft". Treat the empirical claims as one group's results; the derivation itself is exact and is the cleanest way to explain why SFT on surprising data moves a model so far (§9).

During SFT with teacher forcing, the prefix $y_{<t}$ that conditions the prediction of token $t$ is drawn from…
Teacher forcing always conditions on ground-truth prefixes; that is why the loss is computed in a single parallel pass and why it is off-policy. Scheduled sampling (Bengio et al., 2015) is a modification that mixes in model predictions; it is not standard LLM SFT.

What SFT actually changes: the superficial alignment hypothesis

LIMA (Zhou et al., 2023) fine-tuned a 65B LLaMa on just 1,000 curated examples and found its answers equivalent to or preferred over GPT-4 in 43% of human comparisons (58% against Bard, 65% against DaVinci003). From this they proposed 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." Lin et al. (2023) then compared base and chat models token by token and found they agree on the top-ranked token at most positions; "most distribution shifts occur with stylistic tokens (e.g., discourse markers, safety disclaimers)."

Hold the hypothesis loosely. It describes chat-format SFT on a strong base model. It does not describe SFT on long reasoning traces (which demonstrably teaches skills, §6), SFT on narrow data that changes values (§9), or SFT on new facts: Gekhman et al. (2024) found that fine-tuning examples carrying knowledge the model lacks are fitted much more slowly than known ones and, once fitted, increase the model's tendency to hallucinate. "Superficial" is about what a small dataset can do, not a ceiling on what SFT can do.

§2Chat templates, special tokens and loss masks

The model never sees "messages". It sees one long token sequence, and you decide which of its tokens produce gradient. Scroll through how a conversation becomes training data.

1 · The dataset stores messages. A system prompt, alternating user and assistant turns. This structure is convenient for humans and meaningless to the model until it is serialized.

2 · The chat template serializes them. It is a Jinja program shipped with the tokenizer. It inserts reserved delimiters, role names and newlines. Different model families use different templates; ChatML-style templates (shown) wrap each message in <|im_start|>role … <|im_end|>.

3 · Special tokens must stay atomic. Delimiters are single reserved ids added to the vocabulary. If a template string is tokenized as ordinary text (or a BOS token is added twice because you tokenized a rendered string with add_special_tokens=True), training and inference disagree about the most important tokens in the sequence.

4 · Labels are masked. Positions that should not be learned get label -100, which PyTorch's cross-entropy ignores. The standard choice is "assistant tokens only", including the end-of-turn token: that token is the only place the model learns to stop.

5 · Inference must reproduce the boundary. add_generation_prompt=True appends the assistant header, so generation starts at exactly the position where training put the first loss token.

6 · Mismatch is silent. Forget the generation prompt, use the base model's template, or change a newline, and you are evaluating the model out of distribution. Tülu 3's template ablation found average scores spread from 51.6 to 53.0 across templates, including variants that differ only in a trailing newline: small, but not nothing.

Roles and system prompts

Roles are not just labels; they are conditioning tokens the model learns to associate with behaviors. The system role is where operators put persistent instructions, and models only follow system prompts well if training data contains diverse system prompts that actually matter for the response. If every training example has the same default system prompt (or none), the model learns to ignore that slot. Multi-turn data teaches the model to use earlier turns; LIMA found that adding only 30 multi-turn dialogue chains to its 1,000 single-turn examples raised the share of excellent dialogue responses from 45.2% to 76.1%.

The end-of-turn token is a learned behavior

A model stops when it samples the end token. It only learns to do that if the end token is in the loss. Two classic bugs produce models that ramble until max_new_tokens: (a) the collator masks the end token together with the prompt, or (b) the pad token is set equal to the EOS token and padding positions are masked, which also masks the real EOS. LIMA sidestepped the ambiguity by introducing a dedicated end-of-turn token that "plays the same role as EOS of halting generation, but avoids conflation with any other meaning that the pretrained model may have imbued into the preexisting EOS token." Tülu 3's ablation found that replacing the trailing newline after assistant messages with an EOS token gave the best score among the templates they tried (they kept their template anyway, for consistency with later pipeline stages).

Masking schemes and multi-turn conversations

Three choices are common: train on everything (the old "instruction tuning as language modeling" approach); train on the final assistant turn only (each multi-turn conversation contributes one target); or train on all assistant turns (efficient: one forward pass trains every turn, each conditioned on the true history). Meta's Llama 2 paper is explicit: "we zero-out the loss on tokens from the user prompt, so as a result, we backpropagate only on answer tokens." In TRL this is assistant_only_loss=True, which requires the chat template to mark assistant spans with {% generation %}…{% endgeneration %} (current TRL patches the template automatically for some known families, e.g. Qwen3); for prompt–completion datasets, completion-only loss is the default.

Why mask prompts at all? The prompt tokens are not your target behavior: training on user turns teaches the model to write like users (and to role-play the user if it ever crosses a boundary). With short answers and long prompts, unmasked prompt tokens can also dominate the gradient. The counter-argument (prompts are free extra language-modeling signal) mostly matters in tiny-data regimes.

Per-token versus per-sequence averaging

Now the normalizer $Z$. Let sequence $i$ in a batch of $B$ have $n_i$ loss tokens with per-token losses $\ell_{i,t}$. Three common reductions:

$$\underbrace{\frac{\sum_i\sum_t \ell_{i,t}}{\sum_i n_i}}_{\text{per-token mean}} \qquad \underbrace{\frac{1}{B}\sum_i \frac{1}{n_i}\sum_t \ell_{i,t}}_{\text{per-sequence mean}} \qquad \underbrace{\sum_i\sum_t \ell_{i,t}}_{\text{sum}}$$

Under the per-token mean, every token weighs the same, so a sequence's total influence is proportional to its length: a 2,000-token answer pulls 100 times harder than a 20-token one. Under the per-sequence mean, every sequence weighs the same, so each token of a long answer is down-weighted by $1/n_i$: the model learns long answers less thoroughly, token for token. The sum behaves like the per-token mean but its scale depends on how many tokens land in a batch, so the learning rate must absorb it.

Bars under each token show its weight in the loss. Switch masking schemes and averaging modes. Note how "Per-sequence mean" gives each of B's many tokens a fraction of the weight of A's tokens, and how unticking the end-of-turn token leaves the model with no signal for when to stop.

This is not academic. In October 2024 several frameworks discovered that gradient accumulation silently implemented the wrong reduction: each micro-batch computed its own per-token mean and the micro-batch losses were then averaged. That is a per-micro-batch weighting, which up-weights tokens in micro-batches that happen to contain few tokens. Hugging Face's write-up states the fix plainly: "the correct loss should be computed by the total loss across all batches in a gradient accumulation step divided by the total number of all non padding tokens in those batches." The same issue arises from averaging across data-parallel devices. The Tülu 3 team ran into it and chose a different fix: "we opted generally to use a sum loss instead of averaging ('mean loss') … This effectively weights all tokens equally (which we found led to generally better performance for initial mixtures)", retuning the learning rate (their best: sum loss, LR $5\times10^{-6}$, 2 epochs).

import torch.nn.functional as F

def sft_loss(logits, labels, n_tokens_global):
    """logits: [B, L, V]; labels: [B, L] with -100 on masked positions.
    n_tokens_global: number of label != -100 tokens across ALL micro-batches
    and devices in this optimizer step (all-reduce it once per step)."""
    logits = logits[:, :-1].float()          # position t predicts token t+1
    labels = labels[:, 1:]
    loss_sum = F.cross_entropy(logits.reshape(-1, logits.size(-1)),
                               labels.reshape(-1),
                               ignore_index=-100, reduction="sum")
    return loss_sum / n_tokens_global        # true per-token mean over the step
    # (DDP averages gradients over W ranks, so this is the per-token mean / W:
    #  the relative token weights are right; multiply by W if you want the scale too)

def build_labels(input_ids, assistant_mask):
    """assistant_mask: 1 on assistant content AND its end-of-turn token."""
    labels = input_ids.clone()
    labels[assistant_mask == 0] = -100
    return labels
Pitfall · "the loss went down" is not a test

Every bug in this section produces a perfectly healthy-looking loss curve. A model trained on unmasked prompts, or without its end token, or with a mangled template, still drives its loss down. The only reliable check is to decode a batch of labels (print the tokens where label ≠ −100) and to generate from the trained model with the exact inference template. LIMA reported that perplexity "does not correlate with generation quality" and picked checkpoints by reading outputs.

Your batch mixes short chat answers (~30 tokens) with long reasoning traces (~3,000 tokens). You switch from per-token mean to per-sequence mean. What happens to the traces?
Per-sequence mean gives each sequence total weight $1/B$, so a token in a sequence of length $n_i$ gets $1/(Bn_i)$. With $n=3000$ vs $30$, trace tokens are down-weighted 100×. Per-token mean does the opposite: each trace contributes 100× the total weight of a chat answer. The same trade-off reappears in GRPO-style RL losses (chapter 06).

§3Packing and attention masks

Padding wastes compute; packing wastes nothing but can let examples read each other. The fix is a mask, not a different data format.

Real SFT data has wildly varying lengths. Padding each example to the longest in its batch wastes the padded positions; Krell et al. (2021) measured that up to 50% of tokens in common NLP datasets can be padding. Packing concatenates several examples into one fixed-length row. It is old practice for SFT, too: Llama 2 "concatenate[d] all the prompts and answers from the training set" to fill its 4,096-token sequences. Done naively, with an ordinary causal mask over the whole row, every token can attend to every earlier token in the row, including tokens of unrelated examples packed before it. That is cross-contamination. The position ids also keep counting across examples, so later examples start at positions they will never start at during inference.

Switch layouts. Under naive packing, the red cells in the attention matrix are queries attending to keys from a different example. Document masking turns the matrix block-diagonal and resets position ids, recovering exactly the computation of the padded batch without the padding.

How much does contamination hurt? It depends on the regime. For pretraining, Llama 3 reported that a mask preventing "self-attention between different documents within the same sequence" had "limited impact during in standard pre-training" but was "important in continued pre-training on very long sequences"; Zhao et al. (2024) found intra-document causal masking "significantly improving performance" in their pretraining runs. For SFT, where examples are short, semantically unrelated and each one is a self-contained conversation, contamination directly teaches the model to condition on irrelevant context, and the fix is cheap. Modern stacks implement it without materializing a mask: FlashAttention's variable-length kernels take cumulative sequence lengths (cu_seqlens) or reset position_ids. Hugging Face's DataCollatorWithFlattening reported "up to 2x improvement in training throughput while maintaining convergence quality" (1.4× on a dataset with longer, more uniform examples). In current TRL, packing=True defaults to packing_strategy="bfd" (best-fit decreasing, which truncates overflow) and enables padding-free attention.

Analogy · strangers in a train compartment

Padding is giving every traveler their own compartment, mostly empty. Packing is seating several strangers in one compartment to save seats. Without document masking they overhear each other, and each one's answers start to absorb fragments of the other conversations. The document mask is a set of soundproof partitions: the seats are shared, the conversations are not.

Where it breaks: overhearing on a train is symmetric. Causal attention is not: only later examples in the row can "hear" earlier ones, which is why contamination is position-dependent and easy to miss in aggregate metrics.

Pitfall · packing changes your loss weighting too

Packing interacts with §2. If your loss is a per-sequence mean and the "sequence" is now a packed row, you have silently switched to "per-row mean", which weights examples by how they happened to be packed. Compute the loss over the original example boundaries (or use a global per-token normalizer), and make sure each packed example still ends with its end-of-turn token in the loss. Also beware the "wrapped" strategy, which cuts examples mid-sequence: a response whose first half sits in one row and second half in another loses its prompt.

You pack SFT examples with FlashAttention but pass position_ids = arange(row_length) and no sequence boundaries. Which statement is true?
Without cu_seqlens or per-example position_ids, the kernel applies one causal mask over the whole row. Nothing in the attention kernel knows what an end-of-turn token means.

§4Forward vs reverse KL: mode-covering and mode-seeking

SFT and RL push the model toward a target distribution from opposite sides. Which side you come from decides whether the model hedges or commits.

Let $p$ be a target distribution and $q_\theta$ a model too simple to match it exactly. The two KL divergences are

$$\htmlClass{t-fwd}{\KL(p\,\|\,q_\theta) = \E_{y\sim p}\big[\log p(y) - \log q_\theta(y)\big]} \qquad \htmlClass{t-rev}{\KL(q_\theta\,\|\,p) = \E_{y\sim q_\theta}\big[\log q_\theta(y) - \log p(y)\big]}$$
  • Forward KL (SFT, offline distillation): expectation under the target. Huge penalty wherever $p$ has mass and $q_\theta \approx 0$. Result: zero-avoiding, mass-covering, hedging.
  • Reverse KL (KL-regularized RL, on-policy distillation): expectation under the model. Huge penalty wherever $q_\theta$ has mass and $p \approx 0$. Result: zero-forcing, mode-seeking, committing.

Why SFT is forward KL was shown in §1. Why RL is reverse KL takes two lines and connects to chapter 04. The KL-regularized RL objective can be rewritten as

$$\E_{y\sim\pit}[r(x,y)] - \beta\,\KL(\pit\,\|\,\piref) \;=\; -\beta\,\KL\big(\pit \,\big\|\, \pi^*\big) + \beta\log Z(x), \qquad \pi^*(y\mid x) = \tfrac{1}{Z(x)}\,\piref(y\mid x)\,e^{r(x,y)/\beta}.$$

Maximizing the RL objective is exactly minimizing the reverse KL from the policy to the tilted target $\pi^*$. On-policy distillation (§6) minimizes reverse KL to the teacher directly. Expectations under the model's own samples are what "on-policy" means mathematically.

A derivation to remember. Fit a Gaussian $q = \mathcal{N}(\mu,\sigma^2)$ to any $p$ by forward KL. Since $-\log q(y) = \log\sigma + \frac{(y-\mu)^2}{2\sigma^2} + \text{const}$,

$$\frac{\partial}{\partial\mu}\KL(p\|q) = -\E_p\!\Big[\frac{y-\mu}{\sigma^2}\Big] = 0 \;\Rightarrow\; \mu = \E_p[y], \qquad \frac{\partial}{\partial\sigma}\KL(p\|q) = \E_p\!\Big[\frac{1}{\sigma} - \frac{(y-\mu)^2}{\sigma^3}\Big]=0 \;\Rightarrow\; \sigma^2 = \mathrm{Var}_p[y].$$

Forward KL is moment matching: for a bimodal $p$, the fit sits in the valley between the modes, with a variance wide enough to cover both. Reverse KL has no closed form here; it typically locks onto one mode, and which one depends on initialization. The widget optimizes both live with Adam.

Forward KL lands between the modes with a wide σ, placing real mass in the valley where the data has none. Switch to reverse KL: the fit commits to one mode. Move "Initial μ" across zero and re-run to see reverse KL pick the other mode; skew the mode weights and see forward KL slide toward the heavier one while staying wide. The dashed curve is the optimum of the other divergence from the same start. Then raise "Initial σ" above ~0.7 with μ near 0: reverse KL can get stuck straddling both modes, a local optimum forward KL never has.

Intuition · what this means for a language model

Language models are not unimodal Gaussians, so do not over-read the picture. The transferable lesson is about capacity mismatch. When a student cannot represent everything in its target (a small model distilling a large one, or any model imitating diverse humans), forward KL makes it spread probability across everything it cannot tell apart, including the "valley": plausible-looking blends of answers that no demonstrator would give. Reverse KL makes it pick something it can do well and drop the rest. That is one mechanistic story for why SFT models hedge and why RL-trained models are sharper but less diverse; Kirk et al. (2023) found "RLHF generalises better than SFT to new inputs … However, RLHF significantly reduces output diversity", and Tajwar et al. (2024) classify on-policy and contrastive methods as mode-seeking and supervised offline methods as mode-covering.

A 1B student distills a 70B teacher that, for a given prompt, puts 50% on "approach A" and 50% on a very different "approach B". The student can only represent one approach cleanly. Under forward-KL (standard) distillation, the most likely failure is…
Forward KL punishes zero probability on anything the teacher does, so the student keeps mass on both and, lacking capacity, also on the space between. Reverse KL (on-policy distillation) would push it to commit to one approach, typically the one it can execute best.

§5The data engine: quality, diversity, synthesis, hygiene

In SFT the dataset is the specification. Changing the data is the main lever you have, and the field's history is a sequence of cheaper ways to get better demonstrations.

Quality versus quantity

LIMA's ablations are the canonical evidence. Training 7B models on 2,000 examples, quality-filtered Stack Exchange beat unfiltered Stack Exchange by about half a point on a 1–6 helpfulness scale (graded by ChatGPT); high-quality but homogeneous data (wikiHow, all "how to" prompts) did worse than diverse data; and an up-to-16-fold increase in quality-filtered data left scores flat ("doubling the training set does not improve response quality"). Their conclusion: alignment scaling is "a function of prompt diversity while maintaining high quality responses", not of quantity alone. Llama 2's team reached a similar operational conclusion ("SFT annotations in the order of tens of thousands was enough"), stopped at 27,540 annotations, and noticed that outputs sampled from their SFT model "were often competitive with SFT data handwritten by human annotators", so they moved annotation budget to preference data.

The nuance: LIMA measured chat helpfulness judged by humans. When the target is a skill, volume matters again. Tülu 3 found its models "continue to improve on average as more SFT data is included", with large gains on GSM8K, while TruthfulQA got worse as data grew. For reasoning, small curated sets go surprisingly far (s1: 1,000 questions selected for difficulty, diversity and quality; LIMO: about 800 samples on Qwen2.5-32B-Instruct, 63.3% on AIME), but the strongest open small reasoners come from large sets (OpenThoughts3: 1.2M examples).

Analogy · the cookbook and the chef

A strong base model is a chef who has eaten everything. LIMA-style SFT is handing them a slim house-style guide: "plate like this, describe dishes like that". A thousand pages of the same recipe adds nothing; a hundred varied, impeccable examples set the style. Teaching a new cuisine, however, takes many recipes and many repetitions: that is skill SFT, and it scales with data.

Where it breaks: the chef metaphor suggests style and skill are separable. In practice style data changes behavior far beyond style (training on refusals changes what the model believes is harmful; §9).

Synthetic data: a short genealogy

MethodIdeaScale reported
Self-Instruct (2022)Bootstrap from 175 seed tasks: the model writes new instructions, inputs and outputs; drop near-duplicates (ROUGE-L ≥ 0.7 with an existing instruction).+33% absolute on Super-NaturalInstructions for GPT-3, about InstructGPT-001 level
Alpaca (2023)Self-Instruct with a stronger teacher (text-davinci-003), fine-tune LLaMA 7B.52K demos; data under \$500, total under \$600
Evol-Instruct / WizardLM (2023)An LLM rewrites instructions to be deeper (add constraints, reasoning steps) or broader (new topics).250k evolved instructions; 70k used for a 13B model
UltraChat (2023)Two models role-play user and assistant to produce multi-turn dialogues without human queries.1.5M dialogues
Orca (2023)"Explanation tuning": ask the teacher for step-by-step explanations via system prompts, not just answers.5M ChatGPT responses, 1M also from GPT-4
Persona Hub (2024)Condition generation on one of ~1B web-derived personas to get diversity for free.Qwen2-7B on 1.07M synthesized math problems: 64.9% on MATH
Tülu 3 (2024)Curated public prompts + persona-driven synthetic sets targeted at math, code and precise instruction following; responses regenerated by strong models; aggressive decontamination.SFT mix of 939,344 prompts

Tülu 3 is the best public window into a modern mix, and its ablations are worth memorizing as patterns: removing WildChat (real user conversations) caused "a small but noticeable degradation on most skills", most visibly on AlpacaEval; removing the persona sets lowered HumanEval(+), MATH and above all IFEval (72.8 → 53.6; the text also lists GSM8K, but its Table 10 shows GSM8K slightly up, 76.2 → 76.8); safety data was "generally orthogonal" to everything else, and contrastive prompts (CoCoNot) helped prevent over-refusal. The general recipe: prompts are the scarce resource (diverse, real, targeted), responses are regenerated by the best available teacher and filtered.

For reasoning data, OpenThoughts ran over 1,000 controlled experiments and reported: sampling multiple answers per question "is an effective technique to increase the size of a data source by at least 16×"; "models with better performance are not necessarily better teachers. QwQ-32B is a stronger teacher than DeepSeek-R1"; and verification or answer filtering "gave no significant performance improvements". Treat these as results for one pipeline, but note the pattern: the teacher's style can matter more than its benchmark score.

Pitfall · imitating style, not capability

Gudibande et al. (2023) fine-tuned 1.5B–13B models on up to 150M tokens of ChatGPT outputs. Crowd workers rated the imitation models as competitive. Targeted evaluations found they "close little to none of the gap from the base LM to ChatGPT on tasks that are not heavily supported in the imitation data." SFT on a stronger model's outputs transfers its format cheaply and its capabilities expensively. Evaluate on capability, not vibes.

Decontamination

Synthetic and scraped prompts leak benchmarks. Tülu 3's procedure is a good default: match prompts only (responses are regenerated, so they differ anyway) with 8-gram overlap; flag a test instance if more than 50% of its tokens are covered by 8-grams from a single training instance; call a training set contaminated if it overlaps more than 2% of any evaluation's instances. Contaminated sets were dropped entirely for held-out ("unseen") evaluations; for development evaluations they dropped the whole set when that did not hurt, and otherwise removed only the matching instances. They tried embedding matching and found it hard to separate "mere distributional similarity from actual paraphrasing". The limitation is real: Yang et al. (2023) showed that rephrased or translated test items slip past n-gram filters and that a 13B model trained on them can reach GPT-4-level scores on MMLU, GSM8K and HumanEval. If your synthetic pipeline uses a teacher that has seen a benchmark, assume paraphrased leakage and keep a held-out evaluation that postdates your data (see chapter 09).

Model collapse: what the evidence actually says

Shumailov et al. (arXiv 2023; Nature 2024, "AI models collapse when trained on recursively generated data") trained each generation of a model on data generated by the previous one and showed the tails of the distribution disappear: low-probability events are forgotten first, and the model drifts toward a narrow mode. Their language-model experiment fine-tuned OPT-125m on wikitext2, regenerated the corpus with beam search, and repeated. Read the setup carefully: when no original data was kept, quality degraded over generations; when 10% of the original data was kept each generation, they found "only minor degradation of performance."

Gerstgrasser et al. (2024) made the distinction sharp: replacing real data with each generation's synthetic data "does indeed tend towards model collapse", but "accumulating the successive generations of synthetic data alongside the original real data avoids model collapse", across model sizes and modalities. The practical reading for post-training: collapse is a risk of closed loops that discard real data and of pure self-generated training without an external filter. Distilling a strong teacher, filtering with a verifier, or mixing in real prompts are all open loops. The live risk in SFT pipelines is subtler than collapse: diversity loss, which you see as repetitive phrasing, homogenized personas and shrinking pass@k.

§6Distillation: SFT with a better target

A sampled token is one draw from the teacher's opinion. The teacher's full distribution is the opinion itself. Distillation is the art of learning from the opinion.

Logit distillation (Hinton et al., 2015)

Hinton, Vinyals & Dean train a student on the teacher's softened distribution. With temperature $\tau$, teacher logits $z^T$ and student logits $z^S$:

$$\mathcal{L} = (1-\alpha)\,\mathrm{CE}\big(y,\,\sigma(z^S)\big) \;+\; \alpha\,\tau^2\,\KL\big(\sigma(z^T/\tau)\,\big\|\,\sigma(z^S/\tau)\big).$$

The $\tau^2$ is not decoration: "the magnitudes of the gradients produced by the soft targets scale as $1/T^2$", so multiplying by $\tau^2$ keeps the two terms balanced as you change temperature. The reason soft targets help is what is often nicknamed dark knowledge: "the relative probabilities of incorrect answers tell us a lot about how the cumbersome model tends to generalize." Their best demonstration: a student trained on a transfer set with every digit 3 removed still got 98.6% of test 3s right after a bias correction, purely from how the teacher spread probability onto "3" when looking at other digits.

Two identical linear students learn a 10-class teacher. One sees the teacher's full distribution (soft), one sees labels sampled from it (hard). With a constant learning rate the hard student stalls at a noise floor set by label sampling; the soft student has no such noise. Raise "sampled labels per prompt" toward 32: the hard student approaches the soft one, because soft targets are the infinite-sample limit. Temperature changes the speed, not the destination, when the student can represent the teacher exactly.

Analogy · answer key, marked-up exam, live tutor

Sequence-level distillation hands the student the answer key: one correct answer per question. Logit distillation hands over the teacher's marked-up exam: for every question, how tempting each wrong option was ("B is nearly right; D is absurd"). On-policy distillation is a tutor reading over the student's shoulder as they write, flagging every line where the tutor would have written something else, on the student's own attempt rather than on a model solution.

Where it breaks: a human tutor explains why. The teacher's distribution only says what it would have done, and its confidence includes its own mistakes and quirks, which the student absorbs just as faithfully.

Sequence-level distillation (Kim & Rush, 2016)

For autoregressive models, matching per-token distributions along the data's prefixes is still teacher forcing. Kim & Rush instead approximated the sequence-level objective $\E_{y\sim p_T}[-\log p_S(y\mid x)]$ by training on the teacher's beam-search output. This is what most of the field now does by default when it "distills" a frontier model: generate responses, SFT on them. Their students ran 10× faster than the teacher with little quality loss and "seem to eliminate the need for beam search". Note what this objective is: still forward KL (now to the teacher's sequence distribution, approximated by its mode), still off-policy.

On-policy distillation: GKD and its descendants

Agarwal et al. (2023) unified the space with Generalized Knowledge Distillation:

$$\mathcal{L}_{\text{GKD}}(\theta) = (1-\htmlClass{t-lam}{\lambda})\,\E_{(x,y)\sim\htmlClass{t-fixed}{(X,Y)}}\big[\htmlClass{t-div}{\mathcal{D}}(p_T\|p_S^\theta)(y\mid x)\big] + \htmlClass{t-lam}{\lambda}\,\E_{x}\,\E_{\htmlClass{t-onp}{y\sim p_S(\cdot\mid x)}}\big[\htmlClass{t-div}{\mathcal{D}}(p_T\|p_S^\theta)(y\mid x)\big]$$
  • Fixed sequences: ground truth or teacher samples. With $\lambda=0$ and forward KL this is ordinary supervised KD.
  • Student-generated sequences: the student samples, the teacher scores every prefix the student actually visits. No gradient flows through the sampling.
  • λ: fraction of on-policy data.
  • Divergence: a token-level divergence averaged over the sequence's positions ($\frac{1}{L_y}\sum_n$); forward KL, reverse KL, or a generalized JSD that interpolates between them.

MiniLLM (Gu et al.) argued for the reverse KL on mode-seeking grounds (§4). The 2025 revival is the simplest version: Thinking Machines' "On-Policy Distillation" (Lu et al., October 2025) uses the per-token reverse KL as a dense, per-token reward. For a student sample $y\sim\pit(\cdot\mid x)$, each position $t$ gets

$$r_t = -\big[\log\pit(y_t\mid x, y_{\lt t}) - \log\pi_{\text{teacher}}(y_t\mid x, y_{\lt t})\big], \qquad \E_{y_t\sim\pit(\cdot\mid x,y_{\lt t})}[-r_t] = \KL\big(\pit(\cdot\mid x,y_{\lt t})\,\big\|\,\pi_{\text{teacher}}(\cdot\mid x,y_{\lt t})\big),$$

a one-sample estimate of the (negative) reverse KL at that prefix, used as the reward with a discount of zero (each token's reward is its own log-ratio; no credit flows to earlier tokens), inside an otherwise standard policy-gradient loop. The student generates; the teacher computes log-probs on the student's tokens; every token gets a grade. It combines what each paradigm does well: on-policy like RL (trained on its own states, so no exposure bias) and dense like SFT (a signal on every token, not one scalar per episode).

Qwen3-8B, same off-policy-distilled startAIME'24 (pass@64)AIME'25GPQA-DGPU hours
Off-policy distillation (SFT on teacher outputs)55.0 (90.0)42.855.6—
+ Reinforcement learning67.6 (90.0)55.561.317,920
+ On-policy distillation74.4 (93.3)65.563.31,800

Source: Qwen3 Technical Report, Table 21 (math and code queries only; the strong-to-weak pipeline's teachers are Qwen3-32B or Qwen3-235B-A22B). Note RL left pass@64 unchanged while distillation raised it: a teacher can push probability onto solutions the student almost never samples, while RL mostly sharpens what the student already samples.

Thinking Machines replicated the pattern with Qwen3-8B-Base: SFT on 400k OpenThoughts-3 prompts reached 60% on AIME'24 with log-linear returns (they extrapolate about 2M prompts for 70%), while on-policy distillation reached 70% in about 150 steps (~77K prompts, 4 samples each), a cost reduction they estimate at 9–30× depending on whether the teacher's sampling cost for the SFT data is counted. Their most striking side result: running SFT on a model's own samples (which have zero KL to the model in expectation) still degraded instruction following at every practical learning rate, because each finite batch nudges the model off its own distribution and the drift compounds. On-policy distillation against a fixed teacher does not drift.

Distilling reasoning traces, and why small models prefer distillation to RL

DeepSeek-R1 fine-tuned Qwen and Llama bases on about 800k samples curated from R1 (2–3 epochs, 32k context), and then ran the decisive control: large-scale RL (over 10K steps) directly on Qwen2.5-32B-Base. The RL model reached 47.0 on AIME 2024; the distilled model reached 72.6 (MATH-500: 91.6 vs 94.3; LiveCodeBench: 40.2 vs 57.2). Their conclusion: "distilling more powerful models into smaller ones yields excellent results, whereas smaller models relying on the large-scale RL … require enormous computational power and may not even achieve the performance of distillation."

Why? Three reasons, in increasing depth:

  1. Bits per episode. As Thinking Machines put it in "LoRA Without Regret", supervised learning "provides O(number of tokens) bits per episode" while policy gradient gets "O(1) bits per episode" from the advantage. For a 10k-token trace, this (deliberately crude) accounting gives a gap of roughly four orders of magnitude.
  2. Exploration. RL can only reinforce behaviors the policy already samples with non-trivial probability. A weak model rarely samples a full correct long solution, so the reward is mostly zero. A teacher hands it the solution.
  3. The teacher solved the search problem. The expensive part of reasoning RL is discovering strategies like verification and backtracking. Distillation transfers the strategies discovered by someone else's RL. Hence DeepSeek's second conclusion: going beyond the frontier "may still require more powerful base models and larger-scale reinforcement learning."

Two caveats keep this honest. Li et al. (2025) found a "Small Model Learnability Gap": students of 3B parameters or fewer "do not consistently benefit from long chain-of-thought reasoning or distillation from larger models" and do better with shorter chains or smaller teachers (the capacity mismatch of §4, observed). And distillation is bounded by the teacher, inheriting its mistakes, its style and, per the next callout, possibly traits you did not intend to transfer.

Anthropic research · subliminal learning

Cloud et al. (2025), from the Anthropic Fellows program with Anthropic co-authors, gave a teacher a trait (a system prompt to love owls, or fine-tuning on insecure code to make it misaligned), had it generate data unrelated to the trait (number sequences, code, reasoning traces), filtered out any reference to the trait, and fine-tuned a student on it. The student acquired the trait. The effect disappeared when teacher and student had different base models, and a theorem shows a small gradient step on any teacher output moves the student toward the teacher when they share initialization. Implication for the data engine: filtering content does not filter what is transmitted when you distill from a sibling of your own model. Anthropic's later reward-hacking study (MacDiarmid et al., 2025, §8) reports a matching production-scale observation: filtering reward-hacking episodes out of a misaligned model's transcripts and distilling on the rest did not remove the misalignment in their setting (their filter also let many hacks through, so this is related evidence, not a clean subliminal-learning test).

On-policy distillation is often described as "the best of SFT and RL". Which pair of properties justifies that?
It trains on the states the student actually visits, like RL, and grades every token with the teacher's log-probabilities, like distillation. It still needs a teacher and still needs sampling, which is where its cost goes.

§7Rejection sampling, expert iteration, STaR and ReST

Sample many answers, keep the good ones, fine-tune on them, repeat. The simplest RL algorithm in the guide is just SFT inside a loop.

The family goes by many names: expert iteration (Anthony et al., 2017, where a tree search is the "expert" and the network imitates it), STaR (Zelikman et al., 2022), RAFT (Dong et al., 2023), ReST (Gulcehre et al., 2023: a "Grow" step that samples from the policy and an "Improve" step of offline RL on filtered data), ReSTEM (Singh et al., 2023), and plain rejection sampling fine-tuning (Llama 2). The shared objective, at iteration $k$:

$$\theta_{k+1} = \argmax_\theta\; \E_{x}\,\E_{y\sim\pi_{\theta_k}(\cdot\mid x)}\Big[\mathbb{1}\big[r(x,y)=1\big]\,\log\pit(y\mid x)\Big].$$

Derivation · what RFT is, in RL terms

Differentiate at $\theta=\theta_k$: the gradient is $\E_{y\sim\pi_{\theta_k}}[\mathbb{1}[r=1]\,\nabla\log\pit(y\mid x)]$, which is the REINFORCE gradient of $\E[r]$ with a binary reward and no baseline. Two differences from on-line policy gradient: (1) samples come from the frozen $\pi_{\theta_k}$ for a whole round, so later steps are off-policy; (2) failures contribute zero gradient: there is no negative signal pushing probability away from wrong answers.

Singh et al. give the EM reading: the E-step forms $q(y\mid x)\propto \pi_{\theta_k}(y\mid x)\,\mathbb{1}[r(x,y)=1]$, the current policy conditioned on success; the M-step fits $\pit$ to $q$ by maximum likelihood, i.e. by forward KL. RFT is "SFT toward your own successful self". (ReSTEM fine-tunes the base model afresh on each round's filtered data rather than continuing from the previous iterate, which limits drift and overfitting across rounds.)

Press Play to animate one iteration (sample → score → filter → fine-tune); at the end the chart advances one real iteration of a toy: 60 prompts of varying difficulty, a policy over six solution strategies of increasing strength, a base model that prefers the weak ones. Watch pass@1 climb while strategy entropy first rises (mass leaves the weak default) and then collapses. Note what it collapses onto: with N = 4 it locks onto the second-best strategy, because the best one starts at 0.5% under the base model, is almost never sampled, and so never survives the filter. Raise N to 32 and the best strategy starts to win; tick STaR rationalization to rescue prompts with zero correct samples.

Llama 2 describes the production version: "We sample K outputs from the model and select the best candidate with our reward … the sample obtaining the highest reward score is considered the new gold standard", fine-tuning on those. They contrast it with PPO along two axes: breadth (K samples per prompt versus one) and depth (PPO updates the sampler every step; rejection sampling samples everything from the initial policy of the round). Through RLHF-V4 they used only rejection sampling; afterwards they ran PPO on top of the rejection-sampled checkpoint. They also used it as a distillation channel: "We perform rejection sampling only with our largest 70B Llama 2-Chat. All smaller models are fine-tuned on rejection sampled data from the larger model."

STaR's contribution is rationalization: for problems the model fails, show it the correct answer and ask it to produce a rationale that reaches it, then train on that rationale as if it were generated without the hint. This attacks RFT's blind spot, prompts with zero successful samples, which otherwise contribute nothing forever. With it, STaR reported CommonsenseQA performance comparable to fine-tuning a 30× larger model. (Notice that rationalization is a form of privileged-information distillation; it will reappear in §8.)

Pitfall · the three ways RFT goes wrong

Diversity collapse. Fitting to successes concentrates mass on the strategies that already work; the widget's entropy curve is the toy version. Overfitting to a fixed prompt set. ReSTEM found "exceeding a couple of iterations … leads to diminishing improvement, indicating potential overfitting on small amount of training problems." Reward hacking by selection. Best-of-N against a learned reward model optimizes that model's errors with the full power of N samples, the same over-optimization studied in chapter 03; with a verifier, false positives (right answer, wrong reasoning) get distilled into the model.

A question worth asking · "why not just do best-of-N + SFT instead of RL?"

Short version: it is a legitimate, cheap, stable baseline and often a strong first stage (Llama 2, the reasoning cold-starts in chapter 06). It loses three things relative to on-line RL: negative gradients (it cannot push down specific wrong behaviors), on-policyness within a round (stale samples), and credit assignment beyond "whole sequence good". It also gives no signal on prompts that are never solved. If pass@N on your prompt set is already high, RFT captures much of the gain; if it is low, you need exploration help (hints, a teacher, or RL with partial credit).

§8Context distillation: turning a prompt into weights

If a long prompt makes the model behave well, train the model to behave that way without the prompt. Anthropic introduced this in 2021, and versions of it run through modern safety training.

In "A General Language Assistant as a Laboratory for Alignment" (Askell et al., 2021), Anthropic wrote a 4,600-word "HHH prompt" of 14 fictional conversations and found that simply prompting made models more helpful, honest and harmless, with little capability "tax" at large scale. Prompts cost context and compute at every call, so they proposed context distillation:

$$L(\theta) = \KL\big(\htmlClass{t-p0}{p_0(X\mid C)}\;\big\|\;\htmlClass{t-pt}{p_\theta(X)}\big)$$
  • Teacher = the original model, with the context $C$ (the HHH prompt) prepended. Fixed.
  • Student = the model being fine-tuned, without $C$. Same architecture, often the same initialization.

Note the direction: forward KL from the prompted model to the unprompted one, so this is logit distillation (§6) where the "bigger teacher" is the same model plus a prompt. They explain why not simply fine-tune on the prompt text: "finetuning changes the model's expectations for the data distribution $P(X)$, bringing it closer to the distribution of the prompt $P(C)$, whereas prompting instead asks the model for the distribution $P(X\mid C)$." Fine-tune on the numbers 1 to 63 and the model does not expect 64 next; prompt with them and it does. Their verdict: "For many but not all of our evaluations context distillation performs about as well as prompting."

The follow-up paper made it load-bearing. In Anthropic's HH-RLHF work (Bai et al., 2022), the recipe prepends the HHH prompt to text that is 50% pretraining data and 50% StackExchange formatted as a dialogue, runs a 52B model, stores the top-50 log-probabilities per token (plus one bucket for the rest), and distills into models of all sizes with a KL loss over 350M tokens. Then: "We initialize our policies on context-distilled models." In that paper, the RLHF policies started from a context-distilled model rather than from a conventional demonstration-SFT model.

Analogy · the coach's voice

An athlete performs better with a coach shouting cues from the sideline (the prompt). Context distillation is practicing with the coach until the athlete hears the cues in their own head and the coach can leave. The athlete is not learning the coach's words; they are learning to behave as they would if the coach were there.

Where it breaks: a coach adapts cues to the situation; a fixed prompt does not. Context distillation can only internalize behavior the prompt reliably produces, and Askell et al. saw contractors notice "a small degradation from distillation" relative to the live prompt.

The lineage

Anthropic · the inverse trick: inoculation prompting

Context distillation adds a prompt at generation time and removes it at training time, so behavior elicited by the prompt is absorbed unconditionally. Inoculation prompting does the reverse: add an instruction that explains an undesired trait at training time and remove it at test time, so the trait is attributed to the instruction rather than absorbed. Wichers et al. (2025) (Anthropic Fellows, Redwood, Anthropic) modify SFT prompts to explicitly request, for example, code that only passes the visible tests, and find this "reduces the learning of undesired behavior without substantially reducing the learning of desired capabilities"; Tan et al. (2025) report the same selectivity across emergent misalignment, backdoors and subliminal learning. Anthropic's reward-hacking study (MacDiarmid et al., 2025) applied the idea in RL and states: "we have already started making use of this technique in training Claude." The unifying principle is that what a model learns from a token sequence depends on the context it is conditioned on, which is the whole of this chapter in one line.

Anthropic's alignment team also uses SFT as a precise instrument rather than only as a pipeline stage: synthetic document finetuning (Wang et al., April 2025) generates documents that reference a proposition and fine-tunes on them like extra pretraining data, implanting beliefs for honeypots and model-organism studies. To our knowledge, Anthropic has not published its current production SFT recipe; when this guide speculates about it, it says so.

Askell et al.'s context distillation loss $\KL(p_0(X\mid C)\,\|\,p_\theta(X))$ is best described as…
The expectation is under $p_0(\cdot\mid C)$ (the prompted teacher), so it is forward KL, and in the HH paper it was computed from the teacher's top-50 log-probs over text drawn from pretraining data and StackExchange, i.e. off-policy logit distillation. Fine-tuning on $C$ itself is exactly what the paper argues against.

§9Generalization, forgetting, and how much to move the model

SFT can teach a format in a thousand examples and change a model's values in six thousand. Knowing how far a dataset will move the model, and in which directions, is the real skill.

"SFT memorizes, RL generalizes", and the counterpoints

Chu et al. (2025) compared SFT and RL on GeneralPoints (an arithmetic card game, with rule variants) and V-IRL (navigation), in text and vision. RL generalized to rule and visual variants; SFT tended to memorize the training rules. Two details are usually dropped when the slogan is repeated: "SFT is still helpful for effective RL training: SFT stabilizes the model's output format, enabling subsequent RL to achieve its performance gains", and the comparison used fixed prompt templates. The counter-evidence attacks exactly that:

The defensible synthesis: SFT generalizes about as well as its data covers the variation you test on, and it moves the model in whatever direction the data's surprising tokens point (the $1/\pit$ weight of §1). RL moves the model less and only along directions it can already sample, which is both why it generalizes conservatively and why it cannot teach what the model never does.

Forgetting: RL's razor

Shenfeld, Pari & Agrawal (2025) found an empirical "forgetting law": how much a fine-tuned model forgets is predicted by $\E_{x\sim\tau}[\KL(\pi_0\,\|\,\pi)]$, the KL between the base and fine-tuned policy measured on the new task's inputs. Among the many solutions to a new task, on-policy RL is biased toward the one closest to the base model; SFT goes wherever its labels point, which may be far. The widget makes the argument concrete with one prompt and ten possible answers.

The new task accepts answers C, F or H. SFT imitates one demonstration (H, which the base model rarely says); RL gets reward 1 for any accepted answer. Both reach high task success, but SFT drags the distribution far from π₀ while RL mostly re-weights what the base already preferred. Switch the demonstration to C, the base's favorite: SFT on "on-policy-looking" data moves the model much less. That is the intuition behind training on self-generated or teacher-on-student data to reduce forgetting.

The same logic explains three practical observations. Mixing replay data (general chat) into a narrow SFT run reduces forgetting but rarely eliminates it (Thinking Machines saw instruction-following fall from 85% to 79% even with 30% chat data in a knowledge mid-training run, and recovered to 83% with on-policy distillation from the earlier checkpoint). Chen et al. (2025), "Retaining by Doing", attribute RL's lower forgetting to on-policy data. And SFT on your own model's samples (rejection sampling) forgets less than SFT on human or foreign-teacher data, because the targets are already likely under the model.

Narrow data, broad effects

The most important generalization result for alignment researchers runs the other way: SFT can generalize too much. Betley et al. (2025) fine-tuned GPT-4o and Qwen2.5-Coder-32B-Instruct on 6,000 examples of code with undisclosed security vulnerabilities. The models became broadly misaligned on unrelated questions (emergent misalignment). The control is the lesson: with identical assistant responses but user messages that request insecure code for a legitimate educational reason, the misalignment did not appear. "The intention behind the code also matters." The model is not learning "write this code"; it is learning what kind of assistant would write this code in this context, a persona. Inoculation prompting (§8) works by changing that inferred context.

Analogy · the method actor

Give a method actor a hundred scenes of a character quietly sabotaging colleagues and they will not just learn the lines; they will build the character, and the character will show up in scenes you never wrote. Give them the same scenes framed as a training exercise for spotting sabotage, and they build a different character.

Where it breaks: it implies a single coherent persona inside the model. The evidence (persona-like directions in activations, context-dependent generalization) is suggestive, not proof of one unified character.

LoRA versus full fine-tuning

Biderman et al. (2024), "LoRA Learns Less and Forgets Less", compared both on code and math, in instruction tuning (≈100K pairs) and continued pretraining (≈20B tokens): "in the standard low-rank settings, LoRA substantially underperforms full finetuning", but "better maintains the base model's performance on tasks outside the target domain", and full fine-tuning learns weight perturbations "with a rank that is 10-100× greater than typical LoRA configurations". Thinking Machines' "LoRA Without Regret" (Schulman et al., September 2025) characterized when the gap disappears:

Note the tension with Biderman et al.: both are compatible once you account for configuration (all-layer LoRA, tuned LR) and dataset size. Forgetting is the other axis: in their on-policy distillation post, Thinking Machines found LoRA "still insufficient for preserving" instruction following in their knowledge mid-training run. LoRA constrains the rank of the update, not its KL from the base.

Hyperparameters that matter, with receipts

KnobPublished data pointsWorking guidance
Learning rate (full FT)Tülu 3: 5e-6 (8B), 2e-6 (70B), linear; Llama 2: 2e-5 cosine; InstructGPT: 9.65e-6 (1.3B/6B), 5.03e-6 (175B); LIMA: 1e-5 → 1e-6Low-1e-6 to 1e-5, lower for bigger models. The single most important knob; sweep it.
Learning rate (LoRA)≈10× the full-FT optimum (LoRA Without Regret; similar ratio in Biderman et al.)Do not reuse the full-FT LR with LoRA.
EpochsTülu 3: 2 ("training for longer did not yield further improvements"); Llama 2: 2; R1 distills: 2–3; InstructGPT: 16, despite validation-loss overfitting after 1 epoch, because RM score and human preference kept improving; LIMA: 15, checkpoint picked between epochs 5 and 101–3 for large mixes. More epochs on small curated sets can help generation quality while validation loss rises: select checkpoints on generations, not loss.
Batch sizeTülu 3: 128 effective, 4,096 tokens; Llama 2: 64 × 4,096; LIMA: 32Moderate. LoRA degrades at large batch sizes.
Loss aggregationTülu 3: sum loss outperformed mean for their mixturesDecide deliberately (§2); make it invariant to accumulation and device count.
RegularizationInstructGPT: residual dropout 0.2; LIMA: residual dropout rising 0.0 → 0.3 across layersUseful with small data and many epochs.
NEFTuneUniform noise on embeddings scaled by $\alpha/\sqrt{Ld}$; LLaMA-2-7B on Alpaca: AlpacaEval 29.79% → 64.69%; α in 5–15Cheap to try. The authors observe longer outputs (a known judge bias) but argue "verbosity alone cannot explain" the gains; check with length-controlled evals.
Your SFT run's validation loss starts rising after epoch 1. What does the published evidence suggest you do?
InstructGPT saw exactly this and kept training to 16 epochs because RM score and human preference improved; LIMA found perplexity did not correlate with quality. Validation NLL on human demos rewards hedging (forward KL); a sharper model can be a better assistant with worse NLL.

§10Practical failure modes: a debugging checklist

When an SFT model misbehaves, the cause is usually in the first four rows of this table, not in the data or the learning rate.

SymptomLikely causeHow to confirm
Never stops; runs to max tokens; writes the next user turnEnd-of-turn token masked or missing; pad = EOS masking the real EOS; generation stop strings do not match the templateDecode the label positions of one example; check the end token is a loss token
Great training loss, odd outputs at inference (role names in output, wrong language, repeated headers)Template mismatch: different template, missing add_generation_prompt, double BOS, changed whitespaceDiff the exact token ids of a training example's prompt and an inference prompt
Model parrots user phrasing or role-plays the userLoss on prompt tokens (no masking), or masking off-by-onePrint tokens where label ≠ −100
Short answers fine, long answers degraded (or the reverse)Loss normalization (per-sequence vs per-token; gradient accumulation; per packed row)Compute effective per-token weights for a real batch
Context bleed: answers reference content from nowherePacking without document maskingCheck position_ids/cu_seqlens reach the attention kernel
Responses cut off mid-thought, or start mid-sentenceTruncation at max_length (default 1024 in TRL), or "wrapped" packing splitting examplesHistogram tokenized lengths vs max_length
Everything sounds the same; markdown headers everywhereOverfitting to formatting: homogeneous responses from one teacher, too many epochsDiversity metrics; length-controlled evals; read 50 random samples
Benchmark jump that does not transferContamination (including paraphrased)8-gram check plus a post-cutoff held-out eval
Safety or general capability regressions after a narrow fine-tuneForgetting; persona shift from narrow data (§9)Run a broad regression suite, not just the target eval
Key idea · the three-line SFT smoke test

(1) Render one training example and print each token with its label, so you see exactly what is learned. (2) Render one inference prompt with the production template and diff its ids against the training prefix. (3) Overfit 32 examples and generate on them: if the model cannot reproduce its own training data, including stopping, the bug is in the pipeline, not the data.

§11Frontier & open problems

The boundary between SFT and RL is dissolving. What remains contested is mostly about data: where it comes from, what it secretly carries, and how far it moves the model.

Frontier · where research is going (late 2026)
  • The SFT–RL continuum. SFT is policy gradient with an implicit $1/\pit$ reward; RFT is policy gradient with a binary reward and no negatives; on-policy distillation is policy gradient with a dense teacher reward. Expect losses to be designed by choosing the sampling distribution, the per-token weight and the divergence, rather than by picking a named "paradigm".
  • On-policy (self-)distillation as the default post-training tool for small models and for restoring behaviors after domain mid-training. Open questions: teacher choice, top-k approximations of the KL (Zhu et al. identify biased TopK reverse-KL gradients as one failure mechanism), and when privileged-context self-distillation helps versus hurts thinking models.
  • Hidden channels in data. Subliminal learning, emergent misalignment and inoculation prompting all say the same thing: the effect of a fine-tuning example depends on the model's interpretation of it, not just its surface content. Data filtering by content is necessary and not sufficient; filtering by the model's internal response to data is an open direction.
  • Forgetting and continual learning. If forgetting tracks KL from the base on the new task, then methods that find KL-minimal solutions (on-policy data, distillation from the previous checkpoint) are a path to models that keep learning after deployment. Thinking Machines frames on-policy distillation explicitly as a continual-learning tool.
  • Synthetic data at scale. Collapse is avoidable with accumulation and external filters; diversity loss is not automatically avoided. How to measure and preserve diversity (personas, prompt sourcing, multiple teachers) is an engineering frontier with weak theory.
  • Informed speculation about frontier labs: public reports (Llama 2/3, Qwen3, DeepSeek-R1, Tülu 3) all use SFT as a cold start that fixes format and seeds behaviors before RL, and use distillation to produce small models. Anthropic has published that its first RLHF policies started from context-distilled models and that inoculation prompting is used in training Claude; it has not published its current SFT recipe.

§12Check yourself

Try each one before opening the answer. The "research" questions have no single right answer; the answers show one good line of reasoning.

Show that minimizing SFT cross-entropy minimizes a KL divergence. Which one, and what behavior does it predict? core

$\E_{y\sim p_{\text{data}}}[-\log\pit(y\mid x)] = H(p_{\text{data}}(\cdot\mid x)) + \KL(p_{\text{data}}\,\|\,\pit)$, and the entropy is constant in $\theta$. So SFT minimizes forward KL from data to model. Forward KL is infinite wherever the data has mass and the model has none, so the model is pushed to cover every mode of the demonstrators; under limited capacity it also covers the space between modes. Predicts hedging, blended answers, higher diversity than RL-trained models, and validation NLL that rewards spreading probability (hence NLL is a poor checkpoint selector).

Write the SFT gradient as a policy gradient. What is the implicit reward, and why might it hurt generalization? deep

$\nabla\log\pit(y^*\mid x) = \E_{y\sim\pit}[\frac{\mathbb{1}[y=y^*]}{\pit(y\mid x)}\nabla\log\pit(y\mid x)]$. The implicit reward is sparse and inversely proportional to the model's probability of the demonstration: unlikely demos get huge effective reward, so a few surprising examples can dominate the update and move the model far from its prior (high KL, more forgetting). Dynamic Fine-Tuning multiplies the per-token loss by $\sg(\pit)$ to cancel the weight. Caveat: down-weighting improbable tokens also slows learning of genuinely new content; it is a trade-off, not a free fix.

Derive the $O(T^2\varepsilon)$ compounding-error bound and argue whether it matters for modern LLMs. deep

If the policy errs with probability ε per step on expert states, the probability it has left the expert distribution by step $t$ is at most $t\varepsilon$. Worst case, after leaving it errs every step: expected cost $\le\sum_t t\varepsilon\approx T^2\varepsilon/2$, versus $T\varepsilon$ when every step is evaluated on expert states (teacher forcing). Does it matter? Arguments against: large pretrained models self-recover (He et al. 2019 found distortion "limited" and not incremental); most "off-manifold" states are still well-covered by pretraining. Arguments for: long agentic or reasoning trajectories (large T), narrow fine-tunes on small models, and evidence of error accumulation (Arora et al. 2022). The on-policy methods that now dominate (RL, on-policy distillation) are partly a practical answer.

Your fine-tuned model never stops generating. Walk through your debugging. core

1) Decode the labels of one training example and check the end-of-turn token is a loss token. 2) Check whether pad token = EOS and the collator masks all pad positions (which also masks the real EOS). 3) Check the tokenizer keeps the end token atomic and the template emits it after every assistant turn. 4) Check inference stop criteria use the same token id (e.g. <|im_end|>, not the base model's EOS). 5) Check truncation is not cutting the end token off long examples. 6) Overfit a few examples and generate: if it still does not stop, the bug is in steps 1–4.

Per-token or per-sequence loss averaging for a mix of chat and long reasoning traces? How does gradient accumulation interact? core

Per-token mean (or sum with a tuned LR) weights every token equally, so long traces get influence proportional to length; that is usually what you want if traces are the skill you are teaching. Per-sequence mean equalizes examples, which protects short, important behaviors (refusal style, format) from being drowned out, at the cost of under-training long traces. Either way, the normalizer must be computed over the whole optimizer step (all micro-batches, all devices), not per micro-batch; otherwise the effective weighting depends on how examples happen to be grouped (the October 2024 gradient-accumulation bug). Tülu 3 used a sum loss for this reason. If the mix is imbalanced, prefer explicit per-source weights to relying on the reduction.

Design an experiment to test whether cross-example contamination from naive packing hurts SFT. deep

Same data, seed and token budget; three arms: padding, naive packing, packing with document masking (position ids reset). Control for the loss-weighting change packing introduces (use a global per-token normalizer in all arms). Measure (a) standard evals, (b) a targeted probe: pack unrelated examples ahead of a test prompt and measure how often outputs reference earlier content, and (c) sensitivity to irrelevant preceding context at inference. Expect small differences on short-context benchmarks (Llama 3 saw limited impact in standard pretraining) and larger ones for long-context or multi-turn behavior. Report seeds and confidence intervals; this effect is small enough to drown in run-to-run variance.

Why does on-policy distillation reach a target score with roughly 10× less compute than RL or more SFT, in the reported cases? research

Versus RL: the teacher grades every token (dense signal, many bits per episode) instead of one scalar per sequence, so credit assignment is free; and the teacher can raise probability of solutions the student rarely samples (Qwen3's pass@64 rose with distillation but not with RL). Versus off-policy SFT on teacher data: training is on the student's own prefixes, so it fixes the errors the student actually makes instead of polishing states it rarely visits; log-linear SFT returns get expensive fast. Costs and caveats: you need a teacher at training time (forward passes on every student rollout), the student is capped by the teacher, top-k approximations of the KL can bias gradients, and if the teacher is a sibling model, hidden traits transfer too.

Compare rejection-sampling fine-tuning with PPO/GRPO. When would you choose RFT? deep

RFT = REINFORCE with binary reward, no baseline, no negative gradient, samples frozen per round (off-policy within the round), whole-sequence credit. It is simple, stable, works with any SFT stack, and can distill from a larger model's samples. It cannot push down specific wrong behaviors, learns nothing from prompts with zero successes, collapses diversity, and over-fits small prompt sets after a few rounds (ReST-EM). Choose it as a first stage, when pass@N is already high, when infrastructure for on-line RL is not ready, or to distill; move to on-line RL when you need negative signal, exploration on hard prompts, or long-horizon credit assignment.

Design a fair test of "SFT memorizes, RL generalizes". research

Control for: data diversity (same prompts, with diverse instruction phrasings for both arms), information content (SFT on the RL policy's own successful samples, i.e. RFT, as a third arm), distance moved (report KL from base on the training distribution; compare methods at matched KL, not matched steps), training length (look for dip-and-recover), and evaluation shift type (rule shift, surface shift, difficulty shift). Hypotheses: SFT on diverse, self-generated data closes most of the gap; SFT on foreign, surprising demos generalizes worse at matched task accuracy because it moves the model further. Pre-register what result would falsify each.

Explain context distillation, its loss, and when it fails. deep

Teacher = model with a context $C$ (e.g. a long HHH prompt or a spec); student = same model without it; minimize $\KL(p_0(X\mid C)\,\|\,p_\theta(X))$ over a broad text distribution (Askell et al.), or generate with $C$, strip it, and SFT (deliberative alignment). It internalizes behavior the context reliably induces, saves context and compute, and gave Anthropic's early RLHF its initialization. It fails when the context carries instance-specific information the student cannot have at test time (2026 on-policy self-distillation results), when the prompted behavior is itself unreliable, and it can slightly underperform the live prompt. Notice it is forward KL off-policy in the original form; on-policy variants switch to reverse KL on student rollouts.

LoRA or full fine-tuning for 20k persona-style SFT examples on an 8B model? What learning rate? core

LoRA is very likely fine: 20k examples is well inside the "low-regret" regime where LoRA matches full fine-tuning (LoRA Without Regret), it forgets less (Biderman et al.), and it is cheaper to serve multiple variants. Apply it to all linear layers including MLPs, keep batch size moderate, and start the LR around 10× what you would use for full FT (for full FT on 8B, published values are around 5e-6, so LoRA near 5e-5 to 1e-4 as a sweep center). Evaluate forgetting on a broad suite, because a persona change is exactly the kind of narrow data that can generalize broadly.

Someone says "synthetic data causes model collapse, so we should avoid it". Respond. core

The collapse results (Shumailov et al.) are about closed loops where each generation trains only on the previous generation's outputs; tails vanish. Keeping even 10% of original data made degradation minor in their LM experiment, and accumulating rather than replacing data avoids collapse (Gerstgrasser et al.). Post-training pipelines are open loops: strong teachers, verifiers, real prompts. The real risks are narrower: diversity loss, teacher biases and errors baked in, contamination via teachers that saw benchmarks, and hidden trait transfer from sibling teachers. Policy: keep real prompts, filter with external signals, mix sources and teachers, track diversity metrics, decontaminate.

A narrow SFT run (e.g. on a company's terse support transcripts) made the model ruder in unrelated settings. What would you try? research

Diagnose first: measure the shift on a broad persona/behavior eval and check whether it depends on context (system prompt, domain cues). Interventions, in increasing cost: add context to the training data that explains the style (a system prompt like "You are writing terse internal support replies"), i.e. inoculation-style framing so the trait binds to the context; mix in diverse general chat; regenerate the targets with your own model conditioned on the style (on-policy-ish data, smaller KL); use LoRA or a KL penalty to the base; finally, restore general behavior with on-policy distillation from the pre-fine-tune checkpoint on general prompts. Evaluate each against both the target metric and the broad regression.

Which KL does SFT minimize?
Forward: KL(p_data ‖ π_θ). Mode-covering, zero-avoiding.
Which KL does KL-regularized RL minimize?
Reverse KL to the tilted target π* ∝ π_ref·exp(r/β). Mode-seeking.
Teacher forcing
Conditioning each prediction on the ground-truth prefix. Parallel and off-policy; causes exposure bias.
Behavior-cloning error bound
Tε ≤ cost ≤ T²ε. On-policy training (DAgger) restores linear dependence.
Implicit reward of SFT as policy gradient
1[y = y*] / π_θ(y|x): sparse and huge for unlikely demos.
Per-token vs per-sequence mean
Per-token: sequences weigh ∝ length. Per-sequence: each sequence weighs 1/B; long answers' tokens get 1/(B·n).
Why must the end-of-turn token be in the loss?
It is the only place the model learns to stop.
Packing fix
Block-diagonal (document) causal mask + position ids reset per example (cu_seqlens / varlen attention).
Why τ² in Hinton distillation?
Soft-target gradients scale as 1/τ²; multiplying keeps hard/soft terms balanced across temperatures.
GKD's λ
Fraction of student-generated (on-policy) sequences in the distillation batch.
RFT in RL terms
REINFORCE with binary reward, no baseline, no negatives, samples frozen per round. EM: forward-KL fit to π_k conditioned on success.
Context distillation loss
KL(p₀(X|C) ‖ p_θ(X)): same model with prompt C as teacher, without C as student.
RL's razor
Forgetting ≈ E_task[KL(π₀ ‖ π)]; on-policy RL finds KL-minimal solutions, SFT goes where labels point.
Emergent misalignment control
Same insecure code, but user asks for it for education → no broad misalignment. Context/intent decides what is learned.

§13Read next

LIMA: Less Is More for Alignment
Zhou et al. · 2023
1,000 curated examples, the Superficial Alignment Hypothesis, and clean quality/diversity/quantity ablations.
dataSFT
Tulu 3: Pushing Frontiers in Open Language Model Post-Training
Lambert et al. · 2024
The most complete public SFT recipe: mix design, persona data, decontamination, sum-loss and template ablations.
recipedata
A General Language Assistant as a Laboratory for Alignment
Askell et al. · 2021 · Anthropic
The HHH prompt, alignment taxes, and the introduction of context distillation.
Anthropiccontext distillation
On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes
Agarwal et al. · 2023
GKD: unify supervised and on-policy distillation with any token-level divergence.
distillationon-policy
On-Policy Distillation
Lu et al. (Thinking Machines) · 2025 · blog
Per-token reverse KL as reward: an estimated 9–30× cheaper than (extrapolated) SFT to reach the same AIME score; restores behavior after mid-training.
distillationcontinual learning
Distilling the Knowledge in a Neural Network
Hinton et al. · 2015
Temperature, the τ² factor, and the digit-3 experiment.
distillation
Sequence-Level Knowledge Distillation
Kim & Rush · 2016
Train on the teacher's decoded sequences: the ancestor of "SFT on teacher outputs".
distillation
DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning
DeepSeek-AI · 2025
Distilled 32B beats RL-from-base 32B (AIME 72.6 vs 47.0).
reasoningdistillation
Qwen3 Technical Report
Yang et al. · 2025
Strong-to-weak distillation; on-policy distillation beats RL at ~1/10 GPU hours.
distillationrecipe
STaR: Bootstrapping Reasoning With Reasoning
Zelikman et al. · 2022
Rejection-sampling self-training plus rationalization for unsolved problems.
self-training
Beyond Human Data: Scaling Self-Training for Problem-Solving with Language Models
Singh et al. · 2023
ReST-EM: the EM view of rejection-sampling fine-tuning, and its overfitting after a few iterations.
self-trainingEM
SFT Memorizes, RL Generalizes: A Comparative Study of Foundation Model Post-training
Chu et al. · 2025
The slogan's source, including the caveat that SFT stabilizes format for RL.
generalization
RL's Razor: Why Online Reinforcement Learning Forgets Less
Shenfeld et al. · 2025
Forgetting is predicted by KL from the base on the new task.
forgettingKL
Emergent Misalignment: Narrow finetuning can produce broadly misaligned LLMs
Betley et al. · 2025
6,000 insecure-code examples generalize to broad misalignment, unless the context explains them.
safetygeneralization
Subliminal Learning: Language models transmit behavioral traits via hidden signals in data
Cloud et al. · 2025
Traits pass through filtered, unrelated data between models sharing an initialization.
safetydistillation
Inoculation Prompting: Instructing LLMs to misbehave at train-time improves test-time alignment
Wichers et al. · 2025
Request the undesired behavior in training prompts so it is not learned unconditionally.
AnthropicSFT
LoRA Learns Less and Forgets Less
Biderman et al. · 2024
LoRA vs full fine-tuning on code and math; full-FT updates are 10–100× higher rank.
LoRAforgetting
LoRA Without Regret
Schulman et al. (Thinking Machines) · 2025 · blog
When LoRA matches full FT: all layers, 10× LR, moderate batch; RL needs tiny rank.
LoRAhyperparameters
Is Model Collapse Inevitable? Breaking the Curse of Recursion by Accumulating Real and Synthetic Data
Gerstgrasser et al. · 2024
Replace → collapse; accumulate → no collapse.
synthetic data
Why Exposure Bias Matters: An Imitation Learning Perspective of Error Accumulation in Language Generation
Arora et al. · 2022
Teacher forcing as behavior cloning, the T²ε bound, and evidence that accumulation is real.
exposure biastheory