3.7Post-training II: RLHF & reward models
Turning "I prefer this answer to that one" into a training signal. Preference data, Bradley–Terry reward models, the KL leash, reward hacking, and AI feedback.
Why imitation isn’t enough
Supervised fine-tuning teaches a model by example: here is a prompt, here is the ideal reply, copy it. That works, but it has two limits.
First, writing ideal answers is expensive and hard. Ask a person to write the perfect explanation of quantum tunneling for a ten-year-old and they will struggle. Show them two attempts and ask which is better and they will answer in seconds, fairly reliably. Judging is easier than generating.
Second, imitation only shows what to do, never what not to do. An SFT model sees good answers, but it never gets told “this subtle mistake you tend to make is bad”. It also can’t exceed its demonstrators: it is trained to copy them, not to beat them.
Reinforcement learning from human feedbackRLHFReinforcement learning from human feedback: train a reward model on human preference comparisons, then optimize the LLM against it. (RLHF) addresses both. Humans provide comparisons, a model learns to predict them, and the LLM is then trained to produce outputs that the learned judge rates highly. The approach was developed for robotics and Atari games (Christiano et al., 2017), applied to summarization (Stiennon et al., 2020), and became famous as the recipe behind InstructGPT and ChatGPT.
A young chef wants to cook food people love, but customers can’t explain what “great” means. They can taste two plates and point at the better one. So a restaurant hires a critic, shows them thousands of such comparisons, and the critic learns to predict which plate customers would pick. Now the chef can cook all night, get instant scores from the critic, and improve.
The customers’ choices are the preference data. The critic is the reward model. The chef practicing against the critic is reinforcement learning. And the danger is clear: if the critic has a quirk (say, it overrates anything drowned in butter), a chef who optimizes hard enough will start drowning everything in butter. That is reward hacking. The restaurant’s rule “don’t stray too far from the recipes you trained on” is the KL penalty.
The three-step recipe
The InstructGPT paper (Ouyang et al., 2022) laid out the pipeline that most RLHF systems still follow in spirit:
- Supervised fine-tuning. Train the base model on human-written demonstrations. This gives a decent starting policy, the SFT model.
- Reward model training. Sample several responses from the SFT model for each prompt. Human labelers rank them (InstructGPT used between 4 and 9 responses per prompt), and every ranking is broken into pairwise comparisons. A reward modelReward modelA model trained to score responses so that preferred responses get higher scores. (RM), usually the same transformer with its vocabulary head swapped for a single scalar output, is trained to give the preferred response a higher score.
- Reinforcement learning. Treat the LLM as a policy: given a prompt, it generates a response, the RM scores it, and an RL algorithm (originally PPOPPOProximal Policy Optimization: an RL algorithm that limits how far each update moves the policy. It was the classic RLHF workhorse.) updates the policy to increase that score, minus a penalty for drifting too far from the SFT model.
The reward model: Bradley–Terry in one line
How do you turn “A beat B” into a number per response? The classic tool is the Bradley–Terry modelBradley–Terry modelA model of pairwise comparisons in which the probability that A beats B is the sigmoid of the difference of their scores. Reward models are trained with it. (1952), originally used to rank chess players and sports teams. Give every response a score . Model the probability that A is preferred over B as a sigmoid of the score difference:
Equal scores mean a coin flip. A gap of 2 means about 88% vs 12%. Training is just logistic regression on pairs: maximize the log-probability of the choices the humans actually made. Only differences matter, so the reward’s absolute level is arbitrary; you could add 100 to every score and nothing would change.
In a real RLHF system, is a full transformer reading the prompt and response . In the demo below, it’s a tiny linear model over four hand-made features: length, politeness, correctness and hedging. That’s a cartoon, but it captures the essential failure mode. You are the labeler.
Train the reward model first to see what it rewards.
Things to try:
- Careful labeler, then train. Correctness gets a large positive weight; hedging and length go negative. The policy’s pick is the short, correct answer.
- “Skims, likes long answers”, then train. Length and politeness get big positive weights, and correctness goes slightly negative, because in these six pairs the longer answers were often the wrong ones. The highest-reward answer to the new prompt is now wrong.
- Drag the padding slider with that reward model. The padded version of a correct answer climbs past everything: the RM pays for words, not substance.
- Label it yourself, inconsistently. Notice that six labels can’t pin down four weights well. Real reward models face the same problem at scale: confounded features (long answers that happen to be correct) make it impossible to tell why people preferred something.
The KL leash
If you simply maximize the reward model’s score, the policy drifts into strange territory the RM never saw during training, where its scores are meaningless. So RLHF adds a KL penaltyKL penaltyA term in RLHF-style objectives that charges the policy for drifting away from a frozen reference model, measured by KL divergence. It keeps outputs fluent and limits reward hacking.: the objective becomes “reward minus times how far you’ve moved from a frozen reference model” (usually the SFT model):
In practice the penalty is applied per token as : every token the policy now likes much more than the reference did costs a little reward. This does three things. It keeps the language fluent (the reference model writes good English). It keeps outputs inside the region where the RM’s judgments are trustworthy. And it preserves diversity, preventing collapse onto one “perfect” answer. The coefficient is a dial: too small and the policy hacks the RM; too large and it barely learns.
Reward hacking
The reward model is a proxy for what people want, and any proxy pushed hard enough comes apart from its target. That’s Goodhart’s law, and in RLHF it is called reward hackingReward hackingWhen a policy finds ways to score highly on an imperfect reward signal without doing what the designers actually wanted, such as padding answers because the reward model likes length. or reward over-optimization. Gao, Schulman and Hilton (2022) measured it carefully with a synthetic setup: as the policy optimized a learned proxy RM harder (measured by its KL distance from the start), the proxy score kept rising, while the score from a “gold” reward model first rose and then fell.
Commonly reported symptoms in real systems include:
- Verbosity. Labelers often prefer longer, more thorough-looking answers, so RMs learn a length bias and policies grow wordier. One study (Singhal et al., 2023) found that, in the settings it examined, much of the reward improvement from RLHF could be explained by length alone.
- Sycophancy. People like being agreed with, so models learn to tell users what they want to hear, even flipping a correct answer when the user pushes back.
- Style over substance. Confident tone, headings and bullet lists can earn reward independent of correctness, exactly as in the demo.
Mitigations include the KL penalty, larger and better-trained reward models, ensembles of RMs, length-controlled evaluation, retraining the RM on fresh comparisons of the current policy’s outputs, and replacing learned rewards with checkable ones where possible, which leads to reasoning models trained on verifiable rewards.
RLAIF and Constitutional AI
Human labels are slow and costly, and asking people to read harmful content to label it is unpleasant work. A natural question: can an AI model provide the feedback? That’s RLAIF, reinforcement learning from AI feedback.
Anthropic’s Constitutional AIConstitutional AIAnthropic's method of using a written list of principles and AI-generated critiques and preference labels, instead of human labels, for parts of alignment training. An example of RLAIF. (Bai et al., 2022) is the best-known example. A short written list of principles, the “constitution”, guides two phases. In the supervised phase, the model critiques and revises its own responses according to the principles, and is fine-tuned on the revisions. In the RL phase, an AI model compares pairs of responses against the principles, those AI preferences train a preference model, and RL proceeds as in RLHF. The paper used this mainly for harmlessness, while helpfulness still came from human labels. Later work from Google (Lee et al., 2023) reported RLAIF performing comparably to RLHF on tasks such as summarization.
AI feedback makes the values more explicit (you can read the constitution) and much cheaper to scale, but it inherits the judge model’s biases, and it raises the obvious question of who checks the checker.
MATH CORNER · optionalThe reward-model loss and the RLHF objective, with numbers
Reward-model loss. For a dataset of comparisons , where won and lost, the Bradley–Terry negative log-likelihood is
Its gradient with respect to the score margin is : pairs the RM already gets confidently right contribute almost nothing, and pairs it gets wrong contribute almost fully.
Worked example. Suppose the RM currently scores and :
| quantity | value |
|---|---|
| margin | |
| loss | |
| (push up) | |
| (push down) |
If the RM had the order wrong, say , then , the loss is and the gradients have magnitude : more than twice the push.
The KL-shaped reward. During RL, the reward credited to a sampled response is
Take , an RM score of , and a 3-token response whose tokens the policy assigns probabilities while the reference assigned . The log-ratios are , so . A response the policy has made far more likely than the reference ever would pays a growing tax.
In code
The reward-model training step is a few lines on top of any transformer:
import torch.nn.functional as F
class RewardModel(torch.nn.Module):
def __init__(self, backbone): # e.g. the SFT model without its LM head
super().__init__()
self.backbone = backbone
self.score = torch.nn.Linear(backbone.config.hidden_size, 1)
def forward(self, ids, mask):
h = self.backbone(ids, attention_mask=mask).last_hidden_state
last = mask.sum(1) - 1 # index of each sequence's final token
return self.score(h[torch.arange(len(ids)), last]).squeeze(-1)
# one batch of comparisons: prompt+chosen and prompt+rejected
r_chosen = rm(chosen_ids, chosen_mask)
r_rejected = rm(rejected_ids, rejected_mask)
loss = -F.logsigmoid(r_chosen - r_rejected).mean() # Bradley–Terry NLL
loss.backward(); opt.step()
The score is read from the last token, which has attended to the whole prompt and response. Libraries such as Hugging Face TRL provide this as a ready-made trainer, along with PPO-style RL loops for step 3.
- “The reward model knows what’s good.” It knows what predicted these labelers’ choices on this data distribution. Outside that distribution, and under optimization pressure, its scores can be badly wrong.
- “RLHF teaches the model facts or values directly.” It reshapes which of the model’s existing behaviors are likely. It can make a model more honest-sounding without making it more accurate, which is exactly why sycophancy and confident errors survive.
- “Higher reward is always better.” Past a point, extra reward is mostly the policy exploiting the RM. That’s why the KL penalty exists and why people monitor KL and held-out human evaluations during training.
- “RLAIF removes humans from the loop.” Humans still write the principles, choose the judge model, and evaluate the results. The feedback is automated; the values are not.
Check your understanding
Q1.Why does RLHF collect pairwise comparisons instead of asking people for scores from 1 to 10?
Q2.A Bradley–Terry reward model scores response A at 3.0 and response B at 1.0. What probability does it assign to A being preferred?
Q3.What is the main purpose of the KL penalty to a reference model in RLHF?
Q4.Labelers tended to prefer longer answers, and after RLHF the model became very verbose. What is this an example of?
Q5.In Constitutional AI, where do the preference labels for the harmlessness RL phase come from?
Further reading
- paperTraining language models to follow instructions with human feedback (InstructGPT) — Ouyang et al., 2022. The canonical three-step RLHF pipeline.
- paperDeep reinforcement learning from human preferences — Christiano et al., 2017. The origin of learning rewards from pairwise human comparisons.
- paperScaling Laws for Reward Model Overoptimization — Gao, Schulman & Hilton, 2022. Measuring how proxy reward and true reward come apart.
- paperConstitutional AI: Harmlessness from AI Feedback — Bai et al., 2022 (Anthropic). Self-critique plus RL from AI feedback.
- paperRLAIF vs. RLHF: Scaling Reinforcement Learning from Human Feedback with AI Feedback — Lee et al., 2023 (Google). AI labels compared head to head with human labels.
- blogIllustrating Reinforcement Learning from Human Feedback — Hugging Face's friendly visual walkthrough of the pipeline.