Unit 7 of 11 · about 5 hours · derive, implement

Old and new log probabilities, importance ratios and the PPO clipped surrogate

PPO changes the policy-gradient objective so one rollout batch can support several updates. Its clipping is sign-dependent and must be tested as an objective, not treated as a safety guarantee.

You'll be able to

  • Compute new-over-old action-density ratios from frozen rollout log probabilities.
  • Derive the PPO clipped surrogate and its active gradient branch for each advantage sign.
  • Implement a minimized clipped loss and verify it on fixed actions before training.

Covers

Old and new policy log probabilitiesImportance probability ratios and directionPPO clipped surrogate with advantage-sign cases
1

Read

In this order, only the parts listed

0 of 3 done

  1. CS 185/285 Lecture 9: policy gradients with reused dataBerkeley CS 185/285 Deep Reinforcement Learning (Spring 2026) - Policy Gradients, Actor-Critic and Advanced Policy Gradients

    Lecture 9, Off-Policy Policy Gradient, slides 7 to 10 and 13 to 16: importance sampling, the first-order approximation and clipped weights

    Distinguish the lecture's approximations from the precise clipped surrogate in the paper. Do not infer exact state-distribution correction from an action ratio.

  2. PPO clipped surrogateProximal Policy Optimization Algorithms

    arXiv:1707.06347v2, Section 3, Clipped Surrogate Objective, Equations 6 and 7 and Figure 1, p. 3

  3. PPO: both advantage signsSpinning Up - Intro to Policy Optimization and PPO

    Key Equations: PPO-Clip, Advantage is positive, Advantage is negative, and the KL early-stopping caveat

    Stop before Exploration vs. Exploitation; do not install its implementation.

2

Focus on

  • Recompute the new policy's log density at the stored observation and stored action. Keep the old density from the behavior-policy snapshot: .
  • Maximize . For positive advantage the upper side saturates; for negative advantage the lower side saturates. Movement in the harmful direction is still penalized.
  • Minimization requires the negative surrogate, equivalently the maximum of the two negated branches. Old log probabilities and advantages are fixed, while new log probabilities retain their gradient.
  • The surrogate is a lower bound on the unclipped sampled surrogate, not a general lower bound on true policy return. It does not enforce an actual ratio or KL constraint.
Common mistakes · 3
  • Putting the old policy on top of the ratio. That reverses the intended correction and clipping cases.
  • Resampling actions when computing new log probabilities. The ratio must compare densities of the same stored action.
  • Clamping the ratio and using only that branch. PPO takes a minimum with the unclipped surrogate so harmful changes retain a gradient.
3

Try it yourself

Closed-book, before checking anything

With , enumerate four samples with . The maximized per-sample surrogates are ; the negative batch mean is 0.2. On CPU in float64, differentiate that loss with respect to the four ratios and get . Check centered differences away from the clipping boundaries.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.What ratio should an unchanged policy produce?Answer

    One, up to numerical tolerance, when observation processing, action representation and density evaluation are unchanged.

  2. 2.Does a ratio above the upper clip boundary always have zero policy-loss gradient?Answer

    No. It is flat for positive advantage, but a negative advantage retains the unclipped harmful-change gradient.

  3. 3.What happens at zero advantage?Answer

    That sample's policy-surrogate term and its gradient are zero. Value and entropy terms may still update parameters.

  4. 4.Does the per-action ratio correct the new policy's state visitation distribution?Answer

    No. PPO optimizes a surrogate over old-policy states. Large updates can make this approximation poor.

5

Practice

  • Deep-ML 485: PPO Clipped Surrogate Loss with Clip Diagnostics

    Implement ppo_clip_loss and run the two public cases

    The cases check a batch with all ratios inside the clip interval and a batch with both ratios outside, returning loss and clip fraction. They do not test gradients or a hard KL bound; the statement's claim that clipping prevents excessive deviation is not a guarantee. The section mini-project adds sign-case and gradient regressions.

You're done when

You reproduce all four surrogate and gradient cases, pass the two named practice cases, and explain why ratio clipping is not a hard policy constraint.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 10 more in the section
  • Berkeley CS 185/285 Deep Reinforcement Learning (Spring 2026) - Policy Gradients, Actor-Critic and Advanced Policy GradientsUC Berkeley · primary

    Slides are public at https://rail.eecs.berkeley.edu/deeprlcourse/static/slides/lec-N.pdf; current videos are not, and the public Fall 2023 playlist numbers lectures differently. Study Lectures 5 (policy gradients), 6 (actor-critic), 9 and 10 (advanced policy gradients). Work Homework 2 (src/agents/pg_agent.py: return estimators, reward-to-go, a neural baseline and a GAE sweep); its runs take seconds to minutes on a laptop CPU. The homework pins gym==0.25.2, which fails on NumPy 2, so port it to Gymnasium (terminated and truncated) or pin numpy<2 in its own environment, and turn off its forced WandB logging.

  • Proximal Policy Optimization AlgorithmsOpenAI · required

    Read the clipped objective, implementation variants and experiments. Build hand cases for positive and negative advantages, compare clipped and unclipped losses and show that clipping alone does not enforce a hard KL bound.

  • Spinning Up - Intro to Policy Optimization and PPOOpenAI · support

    Read Part 3 (Intro to Policy Optimization: the simplest policy gradient, reward-to-go, the expected grad-log-prob lemma, baselines) and the PPO page's background, which states that the clipped objective has no hard KL bound. Do not install its code: it needs TensorFlow 1, MPI and the retired Gym stack.

Also in this section

  • Stanford CS224R Spring 2026 - Policy Gradients and Actor-CriticStanford University · support

    Use Lectures 03 (policy gradients) and 04 (actor-critic) as a second derivation, and the Homework 2 PPO handout for its exact GAE recursion and its note that several epochs on one batch is not strictly on-policy. Its runs need cloud GPUs, and its actor is a truncated normal, not a tanh-squashed Gaussian. Follow the Stanford honor code for course materials.

  • Reinforcement Learning: An Introduction (2nd ed.) - Chapter 13Richard Sutton and Andrew Barto · required

    The authors post the full second edition free at incompleteideas.net; cite the printed page numbers. Study Sections 13.1 to 13.5 and 13.7: the policy-gradient theorem, REINFORCE, REINFORCE with baseline, actor-critic and Gaussian policies. Reproduce Example 13.1 (the short corridor) with and without a baseline, and derive the gradient and baseline result in the notation of the shared trajectory schema.

  • High-Dimensional Continuous Control Using Generalized Advantage EstimationSchulman et al. · required

    Derive GAE from TD residuals, implement backward recursion with terminal and truncation masks and sweep and on fixed trajectories before training.

  • The 37 Implementation Details of Proximal Policy OptimizationHuang et al. (ICLR Blog Track 2022) · required

    Use the core and continuous-action details as an audit checklist for your PPO: vectorized environments, advantage normalization, value clipping, entropy, global gradient clipping, learning-rate annealing and observation and reward normalization. For each detail you adopt, show its effect with an ablation on your own task.

  • CleanRL PPOCleanRL · support

    Use the single-file implementation and implementation-details notes as a post-implementation audit. Trace rollout shapes, advantage calculation, minibatch epochs, ratios, clipping, value loss, entropy, seeding and environment semantics. Like the DQN script it reads final_info, which Gymnasium 1.x next-step autoreset no longer provides; pin gymnasium==0.29.1 or patch the episode logging.

  • Hands-on Modern RL - REINFORCE, Actor-Critic and PPOWalking Labs · support

    Use the REINFORCE page, the actor-critic chapter and the PPO and GAE pages for worked numbers: the three advantage-sign cases and the five-step GAE table. code/chapter05_policy_gradient/reinforce_cartpole.py and code/chapter07_ppo/ppo_from_scratch.py run on CPU in minutes. Audit completion masks against the Gymnasium docs (its GAE helper cuts the bootstrap on truncation) and do not adopt its KL sketch as a reference. Pin commit 9231bab of walkinglabs/hands-on-modern-rl; its code/chapterNN folders do not follow the site chapter numbers.

  • Deep-ML - Policy-Gradient ProblemsDeep-ML · support

    Use named problems as closed-book checks after your own implementation passes: 481 (REINFORCE with baseline), 482 (one-step actor-critic), 485 (PPO clipped surrogate with clip diagnostics) and 487 (GAE with episode boundaries). Read each problem's tests before trusting its statement.

  • Reinforcement Learning Control Laboratory - Policy CoreRoadmap-Final · required

    Complete REINFORCE with baseline, actor-critic, GAE and PPO requirements. Match hand-computed log probabilities, advantages, ratios and clipped losses and diagnose stale-policy, ratio, GAE and evaluation leakage defects.

  • Soft Actor-Critic: action-bound density correctionHaarnoja et al. · reference

    Appendix C, Enforcing Action Bounds, Equations 20 and 21 in arXiv:1801.01290v2. Supplies the change-of-variables derivation missing from the pool's action-clipping checklist; do not study SAC training here.

  • Gymnasium vector autoreset modesFarama Foundation · reference

    Read Next-Step Mode, Same-Step Mode and Disabled Mode in the official autoreset explainer, then SyncVectorEnv's reset and step API. Check against Gymnasium 1.4.0; pages read 2026-10-14. Supplies current rollout semantics missing from the older PPO examples.