Trust Regions: TRPO & PPO
Natural gradients, KL constraints and clipping: taking safe policy steps.
A policy-gradient step that is tiny in parameter space can rewrite an agent's behavior, and an on-policy agent then gathers its next batch with the damaged policy. This lesson builds the tools that keep steps safe: a surrogate objective that scores nearby policies using old data, a KL-divergence trust region whose local solution is the natural gradient (TRPO), and PPO's clipped probability ratio, the workhorse of modern deep RL and of RLHF.
What you’ll learn
- Explain why the Euclidean length of a parameter step is the wrong measure of a policy update, and measure it with the KL divergence instead.
- Derive the surrogate objective from the performance difference lemma and show that it matches in value and gradient at the old policy.
- Derive the trust-region step and describe how TRPO computes it with conjugate gradient and a line search.
- Analyze PPO's clipped objective sample by sample, state its KL-penalty variant, and implement its loss and training loop.
- Explain, from multi-epoch experiments on one batch, what clipping protects against and what it does not.
Small in parameters, large in behavior
Gradient ascent measures a step by the Euclidean length of . For a policy that is the wrong ruler. How much the behavior changes depends on where you are and on how the policy happens to be parameterized, and an on-policy learner pays twice for a step that is too long: the worse policy collects the next batch, so one bad update also spoils the data that could have corrected it.
A better ruler compares action distributions. The KL divergence is zero when the two policies act identically in state and grows as the new policy makes the old one's actions unlikely. For a one-dimensional Gaussian policy whose mean moves by while its standard deviation stays fixed, it has a closed form:
Late in training a Gaussian policy has shrunk its standard deviation to . One gradient step moves its mean by , a small change in parameter space. How large is the KL divergence between the old and the new policy, in nats?
Show the answer
2
nats. The new mean sits two old standard deviations away: the new policy puts only about 16% of its actions inside , where the old one put 68%. The same step at changes the policy by nats, 400 times less. A learning rate that was safe early in training is reckless late in it.
The parameterization is an arbitrary choice that the Euclidean ruler takes seriously. Describe the same Gaussian by or by , or a softmax policy by logits shifted by a constant, and plain gradient ascent takes different steps through the same family of policies. Near a deterministic policy the plain gradient also shrinks toward zero (Global Convergence of Policy Gradients shows how badly), so a fixed step size is too long in some places and too short in others.
The rest of this lesson builds three tools: an objective that predicts how good a nearby policy is from data the old policy collected, a KL budget for each update, and two ways of staying within it, TRPO's constraint and PPO's clipping.
A surrogate objective you can evaluate
To choose a step you must predict the return of a candidate policy without running it. The performance difference lemma (proved in Advantages & the Performance Difference Lemma) gives the exact answer in terms of the old policy's advantages:
Replace the new policy's state distribution by the old one's. This is the only approximation, and it defines the surrogate objective:
The logged actions were drawn by , so reweight each one by the probability ratio , an importance weight on a single action (never on a whole trajectory):
At every ratio is 1 and advantages average to zero under their own policy, so . Since , the gradient there is exactly the policy gradient theorem's:
The surrogate is a first-order model of , like a tangent line: exact in value and slope at , increasingly wrong as moves away and its state distribution drifts from the data's. In code it is a batch average, , with advantage estimates from a critic, usually GAE. The constant and the factor are dropped, and so, as in most policy-gradient code, is the weighting of step by (The Policy Gradient Theorem in Depth explains what that changes).
A KL budget, and the natural direction
The theorem is too cautious to use as stated. Its coefficient grows like , about at , so the certified steps are minute, and a maximum over all states cannot be estimated from a batch. TRPO (trust region policy optimization) keeps the structure and makes two practical substitutions: an average KL over the visited states, which a batch can estimate, and a hard constraint with a fixed radius instead of a penalty, because a coefficient that suits early training is wrong later on.
At the KL is zero and so is its gradient (the score has mean zero under the old policy), so it starts quadratically. Its Hessian is the Fisher information matrix , the covariance of the score :
Linearize the surrogate, with , and set the gradient of the Lagrangian to zero:
The constraint is active, , which fixes and gives the step and the improvement the model predicts:
The direction is the natural policy gradient (Kakade, 2001): steepest ascent when distance is measured by KL instead of by parameters, and the same policy change whichever parameterization you pick. TRPO (Schulman et al., 2015) computes the step for networks whose Fisher matrix is too large even to store:
- Collect a batch with and estimate the advantages.
- Compute and solve approximately by conjugate gradient, which touches only through products , each about as costly as one more gradient. The paper ran 10 iterations and computed the products on 10% of the batch.
- Scale to the radius: , with in all of the paper's experiments.
- Backtrack: shrink geometrically until the actual surrogate improves and the actual average KL is at most .
TRPO solves for its step in closed form, yet it still ends every update with a backtracking line search. Why?
- The closed-form step solves a model (a linear surrogate and a quadratic KL), so the true surrogate may fall or the true KL may exceed ; the line search shrinks the step until both checks pass
- To find the largest step size for which the true return improves, measured with fresh rollouts
- Because conjugate gradient returns only the direction of , never its length
- To keep every probability ratio inside
Show the answer
A. The closed-form step solves a model (a linear surrogate and a quadratic KL), so the true surrogate may fall or the true KL may exceed ; the line search shrinks the step until both checks pass
The step is optimal for the local model, which is accurate only for small steps. The line search evaluates the real surrogate and the real average KL on the batch and halves the step (or shrinks it by another factor) until the surrogate has improved and the constraint holds. No new rollouts are needed.
PPO: clip the incentive, keep the penalty
TRPO is complicated to implement, and its second-order step does not fit architectures with noise, such as dropout, or with parameters shared between the policy and the value function. PPO, proximal policy optimization (Schulman, Wolski, Dhariwal, Radford & Klimov, 2017), runs ordinary first-order optimizers for several epochs of minibatches on each batch and builds the caution into the objective instead:
Inside the band the two arguments of the min coincide. Outside it, the min keeps the smaller one, and the clipped argument does not depend on . Case by case (wherever the gradient exists):
A sample stops pulling only after its probability has already moved by more than a factor in the direction its advantage asks for. A move in the wrong direction is never clipped: a good action whose ratio fell below keeps its full gradient back up.
Since , the clipped objective lies below the surrogate everywhere: a pessimistic version that ignores gains beyond the band and keeps every loss.
With , four samples sit at these points during an update: (a) , ; (b) , ; (c) , ; (d) , . Which of them contribute zero gradient to ?
- (a) and (d)
- (b) and (c)
- All four, since every ratio is outside
- (a) and (c)
Show the answer
D. (a) and (c)
(a) is a good action already raised past and (c) a bad action already lowered past : both have moved far enough the way their advantages ask, so their terms are flat. (b) is a good action whose probability fell and (d) a bad action whose probability rose; the min keeps their unclipped terms, which pull them back. Being outside the band is not enough; the direction matters.
The paper's second variant, PPO-penalty, keeps the unclipped surrogate and subtracts , the penalty form that TRPO's theory suggests, with an adaptive coefficient: after each update measure the mean KL ; if halve , and if double it. The constants are heuristic, and the paper reports that the algorithm is not very sensitive to them.
| Objective (PPO paper, Table 1) | Average normalized score |
|---|---|
| No clipping or penalty | −0.39 |
| Clipping, / / | 0.76 / 0.82 / 0.70 |
| Adaptive KL, / / | 0.68 / 0.74 / 0.71 |
| Fixed KL, / / / | 0.62 / 0.71 / 0.72 / 0.69 |
Several epochs on one batch
PPO alternates collection and optimization. With parallel environments it collects steps from each with , computes advantages by GAE and value targets , and then runs epochs of minibatch stochastic gradient steps on one combined loss:
import torch
def ppo_loss(dist, actions, logp_old, adv, values, targets, eps=0.2, c1=0.5, c2=0.0):
"""dist: the current policy's distribution on a minibatch of states, e.g. a
torch.distributions.Categorical; logp_old, adv, targets were stored at collection."""
logp = dist.log_prob(actions)
ratio = torch.exp(logp - logp_old) # rho_t(theta), via logs for stability
clipped = torch.clamp(ratio, 1 - eps, 1 + eps)
policy_loss = -torch.min(ratio * adv, clipped * adv).mean()
value_loss = (values - targets).pow(2).mean()
return policy_loss + c1 * value_loss - c2 * dist.entropy().mean()
# One iteration: roll out N envs for T steps with pi_old, storing logp_old;
# adv = GAE(gamma=0.99, lam=0.95); targets = adv + V_old(s).
# Then for K epochs: shuffle the N*T samples into minibatches and take
# one optimizer step on ppo_loss per minibatch.Only dist and values depend on the current parameters; everything stored at collection time is a constant. For a Gaussian policy over several action dimensions, sum the per-dimension log-probabilities (or wrap the distribution in torch.distributions.Independent).
PPO in practice, and the deeper lessons
The paper's settings became common defaults. For MuJoCo: 2,048 steps per iteration, 10 epochs, minibatches of 64, Adam with step size , and GAE's . For Atari: 8 actors with 128 steps each, 3 epochs, minibatches of 256, and the Adam step size both annealed linearly to zero, a value-loss coefficient of 1 and an entropy coefficient of 0.01. OpenAI Five's Dota 2 agent was trained with PPO at a far larger scale.
In RLHF the policy is a language model, an action is a token, and a learned reward model scores the finished response. InstructGPT (Ouyang et al., 2022) fine-tuned GPT-3 models with PPO on that reward minus a per-token KL penalty toward the supervised fine-tuned model, a second leash on top of clipping that keeps the policy where the reward model can be trusted; its PPO-ptx variant also mixed gradients of the pretraining objective into the update. Critic-free relatives such as GRPO keep PPO's clipped ratio but replace the learned value function by the average reward of several responses to the same prompt (GRPO & Critic-Free Policy Optimization).
Key takeaways
- Policy steps should be measured by how much behavior changes, for example by the KL divergence between old and new action distributions, not by the Euclidean length of the parameter change.
- The surrogate replaces the new policy's state distribution by the old one's; with probability ratios it is computable from old data and matches in value and gradient at .
- A linearized surrogate under a quadratic KL budget gives the natural-gradient step ; TRPO computes it with conjugate gradient on Fisher–vector products and checks it with a line search.
- PPO's clipped objective zeroes a sample's gradient only once its ratio has left in the direction its advantage favors; it lies below the surrogate and suits several epochs of minibatch SGD per batch.
- Clipping limits the damage a noisy batch can do; it does not strictly bound the ratios or the KL, and it does not raise the average gain. PPO with a KL penalty toward a reference model is the classic optimizer of RLHF.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
The surrogate and the exact from the performance difference lemma differ in one ingredient. Which?
- The surrogate uses the new policy's advantages
- The surrogate ignores the discount factor
- The surrogate weights states by the old policy's distribution instead of the new policy's
- The surrogate samples actions from the new policy instead of the old one
Show the answer
C. The surrogate weights states by the old policy's distribution instead of the new policy's
Everything else is exact: both use the old policy's advantages, and the probability ratio reweights old actions without bias. Using the old state distribution is what makes the surrogate computable from old data, and also why it is trustworthy only near : the bound on the gap grows with the KL divergence between the policies.
In a TRPO update, conjugate gradient returns with , and the radius is . Before any backtracking, the step is for which ?
Show the answer
A.
. Check: the quadratic model of the KL is , and the model predicts a surrogate gain of .
PPO-penalty runs with target . After an update, the measured mean KL divergence is . What happens to the penalty coefficient ?
- It is halved, so the next update can move further
- It stays the same, since is within a factor 3 of the target
- It is multiplied by
- It is doubled, because exceeds
Show the answer
D. It is doubled, because exceeds
The rule doubles when and halves it when , leaving it alone in between. A larger makes the next update more conservative, pulling the measured KL back toward the target.
Which statement about PPO's clipped objective is correct?
- It keeps every probability ratio inside throughout the update
- It removes each sample's incentive to move its ratio beyond the band in the direction its advantage favors, but other samples and shared parameters can still push the ratio further, so neither the ratios nor the KL divergence are strictly bounded
- It guarantees that the true return does not decrease
- It raises the average improvement per batch compared with optimizing the unclipped surrogate for the same number of epochs
Show the answer
B. It removes each sample's incentive to move its ratio beyond the band in the direction its advantage favors, but other samples and shared parameters can still push the ratio further, so neither the ratios nor the KL divergence are strictly bounded
A clipped sample contributes zero gradient, nothing more. Its ratio can still drift, through the gradients of other samples that share parameters with it, and there is no restoring force. What clipping reliably does is limit how far one noisy batch can drag the policy, which bounds the damage rather than raising the average gain.
Two engineers train the same family of Gaussian policies, one parameterizing the spread by , the other by . In the limit of small steps, which update moves both through the same sequence of action distributions?
- Plain gradient ascent with equal learning rates
- Neither: the two parameterizations describe different policies
- The natural gradient
- Both, as long as the learning rates are equal
Show the answer
C. The natural gradient
The natural gradient is steepest ascent with respect to the KL divergence, which depends only on the distributions, not on their coordinates; for small steps it traces the same path of policies in any smooth, invertible reparameterization. The plain gradient's direction changes with the coordinates (by the Jacobian of the change of variables).
Go deeper
- The Natural Policy Gradient · Fisher information, covariant updates and the link to policy iteration.
- TRPO & Monotonic Improvement · From conservative policy iteration to a surrogate objective with a KL bound.
- PPO: Clipping & the Details That Matter · What clipping does and does not guarantee, and the implementation choices behind PPO.
Further reading
- J. Schulman, S. Levine, P. Abbeel, M. I. Jordan & P. Moritz, "Trust region policy optimization," ICML (2015).
- J. Schulman, F. Wolski, P. Dhariwal, A. Radford & O. Klimov, "Proximal policy optimization algorithms," arXiv:1707.06347 (2017).
- S. Kakade & J. Langford, "Approximately optimal approximate reinforcement learning," ICML (2002).
- L. Ouyang, J. Wu, X. Jiang et al., "Training language models to follow instructions with human feedback," NeurIPS (2022).