Key takeaways
- Taking too big a step is dangerous. The surrogate objective is only reliable near the old policy, and in reinforcement learning, once the model breaks, the next batch of data it writes gets worse too.
- PPO (Proximal Policy Optimization) clips the probability ratio rt to [1−ϵ,1+ϵ], then takes the minimum with the unclipped version. It only flattens things once the policy has overshot in the direction the advantage favors; fixing mistakes is never held back.
- RLHF (reinforcement learning from human feedback) comes in three steps: supervised fine-tuning → train a reward model → reinforcement learning with PPO.
- The reward model learns from pairs of human preferences. The Bradley–Terry model turns the score gap into a probability, and the loss is just binary cross-entropy.
- The KL penalty tethers the policy to a reference model so it can't game the reward (reward hacking).
From autocomplete to assistant
In 2022, OpenAI used a method called RLHF to turn GPT-3, a model that could only continue text, into an assistant that actually answers questions well. ChatGPT, released later that year, was trained the same way. The method has to solve two problems:
- There's no answer key for a "good answer", so where does the reward come from?
- Once we have a reward, how do we update the model without wrecking it in a single step?
We'll tackle the second problem first. Its answer is PPO, the algorithm that does the heavy lifting inside RLHF.
Recap: where we left off
Last episode's example: the question was "How do I make scrambled eggs?", and the old model wrote three answers, A, B and C, scoring 8, 5 and 2. Subtract the baseline (the expected reward, 4.1) and we get their advantages: +3.9, +0.9 and −2.1.
PPO uses the value function as its baseline, so by convention we replace R(τ) in the policy gradient with the per-step advantage At=R(τ)−Vψ(st). To keep reusing the old model's answers, we weight each answer (in real training, each token) by a probability ratio:
rt=πθold(at∣st)πθ(at∣st)
that is, the new model's probability for it divided by the old model's. Add up rtAt and you have the surrogate objective. Its gradient is each term times the gradient of the log probability:
Jsurrogate(θ)=Eτ∼πθold[t∑rtAt],∇θJsurrogate=E[t∑rtAt∇θlogπθ(at∣st)]
At the starting point the new and old models are identical, every r equals 1, and this is just the ordinary policy gradient. But after a single step, the three answers' probabilities went from 0.2, 0.3 and 0.5 to 0.43, 0.39 and 0.17. The ratios are 2.17, 1.30 and 0.35, all far from 1, and the surrogate objective does nothing to stop them.
That's the question last episode left us with: what goes wrong when r wanders too far, and how do we rein it in?
Why one big step is dangerous
Because the surrogate objective is only an approximation. Near the starting point it hugs the true objective closely, but the farther you go, the worse the fit. Take a small step, and the surrogate says things will improve, and they really do. Take a big step, and the surrogate says it's fantastic while real performance may fall off a cliff.
In a language model there are at least two reasons:
- The advantage is estimated from only a few samples, so it's noisy. Push all the way to the extreme and you amplify the noise too.
- Every question shares the same parameters. Shove one answer's probability way up and you may break something somewhere else.
Worse, in reinforcement learning the next batch of data is written by the updated model itself. One bad step and the data gets worse; update on worse data and it's very hard to climb back out.
So we want each round's new policy to stay close to the old one. "Proximal", meaning nearby, is exactly that idea. Before PPO came TRPO, which used KL divergence to put a hard limit on how far the new policy could move from the old one. It works well but is complicated to implement. PPO swapped in something much simpler: just clip r.
PPO's trick: keep r inside a small range
PPO gives r an allowed range, from 1−ϵ to 1+ϵ. Epsilon is usually 0.2, so the range is 0.8 to 1.2. Inside the range, r stays as it is; outside, it sticks to the boundary:
clip(r,1−ϵ,1+ϵ)=⎩⎨⎧1−ϵr1+ϵr<1−ϵ1−ϵ≤r≤1+ϵr>1+ϵ
Put last episode's three ratios on the line: A and B are clipped to 1.2, and C to 0.8.
Now build PPO's objective one piece at a time:
- the first piece is the same as before, rtAt;
- the second piece swaps rt for its clipped version, times At;
- take whichever of the two is smaller;
- sum over the tokens in each answer, and average over the answers the old policy wrote.
That's PPO's clipped surrogate objective:
JCLIP(θ)=Eτ∼πθold[t∑min(rtAt, clip(rt,1−ϵ,1+ϵ)At)]
Plug in the three answers (ϵ=0.2):
| Ans. |
r |
A |
rA |
clipped |
min |
| A |
2.17 |
+3.9 |
8.47 |
4.68 |
4.68 |
| B |
1.30 |
+0.9 |
1.17 |
1.08 |
1.08 |
| C |
0.35 |
−2.1 |
−0.73 |
−1.68 |
−1.68 |
All three land on the clipped term. The clipped term is a constant that doesn't depend on the parameters, so its gradient is zero. In other words, PPO can tell this step has gone far enough and stops right there.
But wait: why take the minimum at all? Isn't clipping enough on its own?
Why the min? The four cases
Plot one token's contribution as a function of r. The unclipped rA is a straight line; the clipped version is flattened at both ends; PPO takes the smaller of the two.
A > 0: a good action (cases 1 and 2)
Take A=1. The min gives a line that rises, then goes flat once r passes 1.2.
- Case 1: r>1+ϵ, say r=1.5. We take the clipped value (1+ϵ)A, which is 1.2, a constant, so the gradient is zero. In words: this good action is already more than 20% more likely than under the old policy. That's enough. Stop pushing.
- Case 2: r<1−ϵ, say r=0.5. A good action got hurt by earlier steps and its probability went down. Now the unclipped line is the lower one, so we take rA. It slopes, the gradient isn't zero, and PPO pulls the probability back up.
If we only clipped, without the min, case 2's stretch would be flattened and the mistake could never be fixed. That's what the min is for. And between 0.8 and 1.2 the two lines coincide: nothing is clipped, so we get last episode's off-policy gradient, which at exactly r=1 is the ordinary policy gradient.
A < 0: a bad action (cases 3 and 4)
Take A=−1. This is a bad action, so we want its probability to fall, meaning r should get smaller. Taking the smaller line this time, the left side is flat and the right side keeps heading down.
- Case 3: r<1−ϵ, say r=0.5. This bad action's probability has already been pushed down by more than 20%. We take the constant (1−ϵ)A=−0.8, so the gradient is zero. That's enough; stop pushing it down.
- Case 4: r>1+ϵ, say r=1.5. This bad action's probability got pushed up by mistake. We take rA: the bigger r gets, the bigger the penalty, and the gradient keeps dragging it down with no clipping at all. Note that rt is allowed to exceed 1+ϵ here, which makes sense: A<0 means it's a bad token, so we let it keep getting pushed down.
Again, with clipping alone this right-hand stretch would be flattened too, and a bad action that got pushed up could never be pushed back down.
Four cases, one rule
|
r<1−ϵ |
r>1+ϵ |
| A>0 |
use rA, correct as usual |
use (1+ϵ)A, grad 0 |
| A<0 |
use (1−ϵ)A, grad 0 |
use rA, correct as usual |
The two flattened cells: a good action that has gone up enough, and a bad action that has been pushed down enough. The other two cells are a good action whose probability fell and a bad action whose probability rose. Both are moves in the wrong direction, so PPO puts no limit on them and gives the gradient as usual.
Intuition: Clipping is asymmetric. It only kicks in once the policy has overshot in the direction the advantage is pushing it. Fixing a mistake is never held back. Think of a steering lock: you can always correct course, you just can't yank the wheel all the way round.
Mathematically, a flattened stretch is a constant, so its gradient is zero; everywhere else the gradient is last episode's off-policy gradient:
∇θ[(1±ϵ)At]=0,∇θ[rtAt]=rtAt∇θlogπθ(at∣st)
Taking the min means one more thing: the result is never higher than the unclipped rtAt, so it's a pessimistic, conservative estimate:
min(rtAt, clip(rt,1−ϵ,1+ϵ)At)≤rtAt
The model can only climb this discounted objective, so it naturally won't dare to take big steps.
The full PPO loop
- Copy the current policy and freeze it. That's the old policy πθold.
- Use it to generate answers for a batch of prompts. This is the slowest step.
- Score each answer, then use the value network to compute an advantage for every token. Real implementations usually use a finer estimate called GAE, but the idea is the same.
- Take several gradient steps on this same batch, maximizing the clipped objective. Clipping is what makes it safe to take several steps on one batch.
Then the new policy becomes the next round's old policy, and we go back to step 1. Meanwhile, the value network is trained too, so its predictions get closer and closer to the rewards actually received.
Watch out: The cost: the clipped objective is no longer an unbiased estimate. PPO trades a little bias for much more stable training, especially when taking many gradient steps on a single batch. As long as you stay close to πθold, the approximation is good enough.
RLHF: where the reward comes from
So far we've assumed the reward R is simply handed to us. For a chatbot, where does it come from? A math answer can be checked, but ask the model for a poem about autumn and there's no answer key. People can certainly tell good from bad, but reinforcement learning needs scores many thousands of times over, and we can't ask a human every time.
The fix is to collect a batch of human judgments first and train a model to imitate human taste. That model is called a reward model. RLHF then has three steps:
- Supervised fine-tuning (SFT): people write example answers, and the model learns from them by predicting the next word. After this step it talks like an assistant.
- Train the reward model: the SFT model writes several answers to the same prompt, people compare which is better, and those comparisons train the reward model.
- Reinforcement learning: starting from the SFT model, the policy generates answers, the reward model scores them, and PPO updates the policy. There's also a KL penalty.
That's how OpenAI's InstructGPT turned GPT-3 into an assistant in 2022. Let's look closer at steps 2 and 3.
The reward model: learning scores from "which is better"
Why not have people score answers directly? Because scores are hard to keep consistent: the same answer might get a 7 from one person and a 5 from another, and even one person's standards drift over time. But ask which of two answers is better, and people answer quickly and consistently. So the reward model's training data is a set of pairwise preferences.
Take two answers to "How do I make boiled eggs easier to peel?":
- A: Right after boiling, soak them in cold water for a few minutes. The shells will slip off much more easily.
- B: You'll get better with practice.
The rater picked A. The winner is written yw and the loser yl. The reward model gives each answer a score; say A gets Rw=2.0 and B gets Rl=0.5. How do we turn two scores into the probability that A wins?
The Bradley–Terry model says:
P(yw≻yl)=exp(R(x,yw))+exp(R(x,yl))exp(R(x,yw))=σ(R(x,yw)−R(x,yl))
Plug in the numbers: e2≈7.39 and e0.5≈1.65, so A wins with probability about 7.39+1.657.39≈0.82.
The second equality comes from dividing top and bottom by eRw, which gives 1+e−(Rw−Rl)1. That's the sigmoid σ(x)=1+e−x1 from episode 1, applied to the difference between the two scores. A gap of zero means fifty-fifty, a gap of 1.5 gives about 0.82, and the bigger the gap, the closer to 1.
Watch out: Only the gap matters. Add 100 to both scores and the probability doesn't change. Reward model scores are relative, just like Elo ratings in chess.
The reward-model loss: a binary classifier
To train the reward model (parameters φ), we make the raters' choices as probable as possible, which means minimizing the negative log:
L(φ)=−logP(yw≻yl)=−logσ(Rw−Rl)
With a gap of 1.5, the loss is −log0.82≈0.20. If the model ranks them the wrong way round, the gap is −1.5 and the loss jumps to −log0.18≈1.70.
Look familiar? It's the binary cross-entropy from episode 5, −(ylogp+(1−y)log(1−p)), except the label is always y=1 (the winner really did win) and p=P(yw≻yl). So training a reward model is, at heart, a binary classification problem.
Now take a derivative. Write the gap as Δ=Rw−Rl. The sigmoid's derivative is σ′=σ(1−σ), so
∂Δ∂L=−σ(Δ)σ(Δ)(1−σ(Δ))=−(1−σ(Δ))
Gradient descent pushes the winner's score up and the loser's down, both with strength 1−σ(Δ). When the ranking is right that strength is only 1−0.82=0.18; when it's wrong it's 0.82. The more wrong the model is, the harder it gets corrected.
Structurally, a reward model is usually a language model too, often initialized from the SFT model. The last layer, which used to output probabilities over the vocabulary, is swapped for a scoring head that outputs a single number (the notes call it a "language model with a classification head").
Gaming the reward: reward hacking
With a reward model in hand, we can use PPO to maximize its score. But there's a trap: the reward model is only an approximation of human taste. And PPO is a powerful optimizer: wherever the reward model has a loophole, PPO will find it and squeeze through.
Say the reward model has a soft spot for long answers and polite filler. The policy then writes longer and longer answers stuffed with lines like "This is a very good question". The score keeps climbing while people find it more and more annoying. This is reward hacking: gaming the reward. Plotted as curves, the harder we optimize, the higher the reward model's score climbs, while the true human rating goes up at first and then comes back down.
This is Goodhart's law: when a measure becomes a target, it ceases to be a good measure.
The KL penalty: a rubber band on the model
The fix is one more penalty that keeps the policy from straying too far from a reference model πref. This is the RLHF objective:
JRLHF(θ)=Eτ∼πθ[R(τ)−βDKL(πθ∥πref)]
The reference model is usually a frozen copy of the SFT model, never updated during training. We met KL divergence in episode 5:
DKL(p∥q)=x∑p(x)logq(x)p(x)≥0
It measures how far apart two distributions are; it's never negative, and it's zero only when they're identical. β controls how tight the leash is.
Computed token by token
In practice the KL penalty is computed per token: take the log of the ratio between the token's probability under the policy and under the reference model, then multiply by −β. With β=0.1:
| token |
πθ |
πref |
penalty |
| very |
0.6 |
0.1 |
−0.18 |
| good |
0.5 |
0.5 |
0 |
| question |
0.3 |
0.6 |
+0.07 |
Take "very": the policy gives it 60%, the reference model only 10%. log6≈1.79, times β=0.1, is a penalty of 0.18. A token both models agree on gets log1=0: no penalty. For a token the policy likes less than the reference does, the log is negative, so it even earns a small bonus. Any single token can go either way, but averaged over samples from the policy, this comes out to exactly the KL divergence.
These penalties are folded into each token's reward, while the reward model's score (say +2.0) is added on the very last token.
Intuition: The KL penalty works like a rubber band. The policy wants to run off into the reward model's loophole, and the band pulls it back toward the reference model, which still talks sensibly: it can get better, but it can't turn into a monster. If β is too small, the band is too slack and the policy gets dragged into the loophole anyway. If β is too big, the band is too tight, the model barely moves and learns nothing. In practice you strike a balance.
Watch out: Keep the two anchors straight. PPO's clipping is anchored to the old policy, which is updated every round; it keeps each individual step small. The KL penalty is anchored to the reference model, which stays frozen; it keeps the policy from drifting too far in total.
Putting RLHF together: four models in memory
In the RL stage of RLHF, every round of training needs four models in memory at once:
| Model |
Job |
State |
| Policy |
writes answers; the one we train |
trained |
| Reward |
scores answers |
frozen |
| Reference |
per-token reference probabilities for the KL |
frozen |
| Value |
expected reward from each step, for the advantage |
trained |
All four are often sizable language models, so they eat GPU memory and are hard to tune. The two methods in the next episode go straight at this: GRPO drops the value model, and DPO goes further, skipping both the reward model and reinforcement learning.
Recap
PPO answers "how do we update without wrecking the model?": the surrogate objective is only reliable near the old policy, so clip the ratio rt to [1−ϵ,1+ϵ] and take the minimum. A good action that has gone up enough, or a bad one pushed down enough, gets flattened (zero gradient), while wrong-way moves are corrected as usual. It gives up unbiasedness in exchange for the stability to take several steps on one batch. RLHF answers "where does the reward come from?": SFT → train a reward model on pairwise preferences (Bradley–Terry, P=σ(Rw−Rl), a binary cross-entropy loss with label 1) → optimize with PPO, using a KL penalty to tether the policy to a frozen reference model and prevent reward hacking. The price is four models in memory, which is exactly what GRPO and DPO simplify next time.