KL-Regularized Policy Optimization

Dive into Deep Learning · §15.3

KL-Regularized Policy Optimization and Reward Hacking
Bradley–Terry preferences · potential shaping invariance · Goodhart’s law · exponentially tilted optimum · soft value iteration

When the Reward Must Be Learned from Comparisons

Motivation

  • The RLHF Pipeline: Roll out a reference policy \pi_{\textrm{ref}}, fit a reward model \hat{r} to pairwise human comparisons \tau \succ \tau', and optimize a policy against \hat{r}.
  • Reward Hacking (Goodhart’s Law): Because \hat{r} is accurate only on \pi_{\textrm{ref}}’s support, an unregularized policy exploits out-of-support blind spots unless anchored by -\beta D_{\textrm{KL}}(\pi \Vert \pi_{\textrm{ref}}).

A 4x4 Gridworld Benchmark with a Hidden True Reward

Experimental Benchmark

  • To audit reward learning and exploitation against ground truth, we construct a deterministic 4 \times 4 gridworld (\gamma = 0.95) from start state 0 (S) to absorbing goal 15 (G, +1.0):
    • Ordinary moves cost -0.04; entering the two hazard cells (5 and 6) costs -1.50.
  • The reference policy \pi_{\textrm{ref}}(a \mid s) \propto \exp(Q^*(s, a)/0.25) is competent but hesitant: it avoids the hazard lane (p \approx e^{-6}), visiting hazard entries in only 2–4 of 1{,}000 rollouts.

Fitting a Reward Model via Bradley–Terry Regression

Preference Learning

P(\tau \succ \tau') = \sigma\big(r(\tau) - r(\tau')\big) = \frac{1}{1 + e^{-(r(\tau) - r(\tau'))}}

  • Linearity in discounted counts: With c_{s,a}(\tau) = \sum_{t:(s_t,a_t)=(s,a)} \gamma^t, trajectory return is r(\tau) = \mathbf{c}(\tau)^\top \mathbf{r}.
  • Logistic regression: Fitting \hat{\mathbf{r}} on 6{,}000 comparisons is L_2-regularized logistic regression (\lambda_{\textrm{wd}} = 0.02) on count differences \mathbf{c}(\tau) - \mathbf{c}(\tau').

Where the Fitted Reward Is Accurate—and Where It Fails

Support Coverage

Inspecting the fitted reward \hat{r} across all 64 state-action pairs reveals a sharp divide between well-sampled and thin regions:

never visited: 9 pairs; in at least 50 episodes: 46 pairs
rms fit error on those 46: 0.193
moves into the hazards: in [3 4 3 2] episodes, fitted [-0.03 -0.05 -0.02 -0.02]

The Thin-Data Blind Spot: Because moves into the hazard cells (5 and 6) appear in only 2–4 episodes out of 1{,}000, weight decay keeps their fitted rewards near 0.00 instead of their true cost -1.50.

Why Comparisons Cannot See Potential-Based Shaping

Identifiability & Shaping

Why is the RMS error on the 46 well-visited core pairs 0.193 when ordinary step costs are only 0.04?

  • Potential Shaping Invariance: Adding \gamma \Phi(s') - \Phi(s) (with \Phi(\textrm{goal}) = 0) telescopes along every goal-reaching trajectory from s_0, shifting every return r(\tau) by the same constant -\Phi(s_0).
  • In any comparison r(\tau) - r(\tau'), the constant shift -\Phi(s_0) cancels completely, so pairwise preferences identify r only up to a potential \Phi:
rms error on core 0.193, after removing the best shaping term 0.032
Phi(0) = 0.78; moves 13 -> 14 -> goal: fitted -0.08, +0.09, true -0.04, +1.00
  • Weight decay picks the minimum-norm representative (\Phi(0) \approx 0.78), pricing ordinary moves at \approx -0.08—making the unmeasured hazard moves (\hat{r} \approx 0) look cheaper than normal steps.

Reward Hacking in Action: Walking Through the Hazards

Goodhart’s Law

When we run exact value iteration (plan) on the fitted reward \hat{r} and evaluate the resulting deterministic policy under both \hat{r} and the hidden true reward r^*:

plan on true reward  : fitted return -0.24, true return +0.59
plan on fitted reward: fitted return -0.03, true return -2.11
  • Exploiting the Blind Spot: Under \hat{r}, the shortest path 0 \to 1 \to 5 \to 6 \to 7 \to 11 \to 15 straight through both hazard cells scores -0.03 (beating the true optimal path’s -0.24), but earns a catastrophic -2.11 under r^*.
  • Over 24 independent preference datasets, planning on \hat{r} walks through the hazards on 19 datasets and loops forever on 4.

The Single-Decision KL-Regularized Objective

KL Regularization

\max_{\pi}\ \mathbb{E}_{a \sim \pi}\big[r(a)\big] - \beta\, D_{\textrm{KL}}\big(\pi \Vert \pi_{\textrm{ref}}\big)

  • Exponentially tilted optimum: For any \beta > 0, \pi^\star(a) = \frac{1}{Z}\,\pi_{\textrm{ref}}(a)\,e^{r(a)/\beta} with partition function Z = \sum_{a'} \pi_{\textrm{ref}}(a')\,e^{r(a')/\beta}.
  • Exact optimal value: By Gibbs’ inequality, any policy \pi achieves objective value \beta \log Z - \beta D_{\textrm{KL}}(\pi \Vert \pi^\star) \le \beta \log Z.

Visualizing the Exponential Tilt Across Temperatures

Geometry of the Tilt

  • The optimal policy \pi^\star(a) \propto \pi_{\textrm{ref}}(a) e^{r(a)/\beta} reweights the reference distribution rather than ranking actions by reward alone:
    • Support Preservation: Any action with \pi_{\textrm{ref}}(a) = 0 keeps \pi^\star(a) = 0 regardless of r(a).
    • Mild Tilt (\beta = 2): \pi_{\textrm{ref}}’s dip at a_2 survives into \pi^\star (D_{\textrm{KL}} = 0.15\text{ nats}).
    • Strong Tilt (\beta = 0.2): Mass concentrates on the highest-reward action a_5 (D_{\textrm{KL}} = 1.84\text{ nats}).

Numerical Verification Against Exponentiated Gradient

Verification

Running iterative exponentiated gradient ascent \pi \leftarrow \pi \odot \exp\big(\eta(r - \beta \log(\pi/\pi_{\textrm{ref}}))\big) confirms the closed form \pi^\star and log-partition value \beta \log Z to machine precision:

beta = 5.0: pi_beta = [0.233 0.086 0.237 0.232 0.212], reward 1.38, KL 0.02
beta = 2.0: pi_beta = [0.146 0.062 0.2   0.264 0.327], reward 1.74, KL 0.15
beta = 0.5: pi_beta = [0.004 0.004 0.025 0.148 0.819], reward 2.78, KL 1.26
beta = 0.2: pi_beta = [0.    0.    0.    0.009 0.991], reward 2.99, KL 1.84
largest gap to the closed form over the ladder: 1.4e-16
objective at beta = 2: numerical 1.442004, beta log Z = 1.442004

Four Structural Consequences of the Closed Form

Unifying Properties

Property / Limit Mathematical Specialization of \pi^\star(a) = \pi_{\textrm{ref}}(a) e^{r(a)/\beta} / Z Implication for Reinforcement Learning
1. Unregularized Limit (\beta \to 0) Concentrates on \operatorname{argmax}_{a \in \textrm{supp}(\pi_{\textrm{ref}})} r(a) Without a penalty, the optimal policy is deterministic
2. Heavy Penalty (\beta \to \infty) \pi^\star(a) \to \pi_{\textrm{ref}}(a) with D_{\textrm{KL}} \to 0 \beta smoothly interpolates from \pi_{\textrm{ref}} to greedy argmax
3. Uniform Reference (\pi_{\textrm{ref}} = 1/|\mathcal{A}|) -D_{\textrm{KL}}(\pi \Vert \textrm{unif}) = H(\pi) - \log |\mathcal{A}| \implies \pi^\star = \textrm{softmax}(r/\beta) Maximum-entropy RL (§15.5 SAC) and Boltzmann exploration
4. Bayesian Variational Form Prior \pi_{\textrm{ref}}(a) \times Likelihood e^{r(a)/\beta} / Z = \textrm{Posterior } \pi^\star(a) Control-as-inference and Direct Preference Optimization (§15.8)

The Concave Reward–Divergence Frontier

Pareto Frontier

  • Sweeping \beta from 10^{1.5} down to 10^{-1.5} traces the reward–divergence frontier: the maximum expected reward achievable at each KL budget D_{\textrm{KL}}(\pi \Vert \pi_{\textrm{ref}}).
  • The frontier is strictly increasing and concave with slope \beta, ending at \log(1/\pi_{\textrm{ref}}(a^*)) = \log(1/0.15) = 1.90\text{ nats}.
  • Best-of-N Sampling: Drawing N samples from \pi_{\textrm{ref}} and keeping the highest-scored one moves along this same axis with D_{\textrm{KL}} \le \log N - (N-1)/N (\approx 1.83\text{ nats} at N=16).

KL 0 pays 1.15; the frontier ends at KL 1.90, reward 3

Trust Region vs. Fixed-Reference Penalty & KL Direction

Critical Distinctions

  • Moving Trust Region (§15.2) vs. Fixed Penalty (§15.3): Penalizing divergence to the previous iterate \pi_k accumulates tilts \pi_k(a) \propto \pi_{\textrm{ref}}(a) e^{k\,r(a)/\tilde{\beta}} and still converges to the greedy argmax; only a frozen \pi_{\textrm{ref}} changes the destination.
  • Reverse vs. Forward KL: Reverse KL D_{\textrm{KL}}(\pi \Vert \pi_{\textrm{ref}}) suppresses poor actions exponentially (\propto e^{-\Delta(a)/\beta}), whereas forward KL keeps a linear floor (\approx \beta / \Delta(a)).

Multi-Step Decisions: Why Tilt by the Soft Value?

From Bandits to MDPs

In a sequential MDP where -\beta D_{\textrm{KL}}(\pi(\cdot \mid s_t) \Vert \pi_{\textrm{ref}}(\cdot \mid s_t)) is charged at every step, how much is the next state s' worth?

  • Two-Step Demonstration: Suppose the 5-action decision at \beta = 2 is the final step: its best action pays r_{\max} = 3.0, but the penalized optimal policy there earns soft value V_{\textrm{next}} = \beta \log Z = 1.44.
  • One step earlier, the agent chooses between entering that state (r=0) or stopping (r=2):
tilt by the soft value 1.44: pi(enter) = 0.43, objective 1.740
tilt by the best reward 3.00: pi(enter) = 0.62, objective 1.592
beta log Z of the first decision: 1.740
  • Takeaway: Tilting the first decision by the hard max 3.0 enters too often and loses objective value (1.592 < 1.740). Each step must tilt by the soft value \beta \log Z that accounts for all future rewards and future KL penalties.

Soft Value Iteration in Markov Decision Processes

The Soft Bellman Backup

The closed form at every state replaces value iteration’s hard \max_a with a reference-weighted log-sum-exp:

V_\beta(s) = \beta \log \sum_a \pi_{\textrm{ref}}(a \mid s)\, e^{Q_\beta(s, a)/\beta}, \qquad Q_\beta(s, a) = r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V_\beta(s')

def soft_max(Q, p, beta):
    """Row-wise beta log sum_a p(a) exp(Q(a) / beta), and the tilted policy."""
    m = Q.max(1, keepdims=True)                # subtracted for stability
    tilt = p * np.exp((Q - m) / beta)
    V = m[:, 0] + beta * np.log(tilt.sum(1))
    return V, tilt / tilt.sum(1, keepdims=True)

def soft_v(mdp, p, beta, num_iters=400):
    """Soft value iteration V <- soft_max(backup(V)); returns V and pi_beta."""
    V = np.zeros(mdp.num_states)
    for _ in range(num_iters):
        V, pi = soft_max(mdp.backup(V), p, beta)
    return V, pi

Because m_\beta(Q) = \beta \log \sum_a \pi_{\textrm{ref}}(a) e^{Q(a)/\beta} is monotone and shift-equivariant (m_\beta(Q + c) = m_\beta(Q) + c), the soft Bellman operator is a \gamma-contraction in \|\cdot\|_\infty for every \beta > 0.

True Return vs. Fitted Return Across the KL Budget

Overoptimization Curve

  • Solving soft_v on the fitted reward \hat{r} across 36 temperatures \beta \in [10^{-2.5}, 10^1] traces the classic RLHF overoptimization curve (Gao et al., 2023):
    • Fitted return (orange): rises monotonically as \beta decreases and trajectory KL grows.
    • True return (blue): climbs from -0.12 (\pi_{\textrm{ref}}) to a peak of +0.53 at 3.7\text{ nats} (near V^* = +0.59), then plunges to -1.83 as the policy enters the unmeasured hazard lane.

largest soft Bellman residual: 0e+00
reference: true return -0.12; beta = 10: KL 0.001, true return -0.10
peak: true return +0.53 at KL 3.7; smallest beta: -1.83 at KL 14.2

Concept Check: Shaping, Thresholds, and Best-of-N

Check Your Understanding

Work out these three questions from the section’s theory:

  1. Prompt Baseline Invariance: In LLM preference learning, why does replacing r(x, y) with r(x, y) + f(x) for any function f(x) of the prompt leave both the Bradley–Terry likelihood and the tilted policy \pi^\star(y \mid x) completely unchanged?
  2. Loophole Threshold: On a prompt x, the reference policy prefers a normal answer over a “hedged” answer by log-odds 4 (\pi_{\textrm{ref}}(\textrm{hedge})/\pi_{\textrm{ref}}(\textrm{normal}) = e^{-4}), but a flawed reward model pays the hedge +1 more reward. For which \beta does \pi^\star prefer the normal answer?
  3. Selecting \beta: Why can an algorithm optimizing \hat{r}(s,a) - \beta D_{\textrm{KL}} never detect the peak of the true return from its own training metrics?

Answers:

  1. Both responses in a comparison share the same prompt x, so f(x) cancels in r(x,y) - r(x,y'); in \pi^\star(y \mid x), e^{f(x)/\beta} factors out into the partition function Z(x).
  2. The tilted odds are e^{-4} e^{1/\beta} < 1 \iff 1/\beta < 4 \iff \mathbf{\beta > 0.25}.
  3. The fitted return \hat{J}(\pi_\beta) is mathematically guaranteed to increase monotonically as \beta decreases; detecting the true peak requires an independent held-out evaluator or verifier.

Summary: KL Regularization and Preference Optimization

Key Takeaways

Concept / Component Mathematical Form Primary Role & Practical Behavior
Bradley–Terry Model P(\tau \succ \tau') = \sigma(r(\tau) - r(\tau')) Fits reward \hat{r} from pairwise comparisons up to potential shaping \Phi
Reward Hacking \operatorname{argmax}_\pi J_{\hat{r}}(\pi) Exploits low-support state-action pairs where \hat{r} failed to measure penalties
Tilted Optimum (\pi^\star) \pi^\star(a) = \pi_{\textrm{ref}}(a) e^{r(a)/\beta} / Z Exact maximizer of \mathbb{E}_\pi[r] - \beta D_{\textrm{KL}}(\pi \Vert \pi_{\textrm{ref}}) with value \beta \log Z
Soft Bellman Backup V_\beta(s) = \beta \log \sum_a \pi_{\textrm{ref}}(a \mid s) e^{Q_\beta(s,a)/\beta} \gamma-contraction extending KL regularization to sequential multi-step MDPs
KL Budget Trade-off Moderate \beta (3.7\text{ nats} on gridworld) Captures true improvement (+0.53) before out-of-distribution collapse (-1.83)