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 , 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 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 has left 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.
Let , with the sampled action. The new policy leaves 's ratio at exactly 1, inside any band:
With 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 , and an estimate of from the batch itself, where actions were drawn from . With the log-ratio and , two per-sample estimators are common.
By definition , so 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.
Add , a control variate with mean zero: . The sum is still unbiased, and it is nonnegative for every sample because :
Near , , a smooth, small-variance estimate of a quadratic quantity. The names and come from Schulman's (2020) note "Approximating KL divergence", which recommends . Widely used implementations log , 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.
A minibatch contains two samples with ratios and . What are the and estimates of , averaged over the two samples?
- and
- and
- and
- and
Show the answer
A. and
gives and , which cancel: an average of 0, although the policy clearly changed. gives and , both positive, averaging . Both estimators are unbiased over many samples; 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.
| Choice | Finding (Andrychowicz et al., 2021) |
|---|---|
| Policy loss | PPO's clipped loss did best overall; of 0.2–0.3 worked in all five tasks; start at 0.25 |
| Observation normalization | Always use it |
| Value-target normalization | Strong effects either way: crucial on HalfCheetah and Humanoid, harmful on Walker2d |
| Per-minibatch advantage normalization | Little effect |
| Advantage estimator and value loss | GAE with ; neither a Huber loss nor PPO-style value clipping |
| Data reuse | Several passes; shuffle transitions and recompute advantages once per pass |
| Discount | Among the most important hyperparameters; tune per environment, starting at 0.99 |
| Initial policy | Scale the last policy layer's weights down 100×, so actions barely depend on the observation at first, with a small initial standard deviation |
| Optimizer | Adam with ; learning rate a safe default; decay and gradient clipping of secondary importance |
| Entropy or KL regularizers | No significant help in these tasks |
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:
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 largeWhat lives elsewhere: orthogonal initialization (gain 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 , 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, , 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, , exceeds , 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 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:
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 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 , normalize observations, tune , use GAE with , 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.
Which statement is a theorem about PPO's clipped objective (Wang, He & Tan, 2019)?
- Every probability ratio stays in when the objective is optimized by gradient ascent
- Keeping each sampled action's ratio within bounds the KL divergence by
- 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
- Clipping guarantees monotonic improvement whenever
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.
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?
- The clipped objective explains almost all of PPO's advantage over TRPO
- TRPO cannot be combined with code-level optimizations
- PPO keeps its probability ratios inside the clip band, unlike TRPO
- 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.
Which recommendation came out of Andrychowicz et al.'s study of more than 250,000 on-policy agents?
- Always normalize observations, and treat the discount factor as one of the most important hyperparameters to tune per environment
- Clip the value loss as in the reference PPO implementation
- Skip observation normalization; it rarely matters
- Add an entropy bonus; it was essential in every task
Show the answer
A. Always normalize observations, and treat the discount factor as one of the most important hyperparameters to tune per environment
Observation normalization helped everywhere, and 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.
What happens in phasic policy gradient's auxiliary phase?
- An exploratory policy collects fresh data for the value function
- 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
- PPO's clipping is replaced by a hard KL constraint
- 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).