Advanced RL: TRPO, PPO, DDPG & SAC

A robot learns which of three grasps works best. With a big step, plain policy gradient bets everything on the wrong grasp and never tries the good one again. A leash on each step, as in TRPO and PPO, keeps it learning.

Pick an updater and raise the step size. Watch where the policy puts its probability. Then we build, piece by piece, the fence each method puts around a step: the natural gradient, the KL leash, the clip, the critic and the entropy bonus.

You need a little Python, what a probability is and the policy gradient idea from Lectures 9 and 10. We rebuild what we use.

Lecture 11 of 25 in Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page. Every idea is re-taught here in our own words and devices. Next: Lecture 12, Model-Based Control Basics.

Teach a robot to grasp

5

Illustrative toy. Three grasps succeed 80%, 50% and 20% of the time. Each update samples 4 grasps and takes one policy-gradient step on a softmax policy, with the batch's mean reward as baseline. One fixed random seed for all three rules.

Chapter 0

One Bad Step, and the Policy Collapses

Take a step uphill, see where the gradient's promise breaks, and learn why a robot cannot undo it

Your policy-gradient agent works. It runs the policy, estimates which way the return goes up, and moves its weights that way. One number decides how far it moves. You picked that number by hand.

Call the policy's weights θ, the expected return J, and the step size α. The gradient ∇J is the direction in which J rises fastest.

Say it aloud

Theta-prime equals theta plus alpha times the gradient of J with respect to theta.

θ′
theta-prime the new weights after one update.
θ
theta the weights now.
α
alpha the step size, a number you choose.
∇θJ(θ)
the gradient of J the direction that raises the expected return J fastest, measured at θ.
In plain words

Measure the gradient at theta. Multiply it by alpha. Add it to theta to get theta-prime. The gradient promises a gain of about alpha times the gradient squared.

With numbers

With made-up numbers: θ = 0.5, gradient 2, α = 0.1. Then θ′ = 0.5 + 0.1 × 2 = 0.7, and the promised gain is 0.1 × 2 × 2 = 0.4.

Step off the peak

Yellow is the true return. Pink is the straight line the gradient believes. Slide α and compare the promised gain with the real one.

0.10

Illustrative curve. The cliff stands for a region where the new policy visits states the old data never saw.

Near the start, the line and the curve agree. Far out, they part. In supervised learning a bad step costs one noisy batch. In RL the policy collects its own data, so a bad policy collects bad data, and the next gradient comes from that.

The question of this lecture. How big a step is safe? Each method here answers with a different fence: a trust region, the set of new policies close enough to the old one that the gradient's picture still holds.

The failure, as symptom, measurement and fix

The symptom is a return curve that climbs, then drops and stays down. To measure it, log the change in the action probabilities at each update. The fix is to limit that change, which the rest of this page does five ways.

The road

  1. The map: two questions that sort every method.
  2. Natural gradient: measure a step by how much behaviour changes.
  3. TRPO: a hard limit on the KL divergence.
  4. The PPO clip: the same limit, sample by sample, in a plain loss (the hero's PPO).
  5. PPO epochs: many passes over one batch, and when to stop.
  6. DDPG and TD3: a deterministic actor that follows a critic.
  7. SAC: pay the policy to stay spread out.
  8. The race: the hero over 40 seeds, with every knob.
  9. The field guide: terms, numbers, code, links and credit.
Why is a too-large step worse in RL than in supervised learning?

Chapter 1

Two Questions Sort Every Method

Place seven algorithms on a grid by how they use data and what their policy outputs

You have a simulator that runs 10,000 steps a second, and a real arm that runs 20. Which algorithm do you pick for each? The lecture sorts model-free RL by what each method learns.

FamilyWhat it learnsExamples
Value-basedThe best Q-function. The policy acts greedily on it.FQI, DQN
Policy gradientThe policy itself, by climbing the return.REINFORCE, NPG, TRPO, PPO
Actor-criticA critic for the current policy, used to improve the actor.A2C, DDPG, TD3, SAC

No method wins everywhere. Each makes a trade between three things. Sample efficiency is the number of environment steps to good performance. Stability is how little it depends on settings and seeds. Its assumptions cover discrete or continuous actions and the type of policy.

Two yes-or-no questions place every method in this lecture. Is it on-policy, learning only from data the current policy collected, or off-policy, reusing old data from a replay buffer? Is the policy stochastic, giving a probability for each action, or deterministic, giving one action?

Place an algorithm

Columns: how the method uses data. Rows: what the policy outputs. Pick an algorithm.

The grid follows the lecture's two axes. The placement of each method is standard.

Back to the two machines. On the fast simulator, steps are cheap and PPO runs on many copies at once. On the real arm, each step costs seconds and wear, so SAC's reuse of every step matters more. More sample-efficient does not always mean less wall-clock time.

The failure, as symptom, measurement and fix

The symptom is a method that needs weeks of robot time. To measure it, count environment steps to a target return, then convert them to hours at your robot's rate. The fix is to move off-policy when steps are expensive, or to a simulator when they are cheap.

On a real robot, each step costs real seconds. Which property of SAC matters most there?

Chapter 2

Natural Gradient: Measure the Step in Behaviour

Swap a round fence in weight space for a fence in policy space, and gain more for the same change

Plain gradient ascent hides a fence. It picks the best step among all steps of the same length in weight space. But some weights barely move the policy, and others swing it hard. A round fence in weights becomes lopsided in behaviour.

The fix is to measure distance between the two policies themselves. The KL divergence is a standard distance from one probability distribution to another. For a small change Δθ in the weights, the KL is about one half of Δθ times F times Δθ. The Fisher information matrix F records how strongly each direction in weights changes the action probabilities.

Say it aloud

Theta-prime equals theta plus alpha times F-inverse times the gradient of J.

θ′
theta-prime the new weights.
θ
theta the weights now.
α
alpha the step size, set so the KL of the step equals a target ε.
F−1
F-inverse undoes the Fisher matrix: it shrinks sensitive directions and stretches gentle ones.
∇θJ
the gradient of J the plain uphill direction in weights.
In plain words

Take the plain gradient. Multiply it by F-inverse so each direction counts by how much it changes behaviour. Scale by alpha until the KL is epsilon. Add it to theta.

With numbers

With made-up numbers: F has 9 and 1 on its diagonal, the gradient is (1, 1), and the KL budget ε = 0.01. The plain step gains 0.089. The natural step, (0.015, 0.134), gains 0.149 for the same KL.

Fit the step inside the KL fence

The solid ellipse is every step with KL = 0.01. The dashed circle is a round ball in weights. Make one direction more sensitive and compare the two steps.

3.0

Illustrative 2-weight policy with F = diag(k², 1) and gradient (1, 1). The slider sets k. The device scales both steps to KL = 0.01.

At k = 1 the two steps match. As k grows, the round ball pokes far outside the ellipse along θ1: a step there changes the policy much more than its length suggests.

The failure, as symptom, measurement and fix

The symptom is a learning rate that is too big for some layers and too small for others. To measure it, compute the KL between old and new policy after each step. The fix is to set the step by KL, not by weight distance.

Why does the natural gradient use the Fisher matrix instead of the plain length of the weight change?

Chapter 3

TRPO: A Hard Leash on the KL

Score the new policy with the old policy's data, and cap how far the two may drift apart

An exact fact starts TRPO. The advantage of an action is how much better it is than the policy's average. The gain of a new policy over the old one equals the old policy's advantage, summed over the states the new policy visits. We do not have data from the new policy yet. CS 285, Advanced Policy Gradients derives this fact in full.

So TRPO uses the old policy's data and reweights each action. Call the old policy πold, the new one πnew, and the advantage A. The probability ratio πnew / πold says how much more likely the new policy makes that action.

Say it aloud

Maximize the average of pi-new of a given s over pi-old of a given s, times A of s and a, subject to the average KL from pi-old to pi-new being at most delta.

max
maximize choose the new policy that makes the next part largest.
E
the average over states s and actions a in the old policy's batch.
πnew / πold
pi-new over pi-old the probability ratio: 1 if nothing changed.
A(s, a)
A of s and a the advantage of action a in state s under the old policy.
KL(πold ‖ πnew)
the KL from pi-old to pi-new how far the action probabilities moved in that state.
δ
delta the leash: the largest average KL allowed. A common choice is 0.01.
In plain words

Raise the probability of actions with positive A and lower those with negative A. Weight each by the ratio. Reject any new policy whose average KL from the old one is above delta.

With numbers

With made-up numbers: one action has πold = 0.5, πnew = 0.6 and A = +1, so its term is 1.2. The policy moves from (0.5, 0.3, 0.2) to (0.6, 0.25, 0.15): KL = 0.021, above δ = 0.01, so TRPO halves the step.

Why the leash? The ratios carry the whole estimate. If an action had 0.05 under the old policy and 0.99 under the new, one sample counts 0.99 / 0.05 = 19.8 times. A few such samples swamp the estimate. A small KL keeps every ratio near 1.

Climb inside the leash

Brighter is higher return. Each step goes to the best point on the dashed circle, judged by the straight-line model. Set δ, then press Step a few times.

0.010

Illustrative 2-weight landscape. The circle radius is the square root of 2δ, as if F were the identity. Real TRPO also bends the step by F and line-searches it.

The failure, as symptom, measurement and fix

The symptom is slow, complex updates. Each TRPO step needs a conjugate-gradient solve for F−1 and a line search. It also mixes badly with dropout and with layers shared by the policy and value networks. To measure it, time one update. The fix the field chose is PPO.

TRPO scores the new policy with states from the old policy. What makes that valid?

Chapter 4

PPO: The Clip and the Min

Pin the ratio to a narrow band inside the loss, and see which side goes flat

PPO keeps TRPO's ratio and advantage but drops the constrained solve. It puts the leash inside the loss, so plain minibatch gradient ascent works.

Call the ratio at sample t r-t, the advantage A-t, and the band half-width ε. clip(r, 1 − ε, 1 + ε) pins r inside the band. With ε = 0.2, a ratio below 0.8 becomes 0.8, and one above 1.2 becomes 1.2.

Say it aloud

L-clip equals the average over t of the minimum of r-t times A-t, and clip of r-t between one minus epsilon and one plus epsilon, times A-t.

LCLIP
L-clip the objective PPO climbs.
Et
the average over t over the samples in the batch.
min
the minimum keep the smaller of the two terms, the pessimistic one.
rt
r-t the ratio πnew(at|st) / πold(at|st). It is 1 before any update.
At
A-t the advantage of the action taken at sample t.
clip(rt, 1−ε, 1+ε)
clip of r-t the ratio pinned to the band. The PPO paper's default ε is 0.2.
In plain words

For each sample, compute r-t times A-t, and the same with r-t clipped. Keep the smaller. Average over the batch. Where the clipped term wins, the term is flat, so the gradient stops pushing.

With numbers

With made-up numbers: r-t = 1.5, A-t = +2, ε = 0.2. Unclipped 3.0, clipped 1.2 × 2 = 2.4, minimum 2.4. Raise r-t to 2.0 and the term stays 2.4: no more push.

Find the flat side

Dashed: the unclipped r · A. Yellow: L-clip. Flip the sign of A and drag the ratio.

1.50
0.20

The curve is the exact formula. The advantages are made-up numbers.

Ratio rA = +2: LA = −2: LWhat happens
0.51.0−1.6 (flat)A failed grasp already made rarer: stop pushing it down.
1.02.0−2.0No change yet: both terms agree.
1.52.4 (flat)−3.0A good grasp: stop pushing it up. A bad grasp made likelier: full penalty.

Read the last row. A failed grasp that the new policy made more likely keeps its full −3.0 and its gradient. Without the min, that mistake would cap at −2.4 and escape part of its penalty.

The failure, as symptom, measurement and fix

The symptom is a policy that still jumps despite the clip. To measure it, log the clip fraction, the share of samples outside the band. If it is high, lower the learning rate or ε.

ε = 0.2, A = +2, and r = 1.8. What does L-clip do?

Chapter 5

PPO in a Loop: Many Epochs on One Batch

Run gradient steps on one batch until the samples freeze at the edge of the band

The clip lives inside a plain loss, so PPO can do what TRPO cannot: several passes over the same batch. Each pass is an epoch. One PPO iteration runs like this.

  1. Collect. Run the current policy, πold, and store each state, action, reward and πold(a|s).
  2. Score. Compute an advantage A for each sample, here the reward minus the batch mean.
  3. Climb. Take K gradient steps on L-clip. Samples whose ratio leaves the band on their own side stop contributing.
  4. Stop early if the KL from πold passes a limit. Then πnew becomes πold and you collect again.

Run epochs on one batch

Each row is one grasp from the batch. Green worked, red failed. A hollow dot sits outside the band on its own side, so it no longer pushes. Press Epoch, then try a big learning rate.

0.50

Illustrative batch of 8 grasps from πold = (top 0.40, side 0.35, pinch 0.25). The baseline is the mean reward, 0.5, so each advantage is +0.5 or −0.5. One epoch is one full-batch gradient step with ε = 0.2.

Work one sample. The first row is a top grasp that worked, so A = +0.5. Its ratio starts at 1.00 and grows by about 0.06 per epoch at learning rate 0.5. At epoch 4 it reaches 1.24, past the band, so its term goes flat and it stops pulling. All top grasps share one ratio, because the ratio depends only on the action.

Now set the learning rate to 12. One epoch throws the top grasp's ratio far past 1.2 before the clip can act. The clip zeroes the gradient after the jump, not before it.

The failure, as symptom, measurement and fix

The symptom is a collapse even with clipping on. To measure it, log the approximate KL and the clip fraction after each epoch. The fix is a smaller learning rate, fewer epochs, or the early stop on KL.

Why can PPO take many gradient steps on one batch when vanilla policy gradient cannot?

Chapter 6

DDPG and TD3: Follow the Critic

Push a deterministic action up the critic's slope, then stop it from climbing a false peak

PPO throws its data away after each iteration. For a real arm with continuous torques, that waste hurts. DDPG (Deep Deterministic Policy Gradient) keeps every step in a replay buffer and learns two networks.

Call the critic's weights φ and the actor's weights θ. The actor wants the action the critic rates highest, so the gradient flows through the critic into the actor.

Say it aloud

The gradient of J with respect to theta equals the average over s of the gradient of Q-phi with respect to a, at a equals mu-theta of s, times the gradient of mu-theta with respect to theta.

∇θJ
the gradient of J how to change the actor's weights to raise the return.
Es
the average over s over states drawn from the replay buffer.
∇aQφ
the gradient of Q-phi with respect to a which way to move the action to raise the critic's score, at the actor's own action.
∇θμθ(s)
the gradient of mu-theta how the actor's output moves when its weights move.
In plain words

Ask the critic which way to move the action. Pass that direction back through the actor to its weights. Average over replayed states and step the weights.

With numbers

With made-up numbers: the actor is μ(s) = θs with θ = −0.2 and s = 0.5, so a = −0.1. The critic is Q = −(a − 0.3)², with slope 0.8 there. The gradient is 0.8 × 0.5 = 0.4. A step of 0.5 × 0.4 moves θ to 0.0 and a to 0.0, nearer the best action, 0.3.

No reward, ratio or log-probability appears. For a 17-number state and a 6-torque action, the critic returns 6 numbers: raise this torque, lower that one.

Climb the critic, find the false peak

Pink is the learned critic, with one false spike. Dashed yellow is the true value. Set the actor's start, press Climb, then switch on target smoothing.

0.70

Illustrative 1-D action. The spike is a critic error. Smoothing averages the critic over action noise of 0.2, clipped at 0.5, as TD3's target smoothing does to the training target.

The critic learns from its own guesses, so its errors feed back. A deterministic actor finds any false peak and sits on it. TD3 (Twin Delayed DDPG) adds three patches.

PatchWhat it doesWhich error it fights
Twin criticsTrain two critics; the target uses the smaller value.Overestimation of Q
Target smoothingAdd small clipped noise to the target action.Narrow false peaks
Delayed actorUpdate the actor less often than the critic.Chasing a critic that has not settled

The failure, as symptom, measurement and fix

The symptom is critic values that climb while the real return stays flat. To measure it, compare the critic's Q with the return you observe from the same states. The fix is TD3's patches. A deterministic actor also explores nothing alone, so DDPG and TD3 add noise to actions while collecting data.

How does DDPG's deterministic actor learn which action to output?

Chapter 7

SAC: Pay the Policy to Stay Curious

Add an entropy bonus to the reward, and watch a spread-out policy notice when the world changes

SAC (Soft Actor-Critic) keeps DDPG's replay buffer but makes the policy stochastic again. It also pays the policy for being unpredictable. The entropy of a policy measures how spread out its action probabilities are.

Call the probability of action i p-i. The entropy H is zero when one action has all the probability, and largest when all actions are equal.

Say it aloud

H equals minus the sum over i of p-i times log p-i.

H
H the entropy of the policy in one state, in nats.
−
minus makes H positive, because each log p-i is negative.
Σi
the sum over i one term per action.
pi
p-i the probability of action i.
log pi
log p-i the natural log: far below zero for a rare action.
In plain words

For each action, multiply its probability p-i by the log of p-i. Add these up and flip the sign. The result is H.

With numbers

Grasp probabilities (0.90, 0.05, 0.05) give H = 0.394. Near-equal (0.34, 0.33, 0.33) give H = 1.098, close to the 3-action maximum, log 3 = 1.099.

SAC adds that entropy, scaled by a temperature α, to every step's reward. Call the reward r(st, at) and the policy in state st π(·|st).

Say it aloud

J of pi equals the expected value of the sum over t of r of s-t and a-t, plus alpha times H of pi given s-t.

J(π)
J of pi the soft objective SAC maximizes.
E
the expected value the average over many runs of the policy.
Σt
the sum over t one term per step of the run.
r(st, at)
r of s-t and a-t the task reward at step t.
α
alpha the temperature: how much one nat of entropy is worth in reward.
H(π(·|st))
H of pi given s-t the policy's entropy in the state it is in.
In plain words

At each step, take the task reward. Add alpha times the policy's entropy in that state. Sum over the run and average over many runs. That is J of pi.

With numbers

With made-up numbers and α = 0.2: the spread policy earns 0.2 × 1.098 = 0.220 bonus per step, the peaked one 0.2 × 0.394 = 0.079. A grasp step with reward 1 is worth 1.220 or 1.079.

Change the world, see who notices

At attempt 80 the robot gets softer pads, and the side grasp now works 95% of the time. Set the temperature, then press Run.

0.10

Illustrative one-step bandit. The policy is the softmax of value estimates divided by α, which is the best policy for reward plus αH in one step. Estimates update by 10% toward each result. The averages use 50 seeds.

A cold policy never tries the side grasp again, so it never learns it improved. A hot policy finds out, but wastes tries on the pinch. The best temperature sits between. SAC can also tune α itself, toward a target entropy.

The failure, as symptom, measurement and fix

The symptom is a policy that locks onto one action early and never improves. To measure it, log the policy's entropy over training. If it falls to zero while the return is still low, raise α or let SAC tune it.

What does SAC's entropy bonus buy?

Chapter 8

Showcase: Race the Three Updaters

Run the hero's grasp robot 40 times per setting and count how often each rule collapses

One seed proves little. Here the hero's robot runs 40 times with different random seeds at each of six step sizes. A run collapses if, after 30 updates, it gives the top grasp less than 10% probability. You hold every knob from the earlier chapters.

Count the collapses

Each line counts collapsed runs out of 40 at six step sizes. The marker is the step size you pick. Shrink the batch, loosen the leash, widen the clip.

20
0.020
0.20

Illustrative toy, the hero's. PPO splits the same step size over 10 smaller clipped steps on each batch. Seeds 1 to 40 are the same for every rule.

With 4 grasps and step size 20, vanilla collapses in 8 of 40 runs, the leash in none, PPO in none. Push the step to 40 and PPO loses a couple: the clip is a brake, not a wall. Loosen the leash to 0.2 and TRPO-style starts to fail too. Give each update 16 grasps and every rule gets safer, because the gradient is less noisy.

The failure, as symptom, measurement and fix

The symptom is a method that "works" on one seed and fails on the next. To measure it, run 5 or more seeds and report the spread. The fix is a trust region plus enough data per update.

In the race, what happens to every rule's collapse count when each update uses 16 grasps instead of 4?

Chapter 9

The Field Guide

Keep the fences, the numbers, a checklist and the PPO update in code

Every method here answers one question: how big a step is safe? Each puts a different fence around the step, or reuses data so each step costs less.

MethodIts fenceDataPolicy
Vanilla PGNone: a hand-set αOn-policyStochastic
NPGStep measured by F, the KL rulerOn-policyStochastic
TRPOAverage KL ≤ δ, enforcedOn-policyStochastic
PPORatio clipped to [1 − ε, 1 + ε] inside the lossOn-policyStochastic
DDPG, TD3Replay plus target networks; TD3 adds twin critics, smoothing, delayOff-policyDeterministic
SACEntropy bonus αH plus twin criticsOff-policyStochastic

Terms and numbers

TermOne lineNumber to remember
Stepθ′ = θ + α∇J. The promise holds only nearby.0.5 to 0.7, promised gain 0.4
KL for a small stepAbout one half of Δθ F Δθ.Natural step: 0.149 gain vs 0.089 at KL 0.01
Probability ratioπnew(a|s) / πold(a|s); 1 when unchanged.0.99 / 0.05 = 19.8
TRPO leashAverage KL from old to new at most δ.KL 0.021 > 0.01: halve the step
PPO clipmin(rA, clip(r) A); flat for a good action past 1 + ε.r 1.5, A +2: 2.4
DPGCritic slope in a, times actor slope in θ.0.8 × 0.5 = 0.4
EntropyH = −sum of p log p.0.394 peaked, 1.098 spread

Before you pick an algorithm

  1. Where is data cheap? Fast parallel simulator: start with PPO. Real robot: start with SAC.
  2. Is the action continuous? DDPG, TD3 and SAC target it. PPO handles both.
  3. Log the KL and the clip fraction (PPO), or the critic's Q against the observed return (DDPG, TD3, SAC).
  4. Run at least 5 seeds before you trust a result.
  5. Watch the entropy. If it hits zero while the return is low, the policy stopped exploring.

The PPO update in code

pythondef ppo_update(policy, batch, epochs=10, eps=0.2, kl_stop=0.02):
    s, a, logp_old, A = batch                  # logp_old saved when the data was collected
    for _ in range(epochs):
        logp = policy.log_prob(s, a)
        r = (logp - logp_old).exp()          # probability ratio pi_new / pi_old
        L = torch.min(r * A, r.clamp(1 - eps, 1 + eps) * A).mean()
        policy.step(-L)                       # gradient ascent on L-clip
        if (logp_old - logp).mean() > kl_stop:  # approximate KL from the old policy
            break

Keep going on this site

The takeaway. Take the biggest step that keeps the new policy close to the one that collected your data. Measure "close" by behaviour, and log it.

This lesson follows Lecture 11, "Advanced RL", of CMU 16-831 Introduction to Robot Learning, Spring 2024, taught by Guanya Shi. The slides are on the lectures page. The methods come from Schulman et al., TRPO (2015) and PPO (2017); Lillicrap et al., DDPG (2015); Fujimoto et al., TD3 (2018); and Haarnoja et al., SAC (2018).

Now press Present or Teach and explain from memory. Why does one big step collapse a policy? What does the Fisher matrix measure? Why does TRPO's leash keep the ratios honest? Which side of the clip goes flat? How does the DDPG actor follow the critic, and what does SAC pay for? Then go back to the grasp robot, set the step size to 20, and say why only vanilla bets on the side grasp.

Introduction to Robot Learning · CMU 16-831 · Lecture 11: Advanced RL, TRPO, PPO, DDPG and SAC
Next: Model-Based Control Basics · Back to Gleams