Simple Algorithm
Reinforcement Learning · Fixed Point · 28 min

PPO: Clipping & the Details That Matter

What clipping does and does not guarantee, and the implementation choices behind PPO.

PPO is usually described as TRPO with a simpler way of staying close to the old policy. Measured carefully, it is something else. Clipping removes incentives but enforces no trust region, how far PPO moves depends on the optimizer as much as on ϵ\epsilon, and a large part of its benchmark advantage over TRPO traced to implementation details that papers left in appendices. This lesson proves what the clipped objective cannot guarantee, shows how practitioners measure and limit the step, sorts out what the large ablation studies found, and ends with the algorithms built on those lessons.

What you’ll learn

  • Prove that the clipped objective bounds neither the probability ratios nor the KL divergence, and explain how other samples and the optimizer move clipped samples.
  • Derive the unbiased, nonnegative KL estimator (ρ−1)−log⁡ρ(\rho-1)-\log\rho and use it, with the clip fraction, to monitor and stop PPO updates.
  • Summarize what Engstrom et al., Ilyas et al. and Andrychowicz et al. measured about PPO, and what their results do and do not show.
  • Implement PPO's main code-level details: advantage normalization, value clipping, gradient clipping, learning-rate annealing, initialization and observation normalization.
  • Describe rollback and trust-region-triggered clipping, and phasic policy gradient.

What clipping cannot guarantee

A sample's clipped term is flat once its ratio ρt\rho_t has left [1−ϵ,1+ϵ][1-\epsilon,1+\epsilon] in the direction its advantage favors, so the sample stops pulling. That is all clipping does. The samples share parameters, so the other samples' gradients keep moving every probability, including the clipped ones, and an optimizer with momentum keeps moving them on its own. Wang, He and Tan (2019) turned both observations into theorems.

DerivationPart (ii) with three actions
  1. DKL(πold ∥ πnew)=0.5log⁡0.50.5+0.25log⁡0.250.5−u+0.25log⁡0.25u →u→0 ∞\KL\big(\pi_{\text{old}}\,\|\,\pi_{\text{new}}\big)=0.5\log\frac{0.5}{0.5}+0.25\log\frac{0.25}{0.5-u}+0.25\log\frac{0.25}{u}\ \xrightarrow[u\to0]{}\ \infty

    Let πold(⋅∣s)=(0.5,0.25,0.25)\pi_{\text{old}}(\cdot\mid s)=(0.5,0.25,0.25), with a1a_1 the sampled action. The new policy (0.5, 0.5−u, u)(0.5,\,0.5-u,\,u) leaves a1a_1's ratio at exactly 1, inside any band:

  2. With u=10−6u=10^{-6} the divergence is already about 2.9 nats. In continuous state spaces each state typically appears once in a batch, with one sampled action, so the ratio constraint touches one point of each action distribution and says nothing about the rest. For a Gaussian the same happens by shrinking or shifting the distribution while keeping its density at the sampled action within the band.

There is a third reason the objective alone cannot set the step size. At the start of an update every ratio equals 1, so the first minibatch step is a step on the unclipped surrogate, and how far the policy travels before clipping engages is set by the learning rate, the number of epochs and the minibatch size (Engstrom et al., 2020). Clipping limits the incentive; the optimizer determines the distance.

Measuring and limiting the step

Because the objective does not pin down the step, implementations measure it. Two diagnostics are standard: the clip fraction, the share of samples with ∣ρt−1∣>ϵ\abs{\rho_t-1}>\epsilon, and an estimate of DKL(πold ∥ πθ)\KL(\pi_{\text{old}}\,\|\,\pi_{\boldsymbol\theta}) from the batch itself, where actions were drawn from πold\pi_{\text{old}}. With the log-ratio ℓ=log⁡πθ(a∣s)−log⁡πold(a∣s)\ell=\log\pi_{\boldsymbol\theta}(a\mid s)-\log\pi_{\text{old}}(a\mid s) and ρ=eℓ\rho=e^{\ell}, two per-sample estimators are common.

DerivationTwo estimators of the KL divergence
  1. k1=−ℓ,Eπold[k1]=DKL(πold ∥ πθ)k_1=-\ell,\qquad\E_{\pi_{\text{old}}}[k_1]=\KL(\pi_{\text{old}}\,\|\,\pi_{\boldsymbol\theta})

    By definition DKL(πold ∥ πθ)=Ea∼πold[−ℓ]\KL(\pi_{\text{old}}\,\|\,\pi_{\boldsymbol\theta})=\E_{a\sim\pi_{\text{old}}}[-\ell], so k1=−ℓk_1=-\ell is unbiased. But it is negative for every sampled action whose probability rose, so its batch average is noisy and can even come out negative.

  2. k3=(ρ−1)−log⁡ρ ≥ 0,Eπold[k3]=DKL(πold ∥ πθ)k_3=(\rho-1)-\log\rho\ \ge\ 0,\qquad\E_{\pi_{\text{old}}}[k_3]=\KL(\pi_{\text{old}}\,\|\,\pi_{\boldsymbol\theta})

    Add ρ−1\rho-1, a control variate with mean zero: Ea∼πold[ρ]=∑aπθ(a∣s)=1\E_{a\sim\pi_{\text{old}}}[\rho]=\sum_a\pi_{\boldsymbol\theta}(a\mid s)=1. The sum is still unbiased, and it is nonnegative for every sample because log⁡x≤x−1\log x\le x-1:

  3. Near ρ=1\rho=1, k3≈12(ρ−1)2k_3\approx\tfrac12(\rho-1)^2, a smooth, small-variance estimate of a quadratic quantity. The names k1k_1 and k3k_3 come from Schulman's (2020) note "Approximating KL divergence", which recommends k3k_3. Widely used implementations log k1k_1, k3k_3 or both; the "37 implementation details" survey (Huang et al., 2022) points to that note's estimator as unbiased with less variance.

A common safeguard is early stopping: end the epochs on the current batch as soon as the estimated KL exceeds a target, a cheap way to restore something like TRPO's constraint on top of clipping. Others monitor the KL but leave the number of epochs fixed and tune the learning rate instead. In RLHF the KL toward a reference model is also a term of the reward, so it is estimated per token at every step.

Check your understanding

A minibatch contains two samples with ratios ρ=2\rho=2 and ρ=0.5\rho=0.5. What are the k1k_1 and k3k_3 estimates of DKL(πold ∥ πθ)\KL(\pi_{\text{old}}\,\|\,\pi_{\boldsymbol\theta}), averaged over the two samples?

  1. k1=0k_1=0 and k3≈0.25k_3\approx0.25
  2. k1≈0.35k_1\approx0.35 and k3≈0.35k_3\approx0.35
  3. k1=0k_1=0 and k3=0k_3=0
  4. k1≈−0.35k_1\approx-0.35 and k3≈0.25k_3\approx0.25
Show the answer

A. k1=0k_1=0 and k3≈0.25k_3\approx0.25

k1=−ℓk_1=-\ell gives −log⁡2-\log2 and +log⁡2+\log2, which cancel: an average of 0, although the policy clearly changed. k3=(ρ−1)−log⁡ρk_3=(\rho-1)-\log\rho gives 1−0.693=0.3071-0.693=0.307 and −0.5+0.693=0.193-0.5+0.693=0.193, both positive, averaging 0.250.25. Both estimators are unbiased over many samples; k3k_3 never goes negative and is far less noisy for nearby policies.

The details that matter

Engstrom et al. (2020) listed nine "code-level optimizations" in the reference implementation of PPO that the paper does not present as part of the algorithm: value-function clipping, reward scaling by a running estimate of the standard deviation of a discounted sum of rewards, orthogonal initialization with layer-dependent scales, learning-rate annealing for Adam, reward clipping, observation normalization, observation clipping, tanh activations, and clipping the global gradient norm at 0.5. Ablating the first four, they found that reward scaling, learning-rate annealing and the initialization each significantly changed final rewards. They then built two hybrids, PPO-M (PPO's core without the optimizations) and TRPO+ (TRPO with them): whether the optimizations were used mattered significantly more than whether the PPO or the TRPO step was used (TRPO+ came within 8% of PPO on Walker2d, matched it on Hopper and beat it on Humanoid). With the optimizations and enough tuning, PPO without clipping often matched standard PPO. None of the methods kept its ratios inside the clip band, while all of them, with tuned hyperparameters, kept the mean KL divergence small.

Ilyas et al. (2020), from the same group, measured the quantities the theory reasons about. At the batch sizes used in practice, gradient estimates correlated poorly with the "true" gradient computed from far more samples, and the agreement worsened as training progressed and on harder tasks. Value networks fit their regression targets but not the true value function, and as baselines they reduced gradient variance only marginally compared with the true value function, though they still improved performance dramatically over no baseline at all. The surrogate's landscape often did not reflect the true reward landscape. The agents improved anyway, in ways the motivating theory does not predict.

ChoiceFinding (Andrychowicz et al., 2021)
Policy lossPPO's clipped loss did best overall; ϵ\epsilon of 0.2–0.3 worked in all five tasks; start at 0.25
Observation normalizationAlways use it
Value-target normalizationStrong effects either way: crucial on HalfCheetah and Humanoid, harmful on Walker2d
Per-minibatch advantage normalizationLittle effect
Advantage estimator and value lossGAE with λ=0.9\lambda=0.9; neither a Huber loss nor PPO-style value clipping
Data reuseSeveral passes; shuffle transitions and recompute advantages once per pass
Discount γ\gammaAmong the most important hyperparameters; tune per environment, starting at 0.99
Initial policyScale the last policy layer's weights down 100×, so actions barely depend on the observation at first, with a small initial standard deviation
OptimizerAdam with β1=0.9\beta_1=0.9; learning rate 3×10−43\times10^{-4} a safe default; decay and gradient clipping of secondary importance
Entropy or KL regularizersNo significant help in these tasks
More than 250,000 agents, more than 50 implementation choices, five MuJoCo tasks (Hopper, Walker2d, HalfCheetah, Ant, Humanoid). Each recommendation holds relative to the rest of their setup.

An implementation checklist

Huang, Dossa, Raffin, Kanervisto and Wang (2022) catalogued the details of the reference implementations in a widely read survey, "The 37 implementation details of PPO": 13 core details, 9 specific to Atari, 9 to continuous control, 5 to recurrent policies and 1 to multi-discrete actions. The core ones fit in one minibatch step:

python
import torch

def ppo_minibatch_step(policy, value_fn, opt, mb, eps=0.2, vf_coef=0.5, ent_coef=0.0,
                       clip_value=False, max_grad_norm=0.5):
    dist = policy(mb.obs)
    logratio = dist.log_prob(mb.actions) - mb.logp_old
    ratio = logratio.exp()
    adv = (mb.adv - mb.adv.mean()) / (mb.adv.std() + 1e-8)    # per-minibatch normalization
    pg_loss = -torch.min(ratio * adv, ratio.clamp(1 - eps, 1 + eps) * adv).mean()
    v = value_fn(mb.obs).squeeze(-1)
    v_loss = (v - mb.returns) ** 2
    if clip_value:                     # in the reference code; ablations found no gain
        v_clipped = mb.v_old + (v - mb.v_old).clamp(-eps, eps)
        v_loss = torch.max(v_loss, (v_clipped - mb.returns) ** 2)
    loss = pg_loss + vf_coef * 0.5 * v_loss.mean() - ent_coef * dist.entropy().mean()
    opt.zero_grad()
    loss.backward()
    params = [p for group in opt.param_groups for p in group["params"]]
    torch.nn.utils.clip_grad_norm_(params, max_grad_norm)    # global norm
    opt.step()
    with torch.no_grad():
        approx_kl = ((ratio - 1) - logratio).mean().item()     # k3
        clipfrac = ((ratio - 1).abs() > eps).float().mean().item()
    return approx_kl, clipfrac   # caller: anneal the learning rate; stop early if approx_kl is large

What lives elsewhere: orthogonal initialization (gain 2\sqrt2 in hidden layers, 0.01 for the policy's output layer so the first policy barely depends on the observation, 1 for the value output), running observation normalization clipped to ±10\pm10, reward scaling by the running standard deviation of a discounted return, and for continuous actions a state-independent log standard deviation. These are the reference defaults, not laws: the studies above found some of them unhelpful in their settings.

Fixing the clip, and phasic policy gradient

Fixing the clip. Wang, He and Tan (2019) proposed two changes. Rollback replaces the flat stretch outside the band by a slope of the opposite sign, −αρ+const-\alpha\rho+\text{const}, so a sample that has gone too far is pulled back instead of merely ignored. Trust-region triggering clips a sample when the KL divergence of its state, DKL(πold(⋅∣st) ∥ πθ(⋅∣st))\KL\big(\pi_{\text{old}}(\cdot\mid s_t)\,\|\,\pi_{\boldsymbol\theta}(\cdot\mid s_t)\big), exceeds δ\delta, rather than when its ratio leaves the band, tying the trigger to the quantity TRPO's bound is about. They justified the combination (TR-PPO-RB) by TRPO's bound and reported gains over PPO on standard benchmarks. An extended version (Wang, He, Wen & Tan, arXiv 2020) names it Truly PPO, applies the rollback to the KL divergence instead of the ratio, and proves monotonic improvement for the idealized objective under conditions on the rollback slope and the KL threshold.

Phasic policy gradient. Cobbe, Hilton, Klimov and Schulman (2021) started from two observations: when the policy and the value function share a network their objectives interfere, and the value function tolerates far more reuse of each batch than the policy does. PPG alternates two phases. The policy phase runs PPO with separate policy and value networks, by default for one epoch per batch each. Every Nπ=32N_\pi=32 iterations, an auxiliary phase trains an auxiliary value head on the policy network's features, with a behavioral-cloning term that holds the policy itself in place, and trains the value network further on the same data, for 6 epochs over everything collected in the phase:

Ljoint=12 E^t[(Vθaux(st)−V^ttarg)2]⏟value features into the policy network+βclone E^t[DKL(πold(⋅∣st) ∥ πθ(⋅∣st))]L^{\text{joint}}=\underbrace{\tfrac12\,\hat\E_t\Big[\big(V^{\text{aux}}_{\boldsymbol\theta}(s_t)-\hat V^{\text{targ}}_t\big)^2\Big]}_{\text{value features into the policy network}}+\beta_{\text{clone}}\,\hat\E_t\Big[\KL\big(\pi_{\text{old}}(\cdot\mid s_t)\,\big\|\,\pi_{\boldsymbol\theta}(\cdot\mid s_t)\big)\Big]
πold\pi_{\text{old}} is the policy at the start of the auxiliary phase and βclone=1\beta_{\text{clone}}=1 by default. On the Procgen benchmark, PPG improved sample efficiency significantly over PPO.

Key takeaways

  • Clipping zeroes a sample's gradient only after it has moved far enough; other samples and momentum can push its ratio further, and a bounded sampled ratio does not bound the KL divergence (Wang, He & Tan, 2019).
  • The first step of every PPO update is a step on the unclipped surrogate, so the learning rate, epochs and minibatch size set how far the policy moves; implementations monitor the clip fraction and the KL estimate (ρ−1)−log⁡ρ(\rho-1)-\log\rho and often stop early.
  • Code-level optimizations (value clipping, reward scaling, orthogonal initialization, learning-rate annealing, normalization, gradient clipping) mattered more than the choice between PPO's and TRPO's step (Engstrom et al., 2020), and gradient estimates, value networks and surrogate landscapes deviate far from what the theory assumes (Ilyas et al., 2020).
  • Across 250,000 agents: use the PPO loss with ϵ≈0.25\epsilon\approx0.25, normalize observations, tune γ\gamma, use GAE with λ≈0.9\lambda\approx0.9, start from a nearly observation-independent, low-variance policy; value clipping and regularizers did not help (Andrychowicz et al., 2021).
  • Rollback and KL-triggered clipping (Truly PPO) target the gaps in clipping; PPG separates policy and value training and distills value features into the policy network under a behavioral-cloning penalty.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which statement is a theorem about PPO's clipped objective (Wang, He & Tan, 2019)?

  1. Every probability ratio stays in [1−ϵ,1+ϵ][1-\epsilon,1+\epsilon] when the objective is optimized by gradient ascent
  2. Keeping each sampled action's ratio within [1−ϵ,1+ϵ][1-\epsilon,1+\epsilon] bounds the KL divergence by ϵ2/2\epsilon^2/2
  3. For discrete actions with at least three options, or Gaussian policies, the KL divergence between old and new policy in a state is unbounded even when the sampled action's ratio stays in the band
  4. Clipping guarantees monotonic improvement whenever ϵ≤0.2\epsilon\le0.2
Show the answer

C. For discrete actions with at least three options, or Gaussian policies, the KL divergence between old and new policy in a state is unbounded even when the sampled action's ratio stays in the band

The ratio of one sampled action constrains one point of the action distribution. The rest of the distribution can change arbitrarily, for instance by moving the mass of one unsampled action onto another, which drives the KL divergence to infinity. Their other theorem shows the ratios themselves can be pushed further out by the gradients of other samples.

Question 2

Engstrom et al. (2020) compared PPO, PPO-M (PPO without its code-level optimizations), TRPO and TRPO+ (TRPO with PPO's code-level optimizations). What did they conclude?

  1. The clipped objective explains almost all of PPO's advantage over TRPO
  2. TRPO cannot be combined with code-level optimizations
  3. PPO keeps its probability ratios inside the clip band, unlike TRPO
  4. Whether the code-level optimizations were used mattered significantly more than whether the PPO or the TRPO step was used
Show the answer

D. Whether the code-level optimizations were used mattered significantly more than whether the PPO or the TRPO step was used

Swapping the step (clipping or trust region) changed results less than switching the implementation details on or off. This is why fair comparisons of policy-gradient methods need matched implementations.

Question 3

Which recommendation came out of Andrychowicz et al.'s study of more than 250,000 on-policy agents?

  1. Always normalize observations, and treat the discount factor γ\gamma as one of the most important hyperparameters to tune per environment
  2. Clip the value loss as in the reference PPO implementation
  3. Skip observation normalization; it rarely matters
  4. Add an entropy bonus; it was essential in every task
Show the answer

A. Always normalize observations, and treat the discount factor γ\gamma as one of the most important hyperparameters to tune per environment

Observation normalization helped everywhere, and γ\gamma was among the most consequential settings. Value clipping and Huber losses did not help, and entropy or KL regularizers gave no significant gain in their five MuJoCo tasks.

Question 4

What happens in phasic policy gradient's auxiliary phase?

  1. An exploratory policy collects fresh data for the value function
  2. The policy network trains an auxiliary value head on stored data, with a KL term that keeps its action distributions close to what they were at the start of the phase, and the value network trains further on the same data
  3. PPO's clipping is replaced by a hard KL constraint
  4. The policy is distilled into the value network
Show the answer

B. The policy network trains an auxiliary value head on stored data, with a KL term that keeps its action distributions close to what they were at the start of the phase, and the value network trains further on the same data

The auxiliary phase moves value features into the policy network without disturbing the policy (the behavioral-cloning KL term), and reuses the data heavily for value learning, which tolerates far more reuse than policy learning.

Further reading

  • Y. Wang, H. He & X. Tan, "Truly proximal policy optimization," UAI (2019); extended version with C. Wen, arXiv:1903.07940v2 (2020).
  • L. Engstrom, A. Ilyas, S. Santurkar, D. Tsipras, F. Janoos, L. Rudolph & A. Madry, "Implementation matters in deep policy gradients: A case study on PPO and TRPO," ICLR (2020).
  • A. Ilyas, L. Engstrom, S. Santurkar, D. Tsipras, F. Janoos, L. Rudolph & A. Madry, "A closer look at deep policy gradients," ICLR (2020).
  • M. Andrychowicz, A. Raichuk, P. Stańczyk, M. Orsini, S. Girgin, R. Marinier, L. Hussenot, M. Geist, O. Pietquin, M. Michalski, S. Gelly & O. Bachem, "What matters for on-policy deep actor-critic methods? A large-scale study," ICLR (2021).
  • S. Huang, R. F. J. Dossa, A. Raffin, A. Kanervisto & W. Wang, "The 37 implementation details of proximal policy optimization," ICLR Blog Track (2022).
  • K. Cobbe, J. Hilton, O. Klimov & J. Schulman, "Phasic policy gradient," ICML (2021).