Level 3 In-Depth AI · Reinforcement Learning
Proximal Policy Optimization
The most widely used deep-RL algorithm. An actor-critic that reuses each batch of experience for several gradient steps but clips the objective so the policy can never move far from the one that collected the data. The engine of classic RLHF.
- Level
- ●●●●● Advanced
- Reading
- 14 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 19 concepts →
- Quiz
- 5 questions ↓
Read first
Actor-Critic MethodsThis leads to
RLHF and Preference OptimizationThe full path from zero — 19 concepts before this one
- What Is AI?
- Probability Basics
- Derivatives and Slopes
- Vectors
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Reinforcement Learning: The Basics
- Linear Regression
- The Perceptron
- Markov Decision Processes
- Logistic Regression
- Value Functions and Bellman Equations
- Neural Networks
- Policy Gradients
- Actor-Critic Methods
- Proximal Policy Optimization
Read them roughly in this order. See it on the concept map →
Why it matters
Policy-gradient methods (Policy Gradients, Actor-Critic Methods) have an awkward weakness. A single update that is slightly too large can wreck a good policy. Because the next batch of data is collected by that wrecked policy, it may never recover. The usual cure is tiny learning rates, which makes training painfully slow. And since each batch of experience is only valid for the policy that collected it, it gets used for one gradient step and then thrown away.
Proximal Policy Optimization (PPO), published by John Schulman and colleagues at OpenAI in 2017, fixes both problems with one simple change to the objective. It lets you take several gradient steps on each batch, while making sure the new policy stays "proximal", that is close, to the old one. It is easy to implement, works with ordinary optimisers like Adam, and is forgiving about hyperparameters.
Those qualities made PPO the default deep-RL algorithm. OpenAI used it to train OpenAI Five, which beat the reigning world-champion team at Dota 2 in 2019. Above all, PPO is the RL step in classic reinforcement learning from human feedback (RLHF and Preference Optimization). InstructGPT (2022), and through it ChatGPT, was fine-tuned with PPO against a reward model trained on human preferences. If you want to understand how chat models are aligned, this is the algorithm to know.
The intuition
Imagine adjusting the steering on a car you are driving, using notes you took during the last lap. The notes describe how the car behaved with the old steering. If you change the steering a little, the notes are still a good guide. If you change it a lot, the notes describe a different car, and following them could drive you off the road.
PPO measures how much the policy has changed on each action in the batch with a probability ratio:
means no change. means the new policy is 50% more likely to take that action than the policy that collected the data. PPO then says: improve the policy, but once an action's probability has moved more than about 20% (that is, outside ) in the direction you wanted, stop pushing on it. Beyond that band the objective goes flat, so it gives no reward for moving further and the gradient for that sample is zero.
Key idea PPO maximises . It improves the policy using a batch collected by the old policy, but ignores any further gain once the new policy has moved more than ε (about 20%) from the old one on that action. Big, destructive updates become impossible, so each batch can safely be reused for several epochs.
How it works
Reusing old data: the probability ratio
Recall the actor-critic gradient (Actor-Critic Methods): , where is the advantage estimate. This assumes the actions were sampled from the current . Once we take one gradient step, they weren't.
Importance sampling corrects for that. If samples come from a distribution but you want an average under , weight each sample by . Applied here, with the policy that collected the batch, this gives a surrogate objective we can optimise for several steps:
means "average over the time steps in the batch". At the ratio is 1, and the gradient of is exactly the ordinary policy gradient. So nothing is lost on the first step.
The trouble is that this estimate is only trustworthy near . Maximise it hard and the optimiser happily pushes ratios to 10 or 0.01, exploiting noise in the advantages of a single batch. The code below shows exactly that.
The trust region idea, and TRPO
Trust Region Policy Optimization (TRPO) (Schulman et al., 2015) solved this by maximising subject to a constraint: the average KL divergence between old and new action distributions must stay below a small number . KL divergence measures how different two probability distributions are (Entropy, Cross-Entropy and KL Divergence). It worked well and came with a theoretical guarantee of improvement, but it needs second-order optimisation (conjugate gradients and a line search). That is complicated to implement and awkward with modern network designs, such as policy and value networks that share layers.
PPO's clipped objective
PPO gets most of TRPO's benefit with a first-order trick. It clips the ratio and takes the more pessimistic of the clipped and unclipped terms:
Here means "force into the interval ", and is typically 0.2. Taking the minimum makes this a lower bound on the unclipped objective. PPO never takes credit for an improvement beyond the trust band, but it always feels the full penalty for a change in the wrong direction.
Worked through numerically
Take and an advantage of (a good action):
- : unclipped , clipped , objective 2.0. The gradient pushes up.
- : and , objective 2.2. Still inside the band, still pushing.
- : unclipped , but clipped . The min is 2.4, a constant, so zero gradient. The action is already 50% more likely than before, and PPO stops pushing.
- : unclipped , clipped . The min is 1.0, the unclipped term, so the gradient is alive and pulls back up. The policy moved the wrong way on a good action, and PPO corrects it fully.
With an advantage of (a bad action) everything mirrors. At the objective is , clipped and flat: the probability has already dropped enough. At it is , unclipped, so the gradient pushes the probability back down.
The rule of thumb: the clip only switches off the gradient when the policy has already moved far enough in the direction the advantage wants.
The full PPO algorithm
PPO is an Actor-Critic Methods method. Each iteration:
- Collect a batch: run the current policy for steps in each of parallel environments (for example , ). Store states, actions, rewards, and the log-probabilities .
- Estimate advantages with the critic and GAE (Actor-Critic Methods): , typically with and . Normalise them per batch.
- Optimise for epochs (typically 3–10) over shuffled mini-batches, using Adam on the combined loss
That is the clipped policy objective, a value-function loss for the critic (weight ), and an entropy bonus for exploration (weight ). 4. Set , throw the batch away, and repeat.
The PPO paper also described a second variant that replaces the clip with an adaptive KL penalty in the objective. The clipped version performed better in its experiments and is what "PPO" usually means.
In code
First, the objective itself, evaluated for the ratios worked through above:
import numpy as np
def ppo_objective(ratio, adv, eps=0.2):
"""Per-sample PPO-clip objective: min(r·A, clip(r, 1-eps, 1+eps)·A)."""
return np.minimum(ratio * adv, np.clip(ratio, 1 - eps, 1 + eps) * adv)
print(" ratio advantage r·A clipped·A PPO objective gradient?")
for r, A in [(1.0, 2), (1.1, 2), (1.5, 2), (0.5, 2), (1.0, -2), (0.9, -2), (0.5, -2), (1.5, -2)]:
unclipped, clipped = r * A, np.clip(r, 0.8, 1.2) * A
obj = ppo_objective(r, A)
grad = "yes" if obj == unclipped else "no (clipped)"
print(f" {r:4.1f} {A:+5d} {unclipped:+5.2f} {clipped:+5.2f} {obj:+5.2f} {grad}")
# ratio advantage r·A clipped·A PPO objective gradient?
# 1.0 +2 +2.00 +2.00 +2.00 yes
# 1.1 +2 +2.20 +2.20 +2.20 yes
# 1.5 +2 +3.00 +2.40 +2.40 no (clipped)
# 0.5 +2 +1.00 +1.60 +1.00 yes
# 1.0 -2 -2.00 -2.00 -2.00 yes
# 0.9 -2 -1.80 -1.80 -1.80 yes
# 0.5 -2 -1.00 -1.60 -1.60 no (clipped)
# 1.5 -2 -3.00 -2.40 -3.00 yes
Second, what clipping actually buys. A one-step problem with four possible "answers", where answer 0 earns the most on average, though rewards are noisy. This is a miniature of RLHF, where the policy picks a response and a reward model scores it. We collect one batch of 256 samples from a uniform policy, then take 20 gradient steps on that same batch, with and without clipping:
import torch
torch.manual_seed(0)
true_reward = torch.tensor([1.0, 0.5, 0.2, 0.0]) # 4 possible "answers"; answer 0 is best
def collect(logits, n=256):
"""Sample a batch from the current (old) policy and score it."""
dist = torch.distributions.Categorical(logits=logits)
a = dist.sample((n,))
r = true_reward[a] + 0.5 * torch.randn(n) # noisy reward signal
adv = (r - r.mean()) / (r.std() + 1e-8) # normalised advantage
return a, dist.log_prob(a).detach(), adv
def update(logits, a, old_logp, adv, clip, epochs=20, lr=0.5):
logits = logits.clone().requires_grad_(True)
opt = torch.optim.SGD([logits], lr=lr)
for _ in range(epochs): # many passes over ONE batch
ratio = torch.exp(torch.distributions.Categorical(logits=logits).log_prob(a) - old_logp)
if clip: obj = torch.min(ratio * adv, torch.clamp(ratio, 0.8, 1.2) * adv)
else: obj = ratio * adv # plain surrogate, no clipping
opt.zero_grad(); (-obj.mean()).backward(); opt.step()
return logits.detach(), ratio.detach()
start = torch.zeros(4) # uniform policy: 0.25 each
a, old_logp, adv = collect(start)
for clip in (False, True):
new, ratio = update(start, a, old_logp, adv, clip)
p_old, p_new = torch.softmax(start, 0), torch.softmax(new, 0)
kl = (p_old * (p_old / p_new).log()).sum()
print(f"{'PPO-clip ' if clip else 'unclipped'} new probs {p_new.numpy().round(2)} "
f"ratio range [{ratio.min():.2f}, {ratio.max():.2f}] KL(old||new) {kl:.3f}")
# unclipped new probs [0.89 0.05 0.03 0.03] ratio range [0.12, 3.54] KL(old||new) 1.172
# PPO-clip new probs [0.31 0.3 0.2 0.19] ratio range [0.75, 1.24] KL(old||new) 0.027
Without clipping, 20 steps on one noisy batch move the probability of answer 0 from 0.25 to 0.89. Some sampled actions became 3.5 times more likely, and the KL divergence from the old policy is 1.17, which is huge. That is an overconfident leap based on 256 noisy samples. With clipping, the policy makes a modest step in the right direction (0.25 → 0.31 for the best answer, 0.19 for the worst), and the KL is 0.027. Because the clipped samples stop contributing gradient, extra epochs can't push further. The ratio range ends up slightly outside because the last gradient step can overshoot the boundary before the clip takes effect. Real implementations monitor this, and many stop the epochs early if the KL grows past a threshold.
The next step: PPO on a real environment
Stable-Baselines3 implements full PPO (GAE, value loss, entropy bonus, mini-batches, parallel environments). This needs pip install gymnasium stable-baselines3, so it isn't run here:
import gymnasium as gym
from stable_baselines3 import PPO
env = gym.make("LunarLander-v3") # needs: pip install "gymnasium[box2d]"
model = PPO("MlpPolicy", env, n_steps=2048, batch_size=64, n_epochs=10,
gamma=0.99, gae_lambda=0.95, clip_range=0.2, ent_coef=0.0, verbose=1)
model.learn(total_timesteps=500_000)
model.save("ppo_lander")
For language models, Hugging Face's TRL library provides trainers for the RLHF setting (RLHF and Preference Optimization).
PPO and RLHF
In RLHF and Preference Optimization, the RL problem is mapped onto a language model like this:
- State: the prompt plus the tokens generated so far.
- Action: the next token. The policy is the language model, and its softmax over the vocabulary is .
- Episode: one complete response.
- Reward: a reward model, trained on human comparisons of answers, scores the finished response. A per-token KL penalty is subtracted, which keeps the model close to its starting point (the supervised fine-tuned model, ). That stops it drifting into gibberish that happens to fool the reward model.
Everything else is standard PPO: GAE advantages from a value model, the clipped objective, a few epochs per batch. The clip matters even more here than in games. A language model can collapse into repeating whatever phrase the reward model happens to like (reward hacking), and limiting each update is one of the main defences, alongside the KL penalty.
The cost is high: four models (policy, value, reward, reference), each potentially billions of parameters, in memory at once. That cost is why simpler alternatives took off. DPO removes RL altogether by turning preference data into a classification-style loss (RLHF and Preference Optimization). GRPO (Group Relative Policy Optimization, from DeepSeekMath in 2024) keeps PPO's clipped objective but drops the value model. It samples a group of answers to the same prompt and uses each answer's reward relative to the group average as the advantage. GRPO was used to train DeepSeek-R1 and is popular for the Reasoning Models and Test-Time Compute trained on checkable rewards like maths answers and passing tests. It is still PPO's clipped ratio at heart.
Common pitfalls
- Missing implementation details. The PPO paper is short, and many details that matter, such as advantage normalisation, value-loss clipping, orthogonal initialisation, learning-rate annealing, gradient clipping and observation normalisation, live in the reference code. Huang et al.'s "37 implementation details" blog post catalogues them. Start from a trusted implementation (CleanRL, Stable-Baselines3).
- Too many epochs or too large a learning rate. Clipping limits the damage but doesn't eliminate it. Watch the approximate KL and the clip fraction (the share of samples whose ratio is outside the band). If the clip fraction is regularly above about 0.2–0.3, the updates are too aggressive.
- Stale log-probabilities. must be recorded when the data is collected and kept fixed during the epochs. Recomputing it with the updated network makes every ratio 1, and the clip silently does nothing.
- Unnormalised rewards. Rewards on wildly different scales destabilise the critic. Normalise or scale them.
- Reward hacking in RLHF. A higher reward-model score isn't the same as a better answer. Track the KL to the reference model and read samples by hand.
Watch out PPO is "stable" only relative to plain policy gradients. Results still vary a lot across random seeds and implementation details. Always compare across several seeds before trusting that a change helped.
Where it leads
- RLHF and Preference Optimization: PPO's best-known application, along with DPO and RLAIF.
- Reasoning Models and Test-Time Compute: GRPO and related PPO descendants trained on verifiable rewards.
- SAC and TD3: off-policy actor-critics that often beat PPO on sample efficiency in continuous robot control.
- Model-Based RL and World Models: Dreamer and MuZero-style agents learn far more from each sample by planning in a learned model.
- Massively parallel simulation: PPO's simplicity makes it the standard choice for training robot controllers in GPU simulators with thousands of environments at once.
A bit of history
John Schulman and colleagues at Berkeley introduced TRPO in 2015 and generalised advantage estimation the same year. At OpenAI, Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford and Oleg Klimov published "Proximal Policy Optimization Algorithms" in July 2017. It quickly became OpenAI's default. It trained OpenAI Five, which defeated Dota 2 world champions OG in April 2019, and the Dactyl robot hand that learned to manipulate a Rubik's Cube. In 2017 Christiano et al. had already combined RL with a reward model learned from human preferences. OpenAI applied PPO to language models with human feedback for summarisation (2020) and then InstructGPT (2022), whose recipe, supervised fine-tuning followed by a reward model and PPO, produced ChatGPT in November 2022. Schulman was one of the leads of the team that built ChatGPT. As of late 2026, PPO-style clipped policy-gradient methods, above all GRPO and its refinements such as DAPO and GSPO, remain the core RL algorithms in language-model post-training.
Try it
- In the mini-PPO code, change the clip range from 0.2 to 0.05 and to 0.5 (edit
torch.clamp(ratio, 0.8, 1.2)). How do the new probabilities and the KL change?- Increase
epochsfrom 20 to 200 for both variants. Does the clipped version keep moving? Why not?- Add an early-stopping rule: break out of the epoch loop when the approximate KL,
(old_logp - new_logp).mean(), exceeds 0.01. How many epochs run?Hint for 2: once every sample's ratio is outside the band in the direction its advantage favours, the clipped objective's gradient is exactly zero.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Proximal Policy Optimization Algorithms
PPO: a simple, stable policy-gradient method that became the RL default.
Spinning Up in Deep RL
OpenAI's short, precise introduction to deep RL: key concepts and notation, the policy-gradient derivation, and clean reference implementations of VPG, PPO, DDPG, TD3 and SAC.
The 37 Implementation Details of Proximal Policy Optimization
Everything the PPO paper leaves out (advantage normalisation, value clipping, learning-rate annealing, vectorised environments) and how much each detail matters.
Hugging Face Deep RL Course
A hands-on deep reinforcement learning course from Q-learning to PPO. You train agents in games.
Trust Region Policy Optimization
TRPO: limit each policy update by a KL-divergence constraint so performance improves monotonically. PPO is its simpler successor.
CleanRL
Single-file implementations of DQN, PPO, SAC and others, each a few hundred readable lines. Ideal for seeing every detail of a real algorithm in one place.
TRL documentation
Transformer Reinforcement Learning: trainers for supervised fine-tuning (SFT), reward modelling, PPO, DPO and GRPO on Hugging Face models.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/ppo.md