All courses

RLHF with a KL penalty

Maximize E[r(x,y)] − β·KL(π_θ ‖ π_ref) with PPO. Explain why the KL term keeps the policy near the SFT model and how β trades reward against drift.

Builds on: PPO: clipped updates and a learned value baseline, Reward models from human comparisons, Cross-entropy and KL divergence, Supervised fine-tuning on demonstrations

▶ Watch this lesson Start the whole course

What the animation says

Why the policy needs a leash

After fine-tuning, PPO pushes the policy toward whatever the reward model scores highly. But the reward model only learned from comparisons of fine-tuned style answers. Near that kind of text, its scores mean something. Far away, they're guesses. A policy chasing those guesses drifts into odd text that scores high, but that people like less. So we need a leash: room to improve, and a dial for how far it may go.

A per-token fee

Keep a frozen copy of the fine-tuned model. Call it the reference. Every token the policy samples pays a fee: beta times its log-ratio. The log-ratio says how many times more likely the policy made this token than the reference would. Tokens both models agree on cost almost nothing. A token the reference finds near-impossible costs a lot. Now: a token the policy made less likely than the reference would. What does it pay?

On average, the fee is KL

It earns a small credit. Its log-ratio is negative, so the fee flips sign. But averaged over what the policy samples, the fee is the KL divergence, which is never negative. KL is cross-entropy minus the policy's own entropy, so collapsing raises the fee. The policy can't squeeze onto one answer for free. The full goal, for each prompt: expected reward minus beta times KL. Since KL sums over tokens, each token's reward is minus beta times its log-ratio. The last also gets the score.

Per-token rewards in code

Here's one sampled response, four tokens long. These two lines hold each token's log-probability under the policy and under the reference. Beta is zero point one, and the reward model scored the response two. Subtract to get the log-ratios: minus zero point two, zero point four, zero point five, zero. Their sum, zero point seven, estimates the KL. Before we compute the rewards: which token earns a credit? Tap it.

How β reshapes the best policy

These rewards, score included on the last token, feed PPO's usual advantage computation. So what policy does this objective favor? Exactly the reference, reweighted by e to the reward over beta. Three responses. The reference gives them point five, point three, point two. Rewards: zero, one, two. With beta four, the best policy is point four one, point three two, point two seven. Close to the reference. With beta one: point one eight, point two nine, point five three. Now beta is a quarter. Where does the probability go?

The dial, summed up

Beta a quarter: weights point five, sixteen, five hundred ninety-six. About ninety-seven percent on the top response. Small beta: the reward dominates, and the policy chases it. Large beta: the fee weighs more, so the policy stays near the reference. That's RLHF with a KL penalty: reward minus beta times KL, paid token by token. It keeps the policy where the reward model is trustworthy, and keeps it from collapsing.

How far should RLHF let the policy wander?

PPO pushes the policy toward whatever the reward model scores highly. But the reward model was trained on comparisons of SFT-style responses. Far from that kind of text, its scores are guesses, and a policy chasing them can drift into odd text that scores well but that people would not prefer. How do we let the policy improve while keeping it where the reward means something? And how do we set how far it may go?

A per-token fee for leaving the SFT model

Keep a frozen copy of the SFT model, $\pi_{ref}$. Each sampled token pays a fee of $\beta$ times its log-ratio $\log\pi_\theta-\log\pi_{ref}$. That is the log of how many times more likely the policy made the token than $\pi_{ref}$ would. Text both models agree on is nearly free. Text $\pi_{ref}$ finds near-impossible is expensive. A token the policy made less likely than $\pi_{ref}$ would earns a small credit, but on average the fee is the KL, which is never negative. Since $\mathrm{KL}(\pi_\theta\|\pi_{ref}) = H(\pi_\theta,\pi_{ref}) - H(\pi_\theta)$, the fee also rewards keeping entropy. So the policy cannot collapse onto one answer for free.

The KL-penalized objective

$$\max_\theta\ \mathbb{E}_{x}\Big[\mathbb{E}_{y\sim\pi_\theta(\cdot|x)}[r(x,y)] - \beta\,\mathrm{KL}(\pi_\theta(\cdot|x)\,\|\,\pi_{ref}(\cdot|x))\Big]$$ Here $x$ is a prompt drawn from the prompt set and $y$ is the response the policy samples. Because $\log\pi(y|x)=\sum_t\log\pi(y_t|x,y_{<t})$, the KL equals $\mathbb{E}_y\sum_t[\log\pi_\theta(y_t|\cdot)-\log\pi_{ref}(y_t|\cdot)]$. So each token gets the reward $-\beta\cdot$(its log-ratio), and the last token also gets $r(x,y)$. PPO, with its value baseline, then optimizes this per-token reward as usual.

How β moves the best policy

For each prompt $x$, the objective's exact optimum is $\pi^*(y|x)\propto\pi_{ref}(y|x)\,e^{r(x,y)/\beta}$. Take 3 responses with $\pi_{ref}=(0.5,0.3,0.2)$ and rewards $r=(0,1,2)$. - $\beta=4$: weights $(0.5,0.385,0.330)$ give $\pi^*=(0.41,0.32,0.27)$. This stays close to SFT. - $\beta=1$: weights $(0.5,0.815,1.478)$ give $\pi^*=(0.18,0.29,0.53)$. - $\beta=0.25$: weights $(0.5,16.4,596)$ give $\pi^*\approx(0.00,0.03,0.97)$. This is nearly pure reward-chasing.

Turning KL into per-token rewards

This computes the per-token rewards for one sampled response of 4 tokens. The log-ratios are $(-0.2, 0.4, 0.5, 0)$, and their sum, 0.7, is a one-sample estimate of the KL. The first token's log-ratio is negative, so it earns a small credit. The resulting rewards go into PPO's advantage computation.
import numpy as np
logp_pol = np.array([-1.2, -0.5, -2.0, -0.3])  # log pi_theta(y_t|...)
logp_ref = np.array([-1.0, -0.9, -2.5, -0.3])  # log pi_ref(y_t|...)
beta, r = 0.1, 2.0                              # r = reward model score
log_ratio = logp_pol - logp_ref
rewards = -beta * log_ratio
rewards[-1] += r              # sequence reward lands on last token
print(round(log_ratio.sum(), 3))  # 0.7  (KL estimate)
print(rewards)                # [ 0.02 -0.04 -0.05  2.  ]

Remember

RLHF maximizes reward minus $\beta\cdot\mathrm{KL}(\pi_\theta\|\pi_{ref})$, paid as a per-token log-ratio fee. This keeps the policy in the region where the reward model is trustworthy and discourages it from collapsing. The best policy is $\pi_{ref}$ reweighted by $e^{r/\beta}$: a large $\beta$ stays near SFT, and a small $\beta$ chases reward.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.