15.3 KL-Regularized Policy Optimization

Every method of Chapter 14 and of this chapter so far assumed that someone had written down the reward. For a frozen lake or a cart with a pole that is easy: reach the goal, keep the pole upright. For most tasks people care about it is not. Nobody can write a formula that scores a helpful answer, a safe lane change or a readable proof. People can, however, look at two attempts and say which one they prefer, and a reward can be fitted to such comparisons. This is how the first widely used chat models were taught to be helpful: a reward model was fitted to human comparisons, and a policy was then trained against it (Christiano et al., 2017; Ouyang et al., 2022).

A fitted reward raises a question that a written one never did. The model is accurate only where its comparison data provide information, and it guesses elsewhere, while an optimizer searches everywhere. If the optimizer finds a region that the comparisons never covered and where the fitted reward happens to be high, it goes there, and the true quality falls. The remedy that practice settled on is to charge the policy for moving away from the policy that generated the comparisons, by a penalty on the KL divergence from that reference. The trust region of Section 15.2 limited how far each update moves from the previous policy. This penalty is part of the objective instead, so it changes the answer and not only the route to it, and the answer has a closed form: the reference distribution reweighted by the exponential of the reward.

We first build a gridworld whose true reward we know, fit a reward from comparisons, and watch an optimizer exploit its gaps. We then solve the penalized problem for one decision, extend the solution to many steps, and trace how the true quality rises and then falls as the policy moves away from its reference.

15.3.1 Learning a Reward from Comparisons#

To see what goes wrong we need a task whose true reward we know, so that we can hide it from the learner and still grade the result. A small gridworld provides one.

15.3.1.1 The Gridworld and Its Reference Policy#

The world is a 4×44 \times 4 grid with deterministic moves, shown in Figure 15.3.1. An episode starts in the top-left cell and ends when it enters the goal in the bottom-right corner, which pays +1+1. Every other move costs 0.040.04, and a move into either of the two hazard cells side by side in the second row, the hazard lane, costs 1.51.5. The true reward r∗(s,a)r^*(s, a) is the payment for the cell that action aa enters from state ss. The cells are numbered row by row, so the start is state 00, the hazards are states 55 and 66, and the goal is state 1515. The actions 00 to 33 move left, down, right and up, and a move into the wall leaves the agent where it is.

Figure 15.3.1:

The gridworld of this section. (a) Episodes start in state 0 (S) and end in the goal, state 15 (G, +1+1); a move into a hazard cell, 5 or 6, costs 1.51.5 and every other move 0.040.04. Each cell shows in how many of the 1,000 reference trajectories it is visited. (b) The support of every state-action pair: each cell is split into four triangles for the moves left, down, right and up, shaded by the number of trajectories that contain the pair (log scale); a cross marks a pair that never occurs, and the eight moves into the hazard lane are outlined.

The comparisons will be collected from trajectories of one fixed policy, the reference policy πref\pi_{\textrm{ref}}. We make it competent but hesitant: a softmax of the optimal action values at temperature 0.250.25, πref(a∣s)∝eQ∗(s,a)/0.25\pi_{\textrm{ref}}(a \mid s) \propto e^{Q^*(s, a)/0.25}. At the start, the two moves toward the goal have Q∗=0.59Q^* = 0.59 and the two into the walls 0.520.52, so the reference takes each good move with probability 0.280.28 and each wasted one with 0.220.22. A move into a hazard is worth about 1.51.5 less than the alternatives, which the softmax turns into a probability of about e−6e^{-6}, so the reference rarely goes there. The cell builds the arrays P[s,a,s′]P[s, a, s'] and r∗[s,a]r^*[s, a] as a d2l.TabularMDP (Section 14.1), computes Q∗Q^* by running d2l.value_iteration and applying one more backup (Section 14.2), and forms the reference:

gamma = 0.95                                   # a 4 x 4 gridworld
P = np.zeros((16, 4, 16))
for s, a in np.ndindex(16, 4):
    x, y = s % 4, s // 4
    dx, dy = [(-1, 0), (0, 1), (1, 0), (0, -1)][a]   # left, down, right, up
    P[s, a, min(3, max(0, y + dy)) * 4 + min(3, max(0, x + dx))] = 1.0
P[15], P[15, :, 15] = 0.0, 1.0                 # the goal absorbs
bonus = np.full(16, -0.04)                     # every step costs a little
bonus[[5, 6]], bonus[15] = -1.5, 1.0           # a hazard lane; the goal pays
r_true = np.einsum('sat,t->sa', P, bonus)      # r*(s, a): the entered bonus
r_true[15] = 0.0
mdp = d2l.TabularMDP(P, r_true, gamma)
Q_true = mdp.backup(d2l.value_iteration(mdp, 200)[-1])
pi_ref = np.exp(Q_true / 0.25)                 # competent but hedging
pi_ref /= pi_ref.sum(1, keepdims=True)

15.3.1.2 Preferences and the Bradley-Terry Model#

A comparison tells us which of two trajectories a judge preferred, not by how much. The Bradley-Terry model (Bradley and Terry, 1952) turns such answers into a statistical model. It assigns each candidate a scalar score, here the return r(τ)r(\tau) of a trajectory under the reward rr, and treats a comparison as a noisy observation of the score difference:

P(τ≻τ′)=σ(r(τ)−r(τ′)),σ(u)=11+e−u.(15.3.1)P(\tau \succ \tau') = \sigma\big( r(\tau) - r(\tau') \big), \qquad \sigma(u) = \frac{1}{1 + e^{-u}}. \tag{15.3.1}

Thus two trajectories with equal returns are preferred either way with probability one half, and a difference of one unit of return makes the better one win about three times in four.

In the gridworld the return is linear in the reward. Let c(τ)\mathbf{c}(\tau) be the discounted visit counts of a trajectory, one entry per state-action pair: entry (s,a)(s, a) adds γt\gamma^t for every step tt at which the trajectory takes aa in ss. Then r(τ)=c(τ)⊤rr(\tau) = \mathbf{c}(\tau)^\top r, with the reward flattened into 6464 entries, and fitting (15.3.1) is logistic regression with features c(τ)−c(τ′)\mathbf{c}(\tau) - \mathbf{c}(\tau') and the reward as weights. sample_traj returns c(τ)\mathbf{c}(\tau) for one trajectory of πref\pi_{\textrm{ref}}, which ends at the goal or after 4040 steps, and X stacks 10001000 of them. We label 60006000 random pairs by coin flips with the probabilities of (15.3.1) under r∗r^* and fit r^\hat r by gradient ascent on the log-likelihood, with a small weight decay, 0.020.02, so that the fit is well defined on pairs with little data. episodes counts the episodes in which each pair occurs, core marks the pairs that occur in at least 5050, and into lists the four moves into the hazard lane from above and from the sides:

rng = np.random.default_rng(0)
sigmoid = lambda u: 1 / (1 + np.exp(-u))

def sample_traj(mdp, pi, rng, T=40):
    """Discounted visit counts c(tau) of one episode from state 0."""
    s, c = 0, np.zeros((16, 4))
    for t in range(T):
        a = rng.choice(4, p=pi[s])
        c[s, a] += mdp.gamma ** t              # the return is c(tau) . r
        s = mdp.P[s, a].argmax()
        if s == 15:
            break
    return c.ravel()

X = np.stack([sample_traj(mdp, pi_ref, rng) for _ in range(1000)])
R = X @ r_true.ravel()                         # true returns; the fit never sees them
i, j = rng.integers(0, 1000, (2, 6000))
y = (rng.random(6000) < sigmoid(R[i] - R[j])).astype(float)
D = X[i] - X[j]
lr, wd, num_steps = 0.5, 0.02, 4000            # ascent step, weight decay
w = np.zeros(64)
for _ in range(num_steps):                     # logistic regression on (D, y)
    w += lr * (D.T @ (y - sigmoid(D @ w)) / len(y) - wd * w)
r_hat = w.reshape(16, 4)
episodes = (X > 0).sum(0).reshape(16, 4)       # episodes containing each pair
core = episodes >= 50
into = ([1, 4, 2, 7], [1, 2, 1, 0])            # into cells 5, 6 from above, sides
print(f'never visited: {(episodes == 0).sum()} pairs; '
      f'in at least 50 episodes: {core.sum()} pairs')
print(f'rms fit error on those {core.sum()}: '
      f'{np.sqrt(((r_hat - r_true)[core] ** 2).mean()):.3f}')
print(f'moves into the hazards: in {episodes[into]} episodes, '
      f'fitted {np.round(r_hat[into], 2)}')
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 fit has an rms error of 0.190.19 on the forty-six pairs of core. Nine pairs never occur: the four actions at the goal, where every episode has already ended, and the five marked with crosses in Figure 15.3.1. Their fitted rewards stay at the initial value of zero. The moves into the hazard lane from above and from the sides occur in two to four of the thousand episodes each, and the two from below never occur. That is too few to move a fitted reward far from zero, where the weights started and where the weight decay pulls them; truly each costs 1.51.5. A neural reward model would instead extrapolate according to its inductive bias, for better or worse (exercise 4).

15.3.1.3 Invariance to Shaping#

An rms error of 0.190.19 against step costs of 0.040.04 looks large, but most of it is invisible to any comparison. Potential-based shaping, introduced in Section 14.1, adds γΦ(s′)−Φ(s)\gamma \Phi(s') - \Phi(s) to the reward of each move from ss to s′s', for a function Φ\Phi on the states with Φ=0\Phi = 0 at the goal, and Section 14.2 proved that it leaves the optimal policy unchanged. Along a trajectory these terms telescope, so every trajectory from state 00 that reaches the goal changes its return by the same amount, −Φ(0)-\Phi(0). Every comparison involves two trajectories from state 00, so the shift cancels in r(τ)−r(τ′)r(\tau) - r(\tau'), and (15.3.1) cannot detect it. (The one trajectory in ten that is cut off after forty steps keeps a final term γ40Φ(s40)\gamma^{40}\Phi(s_{40}), too small to pin Φ\Phi down.) The comparisons therefore determine the reward only up to shaping, and among the rewards they cannot tell apart, the weight decay prefers the one with the smallest weights.

The cell finds the potential whose shaping term best explains the fit's error on core, in the least-squares sense. Row (s,a)(s, a) of F multiplies Φ\Phi to give γ∑s′P(s′∣s,a) Φ(s′)−Φ(s)\gamma \sum_{s'} P(s' \mid s, a)\, \Phi(s') - \Phi(s), and dropping the last column sets Φ(15)=0\Phi(15) = 0:

err = (r_hat - r_true)[core]
F = (gamma * P - np.eye(16)[:, None, :])[core][:, :15]  # shaping per unit of Phi
Phi = np.linalg.lstsq(F, err, rcond=None)[0]
print(f'rms error on core {np.sqrt((err ** 2).mean()):.3f}, after removing '
      f'the best shaping term {np.sqrt(((err - F @ Phi) ** 2).mean()):.3f}')
print(f'Phi(0) = {Phi[0]:.2f}; moves 13 -> 14 -> goal: fitted '
      f'{r_hat[13, 2]:+.2f}, {r_hat[14, 2]:+.2f}, true '
      f'{r_true[13, 2]:+.2f}, {r_true[14, 2]:+.2f}')
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

Removing the shaping term leaves an rms error of 0.030.03: up to shaping, the fit is good where the data are. The potential rises from about 0.80.8 at the start to about 0.90.9 beside the goal; at the hazard cells, which no pair of core touches, it is left undetermined. Such a potential subtracts about 0.90.9 from the move into the goal and about (1−γ)×0.8=0.04(1 - \gamma) \times 0.8 = 0.04 from every other move, which is what the printed rewards show: the last move pays 0.090.09 instead of 11, and an ordinary move costs 0.080.08 instead of 0.040.04. Both rewards order every pair of trajectories from state 00 alike, and the fitted one has the smaller weights. Under it, the hazard moves, estimated near zero, are cheaper than an ordinary move.

Language models face the same invariance. A comparison there involves two responses yy and y′y' to the same prompt xx, and a reward r(x,y)+f(x)r(x, y) + f(x), for any function ff of the prompt, predicts every comparison as r(x,y)r(x, y) does, so a learned reward is identified only relative to each prompt (exercise 1). Policy-gradient methods are unaffected: subtracting a function of the prompt from the reward is a baseline, which leaves the expected gradient unchanged (Section 14.8). The group mean of GRPO is such a baseline, except that it includes the response's own reward, which scales the expected update by (K−1)/K(K-1)/K for groups of KK responses, as that section showed.

15.3.2 Optimizing a Fitted Reward#

We now do what an agent would do with the fitted reward: find the policy that maximizes it. With the dynamics known, value iteration finds it. plan returns the optimal deterministic policy for a reward as one-hot rows. ret returns the exact return of a policy from state 00 through policy_value of Section 14.2, which solves the linear Bellman equations Vπ=(I−γPπ)−1rπV^\pi = (I - \gamma P_\pi)^{-1} r_\pi in one step. We plan once on the true and once on the fitted reward, and grade both plans under both rewards:

def plan(r):
    """Optimal deterministic policy (one-hot rows) for reward r."""
    m = d2l.TabularMDP(P, r, gamma)
    return np.eye(4)[m.backup(d2l.value_iteration(m, 200)[-1]).argmax(1)]

def ret(pi, r):
    """Exact return of policy pi from state 0 under reward r."""
    return d2l.TabularMDP(P, r, gamma).policy_value(pi)[0]

for name, r in (('true reward  ', r_true), ('fitted reward', r_hat)):
    pi = plan(r)
    print(f'plan on {name}: fitted return {ret(pi, r_hat):+.2f}, '
          f'true return {ret(pi, r_true):+.2f}')
plan on true reward  : fitted return -0.24, true return +0.59
plan on fitted reward: fitted return -0.03, true return -2.11

Under the fitted reward the plan on r^\hat r scores −0.03-0.03, above the −0.24-0.24 of the true optimum. The true optimum's fitted score lies 0.830.83 below its true score, close to the shaping offset Φ(0)=0.78\Phi(0) = 0.78, so only differences between fitted scores mean anything. Under the true reward the two plans score −2.11-2.11 and +0.59+0.59. The plan on r^\hat r walks 0→1→5→6→7→11→150 \to 1 \to 5 \to 6 \to 7 \to 11 \to 15, straight through both hazard cells, a route as short as the safe one along the border and cheaper under r^\hat r. Value iteration optimized the reward it was given; the failure lies in the reward outside the reference's data. Over 2424 preference datasets drawn with different seeds, the plan on r^\hat r crosses the hazard cells in 1919 and never reaches the goal in 44 more; one dataset yields the true optimum.

This failure has a name. Goodhart's law states that a measure loses its value once it becomes a target. In reinforcement learning, a policy that scores highly under a specified or fitted reward while defeating the intended objective is said to hack the reward, and many cases are catalogued in (Krakovna et al., 2020). The approach bonus of Section 14.2, which made the optimal policy circle forever, was the same mechanism with a hand-written error. Here the error is statistical, and it sits where the data are thin.

15.3.3 The KL-Regularized Objective#

The fitted reward deserves trust only where the reference policy went. A policy that stays close to the reference stays where the data are, so we charge for moving away from it. KL divergence is the natural measure here: it is an expectation under the policy itself, so it can be estimated from the policy's own samples, and it is infinite for a policy that takes an action the reference never takes. For a single decision with reward r(a)r(a) over a finite set of actions, a reference πref\pi_{\textrm{ref}} and a coefficient β>0\beta > 0, the KL-regularized objective is

max⁡π Ea∼π[r(a)]−β DKL(π∥πref).(15.3.2)\max_{\pi}\ \mathbb{E}_{a \sim \pi}\big[ r(a) \big] - \beta\, D_{\textrm{KL}}\big( \pi \Vert \pi_{\textrm{ref}} \big). \tag{15.3.2}

The first term is the expected reward, and the second subtracts β\beta units of reward for every nat of divergence from the reference. The coefficient β\beta is the weight of the penalty; the reference stays fixed.

15.3.3.1 The Closed-Form Optimum for One Decision#

Proposition. For β>0\beta > 0, the objective (15.3.2) is maximized by the unique policy

π⋆(a)=1Z πref(a) er(a)/β,Z=∑aπref(a) er(a)/β,(15.3.3)\pi^\star(a) = \frac{1}{Z}\, \pi_{\textrm{ref}}(a)\, e^{r(a)/\beta}, \qquad Z = \sum_{a} \pi_{\textrm{ref}}(a)\, e^{r(a)/\beta}, \tag{15.3.3}

and the maximal value is βlog⁡Z\beta \log Z.

Proof. By construction r(a)=βlog⁡(π⋆(a)Z/πref(a))r(a) = \beta \log\big( \pi^\star(a) Z / \pi_{\textrm{ref}}(a) \big). Substituting into the objective, for any policy π\pi,

Eπ[r]−βDKL(π∥πref)=∑aπ(a) βlog⁡π⋆(a) Zπ(a)=βlog⁡Z−β DKL(π∥π⋆).\begin{aligned} \mathbb{E}_\pi[r] - \beta D_{\textrm{KL}}(\pi \Vert \pi_{\textrm{ref}}) &= \sum_a \pi(a)\, \beta \log \frac{\pi^\star(a)\, Z}{\pi(a)} \\ &= \beta \log Z - \beta\, D_{\textrm{KL}}(\pi \Vert \pi^\star). \end{aligned}

Gibbs' inequality, proved in Chapter 25, says the remaining divergence is nonnegative and zero exactly when π=π⋆\pi = \pi^\star. ■\blacksquare

Thus the optimum multiplies the reference by an exponential tilt er/βe^{r/\beta} and renormalizes, and the value it achieves is a log-partition function. Figure 15.3.2 draws the product for five actions. The reference there is deliberately not monotone in the reward, and its dip at the second action survives a mild tilt: the optimum reweights the reference rather than ranking the actions by reward.

Figure 15.3.2:

The optimum of the penalized objective as a product. Each row multiplies the reference πref=(0.30, 0.10, 0.25, 0.20, 0.15)\pi_{\textrm{ref}} = (0.30,\ 0.10,\ 0.25,\ 0.20,\ 0.15) by the tilt er/βe^{r/\beta} for the reward r=(0, 0.5, 1, 2, 3)r = (0,\ 0.5,\ 1,\ 2,\ 3) and renormalizes, giving π⋆\pi^\star; the top row uses β=2\beta = 2, the bottom β=0.2\beta = 0.2. The reference's dip at a2a_2 survives into π⋆\pi^\star in the top row and is overwhelmed in the bottom row. The margins annotate the two limits: β→∞\beta \to \infty returns the reference, β→0\beta \to 0 a point mass on the best action.

Two boundary cases complete the statement. First, the optimum inherits the reference's support. If πref(a)=0\pi_{\textrm{ref}}(a) = 0, any policy that puts mass on aa has infinite divergence, and (15.3.3) gives aa probability zero, whatever its reward. Second, as β→0\beta \to 0 the optimum concentrates on the best action in the support of πref\pi_{\textrm{ref}}; if several actions tie for best, the limit is the reference renormalized over the tied set.

We check the proposition numerically by solving (15.3.2) with an iterative method that knows nothing of the closed form. solve_kl runs exponentiated gradient ascent: it multiplies the current policy by the exponential of a step size times the gradient, r−β(log⁡(π/πref)+1)r - \beta(\log(\pi/\pi_{\textrm{ref}}) + 1), and renormalizes onto the simplex. The +1+1 is the same for every action and cancels in the normalization, so the code drops it:

p_ref = np.array([0.30, 0.10, 0.25, 0.20, 0.15])
r = np.array([0.0, 0.5, 1.0, 2.0, 3.0])

def solve_kl(r, p, beta, steps=3000, eta=0.3):
    pi = np.full_like(p, 1 / len(p))
    for _ in range(steps):                     # exponentiated gradient ascent
        pi = pi * np.exp(eta * (r - beta * np.log(pi / p)))
        pi /= pi.sum()
    return pi

for beta in (5.0, 2.0, 0.5, 0.2):
    pi = solve_kl(r, p_ref, beta)
    print(f'beta = {beta:3}: pi_beta = {np.round(pi, 3)}, '
          f'reward {pi @ r:.2f}, KL {(pi * np.log(pi / p_ref)).sum():.2f}')
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

As β\beta falls from 55 to 0.20.2 the expected reward rises from 1.381.38 to 2.992.99 and the divergence from 0.020.02 to 1.841.84 nats. The two rows of Figure 15.3.2 are the optima at β=2\beta = 2, with divergence 0.150.15 nats, and at β=0.2\beta = 0.2. We now compare each converged iterate with (15.3.3), and the achieved objective with βlog⁡Z\beta \log Z. pi_star evaluates the closed form, subtracting the largest reward inside the exponential so that it cannot overflow; the shift cancels in the normalization:

def pi_star(r, p, beta):
    star = p * np.exp((r - r.max()) / beta)    # eq_kl_optimum, stabilized
    return star / star.sum()

gap = max(np.abs(solve_kl(r, p_ref, b) - pi_star(r, p_ref, b)).max()
          for b in (5.0, 2.0, 0.5, 0.2))
pi2 = solve_kl(r, p_ref, 2.0)
print(f'largest gap to the closed form over the ladder: {gap:.1e}')
print(f'objective at beta = 2: numerical '
      f'{pi2 @ r - 2.0 * (pi2 * np.log(pi2 / p_ref)).sum():.6f}, '
      f'beta log Z = {2.0 * np.log(p_ref @ np.exp(r / 2.0)):.6f}')
largest gap to the closed form over the ladder: 1.4e-16
objective at beta = 2: numerical 1.442004, beta log Z = 1.442004

The iterates agree with the closed form to floating-point resolution at every β\beta, and the objective matches βlog⁡Z\beta \log Z to six decimal places.

15.3.3.2 Four Consequences of the Closed Form#

Without the penalty, the optimum is a point mass. Letting β→0\beta \to 0 in (15.3.3) sends all mass to the highest-reward action, or, under ties, to the reference's distribution over the tied set. This is the unregularized problem, whose solution is the argmax. The statement concerns the optimum, not the course of a particular training run. The entropy of the PPO policy in Section 15.2 fell during training, which is consistent with movement toward the near-deterministic optimum of PPO's lightly entropy-regularized objective. A penalty with a larger weight makes a stochastic policy optimal.

The coefficient interpolates between the reference and the argmax. The closed form at a very large and a very small β\beta:

for beta in (100.0, 0.01):
    print(f'beta = {beta:6}: pi_star = {np.round(pi_star(r, p_ref, beta), 3)}')
beta =  100.0: pi_star = [0.297 0.099 0.25  0.202 0.153]
beta =   0.01: pi_star = [0. 0. 0. 0. 1.]

Large β\beta reproduces the reference, small β\beta is greedy, and every policy in between is the exact optimum for some value of β\beta.

A uniform reference turns the penalty into an entropy bonus. Against a uniform reference, DKL(π∥uniform)=log⁡∣A∣−H(π)D_{\textrm{KL}}(\pi \Vert \textrm{uniform}) = \log |\mathcal{A}| - H(\pi), so the penalty is a bonus βH(π)\beta H(\pi) for entropy plus a constant, and (15.3.2) becomes the maximum-entropy objective. The closed form specializes to a softmax of the reward:

boltzmann = np.exp(r / 0.5) / np.exp(r / 0.5).sum()
print(np.allclose(pi_star(r, np.full(5, 0.2), 0.5), boltzmann))
True

This is the form of the softmax policies of Section 14.7. The Boltzmann exploration rule of Section 14.4, with β\beta as its temperature, is therefore the exact optimum of a one-step objective with an entropy bonus.

The optimum is a posterior. The closed form (15.3.3) has the form of Bayes' rule: πref\pi_{\textrm{ref}} is a prior, er/βe^{r/\beta} an unnormalized likelihood, π⋆\pi^\star the posterior and ZZ the normalizer. Control-as-inference methods build on this identity, reading rewards as log-likelihoods of an event called optimality and regularized policy optimization as variational inference (Levine, 2018; Korbak et al., 2022).

15.3.3.3 The One-Decision Frontier#

Each β\beta gives one optimum, with an expected reward and a divergence from the reference. Sweeping β\beta traces the best reward attainable at each divergence, the reward-divergence frontier:

front = np.stack([pi_star(r, p_ref, b) for b in np.logspace(1.5, -1.5, 61)])
kl_f = (front * np.log(front / p_ref)).sum(1)
print(f'KL 0 pays {p_ref @ r:.2f}; the frontier ends at KL '
      f'{np.log(1 / p_ref[r.argmax()]):.2f}, reward {r.max():.0f}')
d2l.plot(kl_f, front @ r, 'KL from the reference (nats)', 'expected reward')
KL 0 pays 1.15; the frontier ends at KL 1.90, reward 3

The frontier starts at the reference's average reward, 1.151.15, and ends at the point mass on the best action, whose divergence is log⁡(1/0.15)=1.90\log(1/0.15) = 1.90 nats. It is increasing and concave, with slope β\beta at the optimum for β\beta (exercise 5), so each further nat yields less reward. The two rows of Figure 15.3.2 are two points on this curve. Best-of-NN sampling, which draws NN answers from the reference and keeps the one with the highest reward, moves along the same axis without any training: its divergence from the reference is at most log⁡N−(N−1)/N\log N - (N-1)/N, about 1.81.8 nats for N=16N = 16 (Gao et al., 2023). On the gridworld we will trace the same kind of curve, but grade it with the true reward instead of the reward being optimized.

15.3.3.4 Trust Region versus Penalty#

Trust regions and the fixed-reference penalty both use KL divergence, in different roles.

Two uses of KL divergence. A trust region (Section 15.2) measures divergence from the previous iterate. It limits each update and protects a local approximation, and its reference moves after every update. A fixed-reference penalty (this section) is part of the objective and moves the optimum to (15.3.3). PPO-style fine-tuning of language models uses both: a clipped surrogate relative to the sampling policy for stable updates, and a reward penalty relative to the frozen initial model to control the final policy (Ouyang et al., 2022).

The closed form shows where a trust region alone leads. Suppose every update solves its trust-region problem exactly, with a weight β~\tilde{\beta} on the divergence from the previous iterate, πk+1=argmax⁡πEπ[r]−β~DKL(π∥πk)\pi_{k+1} = \operatorname{argmax}_\pi \mathbb{E}_\pi[r] - \tilde{\beta} D_{\textrm{KL}}(\pi \Vert \pi_k), starting from π0=πref\pi_0 = \pi_{\textrm{ref}}. By the proposition each step multiplies the policy by er/β~e^{r/\tilde{\beta}}, so after kk steps

πk(a)=πref(a) ek r(a)/β~∑a′πref(a′) ek r(a′)/β~,(15.3.4)\pi_k(a) = \frac{\pi_{\textrm{ref}}(a)\, e^{k\, r(a)/\tilde{\beta}}}{\sum_{a'} \pi_{\textrm{ref}}(a')\, e^{k\, r(a')/\tilde{\beta}}}, \tag{15.3.4}

the closed form with coefficient β~/k\tilde{\beta}/k. As kk grows the coefficient goes to zero, and the iterates approach the point mass on the best action. A trust region shapes the path but not the destination; only a fixed reference changes where the iterates converge (exercise 6).

15.3.3.5 The Direction of the Divergence#

The penalty DKL(π∥πref)D_{\textrm{KL}}(\pi \Vert \pi_{\textrm{ref}}) is the reverse divergence in the taxonomy of Section 25.3.2, an expectation under π\pi that can be estimated from the policy's own samples. The closed form shows how it treats an action aa whose reward falls short of the best by Δ(a)>0\Delta(a) > 0: relative to the best action, its probability under π⋆\pi^\star is its reference probability times e−Δ(a)/βe^{-\Delta(a)/\beta}. The forward penalty DKL(πref∥π)D_{\textrm{KL}}(\pi_{\textrm{ref}} \Vert \pi) is infinite for a policy that drops any action the reference takes, and its optimum keeps every action at a floor of order β/Δ(a)\beta / \Delta(a) times its reference probability (exercise 7). Both directions keep every action the reference takes at positive probability for every β>0\beta > 0. They differ in how fast poor actions fade as β\beta shrinks: exponentially in 1/β1/\beta under the reverse penalty, only linearly in β\beta under the forward one.

15.3.4 The Soft Backup#

The gridworld is not a single decision. In an MDP the penalty is charged at every step, and the objective from state 00 becomes

Eπ[∑t≥0γt(r(st,at)−β DKL(π(⋅∣st)∥πref(⋅∣st)))].(15.3.5)\mathbb{E}_\pi\Big[\sum_{t \geq 0} \gamma^t \big( r(s_t, a_t) - \beta\, D_{\textrm{KL}}\big( \pi(\cdot \mid s_t) \Vert \pi_{\textrm{ref}}(\cdot \mid s_t) \big) \big)\Big]. \tag{15.3.5}

At each state the policy faces a one-decision problem of the kind just solved. The question is which reward that decision should be tilted by.

15.3.4.1 One Step before the End#

At the last decision of an episode an action's worth is its reward, and the proposition applies verbatim: the optimum there is the reference tilted by er/βe^{r/\beta}, and the state is worth βlog⁡Z\beta \log Z. One step earlier, an action's worth is its reward plus the worth of the state it leads to. That worth is what the optimal policy there achieves under the penalty, βlog⁡Z\beta \log Z, which is less than the best reward available there. The optimal policy at the last step takes that best action only with some probability and is charged the penalty as well.

A two-step example makes the difference concrete. Let the five-action decision of Figure 15.3.2 with β=2\beta = 2 be the last step of an episode; its value is βlog⁡Z=1.44\beta \log Z = 1.44, although its best reward is 33. One step earlier the agent chooses between entering that decision, which pays nothing at once, and stopping with a sure reward of 22; the reference picks each with probability one half, and there is no discount. The cell tilts the first decision once by the soft value 1.441.44 and once by the best reward 33, and evaluates the penalized objective of both two-step policies:

beta, stop = 2.0, 2.0                          # stopping pays 2 for sure
V_next = beta * np.log(p_ref @ np.exp(r / beta))   # value of the last step
for name, q in (('soft value', V_next), ('best reward', r.max())):
    pi0 = pi_star(np.array([q, stop]), np.array([0.5, 0.5]), beta)
    J = pi0 @ [V_next, stop] - beta * (pi0 * np.log(pi0 / 0.5)).sum()
    print(f'tilt by the {name} {q:.2f}: pi(enter) = {pi0[0]:.2f}, '
          f'objective {J:.3f}')
Z0 = 0.5 * np.exp(V_next / beta) + 0.5 * np.exp(stop / beta)
print(f'beta log Z of the first decision: {beta * np.log(Z0):.3f}')
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

Tilting by the soft value attains the optimum, βlog⁡Z\beta \log Z of the first decision. Tilting by the best reward values the second decision at 33, although the penalized policy there earns only 1.441.44, so it enters too often and loses about 0.150.15. The tilt must use the value that accounts for every later reward and every later penalty.

15.3.4.2 Soft Value Iteration#

Writing this value at every state gives the general form. Let Qβ(s,a)Q_\beta(s, a) be the worth of action aa at state ss under the penalized objective, and Vβ(s)V_\beta(s) the worth of state ss. Applying the proposition at every state, with Qβ(s,⋅)Q_\beta(s, \cdot) in the role of the reward,

Vβ(s)=βlog⁡∑aπref(a∣s) eQβ(s,a)/β,Qβ(s,a)=r(s,a)+γ∑s′P(s′∣s,a) Vβ(s′),(15.3.6)\begin{aligned} V_\beta(s) &= \beta \log \sum_a \pi_{\textrm{ref}}(a \mid s)\, e^{Q_\beta(s, a)/\beta}, \\ Q_\beta(s, a) &= r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V_\beta(s'), \end{aligned} \tag{15.3.6}

and the optimal policy is πβ(a∣s)∝πref(a∣s) eQβ(s,a)/β\pi_\beta(a \mid s) \propto \pi_{\textrm{ref}}(a \mid s)\, e^{Q_\beta(s, a)/\beta}. These are the Bellman optimality equations of Section 14.2 with the maximum over actions replaced by a reference-weighted log-sum-exp, a soft maximum that tends to the hard maximum over the reference's support as β→0\beta \to 0. The hard maximum is biased upward when the action values are noisy estimates, as Section 14.3 demonstrated; the log-sum-exp, being convex, is biased upward too, only less sharply. With a uniform reference this is the soft value iteration of maximum-entropy reinforcement learning.

Value iteration solved the hard equations by sweeping V←max⁡abackup(V)V \leftarrow \max_a \textrm{backup}(V) from V=0V = 0. The same sweep with the soft maximum solves (15.3.6). The proof that the hard sweep contracts (Section 14.2.2.3) used only two properties of the maximum: it is monotone, and adding a constant to every entry adds that constant to the maximum. The soft maximum has both, so the soft sweep is also a γ\gamma-contraction, for every β>0\beta > 0 and every reference (exercise 3). soft_max computes the soft maximum of each row of an array of action values, after subtracting the row's maximum for numerical stability, and returns the tilted policy with it. soft_v sweeps backup followed by soft_max:

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

15.3.4.3 True Return against the KL Budget#

We now trace the frontier on the gridworld, with one change: the optimizer sees the fitted reward r^\hat r, and we grade with the true one. For each of 3636 values of β\beta from 1010 down to 10−2.510^{-2.5}, soft_v computes the exact penalized optimum πβ\pi_\beta for r^\hat r, and we record its true return, its fitted return and its divergence from the reference. For the divergence we use the penalty of the MDP objective, Eπβ[∑tγtDKL(πβ(⋅∣st)∥πref(⋅∣st))]\mathbb{E}_{\pi_\beta}\big[\sum_t \gamma^t D_{\textrm{KL}}\big(\pi_\beta(\cdot \mid s_t) \Vert \pi_{\textrm{ref}}(\cdot \mid s_t)\big)\big] from state 00. It is the KL divergence between the distributions of trajectories that πβ\pi_\beta and πref\pi_{\textrm{ref}} generate when every episode also ends with probability 1−γ1 - \gamma after each step (exercise 2). The code weights the per-state divergences kl by visits, the expected discounted number of visits to each state from state 00, which one linear solve with the transition matrix of πβ\pi_\beta provides. It also records the largest residual of (15.3.6) over the sweep:

m_hat = d2l.TabularMDP(P, r_hat, gamma)
kls, true_ret, fit_ret, resid = [], [], [], 0.0
for beta in np.logspace(1, -2.5, 36):
    V, pi = soft_v(m_hat, pi_ref, beta)
    V_new, _ = soft_max(m_hat.backup(V), pi_ref, beta)
    resid = max(resid, np.abs(V_new - V).max())
    kl = (pi * np.log(np.where(pi > 0, pi / pi_ref, 1.0))).sum(1)
    P_pi = np.einsum('sa,sat->st', pi, P)
    visits = np.linalg.solve(np.eye(16) - gamma * P_pi.T, np.eye(16)[0])
    kls.append(visits @ kl)                    # discounted KL from state 0
    true_ret.append(ret(pi, r_true))
    fit_ret.append(ret(pi, r_hat))
k = int(np.argmax(true_ret))
print(f'largest soft Bellman residual: {resid:.0e}')
print(f'reference: true return {ret(pi_ref, r_true):+.2f}; beta = 10: '
      f'KL {kls[0]:.3f}, true return {true_ret[0]:+.2f}')
print(f'peak: true return {true_ret[k]:+.2f} at KL {kls[k]:.1f}; '
      f'smallest beta: {true_ret[-1]:+.2f} at KL {kls[-1]:.1f}')
d2l.plot(kls, [true_ret, fit_ret], 'KL from the reference (nats)', 'return',
         legend=['true return', 'fitted return'])
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

Every point in the plot is an exact optimum of the penalized objective; the largest Bellman residual is below 10−1010^{-10}. The fitted return rises throughout, and for exact optima it must. If β1<β2\beta_1 \lt \beta_2 and the optima have fitted returns J1,J2J_1, J_2 and divergences D1,D2D_1, D_2, optimality gives J1−β1D1≥J2−β1D2J_1 - \beta_1 D_1 \geq J_2 - \beta_1 D_2 and J2−β2D2≥J1−β2D1J_2 - \beta_2 D_2 \geq J_1 - \beta_2 D_1. Adding the two gives (β2−β1)(D1−D2)≥0(\beta_2 - \beta_1)(D_1 - D_2) \geq 0, so D1≥D2D_1 \geq D_2, and the first inequality then gives J1≥J2J_1 \geq J_2.

The true return behaves differently. It rises from the reference's −0.12-0.12 to +0.53+0.53 at 3.73.7 nats, close to the true optimum of +0.59+0.59, and then falls to −1.83-1.83 as the policy concentrates on the hazard lane. A moderate push on the fitted reward improves the true return, and a stronger one exploits the moves the data never measured. Over 2424 preference datasets the peak lies between about +0.5+0.5 and the optimum +0.59+0.59 at a few nats, and the true return falls after it in 2121. In the other three it does not fall within the swept range: in one the fitted optimum is the true one, and in two the fitted values of the safe and hazard routes nearly tie, so the penalized optimum keeps the safe route down to β=10−2.5\beta = 10^{-2.5}. How far from the reference the peak sits and how deep the fall goes depend on how well the comparisons cover the hazard and on what it costs. Gao et al. (2023) measured the same rise and fall for language models optimized against a learned reward model and graded by a held-out one.

The peak of the true return is invisible to the optimizer, which sees only the fitted curve, and that curve rises monotonically. In practice β\beta is therefore chosen by evaluating the policy against something other than the reward model it was trained on: held-out comparisons, human judgments, or a checker. With a uniform reference the same penalty is an entropy bonus, and Section 15.5 builds an off-policy actor-critic for continuous actions that maximizes it. Its critic evaluates its own policy under the reward with the entropy bonus rather than iterating the log-sum-exp backup; by the identity in the proof of the proposition, the two agree when the policy is the tilted one. Section 15.8 applies the closed form (15.3.3) to the verifier task of Chapter 14, where it predicts the β\beta at which a hedged answer stops paying. Every method so far has learned from fresh samples of the current policy or from a known model; Section 15.4 asks whether a network can learn action values from stored transitions of any policy, as the Q-table of Section 14.3 did.

15.3.5 Summary#

A reward fitted to comparisons is accurate only where the comparisons are. Comparisons between trajectories from a common start cannot see a potential shaping of the reward, and pairs the data never cover keep whatever value the fit started with. An optimizer exploits those gaps: in the gridworld, the plan on the fitted reward walks through hazard cells that the reference rarely entered. Penalizing the KL divergence from the reference changes the objective, and its exact optimum is the reference tilted by er/βe^{r/\beta}, with value βlog⁡Z\beta \log Z; a uniform reference turns the penalty into an entropy bonus. In an MDP the tilt uses the soft action value, which satisfies a Bellman equation with a log-sum-exp in place of the maximum. Sweeping the penalty's weight, the fitted return rises monotonically while the true return peaks at a moderate divergence and then falls, so the weight must be chosen by an evaluation the optimizer does not see.

15.3.6 Exercises#

  1. Identifiability and scale. The Bradley-Terry model (15.3.1) is fitted to comparisons of two responses yy and y′y' to the same prompt xx.
    1. Show that replacing r(x,y)r(x, y) by r(x,y)+f(x)r(x, y) + f(x), for any function ff of the prompt, leaves the likelihood of every such dataset unchanged. Conversely, join two responses to xx by an edge whenever the dataset compares them. Show that two rewards that assign the same preference probability to every compared pair differ by a constant on each connected component of this graph. What is identified when the graph of one prompt has several components?
    2. Suppose that the annotators label according to P(y≻y′)=σ(ω (r∗(x,y)−r∗(x,y′)))P(y \succ y') = \sigma\big(\omega\, (r^*(x, y) - r^*(x, y'))\big) for some consistency ω>0\omega > 0, and that (15.3.1) is fitted by maximum likelihood on unlimited data. Which reward does the fit recover?
    3. Show that the optimum (15.3.3) for the fitted reward at coefficient β\beta is the optimum for r∗r^* at coefficient β/ω\beta / \omega. Suppose that β\beta was tuned against a reward model fitted to the labels of one pool of annotators. How strong a penalty is the same β\beta for a reward model fitted to the labels of a less consistent pool, that is, one with a smaller ω\omega?
  2. [code] Trajectory divergence. Let pπ(τ)p_\pi(\tau) denote the probability that a policy π\pi, started at state 00, produces the trajectory τ=(s0,a0,s1,a1,…,sT)\tau = (s_0, a_0, s_1, a_1, \ldots, s_T) of a fixed horizon TT.
    1. Show that
DKL(pπ∥pπref)=Eπ[∑t=0T−1DKL(π(⋅∣st)∥πref(⋅∣st))].D_{\textrm{KL}}\big(p_\pi \Vert p_{\pi_{\textrm{ref}}}\big) = \mathbb{E}_\pi\Big[\sum_{t=0}^{T-1} D_{\textrm{KL}}\big(\pi(\cdot \mid s_t) \Vert \pi_{\textrm{ref}}(\cdot \mid s_t)\big)\Big].

Which factors of pπ(τ)p_\pi(\tau) cancel, and why can the divergence therefore be estimated from trajectories of π\pi without a model of the transitions?

  1. Let the trajectory instead end after each step with probability 1−γ1 - \gamma, independently of the actions. Show that the divergence between the two trajectory distributions becomes the discounted sum of per-state divergences that the sweep of Section 15.3.4.3 appends to kls as visits @ kl.
  2. Take the policy πβ\pi_\beta at the peak of the true return in that sweep. Average c(τ)⊤log⁡(πβ/πref)\mathbf{c}(\tau)^\top \log(\pi_\beta / \pi_{\textrm{ref}}), with the logarithm taken entrywise and flattened like c(τ)\mathbf{c}(\tau), over 2000 trajectories from sample_traj(mdp, pi, rng, T=400), and compare the average with the divergence of 3.73.7 nats printed at the peak. Some of the per-trajectory values are negative. Why does this not contradict Gibbs' inequality?
  1. [code] Soft backup on the lake. The proof in Section 14.2.2.3 used one property of the maximum, ∣max⁡af(a)−max⁡ag(a)∣≤max⁡a∣f(a)−g(a)∣|\max_a f(a) - \max_a g(a)| \leq \max_a |f(a) - g(a)|.
    1. Let mβ(f)=βlog⁡∑aπref(a) ef(a)/βm_\beta(f) = \beta \log \sum_a \pi_{\textrm{ref}}(a)\, e^{f(a) / \beta}. Show that mβm_\beta is monotone and that mβ(f+c)=mβ(f)+cm_\beta(f + c) = m_\beta(f) + c for every constant cc, and deduce that mβm_\beta has the same property as the maximum. Conclude that the backup (15.3.6) is a γ\gamma-contraction for every β>0\beta > 0 and every reference.
    2. Apply soft_v to the slippery lake of Section 14.2, built as a d2l.TabularMDP, with a uniform reference. Plot Vβ(s0)V_\beta(s_0) against β\beta on a logarithmic grid from 10−410^{-4} to 10210^2. Which two values computed in Section 14.2 does the curve approach at its two ends? Explain with the regularized objective why the curve is monotone.
    3. At about which β\beta does Vβ(s0)V_\beta(s_0) lie halfway between the two limits? Compare this coefficient with the differences between the optimal action values Q∗(s0,a)Q^*(s_0, a) of the lake.
  2. [extended] Neural reward models. ● The linear fit of r_hat leaves the pairs without data near zero, whereas a neural reward model extrapolates according to its inductive bias. Replace the 64 weights w by the outputs of a multilayer perceptron with two hidden layers of 64 ReLU units, one output per state-action pair, and set the row of the goal to zero. Train it on the same D and y with the Bradley-Terry negative log-likelihood, Adam at learning rate 0.010.01, for 2000 full-batch steps.
    1. Train one model whose input is a one-hot code of the state and the action, and one whose input is the two grid coordinates of the state, scaled to [0,1][0, 1], together with a one-hot code of the action, with four seeds each. For every model, report the rms error on core, the fitted rewards of the moves into the hazard cells, and the true return of plan.
    2. Repeat the sweep of Section 15.3.4.3 on each fitted reward. Which representation needs the penalty? Which property of its input explains the difference?
  3. Slope of the frontier. ● Write u=1/βu = 1 / \beta, and let R(u)R(u) and D(u)D(u) denote the expected reward and the divergence DKL(π⋆∥πref)D_{\textrm{KL}}(\pi^\star \Vert \pi_{\textrm{ref}}) of the optimum (15.3.3).
    1. Show that R(u)=ddulog⁡ZR(u) = \frac{d}{du} \log Z and that R′(u)=Varπ⋆(r)R'(u) = \textrm{Var}_{\pi^\star}(r). Then use the value βlog⁡Z\beta \log Z of the proposition to show that D′(u)=u Varπ⋆(r)D'(u) = u\, \textrm{Var}_{\pi^\star}(r).
    2. Conclude that the frontier traced by front and kl_f has slope β\beta at the point π⋆\pi^\star, and that it is increasing and concave whenever rr is not constant on the support of πref\pi_{\textrm{ref}}.
    3. Show that π⋆\pi^\star also solves the constrained problem max⁡πEπ[r]\max_\pi \mathbb{E}_\pi[r] subject to DKL(π∥πref)≤D(u)D_{\textrm{KL}}(\pi \Vert \pi_{\textrm{ref}}) \leq D(u). Which quantity of the constrained problem does β\beta become?
    4. Best-of-NN sampling draws NN independent samples from πref\pi_{\textrm{ref}} and keeps the one with the highest reward. When the reward has a continuous distribution under the reference, show that the divergence of the best-of-NN distribution from the reference is log⁡N−(N−1)/N\log N - (N-1)/N. For the five-action bandit p_ref, r, whose rewards are distinct and increasing, best-of-NN picks action aa with probability F(a)N−F(a−1)NF(a)^N - F(a-1)^N, where F(a)F(a) is the reference probability of the actions up to aa. Plot its expected reward against its divergence for N=1,…,16N = 1, \ldots, 16, together with front and kl_f. How close does it come to the frontier, and does its divergence stay below log⁡N−(N−1)/N\log N - (N-1)/N?
  4. A moving reference. ● The trust region of Section 15.2 measures divergence from the previous iterate. This section showed that the idealized update πk+1=argmax⁡π Eπ[r]−β~ DKL(π∥πk)\pi_{k+1} = \operatorname{argmax}_\pi\ \mathbb{E}_\pi[r] - \tilde{\beta}\, D_{\textrm{KL}}(\pi \Vert \pi_k), started at π0=πref\pi_0 = \pi_{\textrm{ref}}, converges to the argmax.
    1. Now add the fixed-reference penalty of (15.3.2), as PPO-style fine-tuning does, so that πk+1\pi_{k+1} maximizes
Eπ[r]−β DKL(π∥πref)−β~ DKL(π∥πk).(15.3.7)\mathbb{E}_\pi[r] - \beta\, D_{\textrm{KL}}(\pi \Vert \pi_{\textrm{ref}}) - \tilde{\beta}\, D_{\textrm{KL}}(\pi \Vert \pi_k). \tag{15.3.7}

Show that, up to a constant,

log⁡πk+1=βlog⁡πref+β~log⁡πk+rβ+β~,(15.3.8)\log \pi_{k+1} = \frac{\beta \log \pi_{\textrm{ref}} + \tilde{\beta} \log \pi_k + r}{\beta + \tilde{\beta}}, \tag{15.3.8}

and find the limit of πk\pi_k. Which coefficient determines the limit? How fast is the limit approached?

  1. Show that the recursion of part a is the update of solve_kl with a suitable step size, and express that step size through β\beta and β~\tilde{\beta}. Which of the convergent step sizes of solve_kl have no interpretation as a trust region?
  1. [code] Forward-KL penalty. ● Section 15.3.3.5 contrasts the reverse divergence of (15.3.2) with the forward one. Replace the penalty by the forward divergence,
max⁡π Ea∼π[r(a)]−β DKL(πref∥π).(15.3.9)\max_\pi\ \mathbb{E}_{a \sim \pi}\big[r(a)\big] - \beta\, D_{\textrm{KL}}\big(\pi_{\textrm{ref}} \Vert \pi\big). \tag{15.3.9}
  1. Introduce a multiplier mm for the constraint ∑aπ(a)=1\sum_a \pi(a) = 1, and show that the optimum is π(a)=β πref(a)/(m−r(a))\pi(a) = \beta\, \pi_{\textrm{ref}}(a) / (m - r(a)), where m>max⁡ar(a)m > \max_a r(a) is the unique value for which these probabilities sum to one.
  2. Let Δ(a)=max⁡a′r(a′)−r(a)>0\Delta(a) = \max_{a'} r(a') - r(a) > 0 be the reward gap of a suboptimal action aa. As β→0\beta \to 0, how fast does π(a)/πref(a)\pi(a) / \pi_{\textrm{ref}}(a) vanish under the forward penalty, and how fast under the reverse penalty?
  3. For the five-action bandit p_ref, r, compute the forward optimum by bisection on mm. For each penalty, find the β\beta at which the optimum's expected reward is 2.92.9, and compare the two optima action by action. Which actions receive more probability under the forward penalty, and how does this match Section 15.3.3.5?

Discussions