15.2 Trust Regions and Proximal Policy Optimization

The agents of Section 14.9 and Section 15.1 collect eight episodes, take one gradient step, and throw the batch away. Once the agent balances the pole well, those eight episodes are four thousand steps of experience, and all of it informs a single update. The step is also unguarded. Nothing stops a large update from moving the policy a long way, and the next batch is then collected by whatever policy that update produced. Can we take several steps on one batch, and how far may they go?

The answer starts with a fact about parameters. The same change of the parameters can leave a policy's behavior almost unchanged or change it completely, depending on where it starts, so a step size in parameter space does not control the quantity that matters, the change in behavior. In 2015 John Schulman and colleagues made that change the thing to control. Trust Region Policy Optimization (TRPO) bounds the divergence between the old and the new action distributions at the visited states, guided by a theorem on how much improvement such a step guarantees (Schulman et al., 2015). Two years later Proximal Policy Optimization (PPO) replaced the constraint by a clipped objective that any gradient optimizer can run (Schulman et al., 2017). PPO became the default policy-gradient method, from simulated robots to the fine-tuning of language models on human feedback (Ouyang et al., 2022).

This section builds both. A two-action policy shows why parameter distance is the wrong quantity. A change of measure then lets a batch collected by the old policy evaluate a new one, exactly but with a variance that grows with the episode length, and keeping one ratio per step makes the reuse affordable. A short lemma says what that approximation leaves out; TRPO bounds the error and PPO clips it. On CartPole we then measure how many environment steps reuse saves, what goes wrong without the clip, and which numbers to watch while a policy trains.

import gymnasium as gym
torch.set_num_threads(1)

torch.set_num_threads(1) keeps PyTorch from spreading the small matrix products of these networks over many cores, which only slows them down.

15.2.1 Parameter Space versus Policy Space#

Since we update the parameters of the policy, we should ask what a parameter update does to the policy itself. A family of policies with a single parameter θ\theta and two actions answers it; the example comes from Joshua Achiam's lectures on policy optimization (Achiam, 2017). Let

πθ(a)={σ(θ)a=11−σ(θ)a=2,where σ(θ)=11+e−θ.(15.2.1)\pi_\theta(a) = \begin{cases} \sigma(\theta) & a = 1 \\ 1 - \sigma(\theta) & a = 2, \end{cases} \qquad \textrm{where } \sigma(\theta) = \frac{1}{1 + e^{-\theta}}. \tag{15.2.1}

Take two parameter updates of the same size, Δθ=2\Delta\theta = 2, from two different starting points:

πθ=0(a=1)=σ(0)=0.50 → Δθ=2  σ(2)=0.88,πθ=6(a=1)=σ(6)=0.9975 → Δθ=2  σ(8)=0.9997.\begin{aligned} \pi_{\theta=0}(a{=}1) &= \sigma(0) = 0.50 \ \xrightarrow{\ \Delta\theta = 2\ }\ \sigma(2) = 0.88, \\ \pi_{\theta=6}(a{=}1) &= \sigma(6) = 0.9975 \ \xrightarrow{\ \Delta\theta = 2\ }\ \sigma(8) = 0.9997. \end{aligned}

The first update takes the agent from indifference between the two actions to a strong preference for one of them. The second changes nothing that an observer of the agent could detect. The slope of the map from parameter to policy says why: σ′(θ)=σ(θ)(1−σ(θ))\sigma'(\theta)=\sigma(\theta)(1-\sigma(\theta)) is 0.250.25 at θ=0\theta=0 and about 0.00250.0025 at θ=6\theta=6. Figure 15.2.1 draws both updates.

Figure 15.2.1:

Two parameter updates of the same size, Δθ=2\Delta\theta = 2. Left: the map πθ(a=1)=σ(θ)\pi_\theta(a{=}1) = \sigma(\theta) with both updates and the slopes at their starting points. Right: the two action distributions before and after each update.

This difference makes on-policy training fragile. A large noisy update near θ=0\theta=0 can push the policy into saturation. There the frequently chosen action has an almost-zero score, ∇θlog⁡πθ(a=1)=1−σ(θ)≈0.0025\nabla_\theta \log \pi_\theta(a{=}1) = 1 - \sigma(\theta) \approx 0.0025 at θ=6\theta = 6, while the other action has a score near −1-1 but is sampled once in four hundred steps. Later on-policy batches then carry too little evidence to reverse the update. A limit on the Euclidean length of the parameter step does not prevent this, because the same length is harmless at θ=6\theta = 6 and drastic at θ=0\theta = 0.

An update should therefore limit a distance between policies rather than between parameters. Within such a limit the optimizer may take a long parameter step where it changes the policy little, and, as we will see, it may take several steps on the same batch.

15.2.2 Importance Sampling#

15.2.2.1 The Change of Measure#

Every estimator since Section 14.7 has used trajectories sampled from the current policy, so a batch became useless after one gradient step. Suppose instead that the batch was collected by an earlier policy πθold\pi_{\theta_{\textrm{old}}}. Can it still tell us how well an updated policy πθ\pi_\theta does?

Importance sampling gives an exact answer. For any function ff of trajectories,

Eτ∼P(⋅; θ)[f(τ)]=∑τP(τ;θ) f(τ)=∑τP(τ;θold) P(τ;θ)P(τ;θold) f(τ)=Eτ∼P(⋅; θold)[P(τ;θ)P(τ;θold) f(τ)],(15.2.2)\begin{aligned} \mathbb{E}_{\tau \sim P(\cdot;\, \theta)} \big[ f(\tau) \big] &= \sum_\tau P(\tau; \theta)\, f(\tau) = \sum_\tau P(\tau; \theta_{\textrm{old}})\ \frac{P(\tau; \theta)}{P(\tau; \theta_{\textrm{old}})}\, f(\tau) \\ &= \mathbb{E}_{\tau \sim P(\cdot;\, \theta_{\textrm{old}})} \Big[ \frac{P(\tau; \theta)}{P(\tau; \theta_{\textrm{old}})}\, f(\tau) \Big], \end{aligned} \tag{15.2.2}

valid whenever every trajectory the new policy can produce has positive probability under the old one. Softmax policies satisfy this condition, because they never assign zero probability to an action. Applied with f=Rf = R, the return, the identity rewrites the objective as an expectation under the old policy:

J(θ)=Eτ∼P(⋅; θ)[R(τ)]=Eτ∼P(⋅; θold)[P(τ;θ)P(τ;θold) R(τ)].(15.2.3)J(\theta) = \mathbb{E}_{\tau \sim P(\cdot;\, \theta)} \big[ R(\tau) \big] = \mathbb{E}_{\tau \sim P(\cdot;\, \theta_{\textrm{old}})} \Big[ \frac{P(\tau; \theta)}{P(\tau; \theta_{\textrm{old}})}\, R(\tau) \Big]. \tag{15.2.3}

Thus data from the old policy, each trajectory weighted by its likelihood ratio, estimate the new policy's return without bias. The probability of a trajectory is a product of the start-state probability, the policy's action probabilities and the environment's transition probabilities, as in Section 14.7. In the ratio everything but the policy cancels, so the weight needs no model of the environment:

P(τ;θ)P(τ;θold)=∏t=0T−1πθ(at∣st)πθold(at∣st).(15.2.4)\frac{P(\tau; \theta)}{P(\tau; \theta_{\textrm{old}})} = \prod_{t=0}^{T-1} \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\theta_{\textrm{old}}}(a_t \mid s_t)}. \tag{15.2.4}

15.2.2.2 The Exploding Product#

The estimator is unbiased, but its variance grows with the length of the episode. Consider a policy that ignores the state, collects data with πθold=(0.5,0.5)\pi_{\theta_{\textrm{old}}} = (0.5, 0.5), and is evaluated at πθ=(0.6,0.4)\pi_\theta = (0.6, 0.4). Each factor of (15.2.4) is 1.21.2 or 0.80.8 with equal probability, so its mean is 11 and its mean square is (1.44+0.64)/2=1.04(1.44 + 0.64)/2 = 1.04. The factors of different steps are independent, so the trajectory weight WTW_T of an episode of TT steps has mean 11 and variance

Var[WT]=1.04T−1,\textrm{Var}[W_T] = 1.04^T - 1,

which is about 0.50.5 for T=10T = 10, about 5050 for T=100T = 100 and about 3×1083 \times 10^8 for CartPole's 500500 steps. A policy that differs from the data's policy by ten percentage points per decision thus cannot be evaluated from whole CartPole episodes: a handful of trajectories with large weights decide the estimate.

15.2.2.3 The Per-Step Surrogate#

The reward at step tt depends only on the actions taken up to step tt, so the exact correction needs only the ratios ρ0⋯ρt\rho_0 \cdots \rho_t for that reward, where

ρt(θ)=πθ(at∣st)πθold(at∣st).(15.2.5)\rho_t(\theta) = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\theta_{\textrm{old}}}(a_t \mid s_t)}. \tag{15.2.5}

The product ρ0⋯ρt−1\rho_0 \cdots \rho_{t-1} of the earlier ratios corrects for the states: it turns the old policy's distribution of sts_t into the new policy's. Dropping it, and keeping only ρt\rho_t for the action at sts_t, gives a weight whose variance no longer grows with tt. This one approximation evaluates the new policy's actions at the old policy's states. With an advantage estimate A^ti\hat{A}_t^i for step tt of trajectory ii, the resulting surrogate objective averages over all N=∑iTiN = \sum_i T_i steps of a batch of nn trajectories:

L^(θ)=1N∑i=1n∑t=0Ti−1ρti(θ) A^ti.(15.2.6)\hat{L}(\theta) = \frac{1}{N} \sum_{i=1}^n \sum_{t=0}^{T_i-1} \rho_t^i(\theta)\ \hat{A}_t^i. \tag{15.2.6}

The average over steps rather than over trajectories is what the code computes, and it makes the divergence constraint below a mean over states. At θ=θold\theta = \theta_{\textrm{old}} every ratio equals one and ∇θρt=∇θlog⁡πθ(at∣st)\nabla_\theta \rho_t = \nabla_\theta \log \pi_\theta(a_t \mid s_t), so the gradient of L^\hat{L} there points in the same direction as the estimator of Section 14.8: each score weighted by its advantage, with the factor γt\gamma^t dropped, as every implementation since then has done. With advantages standardized to mean zero, L^(θold)=0\hat{L}(\theta_{\textrm{old}}) = 0 exactly. Away from θold\theta_{\textrm{old}} the surrogate becomes less accurate, and the next question is how far it can be trusted.

15.2.3 Trust Regions#

15.2.3.1 The Performance Difference Lemma#

The surrogate evaluates the new policy's actions at the old policy's states. To see what this substitution changes, we compare the two returns exactly. Write Aold(s,a)=Qπθold(s,a)−Vπθold(s)A^{\textrm{old}}(s,a)=Q^{\pi_{\theta_{\textrm{old}}}}(s,a)-V^{\pi_{\theta_{\textrm{old}}}}(s) for the old policy's advantage: how much better action aa is than the old policy's average at ss, when the old policy acts afterward. The following lemma holds for episodes that end at a terminal state, and for continuing tasks with γ<1\gamma \lt 1. Our CartPole runs bootstrap at the 500-step time limit, as in Section 14.9, so the objective they optimize is the continuing one.

Proposition (performance difference lemma, Kakade and Langford (2002)).

J(θ)−J(θold)=Eτ∼P(⋅; θ)[∑t≥0γt Aold(st,at)].(15.2.7)J(\theta) - J(\theta_{\textrm{old}}) = \mathbb{E}_{\tau \sim P(\cdot;\, \theta)} \Big[ \sum_{t \geq 0} \gamma^t\, A^{\textrm{old}}(s_t, a_t) \Big]. \tag{15.2.7}

Proof. Write VV for VπθoldV^{\pi_{\theta_{\textrm{old}}}}. Along any trajectory the sum ∑tγt(rt+γV(st+1)−V(st))\sum_t \gamma^t \big( r_t + \gamma V(s_{t+1}) - V(s_t) \big) telescopes: the interior VV terms cancel in pairs, and the last one is zero at a terminal state or vanishes as t→∞t \to \infty when γ<1\gamma \lt 1. What remains is R(τ)−V(s0)R(\tau) - V(s_0). Now take expectations under τ∼P(⋅; θ)\tau \sim P(\cdot;\, \theta). Given (st,at)(s_t, a_t), the expectation of rt+γV(st+1)r_t + \gamma V(s_{t+1}) over the next state is Qπθold(st,at)Q^{\pi_{\theta_{\textrm{old}}}}(s_t, a_t), by the Bellman equation of the old policy, so the term at step tt becomes γt E[Aold(st,at)]\gamma^t\, \mathbb{E}\big[ A^{\textrm{old}}(s_t, a_t) \big]. On the other side, E[R(τ)]=J(θ)\mathbb{E}[R(\tau)] = J(\theta), and E[V(s0)]=J(θold)\mathbb{E}[V(s_0)] = J(\theta_{\textrm{old}}) because both policies draw s0s_0 from the same start distribution. ■\blacksquare

The lemma says that the new policy improves by the old policy's advantages, summed along the new policy's own trajectories. Grouping its terms by state makes the comparison with the surrogate exact. Let dγπ(s)=(1−γ)∑t≥0γtPr⁡(st=s)d^{\pi}_\gamma(s) = (1 - \gamma) \sum_{t \geq 0} \gamma^t \Pr(s_t = s) be the discounted state-occupancy distribution of Section 14.7, the distribution of states a policy visits with step tt weighted by γt\gamma^t. Then

J(θ)−J(θold)=11−γ∑sdγπθ(s)∑aπθ(a∣s) Aold(s,a).J(\theta) - J(\theta_{\textrm{old}}) = \frac{1}{1-\gamma} \sum_s d^{\pi_\theta}_\gamma(s) \sum_a \pi_\theta(a \mid s)\, A^{\textrm{old}}(s, a).

The surrogate computes this sum with the old policy's occupancy dγπθoldd^{\pi_{\theta_{\textrm{old}}}}_\gamma in place of the new one's; that substitution is its only error. The error depends on how much the state distribution moves, and that depends on how much the policy changes, not on how far the parameters move.

15.2.3.2 The Monotonic-Improvement Bound#

Replacing the occupancy in the last display defines the population version of the surrogate,

Lˉ(θ)=11−γ∑sdγπθold(s)∑aπθ(a∣s) Aold(s,a),(15.2.8)\bar{L}(\theta) = \frac{1}{1-\gamma} \sum_s d^{\pi_{\theta_{\textrm{old}}}}_\gamma(s) \sum_a \pi_\theta(a \mid s)\, A^{\textrm{old}}(s, a), \tag{15.2.8}

of which L^\hat{L} is the sampled estimate, without the factor γt\gamma^t. Since the old policy's advantage averages to zero at every state, Lˉ(θold)=0\bar{L}(\theta_{\textrm{old}}) = 0. How far may θ\theta move before Lˉ\bar{L} stops predicting the improvement? The answer is a bound in terms of the largest change of the action distribution at any state.

Proposition (Kakade and Langford (2002), Schulman et al. (2015)). For γ<1\gamma \lt 1 and Amax⁡=max⁡s,a∣Aold(s,a)∣A_{\max} = \max_{s, a} \lvert A^{\textrm{old}}(s, a) \rvert,

J(θ) ≥ J(θold)+Lˉ(θ)− 4γAmax⁡(1−γ)2 max⁡s DKL(πθold(⋅∣s) ∥ πθ(⋅∣s)).(15.2.9)\begin{aligned} J(\theta)\ &\geq\ J(\theta_{\textrm{old}}) + \bar{L}(\theta) \\ &\quad -\ \frac{4 \gamma A_{\max}}{(1-\gamma)^2}\ \max_s\, D_{\textrm{KL}}\big( \pi_{\theta_{\textrm{old}}}(\cdot \mid s)\ \Vert\ \pi_\theta(\cdot \mid s) \big). \end{aligned} \tag{15.2.9}

The surrogate is right up to a penalty proportional to the largest Kullback--Leibler divergence between the old and new action distributions at any state. Exercise 6 derives it by running the two policies side by side with coupled actions. Both sides of the bound equal J(θold)J(\theta_{\textrm{old}}) at θ=θold\theta = \theta_{\textrm{old}}, so any step that raises the right-hand side raises the true return: maximizing the bound gives monotonic improvement. The constant is too large to use as it stands. At γ=0.99\gamma = 0.99 it is 4⋅0.99/0.012≈40,0004 \cdot 0.99 / 0.01^2 \approx 40{,}000 times Amax⁡A_{\max}, so the steps it certifies are tiny.

TRPO keeps the shape of the bound and replaces its pieces by quantities a batch can estimate. It maximizes the sampled surrogate subject to a budget ΔKL\Delta_{\textrm{KL}} on the mean divergence over the batch's states,

max⁡θ L^(θ)subject to 1N∑i,tDKL(πθold(⋅∣sti) ∥ πθ(⋅∣sti))≤ΔKL,(15.2.10)\begin{aligned} \max_\theta\ &\hat{L}(\theta) \\ \textrm{subject to}\ &\frac{1}{N}\sum_{i,t} D_{\textrm{KL}}\big( \pi_{\theta_{\textrm{old}}}(\cdot \mid s_t^i)\ \Vert\ \pi_\theta(\cdot \mid s_t^i) \big) \leq \Delta_{\textrm{KL}}, \end{aligned} \tag{15.2.10}

with a mean in place of the maximum over all states and a chosen budget, typically ΔKL=0.01\Delta_{\textrm{KL}} = 0.01, in place of the conservative coefficient. It solves this problem with a second-order method, which exercise 7 builds from the pieces of this section. Figure 15.2.2 shows why the constraint lives in policy space.

Figure 15.2.2:

Bounding a policy update. Left: the surrogate LL is tangent to the true objective JJ at θold\theta_{\textrm{old}} but becomes inaccurate after a large policy change. The unconstrained maximizer of LL lowers JJ from 0.820.82 to −0.38-0.38, whereas the best point inside the shaded trust region, DKL≤ΔKLD_{\textrm{KL}} \leq \Delta_{\textrm{KL}} (for one parameter an interval θold±δ\theta_{\textrm{old}} \pm \delta), raises it to 1.521.52. Right: for a three-action softmax policy, the second-order approximation 12Δθ⊤FΔθ≤0.02\frac{1}{2}\Delta\theta^\top F \Delta\theta \leq 0.02 of the divergence constraint, with FF the Hessian of the divergence at θold\theta_{\textrm{old}}, is an ellipse in parameter space. Two parameter steps of equal Euclidean length change the policy by divergences of 0.0090.009 and 0.0620.062: the same parameter distance moves the policy about seven times as far in one direction as in the other.

15.2.3.3 The Clipped Objective#

PPO replaces the constrained second-order problem by a first-order objective with a built-in limit. It does not clip the ratios themselves; it stops rewarding a sample once its ratio has moved beyond a band of half-width ϵclip\epsilon_{\textrm{clip}} around one:

LCLIP(θ)=1N∑i,tmin⁡(ρti(θ) A^ti,clip(ρti(θ), 1−ϵclip, 1+ϵclip) A^ti).(15.2.11)\begin{aligned} L^{\textrm{CLIP}}(\theta) &= \frac{1}{N} \sum_{i,t} \min\Big( \rho_t^i(\theta)\, \hat{A}_t^i, \\ &\qquad\qquad \textrm{clip}\big(\rho_t^i(\theta),\ 1-\epsilon_{\textrm{clip}},\ 1+\epsilon_{\textrm{clip}}\big)\, \hat{A}_t^i \Big). \end{aligned} \tag{15.2.11}

Consider one sample. If A^t>0\hat{A}_t > 0, its contribution grows with ρt\rho_t only until ρt=1+ϵclip\rho_t = 1+\epsilon_{\textrm{clip}}; beyond that the clipped term is the smaller one and its gradient is zero. If A^t<0\hat{A}_t \lt 0, the threshold is 1−ϵclip1-\epsilon_{\textrm{clip}}. With the usual ϵclip=0.2\epsilon_{\textrm{clip}} = 0.2 and an action the old policy chose with probability 0.50.5, a sample with positive advantage stops rewarding the update once the new policy gives that action probability 0.60.6; with negative advantage, once the probability falls to 0.40.4. The minimum makes the limit one-sided: a change that lowers the objective is always counted, while further movement in the favorable direction adds nothing. Figure 15.2.3 plots one sample's contribution for both signs of the advantage.

Figure 15.2.3:

One sample's contribution to the clipped objective (15.2.11) against the ratio ρt\rho_t. For positive advantage it stops increasing above 1+ϵclip1+\epsilon_{\textrm{clip}}; for negative advantage it stops increasing below 1−ϵclip1-\epsilon_{\textrm{clip}}. On the other side of one the minimum keeps the unclipped term, so a change that lowers the objective is never hidden.

Because the ratio itself is not clipped, it can still leave the band, for two reasons. All samples share the network's parameters, so a step taken for one sample moves the ratios of the others; and Adam's momentum keeps moving the parameters for a few steps after a sample's gradient has become zero. Engstrom et al. (2020) measured that PPO's ratios do leave the band and that its divergence per update is not held below any fixed budget. The clip is therefore an incentive rather than a constraint, and unlike (15.2.9) it guarantees no improvement. What it does permit is several passes of optimization over one batch without rewarding ever larger changes of individual action probabilities.

15.2.3.4 The Entropy Bonus#

Implementations often add a small entropy bonus, a weight entropy_coef times the mean entropy of the action distributions at the batch's states. The bonus pushes probabilities away from zero and one, where, as in the two-action example, the frequently chosen action has a small score and recovery is slow. The entropy of a distribution over KK actions is log⁡K\log K minus its divergence from the uniform distribution, so the bonus is a penalty on the distance from the uniform policy.

15.2.4 PPO in Practice#

15.2.4.1 The Advantage Estimate#

Any advantage estimate can fill the place of A^\hat{A} in (15.2.11). We use generalized advantage estimation (GAE) from Section 15.1: Batch.gae sums the TD errors δt=rt+γV^(st+1)−V^(st)\delta_t = r_t + \gamma \hat{V}(s_{t+1}) - \hat{V}(s_t) of the critic backward through each episode with weights (γλ)k(\gamma\lambda)^k, and λ\lambda sets how far ahead each advantage looks. That section found the error of this estimate smallest near λ=0.9\lambda = 0.9 to 0.950.95; 0.950.95 is also the setting of the PPO paper. The advantages are computed with the critic as it stands before it is fit to the batch, the order of the GAE paper (Schulman et al., 2016). td_weight of Section 15.1 used the opposite order, because its actor's weight was the one-step TD error, which rests entirely on the critic. At λ=0.95\lambda = 0.95 the advantage is mostly the batch's own sampled rewards and leans little on the critic, so the order changes no result of this section, and we follow the paper.

15.2.4.2 The Implementation#

We keep the CartPole setup of Section 15.1. The agent is ActorCritic.mlp(4, 2) of Section 14.9: a policy network and a value network, each with one hidden layer of 64 tanh units and its own Adam optimizer with learning rate 10−210^{-2}. Each update collects a batch of eight episodes, and the critic takes critic_steps = 20 regression passes on it. Three hyperparameters are new: num_epochs = 20 passes of the actor over each batch, the half-width epsilon_clip = 0.2 of the band, and the entropy weight entropy_coef = 0.01. Twenty passes is also the CartPole setting of the RL Baselines3 Zoo (Raffin et al., 2021), but the zoo's learning rate is 10−310^{-3}, ten times smaller than ours. At our rate each pass moves the policy far, which makes training fast and is the setting in which the clip matters; the ablation below shows what happens without it.

gamma, lam, num_updates, batch_episodes = 0.99, 0.95, 60, 8
num_seeds, num_epochs, critic_steps = 8, 20, 20
epsilon_clip, entropy_coef = 0.2, 0.01
def cartpole_agent(seed):
    return d2l.ActorCritic.mlp(4, 2, seed=seed)

The per-sample objective is passed to the update as a function. clipped_surrogate is (15.2.11), and plain_surrogate, the term ρtA^t\rho_t \hat{A}_t alone, serves the ablation below; both take the half-width ϵclip\epsilon_{\textrm{clip}} of the band, which only the first one uses.

def clipped_surrogate(rho, adv, epsilon):
    """PPO's per-sample objective eq_ppo_clip: min(rho A, clip(rho) A)."""
    return torch.minimum(rho * adv,
                         rho.clamp(1 - epsilon, 1 + epsilon) * adv)

def plain_surrogate(rho, adv, epsilon):
    """The unclipped per-sample objective rho A."""
    return rho * adv

ppo_epochs receives a batch's states and actions together with the two quantities frozen before reuse: the advantages and the collecting policy's log-probabilities logp_old. It takes num_epochs steps of the actor's optimizer opt_pi on the negated mean surrogate minus the entropy bonus. The entropy needs the whole distribution at each state, so the update computes the log-softmax over all actions once and reads log⁡πθ(at∣st)\log\pi_\theta(a_t \mid s_t) from it. Before each pass it records one row of diagnostics: the fraction of ratios outside the band, the sample mean of log⁡πθold−log⁡πθ\log\pi_{\theta_{\textrm{old}}}-\log\pi_\theta, and the mean entropy. The second number is called the approximate KL: its expectation under the old policy is the divergence DKL(πθold∥πθ)D_{\textrm{KL}}(\pi_{\theta_{\textrm{old}}} \Vert \pi_\theta) at the visited states, although on a finite batch it can come out negative. Since the row is recorded before the pass, the first row is always zero, zero and the old policy's entropy.

def ppo_epochs(ac, obs, act, adv, logp_old, epsilon, num_epochs,
               entropy_coef=0.01, surrogate=clipped_surrogate):
    """num_epochs passes on the mean surrogate plus an entropy bonus, on one
    frozen batch of states and actions; returns [num_epochs, 3] numpy
    diagnostics, recorded before each pass: fraction of ratios outside the
    band, approximate KL, mean policy entropy."""
    obs, act, adv, logp_old = (torch.as_tensor(x)
                               for x in (obs, act, adv, logp_old))
    diag = []
    for _ in range(num_epochs):
        logp_all = torch.log_softmax(ac.policy(obs), dim=-1)
        logp = logp_all.gather(-1, act[:, None]).squeeze(-1)
        rho = torch.exp(logp - logp_old)
        entropy = -(logp_all.exp() * logp_all).sum(-1).mean()
        loss = -surrogate(rho, adv, epsilon).mean() - entropy_coef * entropy
        ac.opt_pi.zero_grad()
        loss.backward()
        ac.opt_pi.step()
        diag.append(torch.stack([((rho - 1).abs() > epsilon).float().mean(),
                                 (logp_old - logp).mean(), entropy]).detach())
    return torch.stack(diag).numpy()

The training loop is the actor-critic loop of Section 15.1 with its single actor step replaced by ppo_epochs and the advantages computed before the critic's passes. rollout plays eight episodes into a Batch. The loop then computes the advantages with Batch.gae and the current critic, and standardizes them over the batch with standardize. It also reads logp_old with log_prob_np, which returns log⁡π(a∣s)\log \pi(a \mid s) for given states and actions as a NumPy array. Next the critic takes its regression passes toward the λ\lambda-return target with Batch.lambda_return of Section 15.1 and fit_value of Section 14.9, and finally the actor takes its passes. Each update yields the environment steps spent so far and the batch's mean return. The diagnostics of each batch go to a list diag that the caller passes in; CLIPPED, KL and ENTROPY name their three columns.

CLIPPED, KL, ENTROPY = 0, 1, 2   # the columns of ppo_epochs' diagnostics

def train_ppo(seed, ac, diag, surrogate=clipped_surrogate,
              num_epochs=num_epochs):
    """PPO on CartPole: freeze the advantages and the collecting policy's
    log-probs, then take num_epochs surrogate passes on each batch. Appends
    each batch's diagnostics to diag; yields (env steps, mean return)."""
    rng, env = np.random.default_rng(seed), gym.make('CartPole-v1')
    env.reset(seed=seed)
    steps = 0
    for _ in range(num_updates):
        b = d2l.rollout(env, ac.act, batch_episodes, rng)
        adv = d2l.standardize(b.gae(ac.value_np, gamma, lam))  # pre-fit critic
        logp_old = ac.log_prob_np(b.obs, b.act)
        for _ in range(critic_steps):   # fresh lambda-return target, per pass
            d2l.fit_value(ac, b.obs, b.lambda_return(ac.value_np, gamma, lam))
        diag.append(ppo_epochs(ac, b.obs, b.act, adv, logp_old, epsilon_clip,
                               num_epochs, entropy_coef, surrogate))
        steps += len(b)
        yield steps, float(b.episode_returns().mean())

15.2.4.3 Reuse against Environment Steps#

How many environment steps does reuse save? We train clipped PPO with one, four and twenty passes per batch, on eight seeds each, stop each run once it has spent 50,000 environment steps, and plot the batch's mean return against the steps spent so far. With one pass every ratio equals one and the clip never acts, so that arm is close to the λ\lambda sweep of Section 15.1, with an entropy bonus, no cap on the gradient, and the advantages computed before the critic's passes. As there, d2l.on_grid places each run on a common grid of steps. These runs need no diagnostics, so each gets an empty list.

budget = 50_000
grid = np.arange(0, budget + 1, 1000)
reuse = {}
for e in (1, 4, 20):
    runs_e = []
    for s in range(num_seeds):
        run = []
        for row in train_ppo(s, cartpole_agent(s), [], num_epochs=e):
            run.append(row)                   # (env steps, mean return)
            if row[0] >= budget:
                break
        runs_e.append(np.array(run))
    reuse[f'{e} epoch' + 's' * (e > 1)] = d2l.on_grid(runs_e, grid, 1)

Plotting the interpolated return curves in reuse against grid shows how batch reuse trades extra gradient passes for fewer environment interactions:

d2l.plot_curves(reuse, xlabel='environment steps',
                ylabel='mean return of the batch', x=grid, reference=500)

Reusing each batch for four epochs reaches the ceiling in about half the environment steps that one epoch needs, roughly 25,000 against 50,000 or more, and in about half the updates; within the 50,000-step budget the one-epoch median stays just short of the ceiling. Going on to twenty epochs changes little by comparison, and no clipped run collapses. The gain comes from the batch: a batch of a few thousand steps holds more information than one gradient step can extract, and the clip lets the optimizer take several steps without moving any action probability too far.

15.2.4.4 The Clipping Ablation#

Four passes are enough to collect most of the gain; at our learning rate, twenty passes move the policy a long way within one batch. Does the clip matter there? We train twenty-epoch PPO on the same eight seeds with the clip on, keeping the trained agents for later checks and the full diagnostics for the next subsection:

arms = {'clipped (PPO)': clipped_surrogate, 'no clip': plain_surrogate}
agents = {arm: [cartpole_agent(s) for s in range(num_seeds)] for arm in arms}
runs, diag = {}, {arm: [] for arm in arms}
runs['clipped (PPO)'] = np.array(
    [list(train_ppo(s, agents['clipped (PPO)'][s], diag['clipped (PPO)']))
     for s in range(num_seeds)])

Then the control, identical in every line except that the surrogate is unclipped. Each arm's diagnostics are then reshaped to (seed, update, epoch, column):

runs['no clip'] = np.array(
    [list(train_ppo(s, agents['no clip'][s], diag['no clip'],
                    surrogate=plain_surrogate))
     for s in range(num_seeds)])
diag = {arm: np.reshape(d, (num_seeds, num_updates, num_epochs, 3))
        for arm, d in diag.items()}

Two criteria summarize each run. A run holds the task if its batch return, once it first reaches 475, never again falls below 250, half the maximum. A run ends dead if its last ten updates average below a return of 100:

def holds(ret):   # reaches 475, then never falls below 250 again
    hit = np.flatnonzero(ret >= 475)
    return len(hit) > 0 and ret[hit[0]:].min() >= 250

for name, r in runs.items():
    held = sum(holds(ret) for ret in r[:, :, 1])
    dead = r[:, -10:, 1].mean(axis=1) < 100
    print(f'{name:>13}: {held} of {num_seeds} seeds hold the task, '
          f'{int(dead.sum())} end dead')
clipped (PPO): 8 of 8 seeds hold the task, 0 end dead
      no clip: 0 of 8 seeds hold the task, 4 end dead

Plotting the batch return trajectories r[:, :, 1] across all updates contrasts the steady plateau of 'clipped (PPO)' with the collapse of 'no clip':

d2l.plot_curves({name: r[:, :, 1] for name, r in runs.items()},
                xlabel='update', ylabel='mean return of the batch',
                reference=500)

At twenty epochs and a learning rate of 10−210^{-2}, every clipped seed reaches the ceiling and holds it. Without the clip, hardly any seed holds it, and some end dead. Over 64 seeds outside the notebook, about one run in twenty holds the task and about half end dead, most of them at a return of about 9, the length of an episode in which the cart is pushed the same way at every step. Eight seeds are too few to show these rates reliably, and the count of dead runs printed above can fall well short of half. Repeated unclipped passes drive the policy into saturation, where, as in the two-action example, the gradient of the chosen action's log-probability is small; the next batches are then collected by the saturated policy, and they rarely contain the actions that would reverse it. The PPO paper's own ablation found the same: its variant with neither a clip nor a penalty was the worst of all those it tested (Schulman et al., 2017). The large learning rate is what makes the clip necessary. At an actor learning rate of 10−310^{-3}, ten times smaller, unclipped PPO no longer collapses on any of ten seeds and reaches the ceiling as fast as clipped PPO, and at 3×10−43 \times 10^{-4} the clip almost never acts. Both rates are slower than ours, however: they need about 35,000 to 40,000 and about 85,000 to 90,000 steps to the ceiling, against about 24,000 here. The large rate makes training fast, and the clip makes the large rate safe.

How often does the clip act? Each update checks every sample once per epoch, and the first epoch begins with ρt=1\rho_t=1 for every sample. We report the fraction of all per-epoch checks outside the band and the same fraction at the last epoch of each batch:

for name, d in diag.items():
    print(f'{name:>13}: ratio checks outside the band: '
          f'{d[..., CLIPPED].mean():.1%} across all epochs')
    print(f'{"":>13}  {d[:, :, -1, CLIPPED].mean():.1%} at the last epoch '
          f'of each batch')
clipped (PPO): ratio checks outside the band: 5.3% across all epochs
               5.0% at the last epoch of each batch
      no clip: ratio checks outside the band: 17.6% across all epochs
               25.1% at the last epoch of each batch

For the clipped runs both counts are near one check in twenty. In the unclipped control ratios leave the band several times as often, and more often at the last epoch of a batch than on average, because nothing stops them from moving further at every pass.

15.2.4.5 Training Diagnostics#

Section 14.9 showed that the value of a policy-gradient loss says nothing about progress: it stays near zero while the return climbs from 20 to 500. What deserves watching are measurements of the update itself, and diag already holds them for every run, seed, update and epoch. We first average over the updates and look at one batch's twenty epochs:

clipped = diag['clipped (PPO)']
d2l.plot_curves({'ratio checks outside the band':
                 clipped[..., CLIPPED].mean(1)},
                xlabel='epoch within the batch', ylabel='fraction',
                x=np.arange(1, num_epochs + 1))
kl = np.median(clipped[..., KL].mean(1), axis=0)
print(f'approximate KL: peak {kl.max():.4f} at epoch {kl.argmax() + 1}, '
      f'{kl[-1]:.4f} at epoch {num_epochs}')
for name, d in diag.items():
    print(f'{name:>13}: approximate KL at the last epoch, median '
          f'{np.median(d[:, :, -1, KL]):.3f}')
approximate KL: peak 0.0085 at epoch 6, 0.0053 at epoch 20
clipped (PPO): approximate KL at the last epoch, median 0.003
      no clip: approximate KL at the last epoch, median 0.139

Within a batch the fraction outside the band is exactly zero at the first epoch, where every ratio equals one. It rises to a peak around the fifth or sixth epoch and then falls to about half the peak by the twentieth. The fall comes from the one-sided minimum. A sample whose ratio has left the band on the losing side keeps the gradient of its unclipped term, which pulls the ratio back, while a sample past the band on the winning side gets no gradient and stays where it is. The approximate KL has the same shape and is about ten times smaller; the cell prints its peak. Without the clip the divergence keeps growing at every pass, and at the last epoch of a batch it is typically tens of times the clipped run's.

Across updates, the entropy of the clipped policies tells how decisive they have become:

d2l.plot_curves({name: d[..., ENTROPY].mean(-1) for name, d in diag.items()},
                xlabel='update', ylabel='policy entropy (nats)')
print(f'clipped: entropy {clipped[:, :5, :, ENTROPY].mean():.2f} over the '
      f'first five updates, {clipped[:, -5:, :, ENTROPY].mean():.2f} over the '
      f'last five')
clipped: entropy 0.65 over the first five updates, 0.25 over the last five

The entropy of the clipped runs falls from about 0.650.65 nats to about 0.250.25: the policy becomes more decisive as it learns, and the entropy bonus slows this without stopping it. The unclipped runs lose their entropy much faster, which is the saturation that ends the runs that die.

The summary fractions hide how the ratios are distributed. We take two identical fresh agents at the start of training, where the drift within a batch is largest, give both the same batch with the same frozen advantages and log-probabilities, and take twenty passes with the clip on in one and off in the other, reading every ratio after each pass. A third twin, collector, collects the batch and stays as it is, the old policy of every ratio:

probe = {arm: cartpole_agent(2) for arm in arms}   # twins
collector = cartpole_agent(2)                     # a third twin, kept fresh
env = gym.make('CartPole-v1')
env.reset(seed=2)
batch = d2l.rollout(env, collector.act, batch_episodes,
                    np.random.default_rng(2))
adv = d2l.standardize(batch.gae(collector.value_np, gamma, lam))
logp_old = collector.log_prob_np(batch.obs, batch.act)
rhos = {}
for arm, surrogate in arms.items():
    R = []
    for _ in range(num_epochs):   # one pass at a time, ratios read after
        ppo_epochs(probe[arm], batch.obs, batch.act, adv, logp_old,
                   epsilon_clip, 1, entropy_coef, surrogate)
        R.append(np.exp(probe[arm].log_prob_np(batch.obs, batch.act)
                        - logp_old))
    rhos[arm] = np.array(R)

d2l.plot_hist (Section 27.9) overlays the histograms of the two sets of ratios after the last pass and marks the band edges with dashed lines:

d2l.plot_hist({arm: r[-1] for arm, r in rhos.items()},
              xlabel=rf'ratio $\rho_t(\theta)$ after {num_epochs} passes',
              ylabel='ratio checks',
              vlines=(1 - epsilon_clip, 1 + epsilon_clip))

After twenty passes the clipped agent's ratios stay near one, with a minority beyond the dashed band edges. The unclipped ratios pile up near zero, and most of the others lie far above the band, up to about two or three. A ratio of two or three is 1/πθold(a)1/\pi_{\theta_{\textrm{old}}}(a) for an action that the fresh policy chose with probability a half or a third and the new policy chooses almost always; a ratio near zero belongs to the other action. How much is such a reweighted batch still worth? The effective sample size of nn importance weights answers this, Neff=1/∑jwˉj2N_{\textrm{eff}} = 1 / \sum_j \bar{w}_j^2, where wˉj\bar{w}_j is the ratio of step jj divided by the sum of all the batch's ratios. It equals nn when all weights are equal and one when a single weight dominates.

ess = {}
for arm, r in rhos.items():
    w = r / r.sum(axis=1, keepdims=True)   # normalized weights per epoch
    ess[arm] = 1 / (w ** 2).sum(axis=1) / r.shape[1]
d2l.plot_curves(ess, xlabel='epoch within the batch',
                ylabel='effective sample size / n',
                x=np.arange(1, num_epochs + 1))
print(f'after {num_epochs} epochs the batch is worth '
      + ' vs '.join(f'{v[-1]:.0%} ({k})' for k, v in ess.items())
      + f' of its {len(batch)} steps')
after 20 epochs the batch is worth 97% (clipped (PPO)) vs 55% (no clip) of its 226 steps

With the clip the weights stay nearly equal through the twentieth epoch. Without it the effective sample size falls well below the clipped arm's, to about half the batch. Saturation explains the value. Suppose the new policy picks an action a∗(s)a^*(s) with certainty. A sample at ss then has weight 1/πθold(a∗∣s)1/\pi_{\theta_{\textrm{old}}}(a^* \mid s) if its action was a∗a^*, which happens with probability πθold(a∗∣s)\pi_{\theta_{\textrm{old}}}(a^* \mid s), and weight zero otherwise. The mean weight is one and the mean squared weight is 1/πθold(a∗∣s)1/\pi_{\theta_{\textrm{old}}}(a^* \mid s), so as the batch grows Neff/nN_{\textrm{eff}}/n approaches the harmonic mean of πθold(a∗∣s)\pi_{\theta_{\textrm{old}}}(a^* \mid s) over the visited states. For a fresh policy that is nearly uniform over two actions, that is about one half. To check this we need the probabilities of all actions, not only of the sampled one; action_probs returns them as a NumPy array, and the untrained twin collector is the collecting policy.

def action_probs(ac, obs):
    """pi(.|s) for a numpy batch of states, as numpy."""
    with torch.inference_mode():
        return torch.softmax(ac.policy(torch.as_tensor(obs)), -1).numpy()
p_old = action_probs(collector, batch.obs)     # the collecting policy
p_new = action_probs(probe['no clip'], batch.obs)
a_star = p_new.argmax(axis=1)                  # the unclipped choice
p_star = p_old[np.arange(len(batch)), a_star]
print(f'unclipped policy: median probability of its choice '
      f'{np.median(p_new.max(axis=1)):.3f}')
print(f'harmonic mean of the old probability of that choice: '
      f'{1 / (1 / p_star).mean():.2f}')
unclipped policy: median probability of its choice 0.996
harmonic mean of the old probability of that choice: 0.49

The unclipped policy is close to deterministic, and the harmonic mean lies within about a tenth of the unclipped arm's effective sample size, slightly below it because the policy is not quite deterministic. The effective sample size counts how evenly the weights are spread; it ignores the advantages and the states the new policy would visit, so it complements the divergence and the clip fraction rather than replacing them.

Finally, a trained clipped agent, acting greedily on the most probable action to remove the noise of sampling, should balance the pole to the time limit:

ac, env = agents['clipped (PPO)'][0], gym.make('CartPole-v1')
env.reset(seed=2)
score = d2l.evaluate(env, ac.act_greedy, num_episodes=100)
print(f'greedy mean return over 100 episodes: {score:.0f}')
greedy mean return over 100 episodes: 500

15.2.4.6 Vectorized Collection and Minibatches#

Our loop plays whole episodes in one environment and takes full-batch passes. Production implementations such as cleanrl/ppo.py (Huang et al., 2022) step NN copies of the environment in parallel for a fixed horizon TT, producing an N×TN\times T rectangle of transitions, and cut every episode that is still running at the rectangle's edge. At the cut the critic supplies the value of the unrecorded future, the same bootstrap that Section 14.9 used at CartPole's time limit. We collect one such rectangle with the trained agent, eight environments for 32 steps:

envs = gym.vector.SyncVectorEnv([lambda: gym.make('CartPole-v1')] * 8)
obs, _ = envs.reset(seed=0)
rng, steps = np.random.default_rng(3), []
for _ in range(32):                       # the fixed 32 x 8 rectangle
    u = rng.random((len(obs), 1))         # inverse-CDF sampling, per env
    act = (u > action_probs(ac, obs).cumsum(1)[:, :-1]).sum(1)
    obs, rew, term, trunc, _ = envs.step(act)
    steps.append((rew, term | trunc))
rew, done = map(np.array, zip(*steps))
print(f'a fixed {rew.shape} rectangle of steps, '
      f'{int(done.sum())} episode boundaries inside it')
print(f'V at the cut, the value of the unrecorded future: '
      f'{ac.value_np(obs).round(0)}')
a fixed (32, 8) rectangle of steps, 0 episode boundaries inside it
V at the cut, the value of the unrecorded future: [100. 100. 100. 100. 100. 100. 100. 100.]

The trained agent does not fall within 32 steps, so all eight trajectories end at the cut, and their values are close to 1/(1−γ)=1001/(1-\gamma)=100, the discounted value of balancing forever. Without the bootstrap, GAE would treat each cut as a fall and give the last actions before it large negative advantages. Gymnasium's vector environments also restart a finished episode by themselves: the step after an episode ends returns the first observation of a new episode with reward zero and ignores the action, so implementations mask that step out of the advantages and the loss. Finally, production code shuffles the rectangle into minibatches and takes a few epochs over them, typically four, so each ratio is checked four times rather than twenty; the smaller steps need less memory and add gradient noise. Exercise 5 builds this loop.

Vectorized collection also changes what a sample costs. This chapter counts environment steps, because on a robot arm every step is real. A physics simulator that runs on the GPU steps thousands of copies of a robot at once (Makoviychuk et al., 2021), so a rectangle thousands of environments wide arrives in a fraction of a second, and the cost that matters is wall-clock time. PPO suits this regime, since a very large batch makes each of its few updates accurate. With the simulator's parameters randomized so that the policy transfers to the real machine, a practice called domain randomization (Tobin et al., 2017), legged robots learn to walk in minutes of training (Rudin et al., 2022). This is why PPO remains the default there, although the methods of the following sections need far fewer steps. They win when the steps are real.

PPO lets an agent take several steps on each batch, and on CartPole four epochs reach the ceiling in half the environment steps of one. Its clip limits how far each step moves the action probabilities, but it bounds the path, not the destination. The entropy of the clipped runs still falls from 0.650.65 to 0.250.25 nats, because the objective is still the return with a small entropy bonus, whose optimum is nearly deterministic. Section 15.3 changes the objective instead: it keeps the policy near a fixed reference, which moves the optimum and not only the path.

15.2.5 Summary#

An on-policy batch of thousands of environment steps should inform more than one gradient step, but equal steps in parameter space can change a policy by very different amounts. Importance sampling evaluates a new policy on old data exactly, with a variance that grows exponentially with the episode length; keeping one ratio per step removes that growth and evaluates the new policy's actions at the old policy's states instead. The performance difference lemma shows that this substitution is the surrogate's only error, and TRPO bounds it by constraining the divergence between old and new action distributions. PPO instead clips each sample's contribution to the objective once its ratio leaves a band around one, which lets a few epochs reuse each batch: on CartPole four epochs reach the ceiling in about half the environment steps of one, and the clip keeps a large learning rate from collapsing the policy. The clip fraction, the approximate KL, the entropy and the effective sample size of the ratios show how far each update moved the policy.

15.2.6 Exercises#

  1. Step limits for one logit. ● Take the two-action policy πθ(a=1)=σ(θ)\pi_\theta(a{=}1) = \sigma(\theta) of Figure 15.2.1 and three ways of limiting an update θ→θ+Δ\theta \to \theta + \Delta: a trust region on the divergence, PPO's clip, and a cap on ∣Δ∣|\Delta|.

    1. Expand DKL(πθ∥πθ+Δ)D_{\textrm{KL}}\big(\pi_\theta \Vert \pi_{\theta+\Delta}\big) to second order in Δ\Delta and show that it equals 12σ′(θ) Δ2\frac{1}{2}\sigma'(\theta)\,\Delta^2. Compute the exact divergence of the two updates with Δ=2\Delta = 2 drawn in the figure, from θ=0\theta = 0 and from θ=6\theta = 6. Which of them stays inside a trust region with ΔKL=0.02\Delta_{\textrm{KL}} = 0.02?
    2. Use the second-order form to find the largest ∣Δ∣|\Delta| that this trust region permits at θ=0\theta = 0 and at θ=6\theta = 6. At θ=6\theta = 6, compute the exact divergence of the two steps of that size, one in each direction. Why is the second-order form much less accurate there than at θ=0\theta = 0?
    3. Now let the clip of (15.2.11) with ϵclip=0.2\epsilon_{\textrm{clip}} = 0.2 limit the step, for one sample with positive advantage. The update raises the probability of the sampled action, so Δ>0\Delta > 0 when the sample is a=1a = 1 and Δ<0\Delta \lt 0 when it is a=2a = 2. Find the largest ∣Δ∣|\Delta| over which the clipped objective still increases, for both actions at θ=0\theta = 0 and at θ=6\theta = 6.
    4. Which of the three limits permits large parameter steps where the policy is insensitive to θ\theta and only small ones where it is sensitive? At θ=6\theta = 6, for which sampled action is the clip looser than the trust region, and for which is it tighter?
  2. Exploding product of ratios. A policy that ignores the state collects episodes with πθold\pi_{\theta_{\textrm{old}}} and the data are used to evaluate πθ\pi_\theta. Write WTW_T for the trajectory ratio (15.2.4) of an episode of TT steps.

    1. Show that E[WT]=1\mathbb{E}[W_T] = 1 and Var[WT]=(1+χ2)T−1\textrm{Var}[W_T] = (1 + \chi^2)^T - 1 under the old policy, where χ2=∑a(πθ(a)−πθold(a))2/πθold(a)\chi^2 = \sum_a \big(\pi_\theta(a) - \pi_{\theta_{\textrm{old}}}(a)\big)^2 / \pi_{\theta_{\textrm{old}}}(a). Check the value 1.04T−11.04^T - 1 of the text for πθold=(0.5,0.5)\pi_{\theta_{\textrm{old}}} = (0.5, 0.5) and πθ=(0.6,0.4)\pi_\theta = (0.6, 0.4).
    2. As the number nn of episodes grows, the effective sample size of the weights WTW_T approaches n/E[WT2]n / \mathbb{E}[W_T^2]. For the two policies of (a), for which nn does this limit equal one at T=200T = 200? Simulate one batch of that many episodes (the number of steps with a=1a = 1 in an episode is binomial) and compute its effective sample size. Why does the batch report a much larger effective sample size than the limit? Which of the two describes the variance of the importance-weighted estimate?
    3. The per-step surrogate (15.2.6) weights each step by a single ratio ρt\rho_t. What is the variance of that weight here, and which approximation in (15.2.6) makes it independent of TT?
  3. What the diagnostics estimate. ● Fix a state ss, draw a∼πθold(⋅∣s)a \sim \pi_{\theta_{\textrm{old}}}(\cdot \mid s), and let ρ=πθ(a∣s)/πθold(a∣s)\rho = \pi_\theta(a \mid s) / \pi_{\theta_{\textrm{old}}}(a \mid s).

    1. The approximate KL of ppo_epochs averages k1=−log⁡ρk_1 = -\log \rho over the batch. Show that E[k1]=DKL(πθold(⋅∣s)∥πθ(⋅∣s))\mathbb{E}[k_1] = D_{\textrm{KL}}\big(\pi_{\theta_{\textrm{old}}}(\cdot \mid s) \Vert \pi_\theta(\cdot \mid s)\big). Then show that k3=(ρ−1)−log⁡ρk_3 = (\rho - 1) - \log \rho has the same expectation and is nonnegative for every sample. Expand both estimators to second order in ρ−1\rho - 1. Why does k3k_3 have a much smaller variance than k1k_1 when the policy changes little? cleanrl/ppo.py logs both.
    2. Problem 2b uses the limit n/E[w2]n / \mathbb{E}[w^2] of the effective sample size of nn independent weights ww with E[w]=1\mathbb{E}[w] = 1. Derive this limit with the law of large numbers. Then show that E[ρ2]=1+χ2\mathbb{E}[\rho^2] = 1 + \chi^2, so that the effective sample size of the weights ρ\rho divided by nn approaches 1/(1+χ2)1 / (1 + \chi^2), where
χ2=∑a(πθ(a∣s)−πθold(a∣s))2πθold(a∣s).\chi^2 = \sum_a \frac{\big(\pi_\theta(a \mid s) - \pi_{\theta_{\textrm{old}}}(a \mid s)\big)^2}{\pi_{\theta_{\textrm{old}}}(a \mid s)}.

Show that χ2≈2DKL\chi^2 \approx 2 D_{\textrm{KL}} to second order in the policy change.

  1. With states drawn from a batch, χ2\chi^2 becomes its average over the visited states. Which values of χ2\chi^2 do the two fractions ess[name][-1] of Section 15.2.4.5 imply? Which approximate KL does the second-order relation of (b) predict for each? Compare each prediction with the k1k_1 estimate of the same ratios, (-np.log(rhos[arm][-1])).mean() for each arm. For which agent does the second-order relation fail? Besides the size of the policy change, which assumption of (b) do ratios violate that are measured on the very batch the policy was trained on?

Adapted from John Schulman, Approximating KL Divergence, estimators k1k_1 and k3k_3.

  1. [code] KL early stopping. ● Besides clipping, an implementation can stop reusing a batch once the policy has moved far enough. Spinning Up's PPO computes the approximate KL before every pass and ends the passes on a batch once it exceeds 1.51.5 times target_kl, which defaults to 0.010.01.

    1. Replace the ppo_epochs call in train_ppo by a loop of single passes, ppo_epochs(..., 1, ...), as the loop that collects rhos in Section 15.2.4.5 does. Before each pass, compute the approximate KL from log_prob_np and apply the stopping rule. Record the number of passes spent on each batch.
    2. Run the unclipped variant with early stopping on the eight seeds of the ablation. Does the stopping rule alone prevent the collapse? How does the number of passes per batch change over training?
    3. Run the clipped variant with early stopping as well. Which of the two mechanisms limits the policy change of a batch in this run? What does the answer say about describing the clip as a trust region?

    Adapted from Joshua Achiam, Spinning Up in Deep RL, PPO implementation, early stopping on target_kl.

  2. [code] The standard recipe. ●● Build the loop that Section 15.2.4.6 describes: eight environments in a gym.vector.SyncVectorEnv stepped for 32 steps per update, GAE over the 32×832 \times 8 rectangle with the critic's value at each cut and the autoreset step masked out, then four epochs over the rectangle in shuffled minibatches of 64, each minibatch taking one ppo_epochs pass with its own standardized advantages and one fit_value step toward the λ\lambda-return target computed before the epochs. Use a learning rate of 10−310^{-3} for both networks.

    1. Train three seeds and record the environment steps until the last eight completed episodes average at least 475. A correct implementation needs about 45,000 steps, between 35,000 and 55,000 on most seeds: more than the four-epoch arm of the reuse experiment in Section 15.2.4.3, which needs about 25,000.
    2. Raise the critic's learning rate to 10−210^{-2}, the rate of our loop, and keep the actor's at 10−310^{-3}. A correct implementation now reaches 475 in about 15,000 to 20,000 steps, fewer than any arm of the reuse experiment. Which network limited the run of (a)? Our loop at the same two rates, without vectorization or minibatches, needs about 35,000 to 40,000 steps. What do the short rectangles change about how often the policy is updated per environment step?
    3. Remove the mask on the autoreset step. Does the run still learn? Which transitions does the unmasked version add to the critic's targets, and why does CartPole barely notice them?
  3. The monotonic-improvement bound. ●● This problem derives (15.2.9) by the coupling argument of Schulman et al. (2015). Take an infinite-horizon task with γ<1\gamma \lt 1 and write π=πθold\pi = \pi_{\theta_{\textrm{old}}}, π~=πθ\tilde{\pi} = \pi_\theta, A=AoldA = A^{\textrm{old}}, and Aˉ(s)=∑aπ~(a∣s) A(s,a)\bar{A}(s) = \sum_a \tilde{\pi}(a \mid s)\, A(s, a). Let ΔTV=max⁡sDTV(π(⋅∣s),π~(⋅∣s))\Delta_{\textrm{TV}} = \max_s D_{\textrm{TV}}\big(\pi(\cdot \mid s), \tilde{\pi}(\cdot \mid s)\big) with the total variation distance DTV(p,q)=12∑a∣p(a)−q(a)∣D_{\textrm{TV}}(p, q) = \frac{1}{2} \sum_a |p(a) - q(a)|.

    1. Show from (15.2.7) that J(θ)−J(θold)=∑tγtEst∼π~[Aˉ(st)]J(\theta) - J(\theta_{\textrm{old}}) = \sum_t \gamma^t \mathbb{E}_{s_t \sim \tilde{\pi}}\big[\bar{A}(s_t)\big], and that the population surrogate (15.2.8) is Lˉ(θ)=∑tγtEst∼π[Aˉ(st)]\bar{L}(\theta) = \sum_t \gamma^t \mathbb{E}_{s_t \sim \pi}\big[\bar{A}(s_t)\big], where st∼πs_t \sim \pi denotes the state distribution at time tt under π\pi.
    2. Two distributions at total variation distance ΔTV\Delta_{\textrm{TV}} can be coupled: there is a joint distribution of (a,a~)(a, \tilde{a}) with marginals π(⋅∣s)\pi(\cdot \mid s) and π~(⋅∣s)\tilde{\pi}(\cdot \mid s) under which P(a≠a~)≤ΔTVP(a \neq \tilde{a}) \leq \Delta_{\textrm{TV}} at every state. Use Ea∼π[A(s,a)]=0\mathbb{E}_{a \sim \pi}[A(s, a)] = 0 to show that ∣Aˉ(s)∣≤2ΔTVAmax⁡|\bar{A}(s)| \leq 2\Delta_{\textrm{TV}} A_{\max}.
    3. Run both policies from the same start state with coupled actions at every step, and let mtm_t count the steps before tt at which the two actions differ. On the event mt=0m_t = 0, the two trajectories coincide up to time tt. Show that
∣Est∼π~[Aˉ(st)]−Est∼π[Aˉ(st)]∣≤4ΔTV(1−(1−ΔTV)t)Amax⁡.(15.2.12)\big|\mathbb{E}_{s_t \sim \tilde{\pi}}[\bar{A}(s_t)] - \mathbb{E}_{s_t \sim \pi}[\bar{A}(s_t)]\big| \leq 4\Delta_{\textrm{TV}} \big(1 - (1 - \Delta_{\textrm{TV}})^t\big) A_{\max}. \tag{15.2.12}
  1. Sum over tt to obtain
∣J(θ)−J(θold)−Lˉ(θ)∣≤4ΔTV2γAmax⁡(1−γ)2,(15.2.13)\big|J(\theta) - J(\theta_{\textrm{old}}) - \bar{L}(\theta)\big| \leq \frac{4 \Delta_{\textrm{TV}}^2 \gamma A_{\max}}{(1-\gamma)^2}, \tag{15.2.13}

and finish the proof with DTV2≤DKLD_{\textrm{TV}}^2 \leq D_{\textrm{KL}}.

  1. Evaluate the coefficient 4γ/(1−γ)24\gamma / (1-\gamma)^2 at γ=0.99\gamma = 0.99. Use (b) to show that Lˉ(θ)≤2ΔTVAmax⁡/(1−γ)\bar{L}(\theta) \leq 2\Delta_{\textrm{TV}} A_{\max} / (1-\gamma). With Pinsker's inequality DKL≥2DTV2D_{\textrm{KL}} \geq 2 D_{\textrm{TV}}^2, show that the bound certifies an improvement only if ΔTV<(1−γ)/(4γ)\Delta_{\textrm{TV}} \lt (1-\gamma) / (4\gamma). How large can Lˉ(θ)\bar{L}(\theta) of a certified step then be, in units of Amax⁡A_{\max}? Compare this limit on ΔTV\Delta_{\textrm{TV}} with the total variation ΔKL/2\sqrt{\Delta_{\textrm{KL}} / 2} that Pinsker's inequality permits at a state whose divergence equals the budget ΔKL=0.01\Delta_{\textrm{KL}} = 0.01 that Schulman et al. (2015) use in all their experiments.
  1. [extended] TRPO from the pieces. ●● Replace the ppo_epochs call in train_ppo by one TRPO update (Schulman et al., 2015) on the constrained problem (15.2.10) with ΔKL=0.01\Delta_{\textrm{KL}} = 0.01, and leave the critic and the advantages unchanged. Treat the parameters of ac.policy as one flat vector, and freeze the collecting policy's action probabilities, action_probs(ac, b.obs), together with logp_old.
    1. Compute the gradient g\mathbf{g} of the surrogate (15.2.6) at θold\theta_{\textrm{old}}. Write a function that returns the Fisher-vector product FvF\mathbf{v}, the Hessian of the mean divergence over the batch's states at θold\theta_{\textrm{old}} applied to v\mathbf{v}, by differentiating the gradient of that divergence a second time. Check it against a finite difference of the gradient.
    2. Solve Fx=gF\mathbf{x} = \mathbf{g} approximately by ten iterations of conjugate gradient, and scale the step to ξx\xi\mathbf{x} with ξ=2ΔKL/x⊤Fx\xi = \sqrt{2\Delta_{\textrm{KL}} / \mathbf{x}^\top F \mathbf{x}}. Halve ξ\xi until the measured mean divergence is at most ΔKL\Delta_{\textrm{KL}} and the surrogate has increased.
    3. Train three seeds and compare them with the clipped runs of Section 15.2.4.4: learning curves, the measured divergence of each update, and the number of halvings. How many gradient and Fisher-vector computations does each method spend per batch?
    4. Engstrom et al. (2020) found that PPO and TRPO perform similarly when their code-level choices are matched. Here the two share every choice except the policy update. Does your comparison agree?

Discussions