PPO reuses one batch for many gradient steps. That is safe only near the old policy. Inside a small KL ball, the estimate from old samples tracks the true gain. Outside it, the two part.
Drag the teal dot, the new policy, across the map. Watch the warm estimate and the purple truth. Then we prove, step by step, why the yellow ball makes reuse safe.
You need policy gradients and PPO's clip and importance weights. We build the rest from zero.
A supplement to UC Berkeley CS 185/285, Deep Reinforcement Learning, taught by Sergey Levine. It follows Lecture 9 and Lecture 10, with Lecture 2, Lecture 21 and sections 2.2 and 5. The words, toys and devices here are our own.
Illustrative toy, ours: a 7-state corridor, 10 steps, two actions, policy π(right | s) = sigmoid(θ1 + θ2 xs). The old policy sits at (0.5, −0.5). Dynamic programming gives every number exactly. The estimate is the average the old samples would give, with no sampling noise. The loop marks an average KL of 0.03.
Chapter 0
Write the exact gradient for reused data, then see the two terms PPO drops
Your robot collected 2,048 steps with the old policy πθ. Plain policy gradient takes one step with them and throws them away. PPO takes about 10 passes over the same batch. Why does that not break the maths?
After the first step, the samples come from πθ, not from the new policy πθ′. Importance weights correct for that. The exact gradient gives each step t three kinds of factor:
Causality, the rule that an action cannot change earlier rewards, already removes the ratios of later actions from the score of step t. The two shortcuts go further. Shortcut 1 drops the future ratios, so the old policy's advantage  stands in for the new one's. Shortcut 2 drops the state ratio. What is left is PPO's gradient.
Grad J at theta-prime is about one over N times the sum over i and t of the action ratio, times grad log pi-theta-prime of a-t given s-t, times A-hat-t.
For each old step, push up the action's chance by its advantage A-hat, scaled by how much more the new policy likes it. No state ratio, no future ratios.
With made-up numbers: the old policy went right with chance 0.5, the new one with 0.6. The ratio is 1.2. With A-hat = +0.5, this step pushes with weight 1.2 × 0.5 = 0.6. A product of ten such ratios would be 1.210, about 6.2.
The device estimates the gain J(θ′) − J(θ) three ways from the same old batches. Watch the trade as the new policy moves away.
Each dot is one batch of 50 old trajectories. The purple line is the true gain. Slide the new policy away from the old one.
The hero's toy. The new policy is (0.5, −0.5) + step × (0.5, −1). 120 batches per row. The first-order row uses the exact old advantage, as a perfect critic would.
The two exact rows stay centred on the truth, but their spread grows as the policies part. The first-order row stays tight, but it drifts high. Lecture 9 calls it "a little bit wrong". The rest of this lesson measures how wrong, and when that is safe.
The failure: you reuse a batch for too many passes. The symptom is a surrogate that keeps rising while fresh returns fall. Measure it by checking each update with new rollouts. The fix is a limit on how far the policy moves, which Chapters 3 to 5 build.
Chapter 1
Prove the performance difference identity by telescoping, and justify shortcut 1
Plain policy gradient has two steps: estimate the advantage of the current policy, then move toward actions with a high advantage. That is policy iteration, the loop that evaluates a policy and then improves it, done softly. So ask the policy iteration question: how much does the new policy gain?
Call the expected return of a policy J. Call the old policy's value of a state V and its advantage A = r + γV(st+1) − V(st). The answer is exact.
J of theta-prime minus J of theta equals the expected value, over trajectories from p-theta-prime, of the sum over t of gamma to the t times A-pi-theta of s-t, a-t.
Run the new policy. Score every step with the old advantage A. Add the scores along each trajectory and average. That average is the gain, exactly.
With made-up numbers and γ = 1: V(s0) = 1.5, rewards 0, 1, 1, values 2.5 then 1.2 then 0. The advantages are 1.0, −0.3 and −0.2. They sum to 0.5, which is the return 2 minus V(s0) = 1.5.
The proof is a telescoping sum. Both policies start from the same state distribution, so J(θ) is the average of V(s0) under either one.
Every V(st) after the first appears once with a plus and once with a minus. Only V(s0) and the rewards survive.
Top: the old advantage at each step of the latest new trajectory. Bottom: the running average of their sums. Draw trajectories and watch it settle.
The hero's toy. Old policy (0.5, −0.5), new policy (1.5, −2.5). The true gain, 1.062, comes from dynamic programming.
Now split the average into states and actions. The actions come from πθ′, and one action ratio moves them onto old samples with no error. So the old advantage is the right weight: shortcut 1 is exact. The states still come from pθ′. That is shortcut 2, and it is harder.
The failure: the identity needs the true old advantage. A biased critic gives a biased gain. Measure it by comparing critic advantages with Monte Carlo returns on a held-out batch. The fix is a low-bias estimator such as GAE with λ near 1.
Chapter 2
Split the new state distribution into "no mistake yet" and the rest, and get both the cloning bound and the state shift bound
A tightrope walker copies an expert and slips with chance ε on each step. One slip, and she is somewhere no demo went: the compounding error of behaviour cloning. Lecture 10 asks the same of a policy update. How far can the new state distribution drift?
Measure drift with the total variation distance, half the summed absolute difference of two distributions: DTV(p, q) = ½ Σx |p(x) − q(x)|. It runs from 0 to 1.
Call a policy ε-close to another if, in every state, their action distributions are at most ε apart in TV. The coupling lemma says you can then run both policies on shared random numbers so they pick different actions with chance at most ε. Until the first disagreement, both visit the same states.
p-theta-prime of s-t equals one minus epsilon to the t, times p-theta of s-t, plus one minus that, times p-mistake of s-t.
With chance (1 − ε)t there was no disagreement yet, so the new policy is where the old one is. With the rest of the chance, it could be anywhere.
With made-up numbers ε = 0.01 and t = 50: (0.99)50 = 0.605. So 60.5% of the new policy's mass at step 50 matches the old policy.
Put this into the TV distance. The shared part cancels, and the TV of the unknown part is at most 1.
D-TV between p-theta-prime and p-theta at step t is at most one minus one minus epsilon to the t, which is at most epsilon t.
The drift at step t is at most the chance of a disagreement by then. That chance grows by at most epsilon per step.
With ε = 0.01 and t = 50: the exact ceiling is 1 − 0.605 = 0.395, and the line gives 0.5.
For cloning, add the expected mistakes over H steps. At step t, the mistake rate on expert states is ε. The drift adds at most 2DTV ≤ 2εt, since a mistake costs at most 1:
With ε = 0.001 and H = 100, that is 10.2 expected mistakes. Independent test errors would give εH = 0.1.
Blue is the mass with no disagreement yet. Yellow is the drift ceiling. Pick a reading, then move ε and H.
Arithmetic from the equations above; ε runs from 0.001 to 0.1 on a log scale.
The failure: the bound can say nothing. With ε = 0.01 and H = 100, εH(H+2) = 102, more mistakes than steps. Check εH first. If it is above about 1, shrink ε or the horizon, or collect data on the learner's own states as DAgger does.
Chapter 3
Bound the error of shortcut 2, turn the bound into a trust region, and swap TV for KL
Shortcut 2 replaces the new state distribution with the old one. Call the result the surrogate Ā(θ′): the old states, the action ratio, and the old advantage. It is what the old batch can estimate. The gain identity uses the new states. How far apart can the two be?
For any function f of the state, a change of distribution moves its average by at most the summed difference times the largest |f|. With the drift from Chapter 2:
Take f as the advantage term of step t and add over the steps.
J of theta-prime minus J of theta is at least A-bar of theta-prime, minus the sum over t of two epsilon t times C.
The true gain is at least the surrogate A-bar, minus a penalty. The penalty grows with epsilon, the step size in TV, and with the horizon.
In our toy, move θ1 by 0.2: ε = 0.050, A-bar = 0.460, penalty 0.248. The bound promises a gain of at least 0.211. The true gain is 0.436.
So maximising the surrogate within a small ε maximises a floor under the true gain. That is a trust region: a set of nearby policies where you can trust the surrogate. In the toy the advantage term itself shrinks with ε, so the penalty is second order and the floor rises before it falls.
Purple is the true gain, warm the surrogate, yellow the guaranteed floor. Pick a direction and slide the step.
The hero's toy, from the old policy (0.5, −0.5). Here C is the largest |advantage term| at each step, computed exactly, and ε is the largest TV over all 7 states.
TV is awkward to constrain. KL divergence is DKL(p ‖ q) = Ex~p[log p(x) − log q(x)]. It is easy to estimate from samples, and Pinsker's inequality links it to TV.
D-TV between pi-theta-prime and pi-theta is at most the square root of one half of D-KL of pi-theta from pi-theta-prime.
Keep the KL from the old policy to the new one small, and the TV gap epsilon stays small too. So a KL limit delta gives a TV limit.
A KL of 0.02 gives ε ≤ √(0.5 × 0.02) = 0.1.
The failure: the guarantee needs a KL limit in every state, but practical methods limit the average KL over visited states. A rarely visited state can still change a lot. Measure the largest per-state KL in the batch beside the average. If one state dominates, lower δ.
Chapter 4
Estimate the KL from the batch, tune its weight by dual ascent, and see what PPO's clip approximates
You cannot enforce a KL limit directly with gradient steps. But you can estimate the KL from the batch you already have. Each old sample gives log πθ minus log πθ′ for the action it took:
The first term does not depend on θ′. So lowering this KL means raising the likelihood of the old actions under the new policy. The penalty does supervised learning on your own batch.
L of theta-prime and beta is about the sum over i and t of the ratio times A-hat-t, plus beta times the average of log pi-theta-prime of the old actions.
Chase the advantage with the surrogate. At the same time, keep assigning high probability to what the old policy did. Beta sets the balance.
With made-up numbers: an old action had chance 0.8, the new policy gives it 0.7. Its KL term is log(0.8/0.7) = 0.134. With β = 0.5 the penalty costs 0.067 for that sample.
Which β? Treat it as a Lagrange multiplier, a price on breaking the limit δ. After the inner steps, raise the price if the KL went over the limit, and lower it if it stayed under. This is dual gradient ascent.
Beta becomes beta plus alpha times the KL minus delta.
If the KL came out above delta, beta goes up by alpha times the excess. If it came out below, beta goes down.
With made-up numbers β = 0.5, α = 2, δ = 0.05 and a measured KL of 0.12: β becomes 0.5 + 2 × 0.07 = 0.64.
Top: the true return after each batch. Bottom: the KL of each update against the yellow limit. Choose a rule and run.
Illustrative toy, ours: 16 trajectories per batch, 10 gradient steps of size 0.3, exact old advantages, δ = 0.05, α = 2. Over 20 seeds, the return fell by more than 0.05 on this many of 20 batches: 3.3 with no penalty, 1.4 with fixed β, 0.05 with dual ascent.
PPO-Clip drops β and caps each sample's ratio instead. Lecture 10 calls it a heuristic approximation to PPO-KL. The PPO chapter works the clip; this table adds why the min is there.
| Case | min(rÂ, clip(r)Â) gives | Effect |
|---|---|---|
| Â > 0, r > 1 + εclip | the clipped term, flat | No reward for pushing the action up further. |
| Â < 0, r < 1 − εclip | the clipped term, flat | No reward for pushing the action down further. |
| Â < 0, r > 1 + εclip | the unclipped term, still falling | The policy pays for drifting toward a bad action. A clip alone would go flat here. |
| Â > 0, r < 1 − εclip | the unclipped term, still rising | The min pulls the policy back toward a good action. |
The failure: the first batch overshoots. In the device's dual run, the first update has a KL near 2.5 before β reacts. Measure the KL after every inner step. The fix is an early stop of the inner loop once the KL passes about 1.5δ.
Chapter 5
Measure a step by how much the policy changes, solve for it with the Fisher matrix, and never build that matrix
Plain gradient ascent takes the best step inside a circle of parameters. But some parameters move the action probabilities far more than others. The right limit is the KL ball from Chapter 3.
Linearise the surrogate around θ: its slope there is the ordinary policy gradient g, because every ratio is 1. Then expand the KL to second order in the step Δθ = θ′ − θ.
D-KL of pi-theta from pi-theta-prime is about one half delta-theta transpose F delta-theta, where F is the expected outer product of grad log pi with itself.
F says how fast the policy's choices change in each direction. Directions that change choices a lot cost a lot of KL.
In our toy at the old policy, F = [[0.238, 0.064], [0.064, 0.073]]. A step Δθ = (0.466, −0.332) gives ½Δθ⊤FΔθ = 0.020. The exact KL is 0.019.
Now maximise g⊤Δθ subject to ½Δθ⊤FΔθ ≤ δ. Setting the Lagrangian's gradient to zero gives a step along F−1g, the natural gradient.
Theta-prime equals theta plus the square root of two delta over g transpose F inverse g, times F inverse g.
Solve F x = g for the direction x. Scale x so the KL of the step is delta. Add it to theta.
In our toy, g = (2.358, 0.140) and F−1g = (12.23, −8.73), so g⊤F−1g = 27.6. With δ = 0.02, α = √(0.04 / 27.6) = 0.038, and the step is (0.466, −0.332). J rises from 1.98 to 2.83.
A plain step of the same length, (0.571, 0.034), spends a KL of 0.038: twice the budget. The natural step turns toward θ2, where the policy is less sensitive.
Warm is plain ascent, teal is natural, over the true return. Rescale the second feature by c, then run.
Toy, ours: π(right | s) = sigmoid(θ1 + θ2 c xs), start (−2, 0). Plain step size 1. Natural δ = 0.05, halved until J rises, like TRPO's line search.
The natural path is the same for every c until the map edge stops it. The plain path depends on how you wrote the policy. Lecture 10 shows this on a Gaussian controller (Peters and Schaal, 2008), where plain gradients point mostly at the noise parameter.
TRPO never builds F. It solves F x = g with conjugate gradient, which needs only Fisher-vector products. Autodiff gives one for about the cost of a gradient. A damping term, (F + ηI)x = g, keeps the solve stable.
The failure: near a deterministic policy, F is almost singular and F−1g explodes. Measure the KL after each step. The fix is damping plus a line search that halves the step until the KL and the surrogate pass.
Chapter 6
Keep the chain, the numbers, the checklist and the code in one place
Policy gradient is soft policy iteration. The gain of a new policy is the old advantage on new trajectories. The surrogate swaps in the old states, and one coupling argument bounds that error by a penalty that grows with the step. So a small KL step is a safe step. PPO-KL enforces it with a penalty priced by dual ascent, PPO-Clip approximates it, and TRPO solves it with the natural gradient.
| Term | Meaning |
|---|---|
| Surrogate Ā(θ′) | The gain estimated on old states with the action ratio and the old advantage. |
| Performance difference identity | J(θ′) − J(θ) is the old advantage averaged over new trajectories. |
| Total variation (TV) | Half the summed absolute difference of two distributions, from 0 to 1. |
| Coupling lemma | Two distributions at TV ε can share random numbers and differ with chance ε. |
| Trust region | The nearby policies where the surrogate is a safe guide. |
| KL, old from new | DKL(πθ ‖ πθ′): old actions, log old chance minus log new chance. |
| Dual ascent | Raise the price β when the KL is over the limit, lower it when under. |
| Fisher matrix F | The expected outer product of the score; the KL's curvature. |
| Natural gradient | F−1g: the steepest step per unit of KL. |
| What | Number | Source |
|---|---|---|
| State drift after t steps | ≤ 1 − (1−ε)t ≤ εt | Lecture 10, the coupling argument (TV with the ½) |
| Cloning mistakes over H steps | ≤ εH(H+2), order εH2 | Lecture 2, Section 2.2 |
| Penalty constant C | order H rmax, or rmax/(1−γ) | Lecture 10 |
| Pinsker | KL 0.02 gives TV ≤ 0.1 | Lecture 10, our arithmetic |
| Clip width | εclip "try 0.1" | Lecture 9 |
| Natural step size | √(2δ / g⊤F−1g) | Section 5 (the Lecture 10 slide writes F, not F−1) |
| Toy: guaranteed step | θ1 + 0.2: floor 0.211, truth 0.436 | Our toy, illustrative |
| Toy: natural step | δ = 0.02, J 1.98 to 2.83 | Our toy, illustrative |
| Method | How it limits the step | Trade |
|---|---|---|
| PPO-KL | Penalty β × KL, β set by dual ascent; many small steps | First order and simple; the KL can overshoot early |
| PPO-Clip | Caps each sample's ratio, with the min for safety | Simplest; no real bound on the KL |
| TRPO | One natural step to the KL edge, then a line search | Closest to the theory; needs conjugate gradient |
pythonimport torch def ppo_kl_update(policy, batch, beta, delta, K=10, alpha=2.0, lr=3e-4): # batch: obs [M, obs_dim], act [M], adv [M], logp_old [M], all from the old policy opt = torch.optim.Adam(policy.parameters(), lr=lr) for _ in range(K): logp = policy.log_prob(batch.obs, batch.act) # [M] ratio = torch.exp(logp - batch.logp_old) # starts at 1 surrogate = (ratio * batch.adv).mean() loss = -(surrogate + beta * logp.mean()) # KL penalty = likelihood of old actions opt.zero_grad(); loss.backward(); opt.step() kl = (batch.logp_old - policy.log_prob(batch.obs, batch.act)).mean().item() if kl > 1.5 * delta: break # early stop return max(0.0, beta + alpha * (kl - delta)) # dual ascent on beta def conjugate_gradient(fvp, g, iters=10, damping=0.1): # solve (F + damping I) x = g using only Fisher-vector products fvp(v) x = torch.zeros_like(g); r = g.clone(); p = g.clone(); rr = r @ r for _ in range(iters): Fp = fvp(p) + damping * p a = rr / (p @ Fp); x += a * p; r -= a * Fp rr_new = r @ r; p = r + (rr_new / rr) * p; rr = rr_new return x def natural_step(g, fvp, delta): x = conjugate_gradient(fvp, g) # x = F^-1 g step_len = torch.sqrt(2 * delta / (g @ x)) # sqrt(2 delta / g^T F^-1 g) return step_len * x # then line-search by halving
Now press Present or Teach and derive the chain from memory: the two shortcuts, the telescoping sum, the coupling bound, Pinsker, the KL penalty and the natural step. Then go back to the map and find a new policy where the estimate says up and the truth says down.
This lesson supplements UC Berkeley CS 185/285, Deep Reinforcement Learning, taught by Sergey Levine. The course page is rail.eecs.berkeley.edu/deeprlcourse. It draws on Lecture 2, Lecture 9, Lecture 10, Lecture 21, and sections 2.2 and 5. The trust region proof follows Schulman, Levine, Moritz, Jordan and Abbeel, Trust Region Policy Optimization (2015). The explanations, toys and devices are ours.