RL from Human Feedback
Reward models from preferences, KL-regularized fine-tuning and direct preference optimization.
Nobody can write down a reward function for "be helpful and harmless", but people can say which of two answers is better. RLHF turns those comparisons into a reward model and then runs policy-gradient RL against it, with a KL penalty that keeps the policy near its starting point. This lesson derives each stage: the Bradley–Terry loss, the closed-form optimum of the KL-regularized objective, the token-level setup used with PPO, and DPO, which reads that closed form backwards to skip the reward model entirely.
What you’ll learn
- Describe the three-stage pipeline (supervised fine-tuning, a reward model, RL with a KL penalty) and the experiments that established it.
- Derive the Bradley–Terry loss as logistic regression on reward differences, with its gradient and its invariance to per-prompt shifts.
- Derive the optimum of the KL-regularized objective with a Lagrange multiplier, and explain what controls.
- Write generation as a token-level MDP with a per-token KL penalty, and explain how PPO is applied to it.
- Derive the DPO loss from the closed-form optimum, and name the main practical failure modes: rater disagreement, length bias, sycophancy and overoptimization.
Three stages, from backflips to InstructGPT
RLHF grew out of a short line of experiments. Christiano et al. (2017) trained Atari and MuJoCo agents from human preferences between pairs of short trajectory segments, fitting a reward model and running deep RL against it at the same time. Ziegler et al. (2019) applied the idea to a pretrained language model; Stiennon et al. (2020) to summarization, where optimizing a learned reward gave summaries that people preferred to those from optimizing the standard ROUGE score; and Ouyang et al. (2022) to general instruction following, producing the InstructGPT models.
The recipe that emerged has three stages. Throughout, is a prompt, a response made of tokens, and a policy is an autoregressive language model, .
| Stage | Data | Objective | Produces |
|---|---|---|---|
| demonstrations written by people | maximum likelihood, | the reference policy , also RL's starting point |
| comparisons with preferred to | Bradley–Terry maximum likelihood | a reward model |
| prompts only; responses are sampled from the current policy | , classically with PPO | the final policy |
The reward model is logistic regression
The Bradley–Terry model (Bradley & Terry, 1952) says that a rater prefers to with probability , where . Fitting it by maximum likelihood gives the reward model's loss.
For one comparison write the margin . The negative log-likelihood of the dataset is
Since , one term's gradient is
A descent step pushes the chosen response's score up and the rejected one's down, in proportion to : the model's current probability of ordering this pair wrongly. Pairs it already orders confidently contribute almost nothing.
With a linear reward this is exactly logistic regression on the feature differences , every label equal to 1, so the loss is convex in . In practice the reward model is a language model whose output layer is replaced by a scalar head that scores each complete response.
Two facts about this loss shape everything downstream. First, it uses only differences of rewards for the same prompt, so fits the data exactly as well as , for any function . Rewards are identified only up to a per-prompt shift, and comparing reward values across prompts means nothing. (InstructGPT fixed the shift by adding a bias so that the labelers' demonstrations scored 0 on average.)
Second, a ranking of responses yields comparisons that share responses and are strongly correlated. Shuffled into the data as independent examples, they made InstructGPT's reward model overfit within a single epoch; putting all comparisons from one prompt into one batch element fixed this, and needs only one forward pass per response.
import torch.nn.functional as F
def reward_model_loss(rm, prompts, chosen, rejected):
"""rm(prompts, responses) returns one scalar score per example, shape (B,)."""
margin = rm(prompts, chosen) - rm(prompts, rejected)
loss = -F.logsigmoid(margin).mean() # Bradley-Terry negative log-likelihood
accuracy = (margin > 0).float().mean() # how often the RM orders a pair as the rater did
return loss, accuracyF.logsigmoid computes stably. The ordering accuracy reported in training logs cannot approach 100%: when two raters disagree on about a quarter of comparisons, no model can predict every label.
Every response to one prompt gets its reward-model score increased by 5; scores for other prompts are unchanged. What happens to the Bradley–Terry loss and to the KL-regularized optimal policy?
- The loss gets worse, because the rewards are no longer calibrated
- Neither changes: the loss sees only differences within a prompt, and a constant does not change the optimal policy for that prompt
- The loss is unchanged, but the policy will now favor prompt
- Both change, because larger rewards produce larger policy-gradient steps
Show the answer
B. Neither changes: the loss sees only differences within a prompt, and a constant does not change the optimal policy for that prompt
Every comparison is within one prompt, so the +5 cancels in every margin. In the optimum derived next, a constant multiplies the tilted distribution by , which normalization removes. A constant can still add noise to sampled gradients, which is one reason implementations normalize rewards or subtract a baseline.
RL on a leash: the KL-regularized optimum
Stage 3 maximizes, for each prompt, the expected reward minus a penalty for moving away from :
Fix and drop it from the notation. Treat for each response as a variable, constrained by with a Lagrange multiplier . (A response with must get , or the KL is infinite.)
Set the derivative with respect to each to zero and solve:
The last factor does not depend on , so normalization fixes it, through the partition function :
This stationary point is the maximum. The expected reward is linear in and is strictly convex, so the objective is strictly concave on the probability simplex and has exactly one maximizer; the KL term's derivative diverges at the boundary, so that maximizer is interior. Every response with keeps positive probability: the penalty forbids collapse onto a single answer.
acts as a temperature. As , ; as , concentrates on the highest-reward responses that can produce. The same form appears in maximum-entropy RL, where a policy proportional to is optimal (Maximum-Entropy RL & Soft Actor–Critic), and in Control as Inference, which reads as a posterior with prior and likelihood .
Three responses have and rewards . With , . What probability does give the best response when , in percent?
Show the answer
80 %
The weights are , and ; normalizing gives . Halving raises the expected reward from 1.35 to 1.76 and the KL divergence from the reference from 0.32 to 0.92 nats.
Token by token: RLHF with PPO
The closed form cannot be used directly, because sums over every possible response. Instead the policy is trained by RL on an MDP. The state is the prompt plus the tokens written so far, ; the action is the next token , which is appended deterministically; and an end-of-sequence token closes the episode. The reward model scores only complete responses, while the KL penalty is spread over the tokens (Ziegler et al., 2019; Stiennon et al., 2020).
def per_token_rewards(logp, logp_ref, rm_score, beta):
"""logp, logp_ref: (T,) log-probs of the sampled tokens under the policy and pi_ref;
rm_score: the reward model's score of the whole response (a scalar tensor)."""
rewards = -beta * (logp - logp_ref).detach() # KL penalty, one term per token
rewards[-1] = rewards[-1] + rm_score # the reward model speaks only at the end
return rewards # then GAE and PPO, as for any episodic taskSummed over an episode the penalty terms give , whose expectation under is . The undiscounted return therefore has exactly the expected value of the KL-regularized objective. A single response's log-ratio can be negative; only its average is a divergence.
From here PPO runs as on any episodic task: a value head estimates , generalized advantage estimation turns the per-token rewards into advantages, and the clipped surrogate limits each update (Trust Regions: TRPO & PPO). The price is memory and tuning. Four large networks are held at once: the policy, the frozen reference, the reward model and the value network. InstructGPT also mixed a pretraining log-likelihood term into the objective ("PPO-ptx") to limit regressions on standard benchmarks.
RLHF with PPO has two mechanisms that limit how far the policy moves: PPO's clipping of the ratio , and the penalty . Which one changes where training ends up?
- The clipping: it bounds the final policy's distance from
- Both, equally
- Neither: only the reward model decides the end point
- The penalty to : it is part of the objective, whose optimum is , while clipping only limits the size of each update
Show the answer
D. The penalty to : it is part of the objective, whose optimum is , while clipping only limits the size of each update
is refreshed at every iteration, so clipping restrains the step, not the destination: run long enough, a clipped optimizer can travel arbitrarily far from where it began. The penalty against the fixed changes the objective itself, and with it the optimum.
DPO: the reward model you already have
The closed form can be read backwards. Taking logarithms of expresses the reward through the policy it induces:
Substitute this into the Bradley–Terry model. The intractable term is the same for both responses to a prompt, so it cancels from their difference, which is all that Bradley–Terry uses. Fitting the policy itself to the comparisons by maximum likelihood gives direct preference optimization (Rafailov et al., 2023):
import torch.nn.functional as F
def dpo_loss(logp_w, logp_l, ref_logp_w, ref_logp_l, beta=0.1):
"""Summed log-probs of whole responses, shape (B,), under the policy and the frozen reference."""
margin = beta * ((logp_w - ref_logp_w) - (logp_l - ref_logp_l))
return -F.logsigmoid(margin).mean()Each log-probability is the sum of a response's token log-probabilities. The reference terms do not change during training, so they can be computed once in advance.
| Aspect | RLHF with PPO | DPO |
|---|---|---|
| Data | prompts, with responses sampled during training | a fixed set of comparisons |
| Networks in memory | policy, reference, reward model, value network | policy, plus reference log-probabilities |
| What it optimizes | the KL-regularized objective, by on-policy RL | the Bradley–Terry likelihood of the implicit reward |
| Sees its own outputs? | yes: it samples and scores its own responses | only if new comparisons of its outputs are collected |
What goes wrong in practice
Each stage of the pipeline adds its own distortions, and RL amplifies them:
- Disagreement. Raters disagree on roughly a quarter of comparisons, and the reward model learns a single aggregate of their choices. When raters differ systematically, that aggregate behaves like a vote, not like an average of their preferences (Reward Models from Preferences).
- Length. Preferred answers tend to be longer, and reward models learn the correlation. Singhal et al. (2024) found that optimizing a reward for length alone reproduced most of the gains of RLHF over supervised fine-tuning in their settings.
- Sycophancy. Human raters, and preference models trained on their choices, sometimes prefer convincingly written answers that agree with the user over correct ones, and optimizing against such models can trade truthfulness for agreement (Sharma et al., 2024).
- Overoptimization. As the policy moves away from , the proxy reward keeps rising while true quality peaks and falls (reward overoptimization; Gao, Schulman & Hilton, 2023), as in the widget above.
Comparisons need not come from people. Constitutional AI (Bai et al., 2022) had a model judge responses by a brief written set of principles, its "constitution", and trained on those AI-generated preferences (RLAIF); the Deep Learning course covers learning from AI feedback. The RL machinery is unchanged. Only the source of the comparisons differs, and with it the biases the reward model inherits.
Key takeaways
- RLHF in three stages: supervised fine-tuning gives ; a reward model is fitted to comparisons by Bradley–Terry maximum likelihood; RL maximizes , classically with PPO on a token-level MDP.
- The Bradley–Terry loss is logistic regression on within-prompt reward differences. Its gradient weights each pair by the probability of misordering it, and rewards are identified only up to a per-prompt shift.
- The KL-regularized objective has the unique optimum ; interpolates between the reference () and the reward's maximizers ().
- Inverting the optimum writes the reward as ; substituting into Bradley–Terry cancels and gives DPO, a supervised loss on fixed comparisons.
- Rater disagreement, length and sycophancy biases, and overoptimization are built into the pipeline, because the reward model is a proxy fitted where puts its mass.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
During reward-model training, which comparison produces the largest gradient step?
- One the model already orders correctly, by a large margin
- One the model currently orders wrongly, by a large margin
- Every comparison produces a step of the same size
- One between two identical responses
Show the answer
B. One the model currently orders wrongly, by a large margin
The gradient of is weighted by , the model's probability of misordering the pair. With large and negative this weight is close to 1; with large and positive it is close to 0.
In the KL-regularized optimum , what happens as ?
- approaches
- becomes uniform over all responses
- concentrates on the highest-reward responses among those can produce
- concentrates on the response considers most likely
Show the answer
C. concentrates on the highest-reward responses among those can produce
Dividing by a small makes dominated by the largest rewards, so all mass moves to the reward's maximizers within the support of . This is the regime where the reward model's errors are exploited most.
Why did InstructGPT put all comparisons from one ranking into a single batch element instead of shuffling them as separate examples?
- Comparisons from one ranking share responses and are highly correlated; treated as independent they made the reward model overfit within one epoch, and batching them needs only one forward pass per response
- The Bradley–Terry model cannot be applied to rankings
- To give every prompt the same weight in the KL penalty
- Because labelers' rankings are always transitive
Show the answer
A. Comparisons from one ranking share responses and are highly correlated; treated as independent they made the reward model overfit within one epoch, and batching them needs only one forward pass per response
Each response appears in comparisons, so shuffled pairs repeat the same responses many times per epoch. Grouping them removes the overfitting and is cheaper: one forward pass per response rather than two per comparison.
Why does the partition function disappear from the DPO loss?
- Because for every prompt
- Because DPO assumes that is very small
- Because the reference policy is uniform
- Because the Bradley–Terry model uses only the difference of two rewards for the same prompt, and is common to both
Show the answer
D. Because the Bradley–Terry model uses only the difference of two rewards for the same prompt, and is common to both
Writing and taking cancels the prompt-dependent term. That is what makes the loss computable from log-probabilities alone.
Go deeper
- Reward Models from Preferences · Bradley–Terry models, their assumptions, and how they fail.
- Direct Preference Optimization & Its Relatives · The closed-form optimum of KL-regularized RL, and DPO, IPO and KTO.
- Reward Overoptimization & Goodhart’s Law · Scaling laws for reward hacking, and how to resist it.
Further reading
- P. F. Christiano, J. Leike, T. B. Brown, M. Martic, S. Legg & D. Amodei, "Deep reinforcement learning from human preferences," NeurIPS (2017).
- N. Stiennon, L. Ouyang, J. Wu, D. M. Ziegler, R. Lowe, C. Voss, A. Radford, D. Amodei & P. Christiano, "Learning to summarize from human feedback," NeurIPS (2020).
- L. Ouyang et al., "Training language models to follow instructions with human feedback," NeurIPS (2022).
- 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).