Skip to main content

PPO from first principles

From REINFORCE to PPO in numpy: a critic, GAE and the clipped objective, a bug that passed two of three tests, and a baseline that was losing to its own optimizer.
reinforcement learning
numpy
debugging
Published

December 3, 2026

This is the next step in my series of reimplementing RL algorithms by hand, on the way to the methods used for LLM post-training. Last time it was DQN. This time it’s PPO, in plain numpy, built on top of the REINFORCE I had already written. PPO matters beyond CartPole: it’s the algorithm InstructGPT used for RLHF, and GRPO, which comes next, is PPO with one piece removed.

Where I started: REINFORCE

REINFORCE learns a policy directly. A small network maps the state to \(p = P(\text{right} \mid s)\), the agent samples actions from it, and after a batch of episodes every action is nudged in proportion to how well things went afterwards:

\[ \nabla J \approx \sum_t \nabla \log \pi(a_t \mid s_t)\; \hat G_t \]

Here \(\hat G_t\) is the discounted return from step \(t\), standardized across the batch so that roughly half the actions get pushed up and half get pushed down. For a sigmoid policy, the last link of the chain rule is simply \(\partial \log \pi / \partial\, \text{logit} = a - p\).

It works, but it is wasteful. Every batch of episodes buys exactly one gradient step and is then thrown away, and \(\hat G_t\) adds up hundreds of random rewards, so it is noisy.

What PPO adds

PPO (Schulman et al., 2017) keeps the same actor and makes three changes:

  1. A critic. A second network learns \(V(s)\), the expected return from a state. It replaces the batch average as the baseline, so each action is judged against what was expected from that particular state.
  2. GAE advantages. Once you have \(V\), you no longer need to wait for the episode to end to score an action. GAE blends one-step TD errors with Monte Carlo returns.
  3. Reuse each rollout, safely. PPO collects a fixed 2048 steps, then trains on them for 10 epochs of minibatches. After the first update, the policy is no longer the one that collected the data, so each sample is reweighted by \(\pi_\text{new}/\pi_\text{old}\), and that ratio is clipped so no single rollout can move the policy too far.

flowchart LR
    E[CartPole] -- "s" --> A["actor<br/>sample a ~ π(·|s)"]
    A -- "a" --> E
    E -- "2048 steps:<br/>s, a, log π_old, r, s', terminated, done" --> G["GAE<br/>advantages, returns"]
    C["critic V(s)"] --> G
    G -- "10 epochs × minibatches of 64" --> U["clipped objective → actor<br/>MSE to returns → critic"]
    U -. "Adam" .-> A
    U -. "Adam" .-> C

The critic: biases this time

The critic has the same two-layer shape as the actor, with one difference that I learned the hard way in the DQN post: it has biases. The upright, centred CartPole state is \(s \approx 0\), and its value should be close to 100. Without biases, a ReLU network outputs exactly 0 at \(s = 0\), whatever its weights are. The critic is trained by plain regression of \(V(s)\) on the returns that GAE produces.

GAE, and the bug that passed two of three tests

GAE starts from the one-step TD error, which trusts the critic for everything after one real step:

\[ \delta_t = r_t + \gamma\, V(s_{t+1})\,(1 - \text{terminated}_t) - V(s_t) \]

The advantage is a discounted sum of these, each step further into the future weighted by a factor of \(\gamma\lambda\) less:

\[ A_t = \delta_t + (\gamma\lambda)\,\delta_{t+1} + (\gamma\lambda)^2\,\delta_{t+2} + \dots \]

With \(\lambda = 0\) this is pure TD (low noise, biased if \(V\) is wrong). With \(\lambda = 1\) the sum telescopes to \(G_t - V(s_t)\), the Monte Carlo advantage. PPO uses \(\lambda = 0.95\). You never compute the sum directly. Instead you walk backwards through the rollout, the same way you compute discounted returns:

\[ A_t = \delta_t + \gamma\lambda\,(1 - \text{done}_t)\,A_{t+1} \]

The two episode-end flags do different jobs, which took me a while to see:

  • terminated (the pole fell) goes inside \(\delta_t\). A real end has no future value.
  • done (terminated or the 500-step time limit) goes in the recursion. A 2048-step rollout contains several episodes, and \(A_{t+1}\) may belong to the next one, so it must not leak backwards.

On a time-limit truncation the pole is still up, so \(\delta_t\) still bootstraps from \(V(s_{t+1})\), but the chain stops there.

My first version looped forward, for i in range(T). Two of the three unit tests passed. It took me a moment to see why: one test used \(\lambda = 0\) and the other had an episode end at every step. Both cut the chain between steps, so the order of the loop never mattered. Only the \(\lambda = 1\) test actually needed \(A_t\) to depend on \(A_{t+1}\), and that’s the one that failed. A forward loop makes every step sum up the past instead of the future, and applies done to the wrong side of the boundary.

The fix was reversed(range(T)). (On the way there I briefly flipped (1 - done) to done too, which made things worse.) To see how much the direction matters, here is full PPO training with each loop:

experiment harness: my ppo.py and policy_gradient.py, with switches to put each bug back
import time, warnings, functools
import numpy as np, gymnasium as gym, matplotlib.pyplot as plt
import rl_basics.ppo as ppo
import rl_basics.policy_gradient as pg
from rl_basics.optim import Adam
warnings.simplefilter("ignore")

GAE = ppo.compute_gae

def gae_forward(rewards, values, next_values, terminateds, dones, gamma=0.99, lam=0.95):
    """My first compute_gae: identical, except the loop runs forward."""
    adv, g = np.zeros(len(rewards)), 0.0
    for i in range(len(rewards)):
        d = rewards[i] + gamma * next_values[i] * (1 - terminateds[i]) - values[i]
        g = d + gamma * lam * (1 - dones[i]) * g
        adv[i] = g
    return adv, adv + values

def run_ppo(seed, gae=GAE):
    ppo.compute_gae = gae
    t = time.time()
    _, _, R = ppo.train_ppo(gym.make("CartPole-v1"), seed=seed)
    ppo.compute_gae = GAE
    return np.array(R, float), time.time() - t

# REINFORCE: reinforce() builds its optimizer as Adam(model, lr=lr) and steps on -grad
_T = [1]
_backward = pg.policy_backward
def _spy(model, eph, epx, epdlogp):
    _T[0] = len(epdlogp)
    return _backward(model, eph, epx, epdlogp)

class SGD:      # my first version: params += lr * grad / n_steps
    def __init__(self, params, lr): self.lr = lr
    def step(self, params, grads):
        for k in grads: params[k] -= self.lr * grads[k] / _T[0]

class FlippedAdam(Adam):  # handing Adam the ascent gradient as-is
    def step(self, params, grads): super().step(params, {k: -v for k, v in grads.items()})

def run_reinforce(seed, opt=Adam, lr=1e-2, n_episodes=1500):
    pg.Adam, pg.policy_backward = opt, _spy
    t = time.time()
    _, R = pg.reinforce(gym.make("CartPole-v1"), n_episodes=n_episodes, lr=lr, seed=seed)
    pg.Adam, pg.policy_backward = Adam, _backward
    return np.array(R, float), time.time() - t

BLUE, ORANGE, AQUA, PURPLE, GREY = "#257de0", "#f47230", "#00b894", "#8e6bd8", "#8a8a8a"
plt.rcParams.update({
    "figure.dpi": 110, "font.size": 10, "axes.spines.top": False, "axes.spines.right": False,
    "axes.edgecolor": "#bbbbbb", "axes.grid": True, "grid.color": "#ececec",
    "axes.titlesize": 11, "axes.titleweight": "bold", "axes.titlelocation": "left",
    "lines.linewidth": 1.8, "legend.frameon": False,
})

def rolling(R, w=20):
    return np.convolve(R, np.ones(w) / w, "valid")

def curve(R, w=20):  # CartPole pays 1 per step, so cumsum(returns) = environment steps
    return np.cumsum(R)[w - 1:], rolling(R, w)

def note(ax, x, y, text):
    ax.text(x, y, text, fontsize=8.5, color="#555555")
code
ppo_runs = {(g, s): run_ppo(s, gae) for g, gae in [("backward", GAE), ("forward", gae_forward)]
            for s in range(3)}

fig, ax = plt.subplots(figsize=(7.5, 3.6))
for g, c in [("backward", BLUE), ("forward", ORANGE)]:
    for s in range(3):
        x, y = curve(ppo_runs[(g, s)][0])
        ax.plot(x, y, color=c, lw=1.4, label=f"GAE loop {g}" if s == 0 else None)
ax.axhline(22, color=GREY, lw=1, ls="--"); note(ax, 70000, 34, "random policy ≈ 22")
ax.set(title="Return", xlabel="environment steps", ylabel="return (rolling 20)", xlim=(0, 100000))
ax.legend(loc="upper left"); fig.tight_layout(); plt.show()
Figure 1: PPO with the GAE loop running backward (correct) and forward (my first version), 3 seeds each.

With the backward loop, PPO solves CartPole. With the forward loop, it settles at about 10, which is worse than random, the same signature as the bias-free DQN. The advantages it computed had nothing to do with the consequences of each action, so the policy collapsed onto a single action. A unit test that can’t tell the loop direction apart is only checking part of the logic.

The clipped objective

With \(r_t = \pi_\text{new}(a_t \mid s_t) / \pi_\text{old}(a_t \mid s_t)\), PPO maximizes

\[ L = \operatorname{mean}\Big(\min\big(r_t A_t,\ \operatorname{clip}(r_t, 1-\epsilon, 1+\epsilon)\,A_t\big)\Big), \qquad \epsilon = 0.2 \]

My first reading was that clipping zeroes out the gradient whenever the ratio leaves \([0.8, 1.2]\). That’s only half right. Working through the four cases is what made it click:

\(A\) ratio what happened min picks gradient
> 0 1.5 good action made more likely clipped 0: enough for this rollout
> 0 0.5 good action made less likely unclipped \(r A\): push it back up
< 0 0.5 bad action made less likely clipped 0: enough
< 0 1.5 bad action made more likely unclipped \(r A\): push it back down

The min makes the objective pessimistic. PPO stops rewarding progress past the trust region, but it always keeps the gradient that undoes a move in the wrong direction. Clipping alone would freeze the policy after a bad update. In code, the mask comes from comparing the two terms, not from checking whether the ratio is in range:

ratio = np.exp(new_logp - old_logp)
part1 = ratio * advantages
part2 = np.clip(ratio, 1 - clip_eps, 1 + clip_eps) * advantages
unclipped = part1 <= part2                     # ties = ratio inside the range
grad = unclipped * ratio * advantages / N      # d(ratio)/d(log pi) = ratio

From there, it’s the same chain rule as REINFORCE: multiply by \(a - p\) to get to the logit and backprop through the actor. Adam minimizes, so it gets the negative gradient. The full loop is train_ppo.

The baseline was broken

With all of that working, I wanted the obvious comparison: PPO against my REINFORCE, on the same environment, measured in environment steps. PPO solved CartPole on every seed. REINFORCE didn’t learn at all. After 3000 episodes it was still at about 30, which is random-policy level.

That didn’t look like “PPO is better”, it looked like REINFORCE was broken. My REINFORCE used plain SGD on the step-averaged gradient at lr 1e-2, and that step was simply too small to move the policy. Getting it to work properly took three attempts:

code
variants = [
    ("SGD, lr 1e-2 (first version)", SGD, 1e-2, ORANGE),
    ("Adam, gradient sign flipped", FlippedAdam, 1e-2, PURPLE),
    ("Adam, lr 3e-4 (its default)", Adam, 3e-4, GREY),
    ("Adam, lr 1e-2", Adam, 1e-2, BLUE),
]
rf_runs = {(name, s): run_reinforce(s, opt, lr) for name, opt, lr, _ in variants for s in range(3)}

fig, ax = plt.subplots(figsize=(7.5, 3.8))
for name, _, _, c in variants:
    ys = [rolling(rf_runs[(name, s)][0], 50) for s in range(3)]
    n = min(map(len, ys))
    for y in ys: ax.plot(y, color=c, lw=0.8, alpha=0.3)
    ax.plot(np.mean([y[:n] for y in ys], 0), color=c, label=name)
ax.set(title="Return", xlabel="episode", ylabel="return (rolling 50)")
ax.legend(loc="upper left"); fig.tight_layout(); plt.show()
Figure 2: REINFORCE, same algorithm, four optimizer setups. Mean of 3 seeds; thin lines are individual seeds.
  1. Swapping in Adam made it worse. The return sank below random, to about 10. policy_backward returns the gradient of the expected return, which you want to go up, and Adam always steps down. Passing it in unchanged meant gradient descent on the return, which teaches the agent to drop the pole. The old SGD code had +=, and I didn’t carry that over.
  2. With the sign fixed, still nothing. I had written Adam(model), so the function’s lr argument was silently ignored, and Adam’s default of 3e-4 is far too small here.
  3. Adam(model, lr=lr): it passes 400 in about 1000 episodes on every seed.

Same algorithm, same gradients. The only difference between “learns nothing” and “solves it” was the optimizer. DQN taught me the same lesson from the other side: there, SGD diverged and Adam kept it bounded.

PPO vs REINFORCE, fairly

With both on Adam:

code
fig, ax = plt.subplots(figsize=(7.5, 3.6))
rows = []
for name, runs, c in [("PPO", [ppo_runs[("backward", s)] for s in range(3)], BLUE),
                      ("REINFORCE", [rf_runs[("Adam, lr 1e-2", s)] for s in range(3)], ORANGE)]:
    for s, (R, secs) in enumerate(runs):
        x, y = curve(R)
        ax.plot(x, y, color=c, lw=1.4, label=name if s == 0 else None)
        hit = x[np.argmax(y >= 475)] if (y >= 475).any() else np.nan
        rows.append((name, s, hit, R.sum(), secs))
ax.axhline(500, color=GREY, lw=1, ls=":")
ax.set(title="Return", xlabel="environment steps", ylabel="return (rolling 20)", xlim=(0, 200000))
ax.legend(loc="lower right"); fig.tight_layout(); plt.show()

for name, s, hit, steps, secs in rows:
    print(f"{name:9s} seed {s}: 20-ep avg ≥ 475 after {hit:>7,.0f} steps   "
          f"({steps:,.0f} steps in {secs:.1f} s)")
Figure 3: Both with Adam, 3 seeds each, measured in environment steps. PPO’s runs stop at its default budget of 100k steps.
PPO       seed 0: 20-ep avg ≥ 475 after  46,772 steps   (98,272 steps in 2.9 s)
PPO       seed 1: 20-ep avg ≥ 475 after  46,027 steps   (98,027 steps in 2.9 s)
PPO       seed 2: 20-ep avg ≥ 475 after  52,035 steps   (98,029 steps in 2.9 s)
REINFORCE seed 0: 20-ep avg ≥ 475 after 131,082 steps   (540,584 steps in 4.2 s)
REINFORCE seed 1: 20-ep avg ≥ 475 after 113,222 steps   (497,636 steps in 3.9 s)
REINFORCE seed 2: 20-ep avg ≥ 475 after 152,140 steps   (511,601 steps in 4.7 s)

PPO reaches a 20-episode average of 475 in about 50k environment steps. REINFORCE gets there too, but it takes roughly 2.5 to 3 times as many steps and wobbles a lot more on the way. The gap comes from the three changes. Each 2048-step rollout is used for 320 gradient steps instead of one, the critic gives every action a baseline specific to its state, and GAE trades a little bias for much less noise.

In wall-clock time it’s the other way around. REINFORCE gets through environment steps faster, because it does far less computation per step. PPO is the better choice when samples are the expensive part. In LLM training they are, since every sample is a generated completion, and that’s why RLHF uses PPO.

What I’d tell myself before starting

  • A test that can’t see the bug doesn’t test the logic. Two of three GAE tests passed with the loop running in the wrong direction, because those tests cut the chain.
  • Worse than random means collapse, again. Last time it was missing biases, this time it was scrambled advantages.
  • Check the baseline before celebrating. “PPO beats REINFORCE” was mostly “Adam beats SGD at lr 1e-2”.
  • Ascent vs descent bites every time an optimizer that minimizes meets an objective you maximize. It’s worth a one-line comment at the call site.
  • Silent defaults are bugs too. Adam(model) ran without any error and ignored my learning rate.

Next is GRPO. You take this PPO, remove the critic, and use the average reward of a group of answers to the same prompt as the baseline. It’s what DeepSeek used to train R1.