Part II · Scaling Up: Function Approximation & Deep RL
10.Policy Gradients: REINFORCE → PPO
“Policy search methods are often the preferred approach in robotics, as they scale to high-dimensional continuous action spaces and allow the incorporation of task-appropriate prior structure into the policy.”
Chapter 9 hit a wall: computing max over actions requires enumerating them, and robots command continuous torques. So stop learning a value function and extracting a policy from it — parameterize the policy directly and ascend the gradient of expected return. The policy gradient theorem makes that computable despite the fact that the distribution you are averaging over depends on the parameters you are differentiating. The result is PPO: the algorithm behind more real-world robot RL successes than every method in Chapter 9 combined.
Foundation
The policy gradient theorem with full derivation, score-function estimators and their variance, baselines and advantage, GAE, the performance-difference lemma, TRPO’s trust region, and PPO’s clipped surrogate.
Conceptual
Three unbiased gradient estimators sampled hundreds of times, so the variance collapse from baselines is something you see rather than something you are told.
Practical
REINFORCE → A2C → PPO in burn with rayon-vectorized environments, solving Pendle's swing-up with a Gaussian policy.
After this chapter you can
- State three concrete reasons robotics prefers policy search over value-based methods
- Derive the policy gradient theorem line by line, including why the state-distribution term vanishes
- Explain why baselines reduce variance without introducing bias, and derive the advantage form
- Derive GAE and identify it as Chapter 7’s λ-return applied to advantages
- Explain the trust-region argument and how PPO’s clipped surrogate approximates it cheaply
- List the implementation details that actually decide whether PPO works, and why each matters
10.1 Why robotics chose policy search
Three reasons, all of which matter more on hardware than on benchmarks.
Continuous actions are natural. A policy that outputs the mean and standard deviation of a Gaussian over joint torques needs no argmax. Chapter 9's wall simply is not there.
Updates are smooth. A small parameter change produces a small change in behaviour. Value-based methods can flip the argmax at many states from one gradient step to the next, and a robot whose policy changes discontinuously mid-training is a robot that breaks something. This alone is worth a great deal of sample efficiency.
Prior structure fits naturally. You can constrain the policy class to whatever you know: a movement primitive with learnable weights (Chapter 17), a residual on top of a hand-tuned controller, an action space that respects joint limits by construction. Kober and colleagues make this argument at length, and it remains correct.
The cost is that policy gradient methods are usually on-policy — data must come from the current policy, so it is discarded after each update. That is expensive. It is also, per Chapter 8, exactly why they are stable: dropping the off-policy ingredient breaks the deadly triad.
10.2 The policy gradient theorem
Parameterize the policy as and define the objective as expected return from the start-state distribution:
We want . The difficulty is immediate: averages over trajectories whose distribution depends on . Differentiating an expectation whose measure moves is not a routine operation.
The score-function identity resolves it. For any distribution ,
which is just the chain rule on , rearranged. It converts a gradient of a probability into an expectation of a gradient — and expectations we can sample.
Theorem 10.1— Policy gradient theorem
For the episodic objective,
where is the on-policy state distribution.
▸Proof
Start with the gradient of the state-value function and expand using and the product rule:
Now expand . The reward and the dynamics do not depend on , so
Substituting gives a recursion in :
Unrolling this repeatedly, each step pushes the term one transition further into the future while accumulating a . Collecting terms by the number of steps needed to reach each state gives
and the bracketed quantity is precisely the (discounted) on-policy state distribution . Finally, apply the score-function identity to turn the inner sum into an expectation over actions drawn from .
REINFORCE turns the theorem into an algorithm: sample an episode, and for each step update
It is unbiased and it is nearly unusable, because the variance of is enormous — the return accumulates every random event in the trajectory, and multiplying that by the score function does not help.
10.3 Baselines and advantage
Chapter 3 already gave the fix. Subtract any function that does not depend on the action:
▸Why the baseline is free
The added term has expectation zero:
Since for every , its gradient is zero, so the whole term vanishes. The estimator's mean is unchanged; only its variance moves.
The best practical baseline is , which makes the multiplier the advantage:
The interpretation is exactly right. Advantage asks "was this action better than what I typically do here?" rather than "was this outcome good?" — and only the first question carries information about which action to prefer. A state where everything goes well produces large returns for every action, and without a baseline all of them get reinforced.
Three unbiased estimators, three very different variances
ch10-gradient-varianceThe same policy gradient, estimated 600 times under each scheme. All three centre on the same value.
REINFORCE
6.76
mean ≈ 1.215 — all unbiased
+ baseline
0.260
mean ≈ 0.993 — all unbiased
+ GAE
0.128
mean ≈ 1.009 — all unbiased
Sampling distribution of the gradient estimate
- REINFORCE
- + baseline
- + GAE (λ=0.95)
Turn up the reward offset. REINFORCE's histogram spreads badly even though a constant added to every return says nothing about which action was good — the score function multiplies it regardless. The baseline subtracts it straight back out. All three estimators have the same mean throughout; only the spread differs, and spread is what you pay for in samples.
10.4 Actor–critic and GAE
We do not know , so learn it: a critic trained by the TD methods of Chapter 6, and an actor updated by the policy gradient using the critic's advantage estimate. This is generalized policy iteration again — Chapter 5's pattern, with a parameterized policy and a learned value.
How should the advantage be estimated? The one-step form has low variance and inherits the critic's bias. The Monte Carlo form is unbiased and noisy. This is Chapter 7's dilemma verbatim, so it takes Chapter 7's answer.
Generalized advantage estimation is the -return applied to advantages:
At it is the one-step TD error; at it is the Monte Carlo advantage. In practice works across an unusually wide range of tasks, which is why it is one of the few hyperparameters practitioners rarely touch.
10.5 Trust regions and PPO
One problem remains, and it is the one that decides whether training survives.
Policy gradient tells you a direction, not a step size. Take too large a step and the policy changes drastically; the data you collected is now from a policy that no longer exists, the next batch is collected under a worse policy, and performance collapses without recovering. Unlike supervised learning, a bad update poisons all future data.
The performance-difference lemma quantifies the risk: the improvement from to is exactly
where the states are drawn from the new policy's distribution — which we cannot sample without running it. Approximating by gives a surrogate objective that is accurate only while the policies remain close. TRPO enforces closeness with a hard KL constraint and solves the resulting problem with conjugate gradients — principled, and heavy.
PPO achieves nearly the same effect with a clipped objective. With the probability ratio :
use burn::prelude::*;
pub struct PpoConfig {
pub clip_eps: f32,
pub entropy_coef: f32,
pub value_coef: f32,
pub target_kl: f32,
}
pub struct PpoDiagnostics {
pub policy_loss: f32,
pub value_loss: f32,
pub entropy: f32,
pub approx_kl: f32,
pub clip_fraction: f32,
}
impl<B: AutodiffBackend> Ppo<B> {
pub fn surrogate(&self, batch: &RolloutBatch<B>, cfg: &PpoConfig)
-> (Tensor<B, 1>, PpoDiagnostics)
{
let (mean, log_std) = self.actor.forward(batch.states.clone());
let log_probs = gaussian_log_prob(&mean, &log_std, &batch.actions);
// r_t(θ) = π_θ(a|s) / π_old(a|s), computed in log space for stability.
let ratio = (log_probs.clone() - batch.old_log_probs.clone()).exp();
// Advantage normalization — not optional in practice.
let adv = normalize(batch.advantages.clone());
let unclipped = ratio.clone() * adv.clone();
let clipped = ratio.clone().clamp(1.0 - cfg.clip_eps, 1.0 + cfg.clip_eps) * adv;
// min() takes the pessimistic branch: the update never profits from
// stepping outside the trust region in either direction.
let policy_loss = -unclipped.min_pair(clipped).mean();
let values = self.critic.forward(batch.states.clone()).squeeze(1);
let value_loss = (values - batch.returns.clone()).powf_scalar(2.0).mean();
let entropy = gaussian_entropy(&log_std).mean();
let loss = policy_loss.clone()
+ value_loss.clone() * cfg.value_coef
- entropy.clone() * cfg.entropy_coef;
// Schulman's low-variance KL estimator; early-stop the epoch if it spikes.
let log_ratio = log_probs - batch.old_log_probs.clone();
let approx_kl = ((log_ratio.clone().exp() - 1.0) - log_ratio).mean();
let clip_fraction = ratio
.sub_scalar(1.0)
.abs()
.greater_elem(cfg.clip_eps)
.float()
.mean();
(loss, PpoDiagnostics {
policy_loss: policy_loss.into_scalar().elem(),
value_loss: value_loss.into_scalar().elem(),
entropy: entropy.into_scalar().elem(),
approx_kl: approx_kl.into_scalar().elem(),
clip_fraction: clip_fraction.into_scalar().elem(),
})
}
}10.6 Chapter bridge
We changed what is learned. Instead of a value function with a policy extracted from it, the policy is the parameter vector, and the policy gradient theorem makes its gradient estimable from experience alone — with no model, and with the state-distribution shift already absorbed. Baselines and GAE tamed the variance; trust regions tamed the step size; PPO made the whole thing simple enough to run with Adam.
What we did not fix is sample efficiency. PPO is on-policy: every batch is used for a few epochs and thrown away. For a simulator with thousands of parallel environments that is acceptable, and Chapter 18 shows it is how locomotion is actually trained. For a robot learning on hardware, discarding data is a luxury nobody can afford.
Chapter 11 returns to off-policy learning — this time with continuous actions and a replay buffer, accepting the deadly triad's risks in exchange for reusing every transition many times. Reacher gets his proper debut as a continuous-control task, and maximum-entropy RL turns exploration from a schedule you tune into a quantity the objective optimizes.
- 01Foundation●●●The theorem, unrolled
Reproduce the proof of Theorem 10.1, being explicit about the unrolling step and how the discounted state distribution μ emerges. State exactly where the assumption that p and r do not depend on θ is used.
- 02Foundation●●●Baselines are free
Prove that any action-independent baseline leaves the policy gradient unbiased. Then derive the variance-minimizing baseline and explain why v_π(s) is used instead despite not being optimal.
- 03Foundation●●●GAE telescopes
Show that GAE with λ = 1 reduces to the Monte Carlo advantage and with λ = 0 to the one-step TD error. Then write GAE as an exponentially weighted average of n-step advantage estimators, mirroring Chapter 7’s λ-return.
- 04Foundation●●●Reading the clip
Sketch L^CLIP as a function of the ratio r, separately for positive and negative advantage. Mark where the gradient is zero. Then explain what the min() adds over simply clipping the ratio.
- 05Conceptual●●●Variance versus offset
In the gradient lab, record the variance of all three estimators at reward offsets of 0, 10, 20, 40. REINFORCE should scale with the offset while the baseline versions do not. Explain the mechanism.
- 06Conceptual●●●The GAE frontier
Sweep GAE λ from 0 to 0.99 and record estimator variance. Then argue why the lowest-variance setting is not necessarily the best choice for learning.
- 07Practical●●●Build the ladder
Implement REINFORCE, then add a baseline, then GAE, then clipping — four algorithms, each a small edit of the last. Run all four on Pendle’s swing-up across five seeds and plot the learning curves together.
- 08Practical●●●Ablate the details
Take working PPO and disable, one at a time: advantage normalization, observation normalization, gradient clipping, the entropy bonus. Quantify the damage from each. At least one should hurt more than you expect.
References
Baseline references
- Sutton, R. S. & Barto, A. G. (2018). Reinforcement Learning: An Introduction. MIT Press, 2nd editionChapter 13: the policy gradient theorem, REINFORCE, baselines, and actor–critic methods.
- Kober, J., Bagnell, J. A. & Peters, J. (2013). Reinforcement Learning in Robotics: A Survey. International Journal of Robotics Research 32(11)§2.2.2 policy search, and §2.3 value-function approaches versus policy search — the argument reproduced in §10.1.
- Tang, C. et al. (2024). Deep Reinforcement Learning for Robotics: A Survey of Real-World Successes. Annual Review of Control, Robotics, and Autonomous Systems link§5 — the finding that stable on-policy methods dominate the mature zero-shot sim-to-real results.
Further reading & modern sources
- Williams, R. J. (1992). Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine Learning 8REINFORCE, in the original.
- Sutton, R. S., McAllester, D., Singh, S. & Mansour, Y. (2000). Policy Gradient Methods for Reinforcement Learning with Function Approximation. NeurIPS 12The policy gradient theorem, with the compatible-function-approximation condition.
- Schulman, J., Levine, S., Abbeel, P., Jordan, M. & Moritz, P. (2015). Trust Region Policy Optimization. ICML 2015The performance-difference lemma, the monotonic improvement bound, and the KL-constrained update.
- Schulman, J., Moritz, P., Levine, S., Jordan, M. & Abbeel, P. (2016). High-Dimensional Continuous Control Using Generalized Advantage Estimation. ICLR 2016GAE — Chapter 7’s λ-return, applied to advantages.
- Schulman, J., Wolski, F., Dhariwal, P., Radford, A. & Klimov, O. (2017). Proximal Policy Optimization Algorithms. arXiv:1707.06347 linkThe clipped surrogate objective.
- Engstrom, L., Ilyas, A., Santurkar, S., Tsipras, D., Janoos, F., Rudolph, L. & Madry, A. (2020). Implementation Matters in Deep RL: A Case Study on PPO and TRPO. ICLR 2020The evidence behind §10.5’s warning: the surrounding machinery contributes as much as the objective.
