Fine-Tuning & Aligning Large Models
Instruction tuning, policy gradients from REINFORCE to PPO, and learning from preferences.
Labelers preferred the answers of a 1.3-billion-parameter InstructGPT model to those of the 175-billion-parameter GPT-3, a model with the same architecture and over 100 times as many parameters. The difference was post-training: about 13,000 written demonstrations, a reward model learned from human rankings, and a reinforcement learning stage. For the 175-billion-parameter version, the SFT and RL stages together took under 2% of the compute used to pretrain GPT-3 (Ouyang et al., 2022). This lesson derives the machinery: supervised fine-tuning, policy gradients from REINFORCE to PPO, and rewards learned from preferences.
What you’ll learn
- Write the supervised fine-tuning loss for chat data, with a chat template and a loss mask on the prompt, and explain what it changes in a base model.
- Derive the policy gradient (REINFORCE), and prove that subtracting a baseline keeps it unbiased.
- Explain PPO's clipped surrogate objective and the KL penalty to a reference model, and how each limits how far the policy moves.
- Describe the RLHF pipeline (demonstrations, a Bradley–Terry reward model, KL-regularized RL), direct preference optimization as an RL-free alternative, and reinforcement learning with verifiable rewards.
From base model to assistant
Pretraining by next-token prediction produces a base model: a distribution over continuations of web-like documents. Give it "Write a haiku about rain." and it may write a haiku, or it may add three more writing prompts, as if the request were one line of a worksheet. Both are plausible continuations of a document. An assistant should treat the text as a request from a user and answer it.
Post-training reshapes the base model's distribution toward helpful, honest and harmless responses, using orders of magnitude less data and compute than pretraining. The recipe that made this standard, InstructGPT, had three stages:
| Stage | Data | Objective | In InstructGPT |
|---|---|---|---|
| prompts with responses written by labelers | maximize the likelihood of the response | about 13,000 prompts, 16 epochs |
| labelers' rankings of 4 to 9 sampled responses per prompt | a Bradley–Terry loss on every pair from each ranking | 33,000 prompts; one 6-billion-parameter reward model for all policy sizes |
| prompts only; the reward model scores each sampled response | PPO on the reward minus a KL penalty toward the SFT model | 31,000 prompts, 256,000 episodes, |
Think first A base model has read millions of haiku. If it can already write one, what does supervised fine-tuning on demonstrations teach it?
Mostly which of its behaviors to produce when a prompt arrives: the format, persona and conventions of an assistant, and when to stop. Demonstrations select from the base model's repertoire far more than they add to it. How far this "superficial" view holds, and where it breaks, is the subject of Instruction Tuning & Its Data.
Supervised fine-tuning on demonstrations
A conversation is a list of messages with roles. Before training, a chat template renders it into one token sequence, with special tokens that mark where each role's turn begins and ends:
<|system|>You are a helpful assistant.<|end|>
<|user|>Write a haiku about rain.<|end|>
<|assistant|>Soft drops on the roof,
the gutter hums its one note,
the street smells of stone.<|end|>A schematic template. The role markers and the end-of-turn token are extra tokens added to the vocabulary, and every model family defines its own. A model served with a template other than the one it was tuned on often responds worse.
Let be everything before the assistant's turn (system prompt, earlier turns, markers) and the assistant's tokens, ending with the end-of-turn token. SFT is maximum likelihood on the responses alone:
def sft_loss(model, ids, is_response):
"""ids: (B, T) chat-formatted token ids; is_response: (B, T) True on assistant tokens."""
labels = ids.masked_fill(~is_response, -100) # -100 = "ignore" for cross_entropy
logits = model(ids)[:, :-1] # position t predicts token t + 1
return F.cross_entropy(logits.reshape(-1, logits.size(-1)),
labels[:, 1:].reshape(-1), ignore_index=-100)Loss masking in PyTorch, for a model that returns logits of shape (B, T, |V|). The loss is averaged over the response tokens of the whole batch, so long responses weigh more than short ones; Instruction Tuning & Its Data discusses that choice, packing several examples into one sequence, and when keeping some loss on the prompt helps.
InstructGPT's SFT models overfit on validation loss after one epoch, yet the authors trained for 16 epochs. Why can that be the right call?
- Validation loss is meaningless for language models
- More epochs always reduce validation loss eventually
- The goal is responses people prefer, and the reward-model score and human ratings kept improving with more epochs
- The extra epochs were needed to learn the chat template
Show the answer
C. The goal is responses people prefer, and the reward-model score and human ratings kept improving with more epochs
Ouyang et al. selected the SFT model by reward-model score, which, like human preference ratings, kept improving despite the rising validation loss. Likelihood of held-out demonstrations measures how well the model imitates one labeler's exact wording; post-training is judged by the quality of what the model itself generates.
By default SFT updates every weight. Parameter-efficient methods train a small fraction instead, such as low-rank adapters (Fine-Tuning & Transfer, Low-Rank Adaptation in Depth), and any fine-tuning can erode skills learned earlier (Catastrophic Forgetting & Continual Learning). SFT has a deeper limit: it can only imitate. To make responses better than the demonstrations, the model must be scored on its own samples.
A language model is a policy
In reinforcement-learning terms, a prompt is a state, a whole response is an action, and the model is a policy . A reward scores complete responses: a reward model's estimate of human preference, or a program that checks the answer. Post-training by reinforcement learning maximizes the expected reward
Two things block ordinary backpropagation: is sampled, a discrete choice, and need not be differentiable at all; a unit test passes or fails.
For one prompt, write the expected reward as a sum over responses. Only the probabilities depend on :
Use to turn the sum back into an expectation under the policy, which samples can estimate:
The log-probability of a response is a sum over its tokens, so its gradient is exactly what backpropagation computes for the SFT loss of that sampled response:
REINFORCE (Williams, 1992) averages over sampled responses. The estimate is unbiased but noisy: when all rewards are positive, every sample is pushed up, the good ones only slightly more.
A baseline that does not depend on the sampled response can be subtracted for free, because the score function has mean zero:
So weighting each sample by the advantage leaves the expected gradient unchanged. With , above-average responses are reinforced and below-average ones suppressed, and the variance falls.
A toy policy picks one of three responses A, B, C with softmax probabilities , , . It samples B, which earns reward ; the baseline is . With learning rate , by how much does one REINFORCE step raise B's logit? (For a softmax, .)
Show the answer
0.28
The step is , which moves the probabilities to about . Without the baseline the step would be . Had B earned reward , the baseline would make its logit fall by , whereas without a baseline nothing would happen: the baseline is what lets bad samples push probability away.
PPO: small steps and a KL leash
REINFORCE uses each sample for one gradient step and discards it, which is wasteful when generating a response costs far more than a gradient step on it. To take several steps on one batch, each token's term is reweighted by the ratio between the current policy and the one that sampled it, with . Maximized without limit, drives the policy far from , where the samples no longer represent it and the advantage estimates are stale, and training can collapse. PPO (Schulman et al., 2017) clips the ratio:
| Advantage | Ratio | Term kept by the min | Gradient on |
|---|---|---|---|
| raises the token's probability | |||
| , a constant | none: no reward for going further | ||
| lowers the token's probability | |||
| , a constant | none: no reward for going further |
With , a token has advantage and ratio . What does this token contribute to the gradient of ?
- A push to raise further, with weight 2
- A push back toward
- Nothing: the clipped term is the smaller one and does not depend on
- It is removed from the batch and resampled
Show the answer
C. Nothing: the clipped term is the smaller one and does not depend on
, the clipped term, which is constant in . PPO does not actively pull the ratio back; it simply stops rewarding further movement until the next batch is sampled from the updated policy.
For a language model each token is an action, and PPO estimates per-token advantages with a learned value network, a critic that predicts the reward still to come from each prefix, combined by generalized advantage estimation (Schulman et al., 2016). InstructGPT initialized its value network from the reward model. With the frozen reference model, that puts four large networks in play: policy, reference, reward and value. The Reinforcement Learning course derives PPO from trust-region methods and analyzes advantage estimation. Clipping limits each round of updates; a second constraint limits the whole run:
Why a leash? The reward model learned from responses near the SFT model's and is accurate only there. Optimized without limit, the policy drifts toward responses that the reward model overrates, reward hacking. In a synthetic setup where a fixed "gold" reward model stands in for people, the gold score first rises, then falls as the KL grows (Gao, Schulman & Hilton, 2023). The coefficient sets the exchange rate between reward and drift; InstructGPT used .
Learning from preferences
People compare two responses more reliably than they score one, and more cheaply than they write one. The Bradley–Terry model turns comparisons into a reward: response is preferred to with probability of the reward difference, and the reward model is fitted by maximum likelihood.
Think first Only differences of rewards for the same prompt enter this loss. What does that say about a reward model's raw scores?
They are defined only up to a constant per prompt. A score of 3.2 means nothing alone, and scores for different prompts are not on a common scale, which is one more reason RL subtracts a baseline per prompt. InstructGPT shifted its reward model so that labelers' demonstrations scored 0 on average. The targets are noisy, too: training labelers agreed with each other on of comparisons.
InstructGPT's final objective (they called it PPO-ptx) adds a third term, the log-likelihood of pretraining text, to limit regressions on tasks the preference data never covered:
The results set the pattern for later assistants. The 1.3-billion-parameter InstructGPT was preferred to the 175-billion-parameter GPT-3; the 175-billion-parameter InstructGPT was preferred to GPT-3 of the time, and of the time when GPT-3 was given a few-shot prompt; and on closed-domain tasks such as summarization it made up information about half as often (21% against 41%). Held-out labelers who wrote none of the training data preferred it at about the same rate.
Direct preference optimization. The maximizer can be inverted: . Substituted into the Bradley–Terry likelihood, the normalizer cancels and a loss on the policy alone remains (Rafailov et al., 2023):
No reward model is trained and nothing is sampled during training: DPO is a classification loss on fixed preference pairs. The Artificial Intelligence course derives it and its failure modes. Open recipes often combine the families: Tülu 3 applies SFT, then DPO, then reinforcement learning with verifiable rewards (Lambert et al., 2024).
Verifiable rewards, and knowing whether it worked
For some tasks the reward needs no model. A math problem has a reference answer; a program has unit tests. Reinforcement learning with verifiable rewards (RLVR, a name from Lambert et al., 2024) gives reward 1 when the extracted answer matches or the tests pass, and 0 otherwise. There is no learned reward model to exploit, though a weak checker can still be gamed: code that special-cases the visible tests passes them without solving the task.
Trained this way at scale, models learn to write long chains of thought before answering: reasoning models. DeepSeek-AI (2025) applied large-scale RL with rule-based rewards for correctness and format directly to a base model, deliberately avoiding neural reward models because they were susceptible to reward hacking. Pass@1 accuracy on the AIME 2024 competition problems rose from 15.6% to over 70% during training, and the average response length grew steadily, with more passages that re-check or revise earlier steps.
| How post-training is evaluated | What it measures | Main pitfall |
|---|---|---|
| Benchmarks with reference answers | knowledge, math, code, instruction-following constraints | test items leaking into training data (contamination); saturation |
| Human pairwise comparisons on held-out prompts | which of two models' responses people prefer (win rate); InstructGPT's main metric | slow and costly; raters reward style, length and confidence |
| An LLM as the judge | the same comparisons, cheaply and at scale | position, length and self-preference biases (Learning from AI Feedback) |
| Regression and safety suites | what got worse: the "alignment tax", harmful or evasive answers | only the failures someone thought to test |
Key takeaways
- Post-training turns a base model, which continues documents, into an assistant with little data and compute: InstructGPT used about 13,000 demonstrations, 33,000 ranked prompts and 31,000 RL prompts, and the SFT and RL stages of its 175-billion-parameter model took under 2% of GPT-3's pretraining compute.
- SFT is maximum likelihood on the responses alone: a chat template marks the roles, and the loss masks the prompt but keeps the end-of-turn token.
- The policy gradient is (REINFORCE). A baseline that does not depend on the sample leaves it unbiased and cuts its variance, weighting each sample by its advantage .
- PPO's clipped ratio keeps each round of updates near the sampling policy; a KL penalty toward the reference model keeps the whole run where the reward model can be trusted.
- Reward models fit Bradley–Terry to comparisons; DPO optimizes the same KL-regularized objective directly from preference pairs; verifiable rewards replace the reward model wherever a program can check the answer.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A training conversation has a system prompt, a user turn and one assistant turn. Under standard SFT, which tokens carry the loss?
- Every token, so the model learns the whole conversation
- The assistant's tokens, including its end-of-turn token
- The user's tokens, since they say what is wanted
- Only the last token of the assistant's turn
Show the answer
B. The assistant's tokens, including its end-of-turn token
The model reads the whole sequence as context but is trained only to produce the assistant's response, and the end-of-turn token in that response is how it learns to stop. Masking the rest keeps the model from spending capacity on predicting users' and system prompts.
In REINFORCE you subtract from each sampled response's reward a baseline : the average reward of responses to that prompt, estimated independently of the sample. What happens to the gradient estimate?
- Its expectation is unchanged and its variance usually falls
- It becomes biased toward average responses
- It no longer needs sampled responses
- Its expectation is scaled by
Show the answer
A. Its expectation is unchanged and its variance usually falls
, so the mean is untouched. Centering the rewards stops the estimator from pushing up every sample when all rewards are positive, which reduces its variance.
Why does PPO clip the probability ratio in its objective?
- To keep the probabilities between 0 and 1
- To bound the size of the reward
- To remove the incentive to move the policy far from the one that generated the samples while a batch is reused for several updates
- To make a KL penalty to the reference model unnecessary
Show the answer
C. To remove the incentive to move the policy far from the one that generated the samples while a batch is reused for several updates
Reusing samples requires importance ratios, which are trustworthy only near . Beyond in the direction the advantage favors, the clipped objective is flat, so there is no gradient pushing further; harmful moves are still counted, because the minimum keeps the worse of the two terms.
Why does RLHF subtract from the reward it maximizes?
- To make training faster
- Because PPO cannot work without it
- To make the policy deterministic
- Because the reward model is reliable only near the responses it was trained on, and without a leash the policy drifts to outputs it overrates
Show the answer
D. Because the reward model is reliable only near the responses it was trained on, and without a leash the policy drifts to outputs it overrates
A learned reward is a proxy. Optimized hard, a policy finds responses the reward model scores highly but people do not: reward hacking. Staying close to the SFT model keeps the policy where the reward model was trained, and preserves fluency and diversity.
A reward model trained with the Bradley–Terry loss scores several responses to one prompt. You add the same constant to all of their scores. How does the loss change?
- It grows in proportion to
- It does not change: the loss depends only on differences of rewards for the same prompt
- It changes sign
- It is minimized at
Show the answer
B. It does not change: the loss depends only on differences of rewards for the same prompt
. Comparisons identify a reward only up to a constant per prompt, which is why InstructGPT shifted its reward model so that the labelers' demonstrations averaged 0 before RL.
Go deeper
- Instruction Tuning & Its Data · How a few thousand demonstrations change a base model, and which data matters.
- Learning from AI Feedback · Constitutional methods, AI judges and models that help supervise models.
- Reinforcement Learning for Reasoning · Verifiable rewards, GRPO and spending more compute at test time.
Further reading
- L. Ouyang et al., "Training language models to follow instructions with human feedback," NeurIPS (2022).
- R. J. Williams, "Simple statistical gradient-following algorithms for connectionist reinforcement learning," Machine Learning 8, 229–256 (1992).
- J. Schulman, F. Wolski, P. Dhariwal, A. Radford & O. Klimov, "Proximal policy optimization algorithms," arXiv:1707.06347 (2017).
- P. F. Christiano, J. Leike, T. B. Brown, M. Martic, S. Legg & D. Amodei, "Deep reinforcement learning from human preferences," NeurIPS (2017).
- R. Rafailov, A. Sharma, E. Mitchell, S. Ermon, C. D. Manning & C. Finn, "Direct preference optimization: Your language model is secretly a reward model," NeurIPS (2023).