Proximal Policy Optimization (PPO)
PPO is one of the most widely used RL algorithms. It is the policy-optimization step in many RLHF pipelines, a common choice for simulated robot locomotion, the algorithm behind OpenAI Five at Dota 2, and a default baseline in many RL libraries. Why? It's almost always good enough, almost never breaks. Stability beats genius, and if you learn one RL algorithm deeply, make it this one.
After this lesson, you will be able to:
- Understand why unconstrained policy gradient updates are catastrophically dangerous: data collected under the old policy becomes invalid if the new policy diverges too far, causing the entire learning signal to be misleading
- Follow the PPO clipped surrogate objective L^CLIP(θ) = E[min(r_t A_t, clip(r_t, 1-ε, 1+ε) A_t)] and explain mechanically why the min-of-two-terms structure prevents the policy from moving beyond the trust region
- Understand why multiple gradient epochs per data batch are safe in PPO (but not in vanilla policy gradients) and how the entropy bonus prevents premature policy collapse
- Know why PPO dominates in practice, its combination of on-policy simplicity, robustness to hyperparameters, and suitability for RLHF makes it the default choice for LLM alignment
Before you start
#The Problem with Vanilla Policy Gradients
Policy gradient methods from the previous lesson have a fundamental instability: the step size is hard to control. A single bad gradient update can push the policy far from the region where it collected data, causing performance to collapse catastrophically.
Why is this a problem technically? The policy gradient theorem gives us the direction to update, but not how far to go. If the learning rate is too high, the policy changes dramatically. The new policy visits completely different states, encounters different rewards, and the gradient computed from old data becomes misleading. This can cascade into catastrophic collapse.
#Trust Regions: The Core Idea
#The PPO Clipped Objective
PPO's objective clips the probability ratio to stay within [1-epsilon, 1+epsilon], preventing the policy from changing too much in any single update:
Drag the ratio and flip the sign of the advantage. Inside the clipping range the objective follows the unclipped line; outside it, the objective goes flat, so there is no gradient pushing the ratio any further.
Let us unpack how the clipping works in different scenarios:
#When the advantage is positive (good action)
The gradient wants to increase the probability of this action (increase r). Without clipping, r could shoot up to 10x or 100x. With clipping at 1+epsilon (e.g., 1.2), the objective is flat beyond r=1.2. There is no gradient incentive to push r further. The policy change is capped.
#When the advantage is negative (bad action)
The gradient wants to decrease the probability (decrease r). Without clipping, r could drop to near 0, essentially eliminating the action. With clipping at 1-epsilon (e.g., 0.8), the objective is flat below r=0.8. The policy cannot reduce this action's probability by more than 20% in one update.
Observe how PPO constrains policy updates compared to vanilla policy gradients. The clipping mechanism prevents the policy distribution from shifting too far in a single update. Toggle the visualization to compare unconstrained updates (which can be catastrophically large) with PPO's conservative, clipped updates.
If PPO's epsilon is set to 0.0 (no clipping range), what happens?
With epsilon = 0, the clipped range is [1.0, 1.0], meaning r is always clipped to exactly 1.0. The clipped term is a constant, so by the case analysis below the objective is flat in exactly the directions that would improve it, and the policy is pinned at the old one. In practice, epsilon = 0.1 to 0.3 works well, with 0.2 being the standard default.
#From TRPO to PPO: deriving the clipped surrogate
min-of-two-terms structure comes from and why it implements a trust region.#Step 1: the performance-improvement bound
The starting point is a classical result by Kakade and Langford (2002), tightened by Schulman et al. (2015) for TRPO. For any two policies π_old and π_new, the expected return of the new policy is bounded below by a tractable surrogate plus a divergence penalty:
The surrogate itself is just an importance-weighted advantage:
In this lesson d^pi denotes the UNNORMALISED discounted visitation, d(s) = P(s_0 = s) + gamma P(s_1 = s) + gamma^2 P(s_2 = s) + ..., which TRPO calls rho. It adds up to 1/(1 - gamma), so the expectation over s is a sum over states. Three short results justify the surrogate: an identity for the improvement, the importance-ratio form, and the fact that its gradient is the policy gradient.
The proof sketch: imagine sampling trajectories under π_new and tracking, at each step, the probability they could have been sampled from π_old. As long as the two policies agree, the rewards are interchangeable; once they disagree, an error term accumulates that is bounded by the per-state KL divergence. The full coupling argument is Theorem 1 of Schulman et al. (2015), with two proofs in its appendix (the first adapts the proof of Theorem 4.1 in Kakade & Langford, 2002).
On its own small 3-state MDP (not the lesson's numbers), this demo lets you move the step s and the clip range eps: near the old policy the surrogate L lies on the true improvement and drifts away roughly as s squared, clipping caps the surrogate's gain, and the mean KL grows as s squared.
#Step 2: TRPO — maximize the surrogate subject to a hard KL constraint
TRPO converts the bound into a constrained optimization problem. Rather than subtract the KL penalty, it imposes it as a hard limit:
F^{-1} g, where g is the surrogate gradient and F is the Fisher information matrix (the local quadratic approximation of KL). A conjugate-gradient solver computes F^{-1} g without materializing F, then a backtracking line search shrinks the step until the constraint holds. It works, but it is complex, expensive, and brittle. Hence the demand for something simpler.Two facts about the KL divergence explain why TRPO's constraint is a quadratic ball around theta_old, and how its step is found. They use the score and Fisher information results of the MLE, MAP and Fisher Information lesson of the Math track.
Now TRPO's constrained problem can be solved in closed form for a small step. The natural gradient is derived in the MLE, MAP and Fisher Information lesson. Here is the version for this constraint.
#Step 3: PPO's clipped surrogate
r_t(θ) = π_θ(a_t | s_t) / π_old(a_t | s_t), then optimize:#Step 4: why min-of-two is a valid lower bound on L
A_t and whether r_t lies inside or outside [1-ε, 1+ε].A_t > 0 (the action was good; gradient pushes r_t upward).- If
r_t ≤ 1+ε: the clip is inactive,surr_clipped = r_t · A_t = surr_unclipped, and the min is justr_t · A_t. Normal gradient flows. - If
r_t > 1+ε: the clip activates,surr_clipped = (1+ε) · A_t < r_t · A_t = surr_unclipped. Theminselects the clipped version(1+ε) · A_t, which is flat inr_t. Gradient w.r.t. θ is zero: the policy gains nothing by pushingr_thigher.
A_t < 0 (the action was bad; gradient pushes r_t downward).- If
r_t ≥ 1-ε: the clip is inactive, the min picksr_t · A_t. Normal gradient flows toward smallerr_t. - If
r_t < 1-ε: the clip activates,surr_clipped = (1-ε) · A_t. NowA_t < 0, so forr_t < 1-εwe getr_t · A_t > (1-ε) · A_t(less negative). Theminselects the clipped(1-ε) · A_t, which is flat inr_t. The gradient is zero: the policy gains nothing by pushingr_tlower. - If
r_t > 1+ε(an overshoot in the wrong direction):r_t · A_t < (1+ε) · A_t, so theminselects the unclippedr_t · A_t. The gradient flows and pullsr_tback down.
min chooses pessimism, which sometimes means the unclipped term and sometimes the clipped term. The result is a lower bound on the true surrogate L everywhere, equal to it inside the interval and wherever the clip would have made the objective look better, and the two agree to first order at r_t = 1.The two derivations below turn the case analysis into formulas. Write f(r) = min(r A, clip(r, 1 - eps, 1 + eps) A) for one sample.
What happens during a PPO update step when r_t > 1+ε AND A_t < 0 simultaneously? (The action was bad, but the new policy has somehow become more likely to take it, e.g. an earlier mini-batch overshot.)
#Step 5: PPO as a first-order approximation of TRPO's trust region
r = 1. For any two distributions p, q with ratio r = q/p:|r_t - 1| ≤ ε (which clipping encourages, though does not strictly enforce, gradients can still push r_t outside in the unclipped regions), then the average KL is bounded by roughly ε² / 2. For ε = 0.2 this gives a KL budget of 0.02 per step, comparable to TRPO's typical δ = 0.01. PPO is a first-order, sample-based, gradient-friendly approximation of TRPO's second-order trust region.#Step 6: the KL-penalty variant (and why RLHF uses it)
β → 0 the penalty vanishes and we recover pure importance-sampled policy gradient (no trust region, dangerous); as β → ∞ the policy cannot move at all and we approach a true trust-region method. Modern RLHF for large language models almost always uses the KL-penalty variant, not the clipped variant, with β (the "KL coefficient") typically in the range 0.01-0.1. The penalty anchors the RL-tuned policy to a frozen SFT reference, preventing the model from "gaming" the reward model by producing distributions wildly different from natural text.The adaptive rule is stated, not derived: measure d, the mean KL after the epochs, and compare it with a target d_targ. If d is below d_targ / 1.5, halve beta, and if it is above 1.5 d_targ, double beta (Schulman et al. 2017, section 4). The factors 1.5 and 2 are heuristics.
In practice the KL is estimated from sampled actions, with the estimator k1 = -log r, or with k3 = (r - 1) - log r, which is unbiased and never negative (derived in the GRPO and DeepSeek R1 lesson and in the ratio derivation above). Many implementations also stop the K epochs early when this estimate passes a target, a practical guard that the clip alone does not provide.
#Step 7: the empirical caveat — implementation matters
#PPO implementation tricks: the difference between paper and production
- Orthogonal weight initialization (
orthogonal_init_): initialize hidden layers with orthogonal matrices scaled bysqrt(2), and the policy output layer scaled by0.01(much smaller): keeps the initial policy near-uniform, preventing premature action collapse. - Advantage normalization per mini-batch: subtract mean and divide by std of advantages within each mini-batch (not across the whole batch); this stabilizes the policy-gradient scale across heterogeneous environments.
- Value function loss clipping: apply the same
(1 - ε, 1 + ε)clip idea to the value loss:V_newis clipped relative toV_old + ε, so a bad value-target sample can't blow up the critic in one update. - Gradient clipping: clip the global gradient norm to
0.5(sometimes1.0) after backprop; a single outlier batch can otherwise produce a parameter step that destroys the policy. - Reward scaling / reward clipping: divide rewards by a running standard deviation and clip to
[-10, 10](especially for Atari, where rewards have huge ranges); makes the value-function regression target numerically stable. - Learning rate annealing: linearly decay the Adam LR from its initial value to
0over training; without this PPO drifts in late training and final-policy quality degrades. - Generalized Advantage Estimation (GAE) with
λ ≈ 0.95: notλ = 1.0(Monte Carlo) and notλ = 0(TD); the0.95sweet spot is empirically near-universal across MuJoCo, Atari, and procgen. - Mini-batch shuffling: shuffle the indices into the rollout buffer every epoch, not just once at the start; without per-epoch shuffling the policy overfits to the order of mini-batches within an epoch.
- Entropy bonus on the policy: add
+0.01 * H[π]to the loss (so the optimizer maximizes entropy); without this the policy collapses to deterministic too quickly and exploration dies. - Number of epochs per rollout:
K = 4(sometimes up to10); Engstrom's ablation showed this is the most sensitive hyperparameter:K = 1is too few (vanilla policy gradient),K = 20overshoots the trust region despite clipping.
ppo.py (Costa et al. 2022), it implements all ten tricks plus correct logging in ~200 lines of PyTorch, audited against OpenAI's reference numbers. The pedagogical companion is Huang's "37 Implementation Details" blog post, which expands the list above with deeper environment-specific tricks (frame-stacking, action-space-specific gradient handling, reward-clipping variants per game).You're porting PPO to a new framework. Ablation studies show your implementation is 30% below CleanRL's reported scores on MuJoCo. Which trick is most likely the single biggest contributor to the gap?
#The Full PPO Algorithm
PPO collects data, then performs multiple epochs of gradient updates on that data:
- Collect data: Run the current policy for N steps across M parallel environments, storing states, actions, rewards, values, and log-probabilities
- Compute advantages: Use GAE (from the previous lesson) to estimate advantages
- Optimize: For K epochs, sample mini-batches from the collected data and update the policy and value networks using the clipped objective
- Repeat: Discard old data, collect fresh data with the updated policy
The three components:
- Clipped policy loss: Updates the actor (policy) with trust region protection
- Value function loss: Updates the critic to better estimate V(s)
- Entropy bonus: Prevents premature convergence by encouraging exploration
The value loss is the squared error between the critic and a target return, and the entropy S is the entropy of the policy at that state (a definition). Generalized Advantage Estimation, which supplies the advantages and the return targets, is derived in the Actor-Critic Methods: A2C, A3C, and IMPALA lesson. The squared error is the right loss because its minimiser is the average return:
#PPO Training Loop: End-to-End Process
#Step 1: Collect Trajectories with Current Policy
Run the current policy across M parallel environments for N steps each. At each step, record the state, action, reward, value estimate V(s), and the log-probability of the action under the current policy. This creates a batch of M x N transitions.
The log-probabilities are saved because PPO needs them later to compute the probability ratio between the old and updated policies. These are the "old policy" probabilities.
#Step 2: Compute Advantages A_t
Using Generalized Advantage Estimation (GAE), compute the advantage at each time step. The advantage A_t measures how much better the actual outcome was compared to what the value function predicted.
GAE with lambda=0.95 provides a smooth balance: it uses the TD error (one-step advantage) exponentially weighted over multiple steps. Positive advantage means "this action was better than expected." Negative means "worse than expected."
#Step 3: Compute Ratio r(theta) = pi_new / pi_old
For each state-action pair in the batch, compute the probability ratio: the new policy's probability of the action divided by the old policy's probability (saved from Step 1). If r = 1, the policies agree. If r = 1.5, the new policy is 50% more likely to take this action.
This ratio is computed as exp(new_log_prob - old_log_prob) for numerical stability. It is the key quantity that PPO monitors and controls.
#Step 4: Clip Ratio to [1-epsilon, 1+epsilon]
Clamp the ratio to the range [1-epsilon, 1+epsilon], typically [0.8, 1.2]. This prevents the policy from changing too drastically in any single update. If the ratio wants to go to 3.0 (triple the probability), clipping caps it at 1.2 (20% increase).
The clipping creates a "trust region", the new policy must stay close to the old policy that collected the data. Beyond the clip boundary, there is no gradient incentive to push further.
#Step 5: Take min(r * A, clip(r) * A)
The min operation is what makes PPO conservative, it prevents the policy from "exploiting" the advantage estimate by moving too aggressively.
#Step 6: Update Policy (Multiple Epochs)
Unlike REINFORCE (which uses each batch once), PPO performs K epochs (typically 3-10) of gradient updates on the same batch data. In the first minibatch of the first epoch the policy is still the old one, so every ratio is exactly 1. Each further update moves the ratios away from 1, so K and the number of minibatches set how far off-policy the late updates are. The clipping mechanism makes this safe, even after multiple passes, the policy cannot move far from where the data was collected.
Each epoch samples random mini-batches from the full batch, computing the clipped loss and updating via Adam optimizer. This extracts maximum learning signal from each batch of environment interactions.
#Step 7: Update Value Function
Simultaneously with the policy, update the value network (critic) to minimize the squared error between its predictions V(s) and the actual returns. A well-trained value function produces better advantage estimates, which produce better policy updates.
The value loss is added to the total objective with a coefficient (typically 0.5). After updates complete, the old batch is discarded, fresh trajectories are collected with the new policy, and the cycle repeats from Step 1.
#Why PPO Dominates
PPO won the RL algorithm popularity contest for several compelling reasons:
#PPO vs. Other Algorithms
| Algorithm | Type | Action Space | Key Feature | Complexity |
|---|---|---|---|---|
| DQN | Value-based | Discrete only | Experience replay + target net | Medium |
| REINFORCE | Policy gradient | Any | Simplest PG, high variance | Low |
| A2C | Actor-critic | Any | Synchronous advantage AC | Low |
| TRPO | Policy gradient | Any | KL constraint (exact trust region) | High |
| PPO | Policy gradient | Any | Clipped objective (approx trust region) | Low |
| SAC | Actor-critic | Continuous | Max entropy + off-policy | Medium |
| TD3 | Actor-critic | Continuous | Twin critics + delayed update | Medium |
Proximal Policy Optimization Algorithms
John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, Oleg Klimov (2017)
The PPO paper. Introduced the clipped surrogate objective as a simpler alternative to TRPO's constrained optimization. Despite its simplicity, PPO has become the most widely used RL algorithm in both research and production, powering OpenAI Five, InstructGPT, and ChatGPT.
You need to train an RL agent with a continuous action space (e.g., robot joint angles). Which algorithm should you NOT use?
DQN requires computing max over Q-values for all actions, which is only possible with a finite, discrete action set. For continuous actions, you need policy gradient methods (PPO, SAC, TD3) that directly parameterize the action distribution.
#Try It Yourself
Tests: Verify that ppoObjective(1.5, 1.0) equals 1.2 (clipped at 1+epsilon). Verify that ppoObjective(0.5, -1.0) equals -0.8 (clipped at 1-epsilon).
#Key Takeaways
- Unconstrained policy updates can be catastrophically large. A single bad gradient step can push the policy far from the data distribution, causing performance to collapse and never recover
- PPO clips the objective to create a trust region. By limiting the policy ratio to the range [1-epsilon, 1+epsilon], PPO prevents destructive updates while still allowing meaningful learning steps
- PPO balances simplicity and performance. Unlike TRPO which requires expensive second-order optimization, PPO achieves similar trust region behavior with a simple clipped objective that is easy to implement and tune
- PPO is the algorithm behind RLHF for LLM alignment. Its stability and reliability made it the standard choice for fine-tuning language models with human feedback, powering ChatGPT-style assistants and other aligned models
Interactive Lab
Drag the probability ratio across the clipping boundary and watch the objective flatten, the single most important diagram for understanding why PPO is the workhorse of modern RL.
#Quick Check
What problem does PPO's clipping mechanism solve?