TRPO: Trust Region Policy Optimization
Limit how far each update can move the policy's action probabilities, measured in KL divergence, and take the largest improving step within that limit.
A policy-gradient step that is too large can wreck a policy that was working. TRPO derives a lower bound on the new policy's return, turns it into a KL budget per update, and solves for the step with conjugate gradient and a line search.
Explaining the paperTrust Region Policy OptimizationThe gradient of expected return gives a direction for changing the policy but no distance. One KL budget, δ = 0.01 per update, worked unchanged on simulated swimming, hopping and walking and on seven Atari games played from raw pixels.
Policy-gradient reinforcement learning fails in a recognizable way. You run the current policy, collect a batch of experience, estimate which direction in parameter space increases reward, and take a step. Most steps help. Occasionally one produces a policy far worse than the one you started with: a walking robot that now falls immediately, or a game agent that puts all its probability on one action and stops exploring. The next batch is collected by that broken policy, so it contains little useful signal, and recovery can take thousands of updates. Lowering the learning rate makes collapses rarer and learning slower, and the right rate changes from task to task and during training.
The objective optimized from a batch is an approximation to expected return, built from states the old policy visited. It agrees with the true return near the old policy and drifts away from it as the policy moves. TRPO (Schulman, Levine, Moritz, Jordan and Abbeel, 2015) quantifies the drift. The page follows the paper in order:
- an exact identity for how much better one policy is than another;
- a surrogate objective that is computable from old data and matches the true return to first order;
- a lower bound on the true return: surrogate minus a penalty on the KL divergence between policies;
- the practical swap of that penalty for a hard KL limit of per update;
- sample estimates of everything, and the conjugate-gradient solve and line search that compute the step.
A two-state problem small enough to solve by hand runs through the first half, so each equation can be checked with numbers.
The step-size problem in policy gradients
The agent lives in a Markov decision process. At each state it samples an action from a stochastic policy ; for a neural policy, a network reads and outputs the parameters of a distribution over actions. The environment then moves to a new state. In this paper the reward depends only on the state, . The quantity to maximize is the expected discounted return, which weights a reward steps in the future by for a discount between 0 and 1:
Three standard quantities make workable. The value is the expected discounted return starting from and following . The action value is the same quantity when the first action is fixed to . The advantage is their difference:
A positive advantage means action at state does better than the policy's average behavior there; a negative one means worse. Averaged over the policy's own action probabilities, the advantage is exactly zero, because is that average of ; the surrogate section uses this.
The running example has two states. In the reward is 0 and the agent chooses between go, which moves it to , and stay, which keeps it in . In the reward is 1 on every step and every action keeps it in . The discount is , the episode starts in , and the policy has one number, . Being in is worth , so . Solving the one-line Bellman equation for gives
At the return is . Going gives ; staying gives . So and , and their policy-weighted average is . In every action has advantage 0, since the action changes nothing.
Let be the discounted number of visits to state . The paper leaves it unnormalized: it sums to over states, not to 1. In the example at , the agent is still in at time with probability , so is the geometric sum of , which is , and . The two sum to . That factor of comes back as a constant in the sampling section.
The exact improvement identity
The derivation starts from an identity due to Kakade and Langford (2002). The return of any policy equals the return of plus the discounted sum of 's advantages, collected along trajectories generated by :
It holds exactly for any two policies. The proof is a telescoping sum. In expectation over the next state, the advantage equals the one-step error . Add these up along a trajectory with weights and each cancels against the next term's . What remains is the trajectory's discounted reward minus . Averaged over trajectories of , those two terms are and , which rearranges to (1).
Grouping the trajectory sum by state, with each state weighted by how often the new policy visits it, gives the form the rest of the paper works with:
Check it on the example, with old policy and new policy (always go). The new policy leaves on the first step, so . Its expected advantage in is . Equation (2) gives , and the formula for gives . For (never go), , the expected advantage is , and (2) gives , which is right: an agent that never leaves collects nothing.
Equation (2) also gives a rule for improving a policy: move probability toward actions with positive advantage. If the expected advantage is nonnegative at every state, the new policy is at least as good. Exact policy iteration, which picks the action with the largest advantage at every state, works for this reason. The obstacle is the weight . It is the new policy's visit count, and you only learn it by running the new policy, which is the thing being designed.
The surrogate objective and why it only works nearby
TRPO replaces the new policy's visit counts with the old policy's. That gives the surrogate objective:
Every term on the right is available from data the old policy collected: its visited states, and its advantages there. The new policy enters only through its action probabilities at those states. It is like re-scoring an old survey with new weights per answer while assuming the same households would respond; for a small change in policy the households barely change, and for a large one the new policy reaches different states and the assumption fails.
In the example, keeps from the old policy. At it predicts , while the true return is . The surrogate overestimates by 0.67 because it assumes the agent still spends 1.82 discounted steps in collecting the advantage of go, when the new policy spends one. At it predicts 6.69 against a true 0. Comparing (2) with (3), the error at any is times the expected advantage in : the surrogate's whole error comes from the change in state visits.
Near the old policy the error is small: for a policy with differentiable parameters, matches to first order at the current parameters : same value and same gradient.
The error term is a product of two factors, the change in visits and the expected advantage under the new policy. Both are zero at : the visits have not changed yet, and the expected advantage of a policy under its own advantages is zero (the property from the first section). The product of two terms that each grow linearly with the step grows quadratically, so its first derivative at vanishes. In the example both slopes at are 2.98.
By (4), a small enough step that improves also improves , but (4) gives no bound on how small. The figure plots both functions for the two-state problem. Move the new policy and watch the gap between the teal line and the amber curve; then move and see the tangent point follow it.
In this problem the true return is concave in , so the surrogate overestimates every move but never points the wrong way: going more often always helps. In a real task the true return eventually turns down as the policy moves, while the surrogate, which ignores the visits that the move changes, keeps rising. The next three sections bound the gap between them.
Measuring policy change: total variation and KL
A bound on the gap needs a measure of how far the policy moved. Distance between parameter vectors is a poor choice, because two networks with nearly identical weights can output very different action distributions, and two networks with very different weights can output the same ones. TRPO measures the change in the action distribution at each state. The first measure is the total variation distance, half the summed absolute difference in probabilities:
It equals the largest difference in probability the two distributions can assign to any single event. The bound in the next section is stated with it, then converted to the KL divergence , which is smooth in the policy parameters and has a simple second derivative. The conversion uses an inequality the paper cites from Pollard:
A cap on KL therefore caps total variation, and with it how differently the two policies can act at that state. The paper's form is looser than the sharp Pinsker inequality, ; the looser one is still valid and only makes the bound more conservative (footnote 4). KL is not symmetric, so the order of arguments is a convention. TRPO puts the old policy first: .
For scale, take the example's state , where the policy is a coin with . Moving to costs nats, which is TRPO's budget, and a total variation of 0.07. In the figure, drag a five-action policy away from a fixed old one and check that stays below the KL at every setting.
The improvement bound and the monotonic guarantee
Kakade and Langford proved a lower bound on the new return for conservative policy iteration, which only allows mixture updates: with probability act like the old policy, with probability act like a better one. Their bound, as TRPO prints it, is
where is the better policy being mixed in, so is the largest expected advantage of at any state. Mixture policies are rarely used in practice. TRPO's main theoretical result (Theorem 1) extends the bound to any pair of stochastic policies, with replaced by the largest total variation between them over states. Converting total variation to KL with the inequality above gives:
In (5), is the KL between the two action distributions at the state where it is largest. Two constants changed from the mixture bound. The coefficient went from 2 to 4, and the extra factor of 2 comes from the coupling argument in the proof, not from the step from total variation to KL. The proof bounds the new policy's expected advantage at each state, . The old policy's expected advantage is zero, so this equals , with drawn from the new policy and from the old. Run both policies with shared randomness so that they pick the same action as often as possible. Two distributions at total variation can be coupled to agree with probability . When the two actions agree, the difference is zero. When they disagree, each advantage can be as large as in magnitude, so the difference can reach . The new policy's expected advantage per state is then at most in magnitude.
was also redefined. In the mixture bound it is the worst state's expected advantage; in (5) it is the largest single anywhere, which is at least as large.
Call the right side of (5), built at the current policy , the function :
It lies below everywhere and equals it at , where the KL is zero and . A function with those two properties is called a minorizer. The paper's Algorithm 1 sets to the maximizer of and repeats. Then
The first inequality uses and . The second holds because maximizes , so it scores at least as well as . The return never decreases. This is a minorize-maximize (MM) algorithm, the family that includes expectation maximization: build a function that touches the objective at the current point and lies below it elsewhere, move to that function's maximum, rebuild there. Picture a tarp stretched under a hilltop in fog, pinned to the ground at your feet and lying below it everywhere else, so any point on the tarp you walk to has ground at least that high above it.
The figure runs Algorithm 1 on a one-dimensional hill, with a quadratic KL penalty of strength . Here is a lower bound exactly when , the steepest downward curvature of the hill. Press Play at the default and watch the iterates reach the top in about 20 steps. Then try : still safe, but each step is of the gradient, and after 20 iterations the return has gone from 0.21 to 0.25 out of a possible 3. Below the bound pokes above the curve (shaded) and the guarantee is gone; below about 0.5 the steps overshoot the peak and the bar strip shows drops.
The guarantee in (6) is a theorem about Algorithm 1 as written: exact advantages, an exact maximization over all policies, the theoretical , and the maximum KL over states. The algorithm the paper runs replaces all four with approximations, and the paper's own abstract says that despite them TRPO "tends to" give monotonic improvement. The theorem motivates the design; it does not certify any particular update of the practical algorithm.
From a penalty to a trust region
Maximizing directly would keep the guarantee, but the theoretical is enormous. At the denominator is , so
which is about 40,000 times the largest advantage. The paper says that with this "the step sizes would be very small."
The two-state problem shows how small, even at . There , and is , or 295. The maximizer of moves the policy from to , a true gain of 0.0075 (Figure 1 shows it with the bound button on). The best policy, , is worth 0.82 more.
A smaller is the obvious fix, and Figure 3 shows the problem with it: the useful value depends on the curvature of the return, which differs between tasks and changes during training. The paper reports that a penalty coefficient is hard to choose robustly, and switches to a hard constraint on the KL, a trust region of radius . TRPO takes the step that maximizes the surrogate among all steps whose KL stays within :
With a penalty, the step length depends on , on the size of the surrogate's gradient, and on the curvature of the KL; with a constraint, the step goes as far as the KL limit allows. The constraint is stated in KL per update, the quantity the bound penalizes, so one value of can serve problems whose rewards and curvatures differ.
Equation (7) has one more change from the theory. The bound uses the maximum KL over all states, which is one constraint per state. TRPO constrains the average KL over states visited by the old policy, , and calls it a heuristic approximation. On cart-pole, the one task where the maximum-KL version was tractable, it learned somewhat more slowly and otherwise behaved similarly. Every experiment in the paper uses . In the example, that budget moves from 0.5 to 0.570 in one update and gains 0.188 (the surrogate predicted 0.209): 28 times the step and 25 times the gain of the penalized step.
The constraint does not make every safe. The figure is a stylized slice through policy space: rises and falls, is its tangent line, and the trust region admits moves up to a KL of (in the figure's own units). TRPO takes the largest step inside the region. Widen past about 1.6 and that step lands past the dotted marker, where the true return is below the starting point while the surrogate still predicts a gain.
Estimating the objective from rollouts
Problem (7) is written with sums over all states and actions and the true advantage function. The paper makes three substitutions to estimate it from samples. The sum over states weighted by becomes an expectation over sampled states, times the constant from the unnormalized visit counts, which does not change the maximizer. The advantage becomes ; the difference is times , which does not depend on , so the objective shifts by a constant. The sum over actions becomes an importance-sampling estimate: sample actions from a distribution and weight each by . Together they turn (7) into the problem TRPO solves:
The importance-sampling identity is exact for every , but its variance grows as moves away from . If the old policy gave an action probability 0.1 and the new one gives it 0.4, each sample of that action counts four times. Keeping the KL small keeps these weights near 1, which is a second reason, separate from the bound, to limit the step.
The paper gives two ways to produce the samples and the estimates. Single path is ordinary policy-gradient sampling. Run the old policy for whole trajectories, so . Every state-action pair on a trajectory is a sample, and its estimate is the discounted sum of the rewards that followed it on the same trajectory. It needs no resets and can run on a physical robot. Each estimate is a single noisy return. The paper's estimator uses it as directly; common implementations, and the code sketch below, subtract a learned value baseline, which shifts the objective by a constant per state and reduces variance.
Vine spends more simulation to get cleaner estimates. Run trunk trajectories, choose a subset of their states (the rollout set), and from each chosen state run short rollouts, one per sampled action; the experiments use about 4 per state. All rollouts reuse the same random number sequence for the environment's noise (common random numbers), so differences between their returns come mostly from the different first actions. With several actions per state, the paper uses a self-normalized estimator, dividing the weighted sum of values by the sum of the weights, which removes the need for a baseline. On the continuous-control tasks is the old policy; on Atari it is uniform over actions, which sometimes explored better. The cost is many more simulator calls per advantage estimate and the ability to reset the simulator to an arbitrary state, so vine runs only in simulation. Toggle between the two schemes:
How TRPO computes the step: natural gradient, conjugate gradient, line search
Problem (8) has to be solved approximately at every update, for policies with up to 33,500 parameters in the paper. TRPO approximates the objective by its gradient (linear in the step) and the average KL by its second-order Taylor expansion around , where the KL and its gradient are both zero:
The matrix is the Hessian of the average KL, the Fisher information matrix (the paper writes it , which collides with the advantage; this page uses ). TRPO computes it analytically: the KL between two distributions of known form is differentiated in closed form, which integrates over all actions at each sampled state. The alternative, the covariance of sampled log-probability gradients, depends on which actions happened to be sampled; the paper tests it as the "empirical FIM" baseline and reports a similar rate of improvement.
Maximizing subject to gives a step along . This direction is the natural gradient (Amari), applied to policies by Kakade as the natural policy gradient. It is the gradient re-measured in KL units. Along a direction where a small parameter change moves the action distribution a lot, is large and the step is short; along a direction the outputs are insensitive to, the step is long. A plain gradient step, the same problem with , moves the same Euclidean distance in every direction. In the figure, increase the anisotropy and compare the gray plain step with the teal KL step.
Forming is out of the question at this size. For the 33,500-parameter Atari policy it has entries, 4.5 GB in 32-bit floats, before any inversion. TRPO never forms it. Conjugate gradient solves using only products for vectors of its choosing, and each Fisher-vector product costs about as much as one gradient. Appendix C writes the product as , where is the Jacobian of the network's distribution parameters and the Fisher matrix of the output distribution with respect to those parameters; a generic Hessian-vector product through the KL, as in the code below, is slightly slower and easier to write. Ten iterations were enough (more did not speed learning). With 10 products per step, a naive implementation would spend over 90% of its compute on them, so the paper computes them on 10% of the batch. serves only as a metric, and the subsample leaves the direction's cost at about one extra gradient.
def conjugate_gradient(Fvp, g, iters=10):
x = zeros_like(g) # running solution of F x = g
r = g.copy() # residual g - F x
p = g.copy() # current search direction
for _ in range(iters):
Fp = Fvp(p) # the only access to F
a = (r @ r) / (p @ Fp)
x = x + a * p
r_new = r - a * Fp
p = r_new + ((r_new @ r_new) / (r @ r)) * p
r = r_new
return xConjugate gradient returns a direction . For the length, under the quadratic model a step costs KL ; setting that to gives the largest allowed :
Both approximations can be wrong at that length: the true KL can exceed , and the true surrogate can fall. TRPO therefore runs a backtracking line search on the actual functions. Starting from , it shrinks the step exponentially until the surrogate improves and the average KL is at most . The paper reports that without the line search the algorithm "occasionally computes large steps that cause a catastrophic degradation of performance." It does not give the shrink factor; the figure halves.
At the defaults the true KL at is , so the full step is rejected and the search accepts . Set the KL nonlinearity below 0 and the model step passes on the first try; raise the surrogate curvature above 1 and the full step loses surrogate value even when its KL is fine.
TRPO differs from the natural policy gradient in this step-length computation. Both use the direction . The natural policy gradient takes
with a fixed step size chosen as a hyperparameter. TRPO recomputes the length every update so that the constraint holds, and the paper's experiments credit this difference with a large improvement on the harder tasks. The same template also covers ordinary policy gradient (replace the KL constraint with ) and policy iteration (drop the constraint and maximize ).
The policies themselves are small. For continuous control, a Gaussian whose mean comes from a fully connected network (hidden-layer size 30 for the swimmer, 50 for the hopper and walker) and whose diagonal covariance is a separate, state-independent vector of log standard deviations. For Atari, two convolutional layers with 16 channels and stride 2 and a 20-unit fully connected layer, 33,500 parameters. One iteration end to end:
# one TRPO iteration, single path, reward maximization
batch = collect_trajectories(pi_old) # states, actions, rewards
Qhat = discounted_returns(batch) # Monte-Carlo Q along each path
Ahat = Qhat - value_baseline(batch.s) # advantage estimates
g = grad_surrogate(pi, batch, Ahat) # gradient of L at theta_old
def fisher_vector_product(v): # F v without ever forming F
sub = subsample(batch.s, frac=0.1) # F is only a metric: 10% suffices
kl = mean_kl(pi_old, pi, sub) # analytic KL, averaged over states
return grad(grad(kl, theta) @ v, theta) # Hessian-vector product
s = conjugate_gradient(fisher_vector_product, g, iters=10) # s ~= F^-1 g
beta = sqrt(2 * delta / (s @ fisher_vector_product(s))) # delta = 0.01
step = beta * s
# backtrack until the TRUE surrogate improves and the TRUE mean KL <= delta.
# the paper says "shrink exponentially"; halving is this sketch's choice.
for _ in range(max_backtracks):
theta_new = theta_old + step
if improved(theta_new) and mean_kl_at(theta_new) <= delta:
break
step *= 0.5Results: simulated locomotion and Atari
The locomotion tasks ran in the MuJoCo simulator: a swimmer (10-dimensional state, 364 policy parameters), a hopper (12-dimensional state, 4,806 parameters) and a walker (8,206 parameters; footnote 5 covers its state size), with rewards for forward progress and small penalties on effort. The hopper used one million simulation steps per iteration for 200 iterations. Both TRPO variants learned swimming, hopping and walking gaits with general-purpose networks, from scratch. The comparisons isolate the design choices:
- The natural policy gradient, identical to single path except for a fixed penalty coefficient (a fixed step size) instead of the KL constraint, with the step size swept in factors of three and the best one kept, did well on the two easier tasks and could not produce hopping or walking gaits that made forward progress.
- The gradient-free methods CEM and CMA, whose sample cost grows with the number of parameters, did poorly on the larger problems.
- The empirical-FIM variant improved at a rate similar to the analytic Fisher, and the maximum-KL constraint learned somewhat more slowly than the average one.
The learning curves average five runs per method. The paper reads them as evidence that constraining the KL is a more robust way to choose step sizes than a fixed penalty.
The Atari experiment tests generality. The same recipe, a convolutional policy trained from raw pixels with and , ran once on each of the seven games from the DQN paper. 500 iterations took about 30 hours on a 16-core machine. TRPO reached reasonable scores on all seven and beat deep Q-learning on four: single path on Enduro (534.6 vs 470), Seaquest (1,908.6 vs 1,705) and narrowly Q*bert (1,973.5 vs 1,952); vine on Q*bert by about four times (7,732.5); both variants on Pong (20.9 vs 20.0). It trailed deep Q-learning on Beam Rider, Breakout and Space Invaders, and the tree-search method UCC-I scored higher than both TRPO variants on all seven games. It was not state of the art, and the paper does not claim it was: unlike the comparison methods, it was not designed for Atari.
The trust-region update became a template. Proximal Policy Optimization (2017), by the same first author, keeps the bounded update and drops the expensive parts: no hard KL constraint, no conjugate gradient, no line search. It clips the probability ratio in the surrogate and optimizes with ordinary stochastic-gradient epochs over minibatches. Deep RL from Human Preferences (2017) trained its simulated-robotics policies with TRPO and its Atari policies with A2C.
Questions you might still have
Does TRPO guarantee that the policy never gets worse?
No. The proof covers the idealized Algorithm 1, with exact advantages, an exact maximization over all policies, the theoretical penalty C, and the maximum KL over states. Practical TRPO uses sampled estimates, a linear/quadratic approximation to find the step, a hard KL limit instead of the penalty, and the average KL instead of the maximum. Each change voids the proof. The paper says the practical algorithm "tends to" improve monotonically.
Why limit the KL divergence instead of the size of the parameter step?
Equal parameter distance does not mean equal change in behavior. Along a sensitive direction a tiny weight change moves the action probabilities a lot; along a flat direction a large weight change barely moves them. KL measures the change in the action distributions directly, so a fixed KL budget allows long steps along insensitive directions and short ones along sensitive directions. A fixed Euclidean step, which is what plain gradient ascent takes, overshoots along the sensitive directions.
Why not just use the penalty with a smaller constant C?
The theory fixes C = 4εγ/(1−γ)², about 40,000 times the largest advantage at γ = 0.99, and that gives tiny steps. Any smaller C has to be tuned, and the right value depends on the curvature of the return, which differs between tasks and changes during training. The paper found a fixed penalty hard to choose robustly, while a KL limit of δ = 0.01 worked unchanged on every task it tried.
What does δ = 0.01 mean in terms of action probabilities?
It is an average KL of 0.01 nats per state. For a two-action state where the old policy picks each action with probability 0.5, the limit allows moving to about 0.57/0.43. With more actions, or a Gaussian over continuous actions, the same budget is shared across the probabilities, and the line search adjusts the step so the measured average KL stays within it.
How expensive is a TRPO update compared with a plain policy-gradient step?
Not much more. The direction needs about 10 conjugate-gradient iterations, each one Fisher-vector product costing about one gradient; computing those products on 10% of the batch brings the total to roughly one extra gradient. The line search then evaluates the surrogate and KL a few times, which needs forward passes only. The expensive part of TRPO is usually collecting the samples.
What is the difference between TRPO and PPO?
PPO keeps the goal of a bounded update and drops the constrained solve. Instead of a hard KL limit enforced with conjugate gradient and a line search, it clips the probability ratio between new and old policy inside the surrogate, and optimizes that with several epochs of ordinary minibatch SGD on each batch. There is no Fisher matrix and no second-order computation. The Proximal Policy Optimization explainer covers it.
Single path or vine: which should I use?
Single path when you cannot reset the system to an arbitrary state, which includes real hardware: it needs only ordinary trajectories. Vine when a simulator can be reset and you can afford many more simulator calls in exchange for lower-variance advantage estimates. In the paper both variants solved the locomotion tasks, and on Atari each beat the other on some games.
Why does the surrogate overestimate the true return?
It keeps the old policy’s state-visit counts. A policy that changes where the agent spends its time changes those counts, and the surrogate ignores the change; its error equals the change in visits times the new policy’s expected advantage. In the two-state example on this page, always going is predicted to score 9.67 and actually scores 9.00, because the new policy spends one discounted step in the start state instead of 1.82. The KL penalty in the bound is the price for that frozen-visits approximation.
Footnotes & further reading
- The paper: Schulman, Levine, Moritz, Jordan, Abbeel, Trust Region Policy Optimization (UC Berkeley, ICML 2015). OpenAI's Spinning Up has an implementation-oriented write-up. It writes the KL constraint with the new policy first, the reverse of the paper's old-first order; the two agree to second order, so they have the same Fisher matrix and the same natural-gradient step.
- The identity, conservative policy iteration and the bound TRPO extends: Kakade and Langford, Approximately Optimal Approximate Reinforcement Learning (ICML 2002).
- The natural gradient direction: Kakade, A Natural Policy Gradient (NeurIPS 2001), building on Amari's Natural Gradient Works Efficiently in Learning (1998).
- The inequality is the form the paper cites from Pollard's Asymptopia; the paper never calls it Pinsker's inequality. The sharp Pinsker inequality, with the convention , is . Using it would halve the penalty . Both are valid; the looser one only makes the bound more conservative.
- An inconsistency to know if you reproduce the experiments: the walker's state dimension is 18 in the main text and 20 in the appendix table, with 8,206 policy parameters either way. Every experiment uses and .
- The successor that replaced the constraint with a clipped ratio: Schulman et al., Proximal Policy Optimization Algorithms (2017). TRPO was also one of the two reinforcement-learning algorithms behind Deep RL from Human Preferences, which noted that TRPO's trust region alone can under-explore when the reward being optimized keeps changing.
How could this explainer be improved? Found an error, or something unclear? I read every message.