Chapter 5 · SFT and PEFT¶
5.1 What does the overall post-training pipeline look like, and what does each stage contribute? ★★¶
One-sentence answer
Post-training usually consists, in order, of supervised fine-tuning (SFT), preference optimization, and reinforcement learning with verifiable rewards (RLVR): SFT teaches the model the chat format and instruction following by imitating demonstrations; preference optimization aligns the model with human preferences among several acceptable responses; and RLVR strengthens reasoning on tasks whose correctness can be checked automatically. In real industrial pipelines, these stages are usually alternated and iterated over several rounds.
I will address three aspects: what problem post-training solves, what each stage contributes, and why the stages come in this order.
(1) The starting point of post-training is that the base model already has knowledge and abilities but only continues text.
A pretrained model (the base model) has read an enormous amount of text, and most of its knowledge and abilities are already in there, but it does only one thing: keep writing. For example, ask it "What is the capital of France?" and it may well continue with a few similar quiz questions instead of answering, because on the web a question is often followed by more questions. Post-training turns this "text continuer" into an assistant that follows instructions, speaks appropriately and matches human preferences. (Pretraining and mid-training are covered in Chapter 2 and Chapter 4.)
(2) The typical pipeline has three stages, each solving the problem left by the previous one.
- SFT: Continue next-token prediction on "prompt → response" demonstrations that were written or curated by people, but compute the loss only on the response. From this the model learns the chat format, how to respond to instructions and when to stop. In essence it is imitation, known in reinforcement learning (RL) as behavior cloning.
- Preference optimization: SFT can only tell the model "this answer is correct"; it cannot tell the model which of two decent answers is better, nor does it show the model what a bad answer looks like. So we collect human comparisons between responses (A is better than B) and use RLHF (train a reward model first, then optimize with PPO; see Chapter 6) or DPO (train directly on the preference data; see Chapter 7) to move the model toward what people prefer.
- RLVR: For tasks such as math and code whose correctness can be checked automatically, use "is the answer correct" directly as the reward and run RL (see Chapter 8). This step is the core of reasoning models such as o1 and DeepSeek-R1.
(3) The order is determined by each stage's cost and prerequisites.
SFT is cheap and stable, and it first gives the model basic formatting and instruction-following ability. RL, by contrast, needs a "reasonably good" starting point: it learns from the model's own samples, so if the starting model cannot even get the format right, nearly every sample receives zero reward and there is no signal to learn from. On the other hand, preference optimization and RL can learn things SFT cannot: judging which answer is better is usually much easier than writing the best answer oneself, so the comparison signal people can provide can exceed the demonstrations they can write; meanwhile, RL trains on responses the model generated itself, so the model can see and correct its own mistakes. SFT, by contrast, always trains with the reference answer as the preceding text (teacher forcing) and never sees how to continue after making a mistake, so once it errs midway at inference it struggles to recover; this problem is called exposure bias.
In summary: SFT is responsible for "being able to talk", preference optimization for "talking well", and RLVR for "thinking correctly"; in industry the three are usually alternated and iterated rather than run strictly once.
Going deeper: comparing the stages, and the pipelines labs actually use
(1) Data, objective and contribution of each stage, from pretraining to post-training.
| Stage | Data | Objective | Contribution |
|---|---|---|---|
| Pretraining | Trillions of tokens of web text, books and code | Next-token prediction | Knowledge, language ability and latent skills, but only continues text |
| Mid-training | Curated high-quality, long-context, math, code and reasoning data | Next-token prediction | Strengthens specific abilities before post-training |
| SFT | Thousands to millions of "prompt → response" demonstrations | Next-token prediction on response tokens only | Chat format, instruction following, style; a good starting point for RL |
| Preference optimization (RLHF / DPO) | Human or AI comparisons between responses | Maximize reward under a KL constraint, or optimize a preference loss directly | Finer-grained helpfulness, harmlessness and honesty |
| RLVR | Math, code and other tasks with verifiable answers | Maximize a correctness reward | Reasoning, long chains of thought and self-checking |
(2) Industrial pipelines are usually multi-stage and iterated over several rounds.
| Model | Post-training pipeline |
|---|---|
| Llama 3 (Dubey et al. 2024) | Repeated "SFT + rejection sampling + DPO" for six rounds, sampling new data from the latest model in each round |
| Tülu 3 (Lambert et al. 2024) | SFT → DPO → RLVR |
| DeepSeek-R1 (DeepSeek-AI 2025) | A small cold-start SFT → reasoning RL → another SFT on data rejection-sampled from the RL model → RL covering all scenarios |
Here rejection sampling means sampling several responses for the same prompt, scoring them with a reward model or a verifier, and keeping only the highest-scoring response as training data (see 5.3).
Follow-up questions
Follow-up 1: If we already have SFT, why do we still need RLHF or RL?
Because imitation has a natural ceiling and blind spots. An SFT model can at best reach the level of its demonstrations; it has only seen good behavior and receives no negative signal; and it always trains with the reference answer as the preceding text, so it suffers from exposure bias. Preference optimization exploits the fact that judging is easier than generating, obtaining a signal beyond the level of the demonstrations; RL trains on the model's own outputs, teaching the model to correct its own mistakes.
Follow-up 2: Can we skip SFT and run RL directly on the base model?
Yes, but at a cost. DeepSeek-R1-Zero ran RL with rule-based rewards directly on the base model, and reasoning behaviors such as long chains of thought and self-checking emerged on their own, but the outputs were hard to read and mixed Chinese and English. DeepSeek-R1 therefore first ran a cold-start SFT on a few thousand high-quality long chain-of-thought examples and then ran RL (DeepSeek-AI 2025).
Follow-up 3: Why do industrial pipelines iterate over several rounds?
Because the model gets stronger after each round, so the data should be regenerated with the new model. For example, in each round Llama 3 used the latest model to sample several responses per prompt, picked the best with a reward model as new SFT data, and collected new preference data. This keeps the training data close to the current model's distribution, and the data quality rises with the model's ability.
Common mistakes
- Do not say SFT teaches the model a lot of new knowledge: Knowledge comes mainly from pretraining; SFT mainly teaches format and behavior (see 5.2).
- Do not conflate RLHF and RLVR: In RLHF the reward comes from a reward model trained on human preferences; in RLVR it comes from a rule-based or programmatic verifier.
- Do not describe post-training as a strict three-step pipeline: Real pipelines are usually multi-stage and iterated over several rounds.
5.2 What does SFT actually teach the model? ★★¶
One-sentence answer
SFT mainly teaches the model "in what format and style to respond", not new knowledge or abilities. LIMA turned a 65B base model into a decent assistant with only 1,000 curated examples, and its authors accordingly proposed the superficial alignment hypothesis: knowledge and abilities come almost entirely from pretraining, and alignment merely makes the model adopt a suitable output style. But the hypothesis has limits: hard skills still improve with more high-quality data, and injecting new knowledge through SFT actually worsens hallucination.
I will address three aspects: the training objective of SFT, the superficial alignment hypothesis and its evidence, and the limits of the hypothesis.
(1) SFT maximizes the likelihood of the demonstrated response given the prompt; in essence it is behavior cloning.
The SFT loss is the same cross-entropy as in pretraining; the only differences are the data and the mask: the loss is computed only on the response tokens (the formula is in "Going deeper" below). From an RL perspective this is behavior cloning, i.e. having the model imitate an expert's behavior. It is simple, stable and cheap, but it carries the natural limits of imitation: the model can at best reach the level of the demonstrations; it has only seen good behavior and never what bad behavior looks like; and during training the preceding text is always the reference answer, while at inference it is the model's own output, so once it makes a mistake midway, it has never learned how to recover (exposure bias).
(2) The superficial alignment hypothesis holds that SFT merely teaches the model which format and style to use in conversation.
LIMA (Zhou et al. 2023) fine-tuned the 65B LLaMA on only 1,000 carefully selected demonstrations, with no RLHF at all; in human evaluation, LIMA's responses were judged as good as or better than GPT-4's in 43% of cases, and clearly better than Alpaca 65B trained on 52,000 examples. From this the authors proposed the superficial alignment hypothesis: almost all of a model's knowledge and abilities are learned during pretraining, and alignment only teaches the model which subdistribution of formats and styles to use when interacting with users. As an analogy, the base model is already a person who knows everything, and SFT only teaches them to "answer in an assistant's voice and in this format". The later URIAL (Lin et al. 2023) gave more direct evidence at the level of token distributions: comparing a base model with its aligned version, the two decode almost identically at the vast majority of positions, and the differences are concentrated on a few stylistic tokens, such as discourse markers and safety-related phrasing. There are similar examples for reasoning models: s1 (Muennighoff et al. 2025), with only 1,000 samples containing reasoning traces, and LIMO (Ye et al. 2025), with only 817, drew out strong math reasoning from Qwen2.5-32B.
(3) The hypothesis has clear limits and should not be read as "SFT learns nothing".
- Hard skills still need more data: LIMA's evaluation mainly targets style and human preference in general chat; on math, code, multi-turn dialogue and safety robustness, more high-quality data keeps helping. LIMA's authors themselves acknowledge that their model is less robust than production models.
- The premise is that the base model already has the ability: s1 and LIMO use a very strong 32B model; the same data applied to a weaker model does not draw out the same ability.
- Injecting new knowledge through SFT worsens hallucination: Gekhman et al. (2024) found that examples containing knowledge unknown to the model are learned much more slowly than examples of known knowledge; and once the model does fit them, its tendency to hallucinate relative to its existing knowledge rises linearly. The reason is that the model does not really memorize the new fact; what it learns is "give a confident, specific answer even when you do not know". New knowledge should therefore be introduced through (continued) pretraining or retrieval; SFT is better suited to teaching behavior than to teaching knowledge.
In summary: SFT teaches behavior, not knowledge; a small amount of high-quality data can unlock abilities the base model already has, but cannot create abilities from nothing.
Going deeper: the SFT loss and the evidence for the hypothesis
(1) The SFT loss is the cross-entropy averaged over response tokens only.
Here \(x\) is the prompt (system prompt plus user input), \(y_t\) is the \(t\)-th token of the response, \(y_{<t}\) is the part of the response before it, \(\pi_\theta\) is the model's next-token probability distribution, and \(m_t\) is the loss mask: 1 for response tokens and 0 for prompt tokens (see 5.4 for why). The denominator \(\sum_t m_t\) averages over all response tokens.
(2) The main evidence supporting and qualifying the hypothesis.
| Work | Setup | Finding |
|---|---|---|
| LIMA (Zhou et al. 2023) | Fine-tuned LLaMA 65B on 1,000 curated examples, no RLHF | As good as or better than GPT-4 in 43% of cases; better than Alpaca 65B trained on 52,000 examples |
| URIAL (Lin et al. 2023) | Compared token distributions of base and aligned models | Differences concentrate on a few stylistic tokens, mostly near the start of the response; in-context learning with just three fixed stylistic examples comes close to SFT or SFT+RLHF models |
| s1 (Muennighoff et al. 2025), LIMO (Ye et al. 2025) | 1,000 and 817 samples with reasoning traces, Qwen2.5-32B | Drew out strong math reasoning |
| Gekhman et al. (2024) | Controlled the share of "new knowledge" examples in closed-book QA | After fitting new-knowledge examples, the tendency to hallucinate rises linearly |
Follow-up questions
Follow-up 1: Why can 1,000 examples turn a base model into a decent assistant?
Because there is little to learn in the first place. According to the superficial alignment hypothesis, the base model already has the knowledge and abilities needed to answer questions, and SFT only needs to make it select the assistant's "way of talking" among many. This selection involves only a small number of stylistic tokens (URIAL's finding), so a small number of high-quality, sufficiently diverse demonstrations is enough to pin it down; low-quality data, on the contrary, teaches bad habits.
Follow-up 2: How does the superficial alignment hypothesis relate to the view that "RL mainly elicits existing abilities"?
Both hold that post-training mainly elicits abilities acquired during pretraining. The practical conclusion is that the ceiling of post-training depends heavily on the base model, so the foundation must be laid in pretraining and mid-training; for example, adding reasoning and math data in mid-training can raise the ceiling of subsequent RL (see Chapter 4 and Chapter 8).
Follow-up 3: If the SFT validation loss starts to rise, should training stop?
Not necessarily; validation loss is not a good metric for selecting SFT models. InstructGPT's SFT models started to rise in validation loss after 1 epoch, yet training on to 16 epochs improved both reward model scores and human preference ratings (Ouyang et al. 2022); LIMA likewise found that perplexity did not correlate with generation quality. The reason is that validation loss measures "predicting every token of the reference answer accurately", whereas what we care about is whether the whole response the model generates itself is good: as the model becomes more certain about the demonstrations, validation loss rises, yet the generated responses may become more decisive and better formed. So how long to train SFT is usually decided by downstream evaluation (LLM judges, benchmarks, manual spot checks).
Common mistakes
- Do not read the superficial alignment hypothesis as "the less SFT data, the better": It says that format and style need only a little data; hard skills still need scale.
- Do not say SFT can be used to instill new facts in a model: Doing so worsens hallucination; new knowledge should be introduced through pretraining or retrieval.
- Do not select checkpoints by SFT validation loss: It is not consistent with generation quality.
5.3 How do you build SFT data? Which matters more, quality or quantity? ★★¶
One-sentence answer
SFT data usually combines a small amount of high-quality, human-written seed data with large-scale synthetic data or data distilled from stronger models, all strictly filtered by a reward model, an LLM judge or a programmatic verifier. For format and style, quality matters far more than quantity; but for hard skills such as math and code, scaling up while keeping quality high remains effective, and the data must also be diverse.
I will address three aspects: where the data comes from, why quality comes first, and when quantity and diversity still matter.
(1) SFT data comes from four main kinds of sources, each with trade-offs.
- Human-written: The highest quality and the most controllable, but expensive, slow and hard to scale. For example, InstructGPT's SFT data consisted of demonstrations written by labelers for about 13,000 prompts (Ouyang et al. 2022).
- Rewritten existing NLP datasets: For example, FLAN (Wei et al. 2021) used templates to rewrite a large number of tasks such as classification, QA and translation into "instruction + answer" form, giving extremely high task diversity; but the answers are often very short, so models trained on them tend to be terse, which is a poor fit for a chat assistant.
- Model-synthesized: For example, Self-Instruct (Wang et al. 2022) has a model start from a few seed tasks to generate new instructions and answer them, and Evol-Instruct (Xu et al. 2023) has a model rewrite simple instructions step by step into more complex ones. Synthetic data is cheap and plentiful and can target specific missing abilities, but its diversity is limited by the generator, and its errors must be filtered out.
- Distilled from stronger models: For example, Alpaca, Vicuna, and the now-common practice of distilling long reasoning chains from reasoning models (see Chapter 9). It is cheap and high quality, but Gudibande et al. (2023) found that models trained to imitate ChatGPT looked about as good as ChatGPT in crowdworker evaluations, yet on targeted factuality and capability evaluations the gap barely closed: a model easily learns the teacher's style but has a hard time learning the teacher's substance.
The mainstream practice is to mix these sources and then filter strictly. A common filtering technique is rejection sampling: sample several responses for the same prompt from the current model, score them with a reward model or a verifier, and keep only the highest-scoring one. For example, a large share of Llama 3's SFT data was obtained this way (Dubey et al. 2024).
(2) Quality comes first because every SFT example is a behavior demonstration.
As 5.2 showed, SFT mainly teaches the model "how to talk", and the model learns everything in the demonstrations, including mistakes, sloppiness, made-up facts, unnecessary refusals and wordy boilerplate. A bad example is therefore not merely "useless"; it directly teaches a bad habit. The evidence is very consistent: LIMA, with 1,000 curated examples, beat Alpaca with 52,000; Llama 2 stopped SFT annotation after collecting 27,540 high-quality annotations, because that set worked better than far larger third-party data (Touvron et al. 2023); AlpaGasus (Chen et al. 2023) had ChatGPT score Alpaca's 52K examples and kept only about 9K high scorers, and the resulting model was clearly better. High quality means the answer is correct, genuinely helpful, consistent in format and style, of appropriate length, free of made-up facts, and ideally within what the model already knows.
(3) Quantity and diversity still matter in two situations.
- Hard skills need scale: "Quality beats quantity" refers to surface behaviors such as format and style. For hard skills such as math, code and reasoning, adding more data usually keeps helping, as long as quality is maintained (especially when answers can be verified).
- Diversity determines how far the model generalizes: A model generalizes only along the directions its data covers. If 80% of the data is short Q&A, the model becomes terse; if many prompts come from the same template, the model fails when the question is phrased differently. Filtering purely by a quality score has a hidden risk too: high-scoring samples tend to cluster in a few task types the scorer favors, so the filtered distribution narrows. The data therefore needs coverage along many dimensions: task type, domain, difficulty, output length, language, single- versus multi-turn, and cases where the model should answer versus refuse.
In addition, when data from several domains is mixed, the mixture ratio matters: too much data from one domain crowds out other abilities and pulls the model's overall style off course, which is why work such as Tülu 3 builds data separately per skill and repeatedly tunes the mixing ratios (Lambert et al. 2024).
In summary: format comes from little-but-excellent data, skills come from scaling up while keeping quality high, and generalization comes from diversity; quantity can never replace quality.
Going deeper: comparing data sources, and common filtering methods
(1) Comparing the data sources.
| Source | Examples | Strengths | Weaknesses |
|---|---|---|---|
| Human-written | InstructGPT demonstrations, Llama 2 SFT data, Dolly, OpenAssistant | High quality, controllable, close to real needs | Expensive, slow, hard to scale; annotators vary in skill |
| Rewritten NLP datasets | FLAN, Super-NaturalInstructions, T0 | Extremely high task diversity, low cost | Short, templated answers; unnatural chat style |
| Real user prompts | LMSYS-Chat-1M, WildChat | Realistic prompt distribution | Responses still need writing or regenerating; privacy and licensing concerns |
| Model-synthesized | Self-Instruct, Evol-Instruct | Cheap, scalable, can target gaps | Limited diversity, contains errors, style converges toward the generator |
| Distilled from strong models | Alpaca, Vicuna, Orca, long reasoning chains from reasoning models | Low cost, high quality | Inherits the teacher's errors; learns style more than substance; terms of service apply |
(2) Common filtering and cleaning methods.
| Method | How | Purpose |
|---|---|---|
| LLM-judge or reward-model scoring | Score each example for quality and keep the high scorers | Quality |
| Rejection sampling | Sample several responses per prompt and keep only the highest-scoring one | Quality, and data close to the model's own distribution |
| Programmatic verification | Check final answers for math, run unit tests for code | Correctness |
| Deduplication | Exact dedup, MinHash near-dedup, embedding-similarity dedup | Avoid over-learning duplicated examples |
| Cluster sampling | Cluster in embedding space, then sample evenly from each cluster | Diversity |
| Joint selection | Consider quality, complexity and diversity together (e.g. Deita, Liu et al. 2023), or select by gradient influence on the target task (e.g. LESS, Xia et al. 2024) | Balance quality and diversity |
| Decontamination | Remove examples that overlap with evaluation sets | Keep evaluation results trustworthy |
Follow-up questions
Follow-up 1: What are the risks of training a small model on data distilled from a strong model such as GPT-4?
The main risk is learning the style without learning the substance. A small model easily imitates the teacher's tone and format, which are exactly what most easily fool evaluators, but the gap in factuality and reasoning does not shrink accordingly (Gudibande et al. 2023). In addition, the teacher's errors and biases are passed down too, and the relevant terms of service must be respected.
Follow-up 2: Why is data obtained by rejection sampling often more useful than external data?
Because it ensures both quality and closeness in distribution. On one hand, after filtering by scoring or verification, what remains are the highest-quality responses; on the other, these responses are generated by the current model itself and are close to its existing way of talking, so the model does not need to make many task-irrelevant changes to imitate someone else's wording, and it therefore learns faster and forgets less (see 5.5).
Follow-up 3: Why decontaminate against evaluation sets before training?
Otherwise evaluation scores are inflated and fail to reflect real ability. If benchmark questions leak into the training data, the model may simply memorize the answers. When building data, one should therefore use n-gram overlap or embedding-similarity checks to remove examples that overlap with evaluation sets.
Common mistakes
- Do not say "the more SFT data, the better": Low-quality data directly teaches bad habits, and quantity cannot replace quality.
- Do not filter by quality score alone: This narrows the data distribution; diversity must be considered at the same time.
- Do not put knowledge the model does not have into the responses: This encourages the model to make up answers (see 5.2).
5.4 What are a chat template and a loss mask, and why is the loss computed only on the response? ★★¶
One-sentence answer
A chat template is the convention of using special tokens to serialize a multi-turn conversation into a one-dimensional token sequence, marking the role and boundaries of each turn; a loss mask sets the labels of the system, user and tool-output parts to "ignore", so that the loss is computed only on the assistant's response. The loss is computed only on the response because the training objective is the conditional distribution \(p(y\mid x)\); doing so also keeps the prompt from diluting the gradient and matches inference, where only the response is generated.
I will address three aspects: what a chat template is, why the loss is computed only on the response, and the implementation details that are easy to get wrong.
(1) A chat template uses special tokens to mark the role and boundaries of each turn.
A model only sees a one-dimensional token sequence; it has no idea what a "user" or an "assistant" is. A chat template is the convention for serializing a multi-turn conversation into one token sequence: special tokens mark the role and the start and end of each turn (an example is in "Going deeper" below), and each model family has its own template. At inference, the server builds the conversation with the same template and appends the opening of an assistant turn as the "your turn" cue, and the model generates until the end token. The most common problem with templates is a mismatch between training and inference, such as a missing system prompt, different newlines or spaces, a missing BOS token, or forgetting the opening of the assistant turn at inference. The model then sees a format at inference that it never saw in training, and quality quietly drops in a way that is hard to debug. One should therefore always use the tokenizer's own template (such as Hugging Face's apply_chat_template) rather than assembling it by hand. Also, if new special tokens are added for the template, their embeddings are randomly initialized, so the corresponding rows of the embedding layer and the output layer must be trained; otherwise the model cannot learn these tokens.
(2) There are three reasons for computing the loss only on the response.
In the implementation, the labels of the tokens in the system and user parts are set to "ignore" (−100 in PyTorch and Hugging Face), so these positions do not count toward the loss. The reasons are threefold:
- The training objective is the conditional distribution \(p(y\mid x)\) in the first place: We want the model to learn "how to answer a given question", not "how to ask". If the loss also covered the user's messages, the model would learn to generate user turns, and at inference it might continue the conversation as a monologue, asking and answering itself.
- The prompt dilutes the gradient: In many datasets the system prompt is identical across thousands of examples, and few-shot examples and long retrieved documents also sit in the prompt. If all these tokens counted toward the loss, a large share of the gradient would go to memorizing templates and repeating the input, and the response we actually care about would be only a small part of the loss.
- It matches inference: At inference the prompt is given by the user and the model only needs to generate the assistant's part, so the training objective should target exactly that.
Note that masking the prompt does not mean ignoring the prompt: the prompt still goes through the forward pass, every response token reads it through attention, and gradients still flow back through the representations at prompt positions. What is removed is only the loss terms for "predicting the next token inside the prompt".
(3) A few implementation details are easy to get wrong.
- Multi-turn conversations: Mask all system, user and tool-output turns, and let every assistant turn contribute to the loss, so that one forward pass trains every response in the whole conversation at once. Tool outputs come from the environment, and the model should not learn to make them up.
- The end token must count toward the loss: The end token at the end of each assistant turn must be trained on, so that the model learns to stop at the right time; if it is left out, the model keeps generating and never stops.
- Packing: Putting several short examples into one context window reduces padding waste, but one must use a per-example attention mask and reset the position ids; otherwise one example will attend to an unrelated previous example.
- How the loss is averaged: Averaging over all response tokens in the batch gives long responses more weight; averaging within each example first and then across examples gives each token of a short response more weight. This choice quietly changes the model's preference for response length.
In summary: the chat template lets the model "recognize" the structure of a conversation, and the loss mask makes the model learn only "how to respond"; details such as template consistency and including the end token in the loss often decide whether fine-tuning succeeds.
Going deeper: a template example and two ways of averaging the loss
(1) An example in ChatML format (used by Qwen and others).
<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
What is 2 + 2?<|im_end|>
<|im_start|>assistant
2 + 2 = 4.<|im_end|>
Only the last line, 2 + 2 = 4.<|im_end|>, contributes to the loss, including the end token <|im_end|>; the labels of all preceding tokens are set to −100. At inference, the server builds the sequence up to <|im_start|>assistant, and the model generates from there until it outputs <|im_end|>. Llama 3 and other models use a different set of special tokens, but the principle is the same.
(2) Token-level and sample-level averaging give responses of different lengths different weights.
Suppose a batch has \(B\) examples, the response of example \(i\) has \(n_i\) tokens, and \(\ell_{i,t}\) is the cross-entropy loss of its \(t\)-th token:
In token-level averaging every token has the same weight, so long responses carry more total weight because they have more tokens; in sample-level averaging every example has the same total weight, so each token of a short response carries more weight. With gradient accumulation there is another caveat: it is equivalent to a large batch only if the loss is normalized by the total number of tokens in the whole large batch; if each micro-batch first averages on its own and the averages are then added, the result no longer matches the large batch. (A similar length bias in RL is discussed in Chapter 8.)
Follow-up questions
Follow-up 1: After masking the prompt, does the prompt still affect the gradient?
Yes. The loss mask removes only the prediction losses at prompt positions; the prompt still goes through the forward pass, and response tokens read the prompt's representations through attention, so the gradient produced by the response loss flows back through these representations to all the parameters.
Follow-up 2: A fine-tuned model never stops generating. What could be wrong?
The most common cause is that the end token was not trained on. For example, the end token was masked out by the loss mask; or the pad token was set to the same token as the end token, so masking out the padding also masked out the real end token. Another common cause is a mismatch between the training and inference templates, so at inference the model does not recognize where it should stop.
Follow-up 3: Is computing the loss on the prompt always bad?
Not necessarily; under certain conditions it actually helps. Shi et al. (2024) found that when instructions are long, responses are short and there are few training examples (exactly the LIMA-like setting), including the prompt in the loss works better. The reason is that it acts as a regularizer: training loss is higher but test loss is lower, so overfitting is reduced. "Loss only on the response" is therefore the default, not a law.
Common mistakes
- Do not say the masked prompt takes no part in the computation: It still goes through the forward pass and affects the gradient through attention.
- Do not forget to include the end token in the loss: Otherwise the model never learns to stop.
- Do not assemble the template by hand: Use the tokenizer's own template to keep training and inference consistent.
5.5 How do you mitigate catastrophic forgetting in SFT? ★¶
One-sentence answer
Catastrophic forgetting means that after fine-tuning on new data, abilities not covered by that data clearly degrade; the root cause is that all abilities share one set of parameters while the fine-tuning gradient comes only from the new data. There are two lines of mitigation: keep giving old abilities a training signal, for example by mixing in general data; and reduce the model's shift away from its original distribution, for example by lowering the learning rate, using LoRA, merging models, or keeping the training targets close to the model's own distribution.
I will address three aspects: why forgetting happens, what mitigations exist, and how to monitor it.
(1) Forgetting stems from shared parameters, and the farther the shift from the original distribution, the worse it gets.
Catastrophic forgetting shows up as worse general knowledge, declining ability in other languages or code, weaker in-context learning and worse calibration, and safety alignment can also break; the drop in general ability caused by alignment training is also called the alignment tax. The reason is that all of the model's abilities share one set of parameters, while the fine-tuning gradient comes only from the new data and no loss term protects the old behaviors; the parameters therefore move toward fitting the new data and, along the way, damage structures that matter for old abilities but are irrelevant to the new task. Consequently, the larger the update and the farther the target distribution is from the model's original distribution, the worse the forgetting: a narrower data domain, more epochs and a higher learning rate all make it worse. This matters especially for SFT: SFT asks the model to imitate text written by others, so the model must learn not only to "get it right" but to "get it right the way someone else does", and the latter brings many changes unrelated to the task. That is also why, on the same new task, on-policy RL usually forgets less than SFT (Shenfeld et al. 2025). Forgetting in domain continued pretraining is covered in Chapter 4.
(2) Mitigations fall into four groups.
- Data mixing (replay): Mix a share of general instruction data or pretraining data into the new data, so that old abilities keep receiving gradient. The cost is extra data and compute, and the mixing ratio needs tuning.
- Limiting the size of the update: Use a smaller learning rate, fewer epochs and early stopping; or use LoRA, which restricts the update to a low-rank space (see 5.8); or regularize the deviation from the original weights, for example with EWC (Kirkpatrick et al. 2016), which weights the penalty by each parameter's importance to old tasks, or with a KL constraint to the original model at the output level. The cost is that the new task is learned less, too.
- Model merging: Interpolate between the fine-tuned and original weights (WiSE-FT, Wortsman et al. 2021), which usually trades a little task performance for a lot of general ability.
- Keeping training targets close to the model's own distribution: For example, first have the model rewrite the target responses in its own words and then train on the rewritten data (Yang et al. 2024); or do SFT only on correct responses that the model generated itself and that passed filtering (rejection sampling fine-tuning); the most thorough option is on-policy RL.
(3) Whatever method is used, general ability and safety must be monitored continuously during training.
Looking only at the target task's score is not enough; a suite of general-ability and safety evaluations should be tracked at the same time. Safety alignment deserves particular care: Qi et al. (2023) found that fine-tuning GPT-3.5 Turbo on just 10 harmful examples (costing less than $0.20 through the API) largely removed its safety guardrails, and even fine-tuning on completely benign, commonly used datasets reduced safety. Safety data is therefore usually mixed in during fine-tuning, and safety is re-evaluated afterward.
In summary: the essence of forgetting is "changing too much and moving too far"; the core of mitigation is to keep training old abilities while keeping the new training targets as close as possible to the model's original distribution.
Going deeper: comparing the methods, and RL's Razor
(1) Principle and cost of each mitigation.
| Method | Principle | Cost |
|---|---|---|
| Data mixing (replay) | Old abilities keep receiving gradient | Extra data and compute; the ratio needs tuning |
| Smaller learning rate, fewer epochs, early stopping | Reduces the total change to the parameters | The new task is learned less |
| LoRA | Restricts the update to a low-rank space | The new task is learned less; insufficient capacity with large data |
| Regularization (L2, EWC, KL) | Penalizes deviation from the original model | Coefficients need tuning; EWC must estimate parameter importance |
| Model merging (WiSE-FT) | Interpolates between original and fine-tuned weights | Loses some task performance |
| Staying close to the model's own distribution (rewriting, rejection sampling, on-policy RL) | Reduces the distribution shift between the training target and the original model | Needs extra sampling or scoring; RL needs a reward |
(2) RL's Razor: the degree of forgetting can be predicted by the KL shift on the new task.
Here \(\pi_0\) is the original model, \(\pi\) the fine-tuned model, \(\tau\) the input distribution of the new task, and \(f\) an increasing function. Shenfeld et al. (2025) found that this KL divergence, measured only on new-task inputs, predicts forgetting on old tasks well, while measures such as the size of the weight change or whether the update is low-rank predict it poorly. RL forgets less because a task usually has many correct solutions, and RL, sampling from the model's own distribution, tends to settle near "the distribution that solves the task and is closest to the original model"; SFT, by contrast, pulls the model toward a fixed set of labels that may be far from the original model. The most convincing control: generating data with the RL-trained model and then running SFT on that data yields the same accuracy–forgetting trade-off as RL. So what matters is not the algorithm itself but how close the final distribution is to the original model. In practice, this KL can be monitored at any time without old data and serves as an early warning of forgetting.
Follow-up questions
Follow-up 1: Why is SFT more prone to forgetting than on-policy RL?
Because SFT's target distribution can be far from the original model, whereas RL only redistributes probability among the model's own samples. SFT imitates fixed text written by others, so the model must learn their wording and style along with the task; RL samples from the model's own distribution and only shifts probability onto rewarded samples, so it ends up closer to the original model. The RL's Razor experiments show that the degree of forgetting is determined mainly by this distribution shift.
Follow-up 2: Why can fine-tuning on benign data also break safety alignment?
Because safety behavior is a "shallow" layer learned in post-training, and it is easily washed away. Qi et al. (2024) pointed out that safety alignment is largely concentrated in the first few tokens of a response, for example whether it starts with a refusal, which they call "shallow safety alignment". Benign data consists entirely of "do whatever is asked, answer directly" demonstrations, so the gradient keeps pushing the model toward compliance while no example maintains the refusal behavior, and this shallow safety layer gets washed away.
Common mistakes
- Do not say LoRA does not forget: LoRA forgets less, but not nothing, and the higher the rank, the more it forgets (see 5.8).
- Do not assume forgetting affects only knowledge: In-context learning, calibration and safety alignment can all degrade.
5.6 How does LoRA work? ★★★¶
One-sentence answer
LoRA freezes the pretrained weight \(W_0\) and adds a low-rank side branch that represents the weight update as the product of two small matrices, \(\Delta W=\frac{\alpha}{r}BA\), training only \(A\) and \(B\); it rests on the observation that the weight update needed for fine-tuning has a very low intrinsic dimension. \(B\) is initialized to 0 and \(A\) randomly, so training starts from the original model and the gradients are nonzero; at inference \(BA\) can be merged back into \(W_0\) with no added latency.
I will address four aspects: the motivation, the method, the initialization, and what it saves.
(1) Motivation: full fine-tuning is expensive, while the update fine-tuning needs is low-dimensional.
Full fine-tuning with Adam and mixed precision needs about 16 bytes of memory per parameter (see Chapter 3), so a 7B model needs about 112 GB for weights, gradients and optimizer states alone; and every task needs its own full copy of the model. On the other hand, Aghajanyan et al. (2020) found that fine-tuning a pretrained model can be done in a very low-dimensional subspace; that is, the "intrinsic dimension" needed for fine-tuning is low. If so, there is no need to update the whole weight matrix; learning a low-rank update is enough.
(2) Method: freeze \(W_0\) and represent the update as the product of two small matrices.
The forward computation of LoRA (Hu et al. 2021) is
where \(x\) is the layer's input, \(h\) its output, and \(W_0\in\mathbb{R}^{d\times k}\) the frozen original weight; \(A\in\mathbb{R}^{r\times k}\) first compresses the \(k\)-dimensional input to \(r\) dimensions, and \(B\in\mathbb{R}^{d\times r}\) then maps it back to \(d\) dimensions; the rank \(r\) is much smaller than \(d\) and \(k\); and \(\alpha\) is a scaling constant, with \(\alpha/r\) controlling the overall magnitude of the branch. Only \(A\) and \(B\) are updated during training, so the trainable parameters drop from \(dk\) to \(r(d+k)\). For example, with \(d=k=4096\) and \(r=16\), the trainable parameters drop from about 16.8 million to about 131 thousand, under 1%. The original paper reported on GPT-3 175B that trainable parameters fell by about 10,000×, memory by about 3×, and quality was on par with full fine-tuning. Later experience indicates that LoRA should be applied to all linear layers, especially the FFN layers.
(3) Initialization: \(B\) at 0 and \(A\) random satisfies both requirements, "start from the original model" and "nonzero gradients".
LoRA's initialization must satisfy two requirements at once:
- \(\Delta W\) must be 0 at the start of training: Then the model with LoRA is initially identical to the pretrained model, and fine-tuning starts from a known good point; if both \(A\) and \(B\) were random, \(BA\) would be a random matrix, which amounts to adding noise to every layer's output and damaging what pretraining learned right from the start.
- The gradients must not be zero: \(B\)'s gradient depends on \(A\), and \(A\)'s gradient depends on \(B\) (the derivation is in "Going deeper" below), so if both were 0, both gradients would be 0 and the parameters would stay put forever.
"One zero, one random" satisfies both: \(B=0\) guarantees \(\Delta W=0\); \(A\) is random, so \(Ax\neq0\) and \(B\) gets a nonzero gradient right from the start of training. In that very first step \(A\)'s gradient is 0, but as soon as \(B\) is updated to something nonzero, \(A\) starts learning too.
(4) Benefits: memory drops sharply, training is somewhat faster, and the update can be merged at inference.
- Memory: Frozen weights need neither gradients nor optimizer states, and these two take exactly 14 of the 16 bytes in full fine-tuning. LoRA only stores the base weights in bf16 (2 bytes per parameter) plus the small adapter and its optimizer states, so a 7B model goes from about 112 GB to about 14 GB plus activations. Activations, however, do not shrink, because the forward and backward passes still go through the whole model.
- Compute: The forward pass is not reduced at all; the backward pass still computes gradients with respect to activations and only skips the weight gradients of the frozen matrices. Training compute per token therefore drops from about \(6N\) to about \(4N\), so training is somewhat faster, but nowhere near as much as the memory savings.
- Deployment: Each task only needs to store an adapter of a few MB to a few hundred MB. At inference one can compute \(W=W_0+\frac{\alpha}{r}BA\) directly, which has exactly the same shape as the original matrix, so there is no extra latency at all; or one can keep the adapters separate, with one base model resident in memory and different adapters attached per request, so a single GPU can serve many customized models at once (e.g. S-LoRA, Sheng et al. 2023).
In summary: LoRA uses "frozen base + low-rank branch + zero initialization" to approximate full fine-tuning with very few trainable parameters; what it saves is mainly memory and storage, not compute or activations.
Going deeper: the gradient derivation, choosing \(r\) and \(\alpha\), and which layers to adapt
(1) Why \(A\) and \(B\) cannot both be 0: their gradients depend on each other.
Let \(g=\partial\mathcal{L}/\partial h\) be the gradient of the loss with respect to the layer's output. Then
If \(A=B=0\), both gradients are 0; if \(B=0\) and \(A\) is random, then \(\partial\mathcal{L}/\partial B\neq0\) and \(B\) can update in the very first step.
(2) The rank \(r\) sets capacity, and \(\alpha/r\) keeps the update size from changing sharply with \(r\).
- Rank \(r\): Determines how complex an update LoRA can express. For adjusting only format and style, \(r=8\) or 16 is often enough; with large data or a new domain, a larger \(r\) is needed, or even full fine-tuning.
- Scaling \(\alpha/r\): \(BAx\) is a sum of \(r\) terms, so without scaling, changing \(r\) changes the size of the branch's output and the learning rate has to be retuned. With \(\alpha/r\), tuning \(\alpha\) under Adam is roughly equivalent to tuning the learning rate, so \(\alpha\) can be fixed (commonly to \(r\) or \(2r\)) and \(r\) changed with little retuning. (rsLoRA (Kalajdzievski 2023) argues that at large \(r\), \(\alpha/r\) shrinks the update too much, and uses \(\alpha/\sqrt{r}\) instead.)
- Learning rate: LoRA's optimal learning rate is usually about 10 times that of full fine-tuning (Schulman & Thinking Machines Lab 2025).
(3) It should be applied to all linear layers, especially the FFN.
The original paper applied LoRA only to attention's \(W_Q\) and \(W_V\). Later experience shows that it should be applied to all linear layers: QLoRA (Dettmers et al. 2023) found that only then does it match full fine-tuning; the Thinking Machines experiments are more direct: attention-only LoRA clearly underperforms FFN-only LoRA, even at the same parameter count (Schulman & Thinking Machines Lab 2025). One explanation is that the FFN holds about two-thirds of each block's parameters and is believed to store much of the knowledge, so many behavioral adjustments need to modify it. The embedding and output layer usually stay frozen and need training only when new tokens are added (see 5.4).
(4) Memory comparison (7B model, excluding activations).
| Full fine-tuning | LoRA | QLoRA | |
|---|---|---|---|
| Base weights | 14 GB (bf16) | 14 GB (bf16, frozen) | About 3.5 GB (4-bit, frozen) |
| Gradients and optimizer states | 98 GB | Adapter only, very small | Adapter only, very small |
| Total | About 112 GB | About 14 GB plus adapter | About 4 GB plus adapter |
Follow-up questions
Follow-up 1: Why is a low-rank update enough? Is it always enough?
It is enough when the data is not large, because the update fine-tuning needs is itself low-dimensional; but it is not enough when the data is very large. Research on intrinsic dimension shows that adapting to a new task only requires adjusting parameters within a very low-dimensional subspace. However, Biderman et al. (2024) found that in large-scale continued pretraining, the weight updates learned by full fine-tuning have a rank 10 to 100 times higher than typical LoRA configurations, so the low-rank assumption no longer holds (see 5.8). Conversely, in RL each episode carries very little information, and rank-1 LoRA can match full fine-tuning.
Follow-up 2: Would the reverse, \(A=0\) and \(B\) random, work?
In theory it also meets both requirements, but in practice it works worse. It likewise gives \(\Delta W=0\), and \(A\) receives a nonzero gradient in the first step. But Hayou et al. (2024) showed that the default "\(B=0\), \(A\) random" can use larger learning rates without making the output unstable, so it learns more efficiently and works better on average.
Follow-up 3: Why does LoRA need a larger learning rate than full fine-tuning?
Because at the same learning rate, LoRA changes the weights less in practice. There is no complete theory yet for why the factor is about 10, but there is a common intuition: LoRA's update is a product of two matrices and \(B\) starts at 0, so early in training each step changes \(\Delta W\) far less than a direct update to \(W\) would; with the \(\alpha/r\) scaling on top, the change is smaller still. Reaching a comparable update size takes a larger learning rate.
Common mistakes
- Do not say LoRA reduces activation memory: The forward and backward passes still go through the whole model, so activations are the same as in full fine-tuning.
- Do not say LoRA's training speedup matches its memory savings: Compute drops only from about \(6N\) to about \(4N\).
- Do not say \(A\) and \(B\) are both initialized to 0, or both randomly: The former gives zero gradients and nothing is learned; the latter damages the pretrained model from the start.
- Do not say LoRA is applied only to attention: That was the original paper's setup; later experience shows the FFN matters more, and LoRA should be applied to all linear layers.
5.7 How does QLoRA work, and what other PEFT methods are there? ★¶
One-sentence answer
QLoRA stores the frozen base weights in a 4-bit NF4 format and temporarily dequantizes them to bf16 for computation, training only the LoRA part in high precision, so that a single 48 GB GPU can fine-tune a 65B model. Other parameter-efficient fine-tuning (PEFT) methods include adapters, which insert small modules sequentially, and prefix tuning and prompt tuning, which learn virtual tokens; but LoRA became the de facto standard because it adds no inference latency after merging, uses no context and works stably.
I will address two aspects: how QLoRA works, and how the other PEFT methods compare with LoRA.
(1) The idea of QLoRA: since the base is frozen, store it in 4-bit and decompress it only for computation.
LoRA already removes the base's gradients and optimizer states, but the base weights themselves still have to be stored in bf16, and a 65B model needs about 130 GB for weights alone. QLoRA (Dettmers et al. 2023) builds on this with three techniques:
- 4-bit NormalFloat (NF4): Plain INT4 spreads its 16 quantization levels evenly across the value range, but pretrained weights roughly follow a zero-mean normal distribution with most values concentrated near 0, so a uniform grid wastes many levels on rarely used tails. NF4 places the 16 levels at quantiles of the standard normal distribution, so every level is used with equal probability.
- Double quantization: Every 64 weights form a block, and each block stores a scaling constant, which costs 0.5 bits per parameter; QLoRA quantizes these scaling constants themselves to 8 bits, bringing the overhead down to about 0.127 bits per parameter.
- Paged optimizer: With long sequences and similar cases, memory can spike suddenly; QLoRA uses NVIDIA unified memory to automatically page optimizer states out to CPU memory when GPU memory runs short.
During training, the weights are stored in NF4 but computation runs in bf16: at each layer, that layer's 4-bit weights are temporarily dequantized to bf16 before the matrix multiplication; gradients likewise flow through the dequantized weights to the LoRA parameters, but the base weights themselves are never updated. The paper reported that the memory needed to fine-tune a 65B model dropped from over 780 GB to under 48 GB, with quality matching 16-bit full fine-tuning. The costs are that every step has to dequantize, so training is slower than plain LoRA, and the quantization error is baked into the base, so only the LoRA part can compensate for it.
(2) Other PEFT methods follow two main lines, "inserting modules" and "learning virtual tokens", and each has clear weaknesses.
- Adapters: Houlsby et al. (2019) insert a small bottleneck MLP (project down, apply a nonlinearity, project up) after the attention and FFN sublayers of each Transformer block, and train only these small modules. Their problem shows up at inference: adapters are new layers inserted sequentially, they cannot be merged back into the original weights the way LoRA can, and in the decode stage with small batches they add noticeable latency.
- Prefix tuning and prompt tuning: These do not change the weights at all, but learn some "virtual tokens" to steer the model. Prompt tuning (Lester et al. 2021) only prepends a few dozen learnable vectors at the input embedding layer; prefix tuning (Li & Liang 2021) prepends learnable vectors to the keys and values of attention in every layer, which is more expressive. They have extremely few parameters, but they use up context length and are harder to optimize; moreover, prompt tuning matches full fine-tuning only when the model is large enough (around ten billion parameters).
LoRA, by contrast, has no inference latency after merging, uses no context, optimizes as stably as full fine-tuning, works well across scales, and its adapters can be swapped at any time, which is why it became the dominant PEFT method. (Improvements around LoRA include DoRA (Liu et al. 2024), which splits the weight into magnitude and direction and adapts them separately, and LoRA+ (Hayou et al. 2024), which gives \(A\) and \(B\) different learning rates.)
In summary: QLoRA further compresses the base's memory with "4-bit storage, 16-bit compute"; and among PEFT methods, LoRA became the de facto standard thanks to being mergeable, using no context and working stably.
Going deeper: NF4 block-wise quantization, and comparing PEFT methods
(1) The block-wise NF4 quantization formula.
Here \(W_{\text{block}}\) is a block of 64 weights and \(c\) the block's maximum absolute value; dividing by \(c\) normalizes the values into \([-1,1]\), and \(q_{\text{NF4}}\) maps each value to the nearest NF4 level. Double quantization then quantizes the blocks' \(c\) values to 8 bits in groups of 256, saving about 0.37 bits per parameter, or about 3 GB for a 65B model.
(2) A memory estimate for a 65B model.
65B parameters stored in 4 bits take about 32.5 GB, plus about 1 GB for the scaling constants, so the base takes about 34 GB in total; the remaining space goes to the LoRA parameters, their optimizer states and the activations, which is why it fits on a single 48 GB GPU. A bf16 base, by comparison, needs about 130 GB.
(3) Comparing PEFT methods.
| Method | What is trained | Where it acts | Extra inference cost | Notes |
|---|---|---|---|---|
| Adapters (Houlsby et al. 2019) | Small bottleneck MLPs | Inserted after the attention and FFN sublayers | Yes: extra sequential layers | Early PEFT method of the BERT era |
| Prefix tuning (Li & Liang 2021) | Learnable key/value vectors in every layer | Attention in every layer | Small: occupies context positions | More expressive than prompt tuning |
| Prompt tuning (Lester et al. 2021) | A few soft-prompt vectors | Input embedding layer only | Small: occupies context positions | Matches full fine-tuning only on large models |
| LoRA (Hu et al. 2021) | Low-rank update \(BA\) to the weights | Linear layers | Zero after merging | The de facto standard |
| (IA)³ (Liu et al. 2022) / BitFit (Ben Zaken et al. 2021) | Scaling vectors / bias terms only | Activations / biases | None or negligible | Very few parameters, low capacity |
Follow-up questions
Follow-up 1: Why is NF4 better than plain INT4?
Because its quantization levels match the distribution of the weights. Pretrained weights roughly follow a normal distribution with most values near 0; NF4 places the levels at quantiles of the normal distribution so that every level is used with equal probability, making it finer in the dense middle and coarser in the rarely used tails. For normally distributed data this is information-theoretically optimal.
Follow-up 2: What should you watch out for when merging a QLoRA-trained adapter into the base?
The key question is which copy of the base it is merged into. The adapter was trained on the quantized base \(\tilde W_0\) (the result of dequantizing NF4), and it partly compensates for the quantization error. If \(BA\) is added to the original 16-bit weights \(W_0\), the result \(W_0+\frac{\alpha}{r}BA\) differs from the trained \(\tilde W_0+\frac{\alpha}{r}BA\), and quality may shift slightly; if it is added to the dequantized \(\tilde W_0\), the result matches training (up to 16-bit rounding), but the merged matrix no longer lies on the NF4 grid, so quantizing it again for deployment introduces new quantization error. The common practice is therefore to merge into the dequantized base and deploy in 16-bit, or not to merge and run the adapter on top of the quantized base.
Follow-up 3: Why do adapters add inference latency while LoRA does not?
Because LoRA's branch is linear and can be merged into the original weights, whereas an adapter is a sequential nonlinear module. LoRA's update \(\frac{\alpha}{r}BA\) has the same shape as \(W_0\), so after adding the two the number of matrix multiplications is unchanged; an adapter has a nonlinear activation in the middle and cannot be merged, so every layer gains an extra piece of computation that must run in sequence. In the decode stage with small batches, the GPU is already underused, and these extra small operators noticeably increase latency.
Common mistakes
- Do not say QLoRA computes in 4-bit: The weights are stored in 4-bit and dequantized to bf16 for computation.
- Do not say QLoRA updates the 4-bit base weights: The base stays frozen throughout; only the LoRA parameters are updated.
- Do not say prompt tuning matches full fine-tuning at any scale: It does so only when the model is large enough.
5.8 How do you choose between full fine-tuning and LoRA? ★★¶
One-sentence answer
The key is the relationship between the amount of data and LoRA's capacity: in small-to-medium SFT and in RL, a correctly configured LoRA (applied to all layers, with a learning rate about 10 times that of full fine-tuning and a batch that is not too large) can match full fine-tuning while forgetting less and costing less; but when there is a lot of data, a new domain to learn or continued pretraining to do, the update needed is not low-rank, and full fine-tuning should be used.
I will address three aspects: why LoRA "learns less and forgets less", why a correctly configured LoRA can match full fine-tuning, and how to choose.
(1) LoRA "learns less and forgets less", and the two are two sides of the same coin.
Biderman et al. (2024) compared the two systematically in code and math, under both continued pretraining (about 20B tokens) and instruction fine-tuning (about 100K examples). In the usual low-rank settings, LoRA is clearly worse than full fine-tuning on the target domain, with the largest gap in continued pretraining; analyzing the weight updates learned by full fine-tuning, the authors found that their rank is 10 to 100 times higher than typical LoRA configurations, showing that when there is a lot of data and a lot to learn, the update actually needed is not low-rank. On the other hand, LoRA retains more of the original abilities outside the target domain and its generations remain more diverse, and it reduces forgetting more effectively than common regularizers such as dropout and weight decay. The reason is that restricting the update to a low-rank space by itself limits how far the model can drift from the original. "Forgetting less" is therefore not free: the higher the rank, the more it learns and the more it forgets.
(2) With the right setup, LoRA can match full fine-tuning on small-to-medium data.
Research from Thinking Machines (Schulman & Thinking Machines Lab 2025) found that, with the right setup, LoRA fully matches full fine-tuning on small-to-medium instruction-tuning and reasoning datasets, as well as in RL. "The right setup" means three things: apply it to all layers, especially the FFN; use a learning rate about 10 times that of full fine-tuning; and do not use too large a batch, because LoRA tolerates large batches less well than full fine-tuning. A gap appears only when the data exceeds LoRA's capacity. This does not contradict Biderman et al.; the key variable is the relationship between the amount of data and capacity: their largest gap was in continued pretraining on over ten billion tokens, which falls squarely in the "data exceeds capacity" regime, whereas most post-training scenarios, such as tens to hundreds of thousands of SFT examples, or RL in which each episode carries little information, are within LoRA's capacity.
(3) Choose according to data scale, task nature and deployment needs.
- Choose full fine-tuning: When there is a lot of data, a new domain to learn or continued pretraining to do, the best possible quality is the goal, and compute is plentiful.
- Choose LoRA: When the data is small to medium, when doing RL, when many customized tasks must be served at once, when GPUs are limited, or when preserving the original abilities matters most.
In summary: choosing between full fine-tuning and LoRA is essentially a trade-off between "learning capacity" and "preserving existing abilities and cost"; as long as the data does not exceed LoRA's capacity, a correctly configured LoRA is usually the better deal.
Going deeper: a comparison table and key numbers from the relevant studies
(1) Full fine-tuning versus LoRA.
| Full fine-tuning | LoRA | |
|---|---|---|
| Trainable parameters | All | Typically about 0.1% to 1% |
| Training memory | About 16 bytes per parameter | Frozen base (2 bytes per parameter in bf16, about 0.5 with QLoRA) plus small adapter states |
| Compute per token | About \(6N\) | About \(4N\) |
| Capacity to learn new skills and knowledge | Highest | Lower; falls behind with large data and continued pretraining |
| Forgetting | More | Less |
| Learning rate | Standard | About 10 times that of full fine-tuning |
| Storage and serving | A full model copy per task | A few MB to a few hundred MB per task; many adapters share one base |
| Best for | Large data, new domains, continued pretraining, highest quality | Small-to-medium SFT, RL, many tasks, limited GPUs |
(2) Key numbers from the relevant studies.
| Study | Setup | Key findings |
|---|---|---|
| Biderman et al. (2024) | Code and math; continued pretraining on about 20B tokens, instruction fine-tuning on about 100K examples | LoRA learns less and forgets less; full fine-tuning's updates have a rank 10 to 100 times higher than typical LoRA configurations |
| Schulman & Thinking Machines Lab (2025) | Small-to-medium SFT and RL | Fully matches with the right setup; optimal learning rate about 10 times higher; attention-only clearly worse than FFN-only; rank 1 suffices in RL; LoRA tolerates large batches less well, independent of rank |
| Shuttleworth et al. (2024) | Compared the weights learned by the two | LoRA's weights contain new high-ranking singular vectors absent from the original model (intruder dimensions); full fine-tuning's do not |
Follow-up questions
Follow-up 1: Are the weight updates learned by full fine-tuning low-rank, and what does that tell us?
Not in the large-data setting. Biderman et al. (2024) found that the weight updates of full fine-tuning have a rank 10 to 100 times higher than typical LoRA configurations. This shows that "fine-tuning updates are low-rank" holds only approximately when the data is not large; when there is a lot of data and a lot of new content to learn, the capacity of low-rank LoRA falls short.
Follow-up 2: Why is even a very low-rank LoRA enough in RL?
Because each episode in RL carries very little information. In policy gradient, an episode ends up with a single scalar reward, providing only about O(1) bits of information, whereas SFT provides a supervision signal at every token. Thinking Machines estimated that a rank-1 LoRA on Llama-3.1-8B has about 3 million parameters, far more than the information absorbed in one math RL run, so the capacity is more than sufficient.
Follow-up 3: If LoRA and full fine-tuning perform the same on the target task, have they learned the same solution?
No. Shuttleworth et al. (2024) found that weight matrices trained with LoRA contain new high-ranking singular vectors absent from the original model, which they call intruder dimensions, whereas weights trained with full fine-tuning do not. LoRA's forgetting of the pretraining distribution is largely localized in these directions, and they keep accumulating when tasks are learned one after another. This suggests that even with equal scores on the target task, the two can behave differently out of distribution and in continual learning.
Common mistakes
- Do not say LoRA is always worse than full fine-tuning: When the data does not exceed its capacity and it is configured correctly, LoRA can fully match it.
- Do not train LoRA with the full fine-tuning learning rate: LoRA's optimal learning rate is about 10 times higher, and too small a learning rate is a common reason LoRA "performs poorly".
- Do not say LoRA's lower forgetting comes for free: It is the other side of "learning less".
5.9 How do SFT and RL differ? Is "SFT memorizes, RL generalizes" correct? ★¶
One-sentence answer
The claim comes from the findings of Chu et al. (2025) in controlled environments: RL trained with an outcome reward generalizes to rule and visual variants unseen in training, whereas SFT tends to memorize the training rules. It makes sense mechanistically, but it should not be oversimplified: SFT's ability to generalize depends heavily on the data, and SFT is itself a prerequisite for RL to work effectively, so the two are complementary.
I will address three aspects: what the experiments found, the mechanism behind it, and why the conclusion should not be oversimplified.
(1) The experiments: when rules or visual conditions change, RL generalizes while SFT tends to memorize.
Chu et al. (2025) used two controlled environments. One is GeneralPoints, a card game similar to "make 24": given four cards, combine their values to reach a target number; the rules can be changed between training and testing, for example J, Q and K all count as 10 in training but as 11, 12 and 13 at test time. The other is V-IRL, a visual navigation task in real street scenes, where a rule change can swap absolute directions (north, south, east, west) for relative ones (turn left, turn right). The result: RL trained with an outcome reward generalizes to unseen rule variants and visual variants, and even improves the model's visual recognition; SFT tends to memorize the training rules, and its performance drops clearly once the rules change. But the authors also stress that SFT is still necessary: stabilizing the output format with SFT first is what allows RL to work effectively.
(2) The mechanism: the two differ in where their training data comes from and in their supervision signal.
- SFT imitates fixed external text, which makes it easy to memorize surface patterns: It requires the model to reproduce someone else's answer token by token, so it learns task-irrelevant wording and surface regularities along with the task.
- RL rewards only the final outcome and trains on the model's own samples: It does not prescribe how to write the answer, only that the result be correct, so what it learns looks more like a reusable problem-solving procedure; at the same time, on-policy updates stay closer to the original model, so general abilities are better preserved (see 5.5), and generalization is naturally better.
(3) But the conclusion should not be oversimplified.
- The experiments are small and controlled: The conclusion comes from small, controlled tasks and may not carry over directly to large-scale general post-training.
- SFT's generalization depends heavily on the data: If the SFT data is diverse enough, or is generated by the model itself and filtered (rejection sampling fine-tuning), or consists of high-quality reasoning chains distilled from a strong reasoning model, SFT can generalize well too; the small models distilled from DeepSeek-R1 are an example.
- Whether RL teaches new abilities is itself still debated: Whether it actually teaches new abilities or merely draws out abilities the base model already has more reliably has not been settled (see Chapter 8).
In summary: the safer reading is that SFT and RL are complementary: SFT handles format and the cold start, and RL makes abilities more robust and more transferable.
Going deeper: a systematic comparison of SFT and RL
(1) How the two differ along several dimensions.
| Dimension | SFT | RL |
|---|---|---|
| Data source | Fixed demonstrations (off-policy) | The model's own samples (on-policy) |
| Supervision signal | A target at every token; dense | One reward per response; sparse |
| Negative signal | None; only sees good behavior | Yes; low-reward samples are pushed down |
| Exposure bias | Present: the preceding text in training is always the reference answer | Absent: the preceding text in training is the model's own output |
| Forgetting | More | Less |
| Cost and stability | Cheap, stable | Needs sampling and scoring; harder to tune |
| Role in the pipeline | Format, cold start | Reasoning, robustness and transfer |
(2) What matters is the data distribution, not just the algorithm.
One control experiment in RL's Razor (Shenfeld et al. 2025) is telling: generating data with the RL-trained model and then running SFT on that data yields the same accuracy–forgetting trade-off as RL itself (see 5.5). This shows that many of the differences between SFT and RL come from whether the training data is close to the model's own distribution, not from the form of the loss function.
Follow-up questions
Follow-up 1: If RL generalizes better, why do SFT first?
Because RL needs a starting point that can earn rewards. RL learns from the model's own samples; if the starting model cannot even produce a stable output format, nearly every sample gets zero reward and there is no signal to learn from. The experiments of Chu et al. (2025) also show that SFT stabilizes the output format, which is what lets RL make gains; DeepSeek-R1-Zero skipped SFT, but its outputs were hard to read and mixed Chinese and English, which is why DeepSeek-R1 added a cold-start SFT.
Follow-up 2: How can SFT gain these advantages of RL as well?
The core is to keep the training data close to the model's own distribution. For example, do SFT only on responses that the model generated itself and that passed verification (rejection sampling fine-tuning); regenerate the data with the current model at the start of each epoch, so that it stays approximately on-policy; or use on-policy distillation, in which a teacher gives token-by-token guidance on responses the student generated itself (see Chapter 9).
Common mistakes
- Do not treat "SFT memorizes, RL generalizes" as a general law: It comes from small, controlled experiments, and SFT's ability to generalize depends heavily on the data.
- Do not say RL can fully replace SFT: Without an SFT cold start, RL often struggles to get going, and output quality is hard to guarantee.