◆ AI All-in-One

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
↗ Plan a path here

Read first

Actor-Critic Methods

This leads to

RLHF and Preference Optimization
The full path from zero — 19 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Derivatives and Slopes
  4. Vectors
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Reinforcement Learning: The Basics
  12. Linear Regression
  13. The Perceptron
  14. Markov Decision Processes
  15. Logistic Regression
  16. Value Functions and Bellman Equations
  17. Neural Networks
  18. Policy Gradients
  19. Actor-Critic Methods
  20. 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:

r=πnew(a∣s)πold(a∣s)r = \frac{\pi_{\text{new}}(a \mid s)}{\pi_{\text{old}}(a \mid s)}

r=1r = 1 means no change. r=1.5r = 1.5 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, rr outside [0.8,1.2][0.8, 1.2]) 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.

0.8 1 1.2 2 Advantage A > 0 (good action) ratio r = π_new(a | s) / π_old(a | s) flat: no reward for going past 1 + ε r · A 0.8 1 1.2 2 Advantage A < 0 (bad action) ratio r = π_new(a | s) / π_old(a | s) flat: no reward for going below 1 − ε r · A orange: PPO objective min(r·A, clip(r, 1−ε, 1+ε)·A), ε = 0.2 · grey dashes: unclipped r·A shaded: the band [0.8, 1.2] where updates are allowed · dot: r = 1, the old policy (A = ±1 here)
Fig. 1 The PPO clipped objective for one sample, as a function of the probability ratio r, computed with ε = 0.2. Left: for a good action (A > 0), the objective rises with r but goes flat beyond 1.2, so there is no incentive to raise its probability further. Right: for a bad action (A < 0), it goes flat below 0.8. In the "wrong" direction (low r for a good action, high r for a bad one) the slope is kept, so mistakes are still corrected.

Key idea PPO maximises min⁡(rA,  clip(r,1−ε,1+ε) A)\min\big(rA,\; \text{clip}(r, 1-\varepsilon, 1+\varepsilon)\,A\big). 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): E[A^t∇θlog⁡πθ(At∣St)]\mathbb{E}\big[\hat A_t \nabla_\theta \log \pi_\theta(A_t \mid S_t)\big], where A^t\hat A_t is the advantage estimate. This assumes the actions were sampled from the current πθ\pi_\theta. Once we take one gradient step, they weren't.

Importance sampling corrects for that. If samples come from a distribution qq but you want an average under pp, weight each sample by p/qp/q. Applied here, with πθold\pi_{\theta_\text{old}} the policy that collected the batch, this gives a surrogate objective we can optimise for several steps:

LPG(θ)=E^t[rt(θ) A^t],rt(θ)=πθ(At∣St)πθold(At∣St)L^{\text{PG}}(\theta) = \hat{\mathbb{E}}_t\left[ r_t(\theta)\, \hat{A}_t \right], \qquad r_t(\theta) = \frac{\pi_\theta(A_t \mid S_t)}{\pi_{\theta_\text{old}}(A_t \mid S_t)}

E^t\hat{\mathbb{E}}_t means "average over the time steps in the batch". At θ=θold\theta = \theta_\text{old} the ratio is 1, and the gradient of LPGL^{\text{PG}} is exactly the ordinary policy gradient. So nothing is lost on the first step.

The trouble is that this estimate is only trustworthy near θold\theta_\text{old}. 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 LPGL^{\text{PG}} subject to a constraint: the average KL divergence between old and new action distributions must stay below a small number δ\delta. 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:

LCLIP(θ)=E^t[min⁡(rt(θ) A^t,  clip(rt(θ), 1−ε, 1+ε) A^t)]L^{\text{CLIP}}(\theta) = \hat{\mathbb{E}}_t\Big[ \min\big( r_t(\theta)\, \hat{A}_t,\; \text{clip}\big(r_t(\theta),\, 1-\varepsilon,\, 1+\varepsilon\big)\, \hat{A}_t \big) \Big]

Here clip(r,1−ε,1+ε)\text{clip}(r, 1-\varepsilon, 1+\varepsilon) means "force rr into the interval [1−ε,1+ε][1-\varepsilon, 1+\varepsilon]", and ε\varepsilon 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 ε=0.2\varepsilon = 0.2 and an advantage of +2+2 (a good action):

  • r=1.0r = 1.0: unclipped 2.02.0, clipped 2.02.0, objective 2.0. The gradient pushes rr up.
  • r=1.1r = 1.1: 2.22.2 and 2.22.2, objective 2.2. Still inside the band, still pushing.
  • r=1.5r = 1.5: unclipped 3.03.0, but clipped 1.2×2=2.41.2 \times 2 = 2.4. The min is 2.4, a constant, so zero gradient. The action is already 50% more likely than before, and PPO stops pushing.
  • r=0.5r = 0.5: unclipped 1.01.0, clipped 0.8×2=1.60.8 \times 2 = 1.6. The min is 1.0, the unclipped term, so the gradient is alive and pulls rr back up. The policy moved the wrong way on a good action, and PPO corrects it fully.

With an advantage of −2-2 (a bad action) everything mirrors. At r=0.5r = 0.5 the objective is min⁡(−1.0,−1.6)=−1.6\min(-1.0, -1.6) = -1.6, clipped and flat: the probability has already dropped enough. At r=1.5r = 1.5 it is min⁡(−3.0,−2.4)=−3.0\min(-3.0, -2.4) = -3.0, 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:

  1. Collect a batch: run the current policy πθold\pi_{\theta_\text{old}} for TT steps in each of NN parallel environments (for example N=8N = 8, T=128T = 128). Store states, actions, rewards, and the log-probabilities log⁡πθold(a∣s)\log \pi_{\theta_\text{old}}(a \mid s).
  2. Estimate advantages with the critic and GAE (Actor-Critic Methods): A^t=∑k(γλ)kδt+k\hat A_t = \sum_k (\gamma\lambda)^k \delta_{t+k}, typically with γ=0.99\gamma = 0.99 and λ=0.95\lambda = 0.95. Normalise them per batch.
  3. Optimise for KK epochs (typically 3–10) over shuffled mini-batches, using Adam on the combined loss
L(θ)=−LCLIP(θ)+c1 E^t[(Vθ(St)−G^t)2]−c2 E^t[H[πθ(⋅∣St)]]L(\theta) = -L^{\text{CLIP}}(\theta) + c_1\, \hat{\mathbb{E}}_t\big[(V_\theta(S_t) - \hat G_t)^2\big] - c_2\, \hat{\mathbb{E}}_t\big[\mathcal{H}[\pi_\theta(\cdot \mid S_t)]\big]

That is the clipped policy objective, a value-function loss for the critic (weight c1≈0.5c_1 \approx 0.5), and an entropy bonus for exploration (weight c2≈0.01c_2 \approx 0.01). 4. Set θold←θ\theta_\text{old} \leftarrow \theta, 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 [0.8,1.2][0.8, 1.2] 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 πθ\pi_\theta is the language model, and its softmax over the vocabulary is πθ(a∣s)\pi_\theta(a \mid s).
  • Episode: one complete response.
  • Reward: a reward model, trained on human comparisons of answers, scores the finished response. A per-token KL penalty −βlog⁡πθ(a∣s)πref(a∣s)-\beta \log \frac{\pi_\theta(a \mid s)}{\pi_\text{ref}(a \mid s)} is subtracted, which keeps the model close to its starting point (the supervised fine-tuned model, πref\pi_\text{ref}). That stops it drifting into gibberish that happens to fool the reward model.
prompt state Policy LLM πθ trained · the actor each token = one action response the trajectory Reward model frozen · one score per answer Reference model frozen copy of the SFT model reward = score − β·KL KL: how far πθ has drifted from the reference, per token Value model V (critic) trained · GAE advantages for every token PPO clipped update a few epochs per batch, ratio kept in [1−ε, 1+ε] update θ four models in memory: two trained (policy, value), two frozen (reward, reference)
Fig. 2 PPO as used in classic RLHF. The policy LLM writes a response to a prompt. A frozen reward model scores it, and a frozen reference model supplies a per-token KL penalty. A value model (the critic) turns these rewards into per-token advantages with GAE. PPO's clipped update then adjusts the policy. Four large models are in play at once.

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. log⁡πθold\log \pi_{\theta_\text{old}} 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

  1. 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?
  2. Increase epochs from 20 to 200 for both variants. Does the clipped version keep moving? Why not?
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. With ε = 0.2 and a positive advantage A = +2, the probability ratio for a sample has reached r = 1.5. What does the PPO objective do for this sample?

  2. For a good action (A > 0), the ratio has fallen to r = 0.5. What does the clipped objective do?

  3. A PPO implementation recomputes log π_old with the updated network at every epoch. What happens?

  4. Why did GRPO become popular for training reasoning models instead of classic RLHF-style PPO?

  5. During PPO training the clip fraction is regularly above 0.3. What does that suggest?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Tutorial

Spinning Up in Deep RL

Joshua Achiam (OpenAI) · 2018 · Intermediate · Free

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.

Course

Hugging Face Deep RL Course

Hugging Face · Intermediate · Free

A hands-on deep reinforcement learning course from Q-learning to PPO. You train agents in games.

Paper

Trust Region Policy Optimization

Schulman, Levine, Moritz, Jordan & Abbeel · 2015 · Advanced · Free

TRPO: limit each policy update by a KL-divergence constraint so performance improves monotonically. PPO is its simpler successor.

Tool

CleanRL

Shengyi Huang et al. · Intermediate · Free

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.

Docs

TRL documentation

Hugging Face · Intermediate · Free

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