# PPO: Clipping the Policy Update So One Batch of Data Can Be Reused for Many Epochs

> PPO makes policy gradients reusable: a clipped probability-ratio objective allows several minibatch epochs on one batch of data, with TRPO-like stability from first-order optimization only. A CartPole experiment compares no clipping with epsilon 0.1, 0.2 and 0.3, 8 seeds each.

- URL: https://dmxsf.com/en/blog/ppo-proximal-policy-optimization-algorithms/
- [DMXSF](https://dmxsf.com/en/about/)
- Published: 2017-07-30
- Updated: 2026-11-11
- Paper notes
- Paper: [Proximal Policy Optimization Algorithms](https://arxiv.org/abs/1707.06347) (John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, Oleg Klimov · arXiv preprint, 2017)

## Why this paper matters

Policy gradient methods sample a batch with the current policy, compute a gradient, update once and throw the batch away. The paper points out that doing several optimization steps on the same batch is not well justified and empirically often leads to destructively large policy updates. TRPO solves this with a KL constraint, but it is complicated and incompatible with noisy architectures (such as dropout) or sharing parameters between the policy and the value function.

This paper (Schulman et al., OpenAI, posted in July 2017) proposes PPO: **an objective that needs only first-order optimization and still allows several minibatch epochs on the same batch.** It is simple and general, and later became widely used in deep reinforcement learning and in early language model RLHF (see [Preference Optimization](https://dmxsf.com/en/wiki/post-training/preference-optimization/) and the [Learning to Summarize explainer](https://dmxsf.com/en/blog/learning-to-summarize-from-human-feedback/)).

## Method

**From the policy gradient to a surrogate objective.** The policy gradient estimator is $\hat g=\hat{\mathbb{E}}_t[\nabla_\theta\log\pi_\theta(a_t\mid s_t)\hat A_t]$. TRPO maximizes a surrogate objective under a KL constraint:

$$
\max_\theta\ \hat{\mathbb{E}}_t\left[\frac{\pi_\theta(a_t\mid s_t)}{\pi_{\theta_{old}}(a_t\mid s_t)}\hat A_t\right]\quad\text{s.t.}\quad\hat{\mathbb{E}}_t\big[\mathrm{KL}[\pi_{\theta_{old}}(\cdot\mid s_t),\pi_\theta(\cdot\mid s_t)]\big]\le\delta
$$

**The clipped surrogate.** Write the probability ratio $r_t(\theta)=\pi_\theta(a_t\mid s_t)/\pi_{\theta_{old}}(a_t\mid s_t)$, so $r(\theta_{old})=1$. The main PPO objective is

$$
L^{CLIP}(\theta)=\hat{\mathbb{E}}_t\left[\min\big(r_t(\theta)\hat A_t,\ \mathrm{clip}(r_t(\theta),1-\epsilon,1+\epsilon)\hat A_t\big)\right]
$$

The intuition: the second term clips the ratio to $[1-\epsilon,1+\epsilon]$, which removes the incentive to move $r_t$ outside the interval; the minimum then makes the final objective a pessimistic lower bound of the unclipped one. In other words, a change in the ratio is ignored only when it would make the objective better, and counted when it makes it worse. Around $\theta_{old}$, $L^{CLIP}$ equals $L^{CPI}$ to first order, and the further $\theta$ moves, the more they differ.

**Adaptive KL penalty (as a baseline).** The alternative subtracts $\beta\,\mathrm{KL}$ from the objective and adapts $\beta$ by comparing the KL after the update with a target $d_{targ}$: if $d<d_{targ}/1.5$ then $\beta\leftarrow\beta/2$, if $d>1.5\,d_{targ}$ then $\beta\leftarrow2\beta$. The paper finds it worse than clipping but keeps it as an important baseline.

**The full algorithm.** With a shared policy and value network the objective adds a value error and an entropy bonus: $L_t^{CLIP+VF+S}=\hat{\mathbb{E}}_t[L_t^{CLIP}-c_1L_t^{VF}+c_2S[\pi_\theta](s_t)]$. Advantages use truncated generalized advantage estimation (GAE): $\hat A_t=\delta_t+(\gamma\lambda)\delta_{t+1}+\cdots$ with $\delta_t=r_t+\gamma V(s_{t+1})-V(s_t)$. Algorithm 1: in each iteration $N$ parallel actors run $T$ steps each, the surrogate is built on these $NT$ samples and optimized for $K$ epochs with minibatch SGD (usually Adam), and then $\theta_{old}\leftarrow\theta$.

## Experiments and findings

**Comparing surrogate objectives (Table 1).** Seven MuJoCo robot tasks, 1 million steps each, 3 seeds per setting (21 runs in total); each run is scored by the average return of its last 100 episodes, normalized so that the random policy is 0 and the best result is 1, then averaged:

| Setting | Average normalized score |
| --- | --- |
| No clipping or penalty | −0.39 |
| Clipping, $\epsilon$ = 0.1 / 0.2 / 0.3 | 0.76 / 0.82 / 0.70 |
| Adaptive KL, $d_{targ}$ = 0.003 / 0.01 / 0.03 | 0.68 / 0.74 / 0.71 |
| Fixed KL, $\beta$ = 0.3 / 1 / 3 / 10 | 0.62 / 0.71 / 0.72 / 0.69 |

The score without clipping is negative because on HalfCheetah it ends up worse than the initial random policy. Clipping with $\epsilon=0.2$ is best. Other experiments: on continuous control, PPO ($\epsilon=0.2$) is compared with TRPO, CEM, vanilla policy gradient with adaptive stepsize, A2C and A2C with trust region, and the paper says it outperforms them on almost all environments. On 49 Atari games, Table 2 counts the games "won" by each algorithm: by average reward over all of training (favoring fast learning), PPO 30, ACER 18, A2C 1; by average reward over the last 100 episodes (favoring final performance), ACER 28, PPO 19, A2C 1, one tie. The paper also trains PPO on three 3D humanoid tasks: forward running, running toward a target whose position keeps changing, and running while being pelted by cubes and having to get up.

## Checking it with code

The central claim of the paper is that several epochs on one batch produce destructively large updates and clipping fixes this. The code implements PPO (Algorithm 1, a single actor) on CartPole: each iteration collects $T=2048$ steps, runs $K=10$ epochs with minibatch 64, Adam learning rate $3\times10^{-4}$, $\gamma=0.99$, $\lambda=0.95$, the same as the MuJoCo hyperparameters in Table 3 of the paper. The networks are two hidden layers of 64 tanh units, policy and value function share no parameters, and there is no entropy bonus. It compares no clipping with $\epsilon=0.1,0.2,0.3$, 8 seeds each, 40 iterations (about 82,000 steps) per run.

Two implementation details are mine and not in the main text of the paper: advantages are standardized per batch, and an episode ending at the 500-step limit is treated as terminal. The environment is the standard CartPole dynamics (return capped at 500), far easier than MuJoCo, so the results are only for watching the mechanism. In the table the ret columns are the average return of the last 10 finished episodes at the end of an iteration, shown as mean±standard deviation over the 8 seeds. The last three columns are measured on each batch right after its update and then averaged over 40 iterations and 8 seeds: KL is estimated as the sample mean of $\log\pi_{old}-\log\pi_{new}$, ">0.2" is the share of samples whose ratio is more than 0.2 away from 1, and max ratio is the largest ratio in the batch.

```python
import math
import random
import statistics as st

import torch
from torch import nn

torch.set_num_threads(1)

class CartPole:
    """Dynamics of the classic-control task CartPole (Euler, 0.02 s step)."""

    def __init__(self, seed):
        self.rng = random.Random(seed)

    def reset(self):
        self.s = [self.rng.uniform(-0.05, 0.05) for _ in range(4)]
        self.t = 0
        return list(self.s)

    def step(self, action):
        x, xd, th, thd = self.s
        force = 10.0 if action == 1 else -10.0
        c, s = math.cos(th), math.sin(th)
        temp = (force + 0.05 * thd * thd * s) / 1.1
        tha = (9.8 * s - c * temp) / (0.5 * (4 / 3 - 0.1 * c * c / 1.1))
        xa = temp - 0.05 * tha * c / 1.1
        self.s = [x + 0.02 * xd, xd + 0.02 * xa, th + 0.02 * thd,
                  thd + 0.02 * tha]
        self.t += 1
        done = abs(self.s[0]) > 2.4 or abs(self.s[2]) > 0.2095 or self.t >= 500
        return list(self.s), 1.0, done

def mlp(n_out):  # two tanh layers of 64 units; no parameter sharing
    return nn.Sequential(nn.Linear(4, 64), nn.Tanh(), nn.Linear(64, 64),
                         nn.Tanh(), nn.Linear(64, n_out))

def train(eps, seed, iters=40, horizon=2048, epochs=10, mb=64):
    """PPO (Algorithm 1 of the paper, one actor); eps=None means no clipping."""
    torch.manual_seed(seed)
    env = CartPole(10_000 + seed)  # the env start states use their own seed
    pi, vf = mlp(2), mlp(1)
    opt = torch.optim.Adam([*pi.parameters(), *vf.parameters()], lr=3e-4)
    obs, ep_ret, rets, log = env.reset(), 0.0, [], []
    for _ in range(iters):
        o, a, lp, r, d, v = [], [], [], [], [], []
        with torch.no_grad():  # 1) sample `horizon` steps with the old policy
            for _ in range(horizon):
                x = torch.tensor(obs)
                dist = torch.distributions.Categorical(logits=pi(x))
                act = dist.sample()
                o.append(x), a.append(act), lp.append(dist.log_prob(act))
                v.append(vf(x).squeeze())
                obs, rew, done = env.step(act.item())
                r.append(rew), d.append(done)
                ep_ret += rew
                if done:
                    rets.append(ep_ret)
                    ep_ret, obs = 0.0, env.reset()
            last_v = vf(torch.tensor(obs)).squeeze()
        o, a, lp_old = torch.stack(o), torch.stack(a), torch.stack(lp)
        v = torch.stack(v + [last_v])
        adv, gae = torch.zeros(horizon), 0.0  # 2) GAE, gamma=0.99, lambda=0.95
        for t in reversed(range(horizon)):
            nd = 0.0 if d[t] else 1.0  # do not accumulate across episode ends
            delta = r[t] + 0.99 * v[t + 1] * nd - v[t]
            gae = delta + 0.99 * 0.95 * nd * gae
            adv[t] = gae
        ret = adv + v[:-1]  # regression target of the value function
        adv = (adv - adv.mean()) / (adv.std() + 1e-8)
        for _ in range(epochs):  # 3) K epochs of minibatches on this batch
            for b in torch.randperm(horizon).split(mb):
                dist = torch.distributions.Categorical(logits=pi(o[b]))
                ratio = (dist.log_prob(a[b]) - lp_old[b]).exp()
                obj = ratio * adv[b]  # Eq. (6); Eq. (7) when eps is set
                if eps is not None:
                    obj = torch.min(obj, ratio.clamp(1 - eps, 1 + eps) * adv[b])
                v_err = (vf(o[b]).squeeze(-1) - ret[b]) ** 2
                opt.zero_grad()
                (-obj.mean() + v_err.mean()).backward()
                opt.step()
        with torch.no_grad():  # after the update: drift on this batch
            logp = torch.distributions.Categorical(logits=pi(o)).log_prob(a)
            ratio = (logp - lp_old).exp()
        log.append((sum(rets[-10:]) / max(1, len(rets[-10:])),
                    (lp_old - logp).mean().item(),
                    ((ratio - 1).abs() > 0.2).float().mean().item(),
                    ratio.max().item()))
    return log

def mean_sd(xs):
    return f"{st.mean(xs):5.0f}±{st.stdev(xs):<3.0f}"

print("setting   ret@20k    ret@41k    ret@82k    KL     >0.2   max ratio")
for eps in (None, 0.1, 0.2, 0.3):
    runs = [train(eps, seed) for seed in range(8)]  # 8 seeds
    ret = lambda i: mean_sd([run[i][0] for run in runs])
    kl = st.mean(x[1] for run in runs for x in run)
    out = st.mean(x[2] for run in runs for x in run)
    mx = st.mean(x[3] for run in runs for x in run)
    name = "no clip" if eps is None else f"eps={eps}"
    print(f"{name:9s} {ret(9)}  {ret(19)}  {ret(39)}  {kl:.4f} {out:6.1%}"
          f"  {mx:5.2f}")
```

Output (CPU, single thread, about 12 minutes):

```text
setting   ret@20k    ret@41k    ret@82k    KL     >0.2   max ratio
no clip     168±137    363±129    326±184  1.1532  57.7%  65.43
eps=0.1     193±23     472±27     497±7    0.0019   0.3%   1.16
eps=0.2     296±64     476±14     500±0    0.0057   5.8%   1.33
eps=0.3     247±71     407±125    496±7    0.0112  16.5%   1.52
```

How to read these numbers:

1. **Without clipping it learns, but unstably.** At 20,000 steps the unclipped return is comparable (168 against 193, 296 and 247), but at 82,000 steps the three clipped settings reach 496 to 500 (standard deviation at most 7) while the unclipped one has only 326±184, and the standard deviation shows how much the seeds differ. This agrees in direction with the paper's Table 1, where no clipping scores negative, although CartPole is much easier than HalfCheetah and nothing ends up worse than random.
2. **Without clipping the updates are two orders of magnitude larger.** The mean KL is 1.15 without clipping and 0.002 to 0.011 with it. Without clipping 57.7% of the samples have a ratio more than 0.2 away from 1 and the largest ratio averages 65.4, so 10 epochs raised the probability of individual actions by dozens of times.
3. **Clipping is not a hard constraint.** With $\epsilon=0.2$, 5.8% of samples still have a ratio more than 0.2 away from 1 and the largest ratio averages 1.33; with $\epsilon=0.3$ it is 16.5% and 1.52. Clipping removes the gradient in the out-of-range direction, but gradients from other samples and Adam's momentum can still push an out-of-range sample further, only by a small amount.
4. **The choice of $\epsilon$ between 0.1 and 0.3 matters little here.** At 82,000 steps all three are at 496 to 500. $\epsilon=0.2$ is fastest at 20,000 steps (296±64 against 193±23 and 247±71), matching the paper's Table 1 where 0.2 ranks first, but the difference from 0.3 is within noise and 8 seeds cannot separate them.

## Limitations and what to keep in mind

- **The paper's comparison is narrow.** Table 1 has only 7 MuJoCo tasks with 3 seeds each, so the claim that 0.2 is best carries noticeable noise; on Atari the two scoring metrics rank the algorithms differently (PPO wins 30 games by average over training, ACER wins 28 by final performance).
- **Implementation details matter.** Later work (Engstrom et al., 2020) found that code-level optimizations such as value-function clipping, learning-rate annealing, and advantage and observation normalization explain most of PPO's gain over TRPO, and the main text of the paper does not stress them. The experiment here also uses advantage standardization.
- **Clipping does not replace a trust region.** As shown above, the ratio can go far outside the clipping interval.
- **The CartPole experiment is teaching scale.** Eight seeds on one simple task cannot stand in for continuous control or language models.
- **Language models use it differently.** In RLHF each token is a time step, the reward arrives only at the end of the sequence, and a KL penalty to the reference model is added, which goes beyond the paper.

## What to take from this paper

1. **Reusing data for many epochs needs a constraint.** It constrains the difference between the new and old policy, not the gradient step size.
2. **Clipping is a first-order stand-in for a trust region.** It removes the incentive to leave the interval while the objective stays a pessimistic lower bound.
3. **It is not a hard constraint.** Looking at the real distribution of the ratio is more reliable than assuming it stays in the interval.
4. **Simple beats exact.** Much simpler than TRPO, often just as good.
5. **Implementation details are part of the algorithm.** Advantage normalization and schedules change the results and have to be reported when reproducing.

## Further reading

- Paper: [Proximal Policy Optimization Algorithms](https://arxiv.org/abs/1707.06347)
- Follow-up study: Engstrom et al., [Implementation Matters in Deep Policy Gradients: A Case Study on PPO and TRPO](https://arxiv.org/abs/2005.12729)
- A work that uses PPO as its general-purpose baseline: Hafner et al., [Mastering Diverse Domains through World Models](https://arxiv.org/abs/2301.04104) (DreamerV3, 2023); [paper breakdown](https://dmxsf.com/en/blog/dreamerv3-mastering-diverse-domains-through-world-models/).
- Related explainers on this site: [Learning to Summarize](https://dmxsf.com/en/blog/learning-to-summarize-from-human-feedback/), [InstructGPT](https://dmxsf.com/en/blog/instructgpt-rlhf/), [GRPO (DeepSeekMath)](https://dmxsf.com/en/blog/deepseekmath-pushing-the-limits-of-mathematical-reasoning/)
- Related Wiki on this site: [Preference Optimization](https://dmxsf.com/en/wiki/post-training/preference-optimization/), [Reasoning RL](https://dmxsf.com/en/wiki/post-training/reasoning-rl/)
- Glossary: [PPO](https://dmxsf.com/en/glossary/#ppo), [GAE](https://dmxsf.com/en/glossary/#gae)

## FAQ

### What does the PPO clipped objective mean?

Let r = π_new(a|s) / π_old(a|s) be the probability ratio of the new and old policy for the same action and A the advantage estimate. PPO maximizes min(r·A, clip(r, 1-ε, 1+ε)·A). For positive A the objective stops growing once r exceeds 1+ε, and for negative A it stops shrinking once r falls below 1-ε. This removes the incentive to push the ratio out of the interval, and taking the minimum keeps the objective a pessimistic lower bound of the unclipped one.

### How does PPO differ from TRPO?

TRPO maximizes a surrogate objective under a constraint that the mean KL between old and new policy stays below δ, solved with conjugate gradients. It is complicated and incompatible with architectures that include noise such as dropout or parameter sharing. PPO needs only first-order optimization, replaces the constraint by clipping (or an adaptive KL penalty) inside the objective, and can run several minibatch epochs with Adam. The paper says it takes only a few lines of change to a vanilla policy gradient implementation.

### Does clipping guarantee that the ratio stays inside [1-ε, 1+ε]?

No. Clipping only removes the gradient in the out-of-range direction, it is not a hard constraint. Gradients from other samples in the same batch and Adam's momentum can still push an out-of-range sample further. In the CartPole experiment here, with ε=0.2, 5.8% of samples still end up with a ratio more than 0.2 away from 1, and the largest ratio in a batch averages 1.33.

### Why is PPO commonly used in RLHF?

The paper says PPO keeps the data efficiency and reliability of TRPO with first-order optimization only, and is simpler and more general (for example the policy and value function can share parameters). Learning to Summarize and InstructGPT both optimize language models with PPO, where each token is a time step, the reward comes from a reward model and a KL penalty to a reference model is added. GRPO later replaced the value network with within-group comparison and kept the clipping idea.
