9.9 — The KL penalty and why it's there
Goal: Define the KL penalty r̃ = r − β KL(π_θ ‖ π_ref). Argue that it prevents (i) reward hacking and (ii) mode collapse. Derive the per-token implementation as a log-ratio reward correction. Identify how β is tuned and why the choice of reference matters.
1. Why this session exists
The RLHF and GRPO formulae of 9.7–9.8 both contain an extra term beyond the reward:
The term looks like an arbitrary regulariser. It is not arbitrary; it is the single most important safety mechanism in RLHF, preventing two structural failure modes that would otherwise destroy the trained model.
This session derives the penalty from first principles, identifies what goes wrong without it, and shows how to tune in practice. The same penalty reappears in DPO's derivation (9.10) — DPO's closed-form solution is exactly the KL-penalised RLHF objective minimised analytically.
2. What goes wrong without the KL
Imagine running PPO with just the raw reward , no KL penalty. The objective is
The policy can drift arbitrarily far from in pursuit of higher reward. Two specific failure modes follow.
2.1 Reward hacking
The reward model is an approximation of human preferences, trained on a finite set of comparisons. It has bugs, biases, and out-of-distribution failures. If the policy drifts far enough, it can find completions that score very high under but are bad under true human preferences.
A canonical example: might have learned that longer answers are preferred (training data was correlated with length). PPO without KL discovers this and produces increasingly verbose completions — eventually arriving at multi-page rambles that score well under but are unhelpful to users.
This is reward hacking (or Goodhart's law in disguise): when a proxy metric becomes the optimisation target, the proxy stops being a good measure. The KL penalty bounds how far the policy can drift, keeping it in the region where is approximately a valid proxy.
2.2 Mode collapse
A second failure: the policy starts to collapse to a single deterministic output per prompt. If one completion scores well, the policy concentrates probability mass on it; the gradient amplifies that concentration; eventually the policy is near-deterministic, producing the same completion for any related prompt.
Mode collapse destroys the model's generative diversity. The pretrained base could write a story in 10 different styles; after PPO without KL, it writes the same story 10 times.
The KL penalty resists collapse because explodes if becomes degenerate (a delta) when has spread mass. The penalty fights collapse and preserves the diversity of .
Both failure modes are practical observations, not theoretical guarantees. InstructGPT (Ouyang et al. 2022)[1] §3.5 documents both; every subsequent RLHF paper that ablates the KL term reproduces them.
3. The penalty term, mathematically
Recall (0.6) the KL divergence between two distributions on :
with equality iff . Two key properties:
- Non-negative. .
- Asymmetric. in general.
- Mode-seeking. The forward direction is infinite if puts mass anywhere doesn't. So if has full support, cannot collapse to a delta on regions outside 's support without paying infinite KL.
In RLHF, (the policy being trained) and (the SFT reference). The penalty term added to the reward:
3.1 Per-token implementation
For autoregressive LLMs, , so
The KL penalty distributes across tokens. In PPO, each token's reward becomes
The reward model fires at the end of the sequence; the KL penalty fires every token as a per-step log-ratio correction. GAE then accumulates these into advantages for PPO.
This per-token implementation has two consequences:
- The penalty is computed online — using and at sampling time. Both must be in memory.
- The KL is "as moves" — strictly , not the symmetric or reversed direction. The asymmetry matters in §3.
3.2 Why forward-KL, not reverse?
The choice (forward, sampling from ) vs (reverse, sampling from ) is not arbitrary.
Forward KL is mode-seeking in the wrong direction for our purposes — strictly speaking, it forces to cover all of 's support, which is what we want for diversity preservation. But sampling from during training is practical — those are the samples PPO already needs for the policy gradient. So forward KL is computed for free from the same samples.
Reverse KL would require sampling from , which is extra forward passes through the frozen reference. Possible but inefficient.
Empirically, forward KL works well enough that the inefficiency-driven choice is also a good choice in practice. DPO's derivation (9.10) uses forward KL implicitly through the same reasoning.
4. Choosing
is the single most important hyperparameter of RLHF after the SFT and reward-model choices.
4.1 Effects of
- : KL term vanishes. Policy can drift arbitrarily; reward hacking and mode collapse dominate.
- : KL term dominates. Policy cannot move from ; RL contributes nothing.
- "just right": policy improves reward while staying close to . Balance of exploration and constraint.
Typical in published recipes. InstructGPT used . LLaMA-2 used . The trend over time has been lower — meaning more freedom for the policy to move — as practitioners have learned where the sweet spot is for different model scales.
4.2 Adaptive
Some implementations adapt during training. The most common rule: monitor the average KL during sampling; if it exceeds a target value , increase ; if it falls below, decrease . This keeps the effective drift bounded.
Adaptive is helpful when the reward model's gradient pushes the policy unevenly across prompts: easy prompts have small gradients (less KL), hard prompts have large gradients (more KL). A fixed either under-constrains hard prompts or over-constrains easy ones. Adaptive control balances them.
4.3 Connection to TRPO / natural gradient
Mathematically, the KL-penalised reward is the Lagrangian of the constrained optimisation
with the Lagrange multiplier. TRPO (Schulman et al., 2015)[2] implements this constraint directly via a trust-region search; PPO with KL penalty approximates it with the dual form. The "KL penalty" is the soft version of the "trust region" idea — penalise instead of constrain.
This makes the KL penalty mathematically natural: it is the Lagrangian formulation of "don't move the policy too far from the reference in one step."
5. The "KL budget" view
A useful mental model: think of the cumulative KL between and as a budget that PPO spends to improve reward.
Empirically, the policy improves reward roughly linearly with KL distance from the reference, up to some point. Past that, reward hacking sets in and the true reward (human preference) degrades even as keeps improving. The "sweet spot" KL budget is implementation-specific but typically nats per completion at convergence.
This is why early stopping on a held-out preference set is standard practice in production RLHF: stop training when the held-out preference rate stops improving, even if score on the training distribution keeps climbing. The KL budget gives a tight handle on this; you can monitor cumulative KL and decide when "enough is enough".
6. Why the reference matters
The KL is computed against , which in the canonical RLHF recipe is — the supervised-fine-tuned model. Three reasons this is the right choice:
(a) SFT is already in the "instruction-following" mode. Using (the pretrained model) as reference would anchor the policy to "next-token predictor" behaviour, which is incompatible with the RLHF goal of "instruction follower." The KL would explode trying to keep an instruction-following policy close to a next-token predictor.
(b) SFT defines the "valid distribution" of completions. Anything outside 's support is suspicious — it's not the kind of response humans tend to write or that the reward model has been trained on. The KL penalty enforces "stay inside what we've validated."
(c) SFT gives us natural diversity. still has high entropy from its pretraining background; this is the diversity we want to preserve. Anchoring to would over-constrain; anchoring to a more focused intermediate model would under-constrain.
A few RLHF variants use or a separate "diversity model" as reference. These are exotic; the standard is .
7. Connection to information theory
The KL penalty has a natural information-theoretic interpretation. measures the additional information required to encode samples from given a code optimised for . In nats:
If , no extra information is required. As diverges, the per-sample "encoding penalty" grows. The penalty is paying for the bits of information by which the new policy departs from the old.
This connects to rate-distortion theory: the policy may distort outputs (increase ) but pays an information-theoretic cost (KL). The Pareto frontier of traces what's achievable; PPO with a particular picks one point on it.
8. What we keep going forward
Three things:
- The KL penalty prevents reward hacking and mode collapse. Both are practical, observed failure modes; the penalty is the structural safeguard.
- Per-token implementation as . PPO's GAE then accumulates these.
- is the most important hyperparameter of RLHF after the reward model. Typical . Adaptive that targets a fixed KL is a common production refinement.
Next session is DPO — Direct Preference Optimization. The derivation builds directly on the KL-penalised objective of this session: solve the RLHF objective in closed form, then re-parameterise to skip the explicit reward model. The most beautiful derivation in the entire roadmap.
(a) State the KL penalty in the form . Identify the asymmetry (forward vs reverse) and explain why forward KL is operationally cheaper.
(b) Derive the per-token form of the KL penalty: show that for an autoregressive LLM, decomposes into a sum of per-token log-ratios.
(c) Without the KL penalty, two specific failure modes appear: reward hacking and mode collapse. Give a concrete example of each — what would the policy do?
(d) A team trains PPO with and observes the policy hardly moves from in 1000 steps. Then they try and observe verbose, repetitive completions after 1000 steps. Suggest a debug procedure.
(e) Show that the KL-penalised reward is the Lagrangian of the constrained problem subject to . State the relationship between and .
References
- [1]
Ouyang, L., Wu, J., Jiang, X., et al. (2022). "Training language models to follow instructions with human feedback" (InstructGPT). arXiv:2203.02155 — Canonical SFT + RM + PPO pipeline (9.1, 9.2, 9.8); per-token KL implementation (9.9); PPO-ptx mixing (9.8 §5.3).
↩ - [2]
Schulman, J., Levine, S., Abbeel, P., Jordan, M., & Moritz, P. (2015). "Trust region policy optimization" (TRPO). arXiv:1502.05477 — Constrained policy update; the precursor PPO simplifies (9.6, 9.9 §4.3).
↩