Trust Regions and Proximal Policy Optimization

Dive into Deep Learning · §15.2

Trust Regions and Proximal Policy Optimization
parameter vs. policy distance · importance sampling · performance difference lemma · TRPO · PPO clipping · batch diagnostics

Why One Gradient Step Wastes a 4,000-Step Batch

Motivation

  • Under-Extracted Information: Thousands of transitions contain far more signal than a single first-order step can absorb.
  • Why Naive Multi-Epoch Reuse Fails: Once \theta updates even once, the batch comes from an older policy \pi_{\theta_{\textrm{old}}}, and repeated unguarded passes drive action probabilities into irreversible collapse.

Parameter Distance Does Not Control Policy Distance

Geometry of Policy Space

  • Consider a 1-parameter Bernoulli policy \pi_\theta(a{=}1) = \sigma(\theta) = (1 + e^{-\theta})^{-1} under two equal parameter steps \Delta \theta = 2 (Achiam, 2017):
    • At \theta = 0 (slope \sigma'(0) = 0.25): \pi(a{=}1) jumps from 0.50 \to 0.88.
    • At \theta = 6 (slope \sigma'(6) \approx 0.0025): \pi(a{=}1) barely shifts from 0.9975 \to 0.9997.
  • Saturation Trap: At \theta = 6, the score \nabla_\theta \log \pi_\theta(a{=}1) = 1 - \sigma(6) \approx 0.0025 vanishes while a{=}2 is sampled only once in 400 trials, trapping on-policy learners.

Change of Measure: Evaluating New Policies on Old Data

Importance Sampling

J(\theta) = \mathbb{E}_{\tau \sim P(\cdot;\, \theta_{\textrm{old}})}\Big[\frac{P(\tau; \theta)}{P(\tau; \theta_{\textrm{old}})}\, R(\tau)\Big]

  • Physics cancellation: Initial distribution \mu_0(s_0) and transition dynamics P(s_{t+1} \mid s_t, a_t) cancel completely in P(\tau; \theta) / P(\tau; \theta_{\textrm{old}}), leaving \prod_{t=0}^{T-1} \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\theta_{\textrm{old}}}(a_t \mid s_t)}.

Why Whole-Trajectory Importance Weights Explode

The Curse of Horizon

  • Exponential variance growth: Even when each step ratio \rho_t \in \{0.8, 1.2\} has tiny variance 0.04, the product W_T = \prod_{t=0}^{T-1} \rho_t has variance \textrm{Var}(W_T) = 1.04^T - 1.
  • 500-step CartPole collapse: At T = 500, \textrm{Var}(W_T) = 3.3 \times 10^8, so a single trajectory dominates the batch; PPO instead keeps only the single-step ratio \rho_t(\theta).

The Per-Step Surrogate Objective

Local Approximation

To eliminate the exponential horizon growth, we drop the historical product \rho_0 \cdots \rho_{t-1} (which corrects the state distribution at time t) and keep only the single-step probability ratio \rho_t(\theta):

\rho_t(\theta) = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\theta_{\textrm{old}}}(a_t \mid s_t)}, \qquad \hat{L}(\theta) = \frac{1}{N} \sum_{i=1}^n \sum_{t=0}^{T_i-1} \rho_t^i(\theta)\, \hat{A}_t^i

  • First-Order Consistency: At \theta = \theta_{\textrm{old}}, every ratio is \rho_t(\theta_{\textrm{old}}) = 1 and \nabla_\theta \rho_t(\theta_{\textrm{old}}) = \nabla_\theta \log \pi_\theta(a_t \mid s_t), so \nabla_\theta \hat{L}(\theta_{\textrm{old}}) equals the standard policy gradient.
  • What Was Dropped: The surrogate \hat{L}(\theta) evaluates the new policy’s action probabilities at the old policy’s state visitation distribution.

The Performance Difference Lemma

Exact Return Decomposition

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)

  • Telescoping proof (Kakade & Langford, 2002): Summing \gamma^t(r_t + \gamma V^{\textrm{old}}(s_{t+1}) - V^{\textrm{old}}(s_t)) telescopes to R(\tau) - V^{\textrm{old}}(s_0).
  • Surrogate error: Population surrogate \bar{L}(\theta) simply replaces new state occupancy d^{\pi_\theta}_\gamma(s) with old d^{\pi_{\theta_{\textrm{old}}}}_\gamma(s).

Monotonic Improvement and Trust Region Bounds (TRPO)

From Theory to TRPO

  • Kakade–Langford / Schulman Bound: The gap between true improvement J(\theta) - J(\theta_{\textrm{old}}) and \bar{L}(\theta) is bounded by the worst-case KL divergence across states: J(\theta) \ge J(\theta_{\textrm{old}}) + \bar{L}(\theta) - \frac{4\gamma A_{\max}}{(1-\gamma)^2} \max_s D_{\textrm{KL}}(\pi_{\theta_{\textrm{old}}} \Vert \pi_\theta)
  • TRPO (Schulman et al., 2015): Because 4\gamma/(1-\gamma)^2 \approx 40{,}000 at \gamma=0.99 is too conservative, TRPO maximizes \hat{L}(\theta) subject to a mean KL constraint \bar{D}_{\textrm{KL}} \le \Delta_{\textrm{KL}} = 0.01 via conjugate gradients.

PPO: First-Order Clipping in Policy Ratio Space

Proximal Policy Optimization

  • PPO (Schulman et al., 2017) replaces TRPO’s second-order Fisher-vector constraint with a first-order clipped surrogate (\epsilon_{\textrm{clip}} = 0.2): L^{\textrm{CLIP}}(\theta) = \frac{1}{N} \sum_{i,t} \min\Big(\rho_t^i \hat{A}_t^i,\ \textrm{clip}(\rho_t^i, 1-\epsilon_{\textrm{clip}}, 1+\epsilon_{\textrm{clip}})\hat{A}_t^i\Big)
  • Pessimistic Lower Bound: When \hat{A}_t > 0, the objective flattens above \rho_t = 1 + \epsilon_{\textrm{clip}} (zero gradient); when \hat{A}_t < 0, it flattens below 1 - \epsilon_{\textrm{clip}}, removing the incentive to push ratios outside [0.8, 1.2].

Why Ratios Still Leave the Band—and the Entropy Bonus

Optimization Nuances

  • Shared Network Coupling & Momentum: Unclipped transitions in a batch move shared weights \theta for already-clipped transitions, and Adam’s first-moment accumulator m_t continues coasting.
  • Losing-Side Slope & Entropy Bonus (0.01): Samples crossing the losing side (\rho < 0.8 for \hat{A} > 0) retain their restoring slope, while +\beta_H H(\pi_\theta) keeps probabilities away from 0 and 1.

Implementing Clipped and Unclipped Surrogates

Code Primitives

We implement both the clipped PPO objective and the unclipped importance-weighted objective (\rho_t \hat{A}_t) so our ablation can compare them under identical conditions:

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

In our CartPole setup (ActorCritic.mlp(4, 2) with 64-unit tanh layers and Adam learning rate 10^{-2}), we use GAE with \gamma = 0.99, \lambda = 0.95, critic_steps = 20, and num_epochs = 20 actor passes per 8-episode batch.

Multi-Epoch Actor Updates and Live Diagnostics

The Inner Epoch Loop

Before each of the num_epochs passes over the frozen batch (obs, act, adv, logp_old), ppo_epochs logs three diagnostic scalars—the clip fraction, the approximate KL \frac{1}{N}\sum (\log \pi_{\theta_{\textrm{old}}} - \log \pi_\theta), and the policy 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 = []

Multi-Epoch Actor Updates and Live Diagnostics (cont.)

The Inner Epoch Loop

Each pass steps the actor on the mean clipped surrogate plus an entropy bonus and records the three diagnostics:

    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 Complete PPO Training Loop

Outer Loop

Each outer iteration collects 8 episodes, freezes the standardized GAE advantages (evaluated with the pre-fit critic) and old log-probabilities, refits the critic for 20 steps toward the \lambda-return, and runs ppo_epochs:

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

The Complete PPO Training Loop (cont.)

Outer Loop

Each iteration: roll out, freeze advantages and old log-probabilities, refit the critic, then run the actor epochs:

    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())

Batch Reuse Halves the Environment Steps Required

Sample Efficiency

  • Across 8 seeds capped at 50{,}000 environment steps, taking 4 epochs per batch reaches the return ceiling (475+) in \sim 25{,}000 steps—half the steps and half the rollouts needed by 1 epoch (\ge 50{,}000 steps).
  • At 1 epoch per batch, every ratio is \rho_t = 1 and the clip never activates, reducing PPO to GAE actor-critic.
  • Increasing reuse from 4 to 20 epochs yields only minor additional speedups while remaining completely stable under clipping.

Ablation: What Happens Without the Clip at 20 Epochs?

The Clipping Ablation

  • At learning rate 10^{-2} and 20 epochs per batch, every single clipped PPO seed (8/8) reaches 500 and holds the task above 250.
  • Without the clip, repeated unguarded passes drive the policy into saturation: over 64 seeds, only \sim 1 in 20 holds the task and half end dead at return \sim 9 (pushing the cart one way until the pole falls).
  • Lowering the actor learning rate 10\times to 10^{-3} prevents unclipped collapse but slows convergence from 24\text{k} to \sim 40\text{k} steps.

clipped (PPO): 8 of 8 seeds hold the task, 0 end dead
      no clip: 0 of 8 seeds hold the task, 4 end dead

Monitoring PPO: Clip Fraction and Approximate KL

Training Diagnostics

  • Because policy-gradient loss stays near zero regardless of performance, we monitor the clip fraction and approximate KL across the 20 epochs inside a batch.
  • At epoch 1, \rho_t = 1 so both are 0. In clipped PPO, the out-of-band fraction peaks around epoch 5–6 (\sim 7\%) and falls back by half by epoch 20.
  • Why does it fall? Samples that cross the band on the losing side (\rho < 0.8 for \hat{A} > 0) retain their unclipped gradient and are pulled back inside.

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

Policy Entropy Decay: Clipped vs. Unclipped Runs

Saturation Diagnostics

  • Controlled Decisiveness: Clipped PPO gradually reduces policy entropy from 0.65 to 0.25\text{ nats} over 60 updates as it masters CartPole, slowed by the entropy_coef = 0.01 bonus.
  • Unclipped Saturation: Without clipping, policy entropy plummets rapidly toward 0\text{ nats} as repeated passes push action probabilities to 0 and 1.

clipped: entropy 0.65 over the first five updates, 0.25 over the last five

Ratio Collapse and Effective Sample Size

Importance Weight Diagnostics

  • After 20 passes on the same initial batch, clipped ratios stay clustered near 1.0, whereas unclipped ratios pile up near 0 and 2 \approx 1/\pi_{\theta_{\textrm{old}}}(a^*).

Ratio Collapse and Effective Sample Size (cont.)

Importance Weight Diagnostics

  • Effective Sample Size (N_{\textrm{eff}} = 1 / \sum_j \bar{w}_j^2): Clipped PPO retains N_{\textrm{eff}}/N \approx 96\%–97\% of the batch at epoch 20, while unclipped saturation cuts N_{\textrm{eff}}/N to roughly half (\approx 47\%–55\%, near the harmonic mean of \pi_{\theta_{\textrm{old}}}(a^* \mid s)).

after 20 epochs the batch is worth 97% (clipped (PPO)) vs 55% (no clip) of its 226 steps

Production PPO: Vectorized Rollouts and Cut Bootstraps

Systems Architecture

Production implementations (cleanrl/ppo.py) step N = 8 parallel environments for a fixed horizon T = 32 to form a 32 \times 8 rollout rectangle, bootstrap at the edge, and train on shuffled minibatches:

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.]

Two production pitfalls: (1) Unfinished episodes at step T must bootstrap \hat{V}(s_T) \approx 100 rather than zero; (2) Gymnasium’s SyncVectorEnv auto-resets on the step after termination, so that transition must be masked out of GAE.

Concept Check: Clipping Thresholds and Truncation Cuts

Check Your Understanding

Test your intuition on three concrete calculations:

  1. First Pass Identity: On epoch 1 of a fresh batch where advantages \hat{A}_t are standardized to mean 0 and unit variance, what are \rho_t(\theta_{\textrm{old}}), L^{\textrm{CLIP}}(\theta_{\textrm{old}}), and \nabla_\theta L^{\textrm{CLIP}}(\theta_{\textrm{old}})?
  2. Relative Band Width: With \epsilon_{\textrm{clip}} = 0.2 and \hat{A}_t > 0, up to what new probability \pi_\theta(a_t \mid s_t) does the objective reward increasing an action that had \pi_{\theta_{\textrm{old}}} = 0.01 versus \pi_{\theta_{\textrm{old}}} = 0.60?
  3. Forgotten Cut Bootstrap: At a 32-step rollout cut where \hat{V}(s_T) = 100, \gamma = 0.99, and \lambda = 0.95, how much does the GAE advantage drop if the cut is mistakenly masked as terminal (\hat{V}(s_T) = 0) at step T-1 and at step T-11?

Answers:

  1. Every \rho_t = 1, so L^{\textrm{CLIP}}(\theta_{\textrm{old}}) = \frac{1}{N}\sum \hat{A}_t = 0, and \nabla_\theta L^{\textrm{CLIP}}(\theta_{\textrm{old}}) = \frac{1}{N}\sum \hat{A}_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) (the exact single-step policy gradient).
  2. Up to 1.2 \times 0.01 = \mathbf{0.012} (+0.002 absolute gain) for the rare action, versus 1.2 \times 0.60 = \mathbf{0.72} (+0.12 gain) for the common action.
  3. At step T-1 it drops by \gamma \hat{V}(s_T) = \mathbf{99}; ten steps earlier (T-11) it drops by (\gamma\lambda)^{10} \cdot 99 \approx \mathbf{54}, falsely punishing good actions before the cut.

Summary: Policy Optimization From REINFORCE to PPO

Key Takeaways

Method Data Reuse per Batch Step Constraint Mechanism Optimization Cost Behavior on CartPole (50\text{k} Budget)
Actor-Critic + GAE 1 pass (\rho_t = 1) Optional gradient norm clip 1 first-order step Reaches \sim 450 near 50{,}000 steps
Unclipped Importance Ratio K passes on \rho_t \hat{A}_t None (unguarded ratio) K first-order steps Collapses to return \sim 9 at K=20, \eta=10^{-2}
TRPO 1 line-searched step Hard mean KL \bar{D}_{\textrm{KL}} \le \Delta_{\textrm{KL}} Conjugate gradient (F\mathbf{x}=\mathbf{g}) Monotonic progress, higher per-update compute
Clipped PPO 4–20 epochs on L^{\textrm{CLIP}} One-sided ratio clip 1 \pm \epsilon_{\textrm{clip}} K first-order Adam steps Solves CartPole (475+) in \sim 25{,}000 steps