Instruction tuning teaches a language model to imitate good responses written by people. But writing perfect responses is expensive, many prompts have no single right answer, and the token-level loss treats all mistakes alike. What people can do easily and cheaply is judge: read two responses and say which one is better.
Reinforcement learning from human feedback (RLHF) turns such judgments into a training signal. It was the key ingredient that turned GPT-3 into InstructGPT and ChatGPT. This reading builds RLHF step by step: the reinforcement learning view of text generation, the policy gradient method, the reward model trained from human comparisons, and the KL penalty that keeps optimization in check.
1Where RLHF fits
Modern language models are trained in stages:
- Pretraining on large amounts of text with language modeling.
- Supervised fine-tuning (SFT, i.e., instruction tuning) on instruction data: prompts paired with good responses.
- Preference optimization on preference data: human judgments of which responses are better. RLHF is the classic method for this stage.
Throughout this reading, $x$ is a prompt and $y$ is a response generated by the model $p_\theta(y\mid x)$. Suppose for now that we have a reward $R(x,y)$: a number saying how good response $y$ is (for example, a human rating). Our goal is to change the model's parameters $\theta$ so that its responses get high reward on average:
$$\max_\theta\ \ \mathbb{E}_{y\sim p_\theta(\cdot\mid x)}\big[R(x,y)\big].$$Unlike the language modeling loss, this objective does not need a reference answer. It only needs a way to score whatever the model produces. But it has a difficulty: $y$ is sampled from the model, and we cannot backpropagate through the sampling of discrete tokens. Reinforcement learning provides the tools to optimize objectives like this.
2Text generation as reinforcement learning
In reinforcement learning, an agent (actor) interacts with an environment. At each step it observes a state $s_t$, takes an action $a_t$ according to its policy, and the environment moves to a new state and may give a reward $r_t$. A sequence $\tau=(s_1,a_1,s_2,a_2,\dots)$ is a trajectory, and the agent tries to maximize the expected total reward $\mathbb{E}_{\tau\sim p_\theta(\tau)}[R(\tau)]$, where $R(\tau)=\sum_t r_t$.
Text generation fits this picture directly:
3Policy gradient: REINFORCE
We want to do gradient ascent on the expected reward:
$$\theta_{t+1} = \theta_t + \alpha\,\nabla_\theta\,\mathbb{E}_{y\sim p_\theta}[R(x,y)].$$Write the expectation as a sum over all possible responses and move the gradient inside:
$$\nabla_\theta\,\mathbb{E}_{y\sim p_\theta}[R(x,y)] = \nabla_\theta\sum_y R(x,y)\,p_\theta(y\mid x) = \sum_y R(x,y)\,\nabla_\theta p_\theta(y\mid x).$$The log-derivative trick, $\nabla_\theta p_\theta = p_\theta\,\nabla_\theta\log p_\theta$ (since $\nabla\log p=\nabla p/p$), turns this back into an expectation:
$$\nabla_\theta\,\mathbb{E}_{y\sim p_\theta}[R(x,y)] = \sum_y p_\theta(y\mid x)\,R(x,y)\,\nabla_\theta\log p_\theta(y\mid x) = \mathbb{E}_{y\sim p_\theta}\big[R(x,y)\,\nabla_\theta\log p_\theta(y\mid x)\big].$$An expectation can be approximated by sampling. Draw $m$ responses $y_1,\dots,y_m$ from the model and average:
$$\theta_{t+1} = \theta_t + \alpha\,\frac{1}{m}\sum_{i=1}^{m} R(x,y_i)\,\nabla_\theta\log p_\theta(y_i\mid x).$$This is the REINFORCE algorithm (Williams, 1992), the simplest policy gradient method. Read the update as: take a gradient step to increase $\log p_\theta(y_i\mid x)$, scaled by the reward. Responses with large positive reward become more likely; responses with negative reward become less likely. We reinforce good actions.
Baselines
If all rewards are positive (say 8.0, 5.0, and 1.2), every sampled response gets pushed up, just by different amounts. Learning still works on average but is slow and noisy. The standard fix is to subtract a baseline $b$, such as the average reward of the batch:
$$\theta_{t+1} = \theta_t + \alpha\,\frac{1}{m}\sum_{i=1}^{m} \big(R(x,y_i)-b\big)\,\nabla_\theta\log p_\theta(y_i\mid x).$$Now better-than-average responses are pushed up and worse-than-average ones are pushed down. Subtracting a constant baseline does not change the expected gradient, but it greatly reduces its variance.
Proximal Policy Optimization (PPO)
Plain policy gradient can take steps that are too large: one bad update can wreck the model, and then all future samples come from a broken policy. PPO, the algorithm used in InstructGPT, keeps each update small: the new parameters $\theta$ should not produce a distribution very different from the parameters $\theta'$ that generated the current samples. One version adds a penalty $\beta\,\mathrm{KL}(p_{\theta}\,\|\,p_{\theta'})$ to the objective; the more common version clips the update instead. The details are beyond this reading; the key idea is stable, small policy updates.
4Modeling human preferences with a reward model
We now have a way to maximize any reward $R$. Where does the reward come from? Asking a human to score every sample during training has two problems:
- Problem 1: humans in the loop are expensive and slow. RL needs many thousands of samples. Solution: train a reward model $RM_\phi(x,y)$ to predict human judgments, and use it as the reward. Modeling preferences becomes a separate NLP problem.
- Problem 2: human ratings are noisy and miscalibrated. One person's 8/10 is another's 6/10. Solution: ask for pairwise comparisons (“which of these two is better?”), which are much more consistent.
An earthquake hit San Francisco. There was minor property damage, but no injuries.
A 4.2 magnitude earthquake hit San Francisco, resulting in massive damage.
The Bay Area has good weather but is prone to earthquakes and wildfires.
Candidate summaries of a news article about a magnitude 4.2 earthquake, ranked by a person as $y_1 \succ y_3 \succ y_2$. A ranking of $k$ responses gives $\binom{k}{2}$ pairwise comparisons.
The Bradley–Terry loss
A reward model is typically a pretrained language model with a small head that outputs one number for the whole (prompt, response) pair. Given a comparison where $y^w$ (“winning”) was preferred over $y^l$ (“losing”), the Bradley–Terry model says the probability that $y^w$ is preferred is
$$P(y^w\succ y^l) = \sigma\big(RM_\phi(x,y^w)-RM_\phi(x,y^l)\big),$$where $\sigma$ is the sigmoid. Training maximizes the likelihood of the observed comparisons:
$$J_{RM}(\phi) = -\,\mathbb{E}_{(x,y^w,y^l)\sim D}\Big[\log\sigma\big(RM_\phi(x,y^w)-RM_\phi(x,y^l)\big)\Big].$$This is logistic regression on the difference of two scores: the model only learns that $y^w$ should score higher than $y^l$. The absolute scale of the reward does not matter.
How good are reward models? In work on summarization (Stiennon et al., 2020), reward models became more accurate at predicting human preferences as both the model size and the amount of comparison data grew, approaching the agreement rate of a single human labeler.
5Putting it all together: the KL penalty
We now have:
- a pretrained (usually instruction-tuned) model $p^{PT}(y\mid x)$, and
- a reward model $RM_\phi(x,y)$ trained on human comparisons.
RLHF makes a copy $p^{RL}_\theta$ of the model, initialized from $p^{PT}$, and optimizes it with policy gradient. The naive objective would be $\mathbb{E}_{y\sim p^{RL}_\theta}[RM_\phi(x,y)]$. Do you see a problem?
The reward model is only an imperfect approximation of human judgment, trained on responses that look like normal model outputs. A powerful optimizer will find responses that the reward model scores highly but people do not actually like: overly long answers, repeated flattering phrases, or strange text the reward model was never trained on. This is reward hacking. The fix is to penalize the model for drifting too far from where it started:
$$\max_\theta\ \ \mathbb{E}_{y\sim p^{RL}_\theta(\cdot\mid x)}\left[RM_\phi(x,y) - \beta\log\frac{p^{RL}_\theta(y\mid x)}{p^{PT}(y\mid x)}\right].$$The model pays a price whenever it makes a response much more likely than the original model would. In expectation, the penalty term is the Kullback–Leibler (KL) divergence between $p^{RL}_\theta$ and $p^{PT}$, and $\beta$ controls how strongly the model is held near its starting point.
Does it work?
In the summarization study of Stiennon et al. (2020), summaries from RLHF-trained models were preferred by human evaluators over the human-written reference summaries, and even a 1.3B-parameter RLHF model was preferred more often than a 12.9B model trained only with supervised learning. Learning from preferences gave a bigger gain than a 10× larger model.
6InstructGPT and ChatGPT
InstructGPT (Ouyang et al., 2022) combined everything into a three-step recipe that became the standard post-training pipeline:
- Collect demonstration data and train a supervised policy. Labelers write good responses to prompts; GPT-3 is fine-tuned on them (SFT).
- Collect comparison data and train a reward model. For each prompt, several model outputs are sampled; labelers rank them from best to worst; a reward model is trained with the Bradley–Terry loss.
- Optimize the policy against the reward model with RL. New prompts are sampled, the policy generates outputs, the reward model scores them, and PPO updates the policy, with the KL penalty toward the SFT model.
ChatGPT was trained with the same methods, with dialogue data: human trainers wrote conversations playing both the user and the AI assistant, and this data was mixed with the InstructGPT data. Many details of how current commercial models are trained have not been published.
Costs of RLHF
RLHF with PPO is powerful but complex. During training it needs several large models at once (the policy being trained, the frozen reference model for the KL penalty, the reward model, and, in PPO, a value model that estimates expected reward), and the optimization can be unstable and sensitive to hyperparameters. This has motivated simpler preference-optimization methods that skip the explicit reward model and RL loop.
7Summary
- RLHF optimizes $\mathbb{E}_{y\sim p_\theta}[R(x,y)]$: no reference answer is needed, only a way to score outputs.
- Text generation is RL: state = prompt + tokens so far, action = next token, policy = the LM, reward at the end.
- REINFORCE: $\nabla\mathbb{E}[R]=\mathbb{E}[R\,\nabla\log p_\theta(y\mid x)]$, estimated with samples; subtracting a baseline reduces variance. PPO keeps updates small.
- A reward model trained on pairwise comparisons with the Bradley–Terry loss replaces expensive, noisy human ratings.
- A KL penalty toward the original model prevents reward hacking.
- InstructGPT: SFT → reward model → PPO. The same recipe produced ChatGPT.
8Practice
Exercise 1: REINFORCE by hand
Two sampled responses get rewards $R(y_1)=3$ and $R(y_2)=1$. Without a baseline, which responses become more likely after one update? With the batch-mean baseline?
Exercise 2: Bradley–Terry
A reward model gives $RM(x,y^w)=2.0$ and $RM(x,y^l)=0.5$. What is the predicted probability that $y^w$ is preferred, and the loss for this comparison? (Use $\sigma(1.5)\approx 0.82$.)
Exercise 3: rankings to pairs
A labeler ranks four responses $A\succ C\succ D\succ B$. How many training pairs $(y^w,y^l)$ does this give? List them.
Quick quiz
9Further reading
- Lambert, Castricato, von Werra & Havrilla (2022). Illustrating Reinforcement Learning from Human Feedback (RLHF). Hugging Face blog. (An illustrated overview of the full pipeline.)
- Stiennon et al. (2020). Learning to Summarize from Human Feedback. NeurIPS.
- Ouyang et al. (2022). Training Language Models to Follow Instructions with Human Feedback. NeurIPS. (InstructGPT.)
- Karpathy (2016). Deep Reinforcement Learning: Pong from Pixels. (An intuitive introduction to policy gradients.)
- Lambert. Reinforcement Learning from Human Feedback (online book). (A complete reference for further study.)