concept / ppo
Next task →
University/Reinforcement Learning/Policy-gradient methods/Proximal Policy Optimization
Reinforcement Learning · Policy-gradient methods · Trust-region-style methods

Proximal Policy Optimization

PPO stabilizes policy-gradient training by limiting how far the policy can move per update: TRPO imposes a hard KL trust region, while PPO uses a clipped importance-ratio surrogate that removes the incentive for overly large probability changes. Combined with generalized advantage estimation and value/entropy losses, it is the default general-purpose on-policy RL algorithm.

39 sectionsresearch240 minhand-authored · structural 80/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

Proximal Policy Optimization (PPO) is an on-policy policy-gradient algorithm that takes several small gradient steps on the same batch of rollout data while preventing destructively large policy changes. Define the probability ratio between the current and the behaviour (data-collecting) policy:

rt(θ)=πθ(At∣St)πθold(At∣St).r_t(\theta)=\frac{\pi_\theta(A_t|S_t)}{\pi_{\theta_{\text{old}}}(A_t|S_t)}.

The clipped surrogate objective is

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

typically with ε=0.2\varepsilon=0.2. The advantage estimates A^t\hat A_t come from generalized advantage estimation (GAE), and the full objective adds a value-function loss and an entropy bonus:

L(θ)=LCLIP(θ)−cv Et(Vθ(St)−R^t)2+ce H[πθ].L(\theta)=L^{\mathrm{CLIP}}(\theta)-c_v\,\mathbb{E}_t\bigl(V_\theta(S_t)-\hat R_t\bigr)^2+c_e\,H[\pi_\theta].

PPO collects a rollout, runs K≈10K\approx10 epochs of minibatch SGD/Adam on it, then discards the data (on-policy) and collects a fresh rollout.

It is the practical successor to TRPO: simpler to implement (first-order optimization only), yet retains the trust-region intuition that large policy updates cause collapse.

2. Why this concept exists

Vanilla REINFORCE with a baseline suffers from high variance and extreme step-size sensitivity: a single large gradient step can assign near-zero probability to the very actions that worked, destroying the policy (policy collapse). TRPO (Schulman et al. 2015) fixed this with a hard KL constraint

max⁡θ Et[rt(θ)A^t]s.t.Et[KL(πθold(⋅∣St)∥πθ(⋅∣St))]≤δ,\max_\theta\ \mathbb{E}_t[r_t(\theta)\hat A_t]\quad\text{s.t.}\quad \mathbb{E}_t[\mathrm{KL}(\pi_{\theta_{\text{old}}}(\cdot|S_t)\|\pi_\theta(\cdot|S_t))]\le\delta,

solved by conjugate gradients and a line search using second-order Fisher information — powerful but complicated, expensive, and incompatible with parameter sharing and dropout.

PPO asks: can we get the same stabilization with only first-order gradients? The clipped surrogate replaces the constraint with a pessimistic lower bound that flattens once rtr_t leaves [1−ε,1+ε][1-\varepsilon,1+\varepsilon] in the beneficial direction. Gradient-based optimizers can then take multiple epochs on one rollout (improving sample use) without the policy running away. Adaptive-KL PPO is the sibling variant that keeps a KL penalty with a dynamically adjusted coefficient.

3. Historical background

Williams (1992) derived REINFORCE: ∇J=E[Gt∇log⁡π(At∣St)]\nabla J=\mathbb{E}[G_t\nabla\log\pi(A_t|S_t)]. Sutton et al. (2000) proved the policy gradient theorem ∇J(θ)=E[∑t∇log⁡π(at∣st)Aπ(st,at)]\nabla J(\theta)=\mathbb{E}[\sum_t\nabla\log\pi(a_t|s_t)A^\pi(s_t,a_t)], replacing the return by an advantage to cut variance. Kakade (2001) introduced the natural policy gradient, preconditioning by the Fisher information matrix.

Schulman et al. (2015) introduced TRPO with its monotonic improvement guarantee and conjugate-gradient solver. Schulman et al. (2016) introduced GAE, giving a tunable bias–variance tradeoff via λ∈[0,1]\lambda\in[0,1]. Schulman et al. (2017) published PPO, showing that the clipped objective reproduces much of TRPO's stability with a few lines of code. PPO became the default in OpenAI Gym baselines, robotics sim-to-real pipelines, and became widely used for RLHF fine-tuning of language models (where the "policy" is the autoregressive token distribution and the clip acts on token log-probability ratios).

4. Fundamental problem

Maximize the expected discounted return J(θ)=Eπθ[∑tγtRt]J(\theta)=\mathbb{E}_{\pi_\theta}[\sum_t\gamma^t R_t] using samples collected from πθold\pi_{\theta_{\text{old}}}, while:

  1. avoiding destructive updates (a large step can permanently remove useful actions once π(a∣s)≈0\pi(a|s)\approx0);
  2. making efficient use of each rollout (multiple gradient epochs without leaving the region where importance sampling is valid);
  3. keeping advantage estimates low-variance but not overly biased;
  4. doing all this with simple first-order optimization, no Hessian–vector products or constraint solvers.

5. First-principles explanation

Fact 1 — likelihood-ratio identity. For trajectories τ\tau,

∇θEπθ[G]=Eπθold[pθold(τ)pθ(τ)G∇θlog⁡pθ(τ)]\nabla_\theta\mathbb{E}_{\pi_\theta}[G]=\mathbb{E}_{\pi_{\theta_{\text{old}}}}\Big[\frac{p_{\theta_{\text{old}}}(\tau)}{p_\theta(\tau)}G\nabla_\theta\log p_\theta(\tau)\Big]

can be rewritten with the per-step ratio rt(θ)=πθ(at∣st)/πθold(at∣st)r_t(\theta)=\pi_\theta(a_t|s_t)/\pi_{\theta_{\text{old}}}(a_t|s_t). The surrogate LCPI(θ)=Et[rtA^t]L^{\mathrm{CPI}}(\theta)=\mathbb{E}_t[r_t\hat A_t] has gradient equal to the policy gradient at θ=θold\theta=\theta_{\text{old}}.

Fact 2 — unconstrained maximization breaks the surrogate. If A^t>0\hat A_t>0, maximizing rtA^tr_t\hat A_t drives rt→∞r_t\to\infty (probability 1 for that action); if A^t<0\hat A_t<0, it drives rt→0r_t\to0. Both are catastrophic when A^t\hat A_t is a noisy estimate and the batch is finite.

Fact 3 — clipping removes the incentive for extremes. With clip(rt,1−ε,1+ε)\mathrm{clip}(r_t,1-\varepsilon,1+\varepsilon), once rt>1+εr_t>1+\varepsilon and A^t>0\hat A_t>0, the clipped term is constant (1+ε)A^t(1+\varepsilon)\hat A_t, so the min selects it and the gradient is zero. Similarly for A^t<0\hat A_t<0 and rt<1−εr_t<1-\varepsilon. The objective is pessimistic: it keeps the penalty for moving far in the harmful direction but stops rewarding further movement in the helpful direction.

Fact 4 — GAE. Temporal-difference errors δt=rt+γV(st+1)−V(st)\delta_t=r_t+\gamma V(s_{t+1})-V(s_t) are low-variance but biased by the value estimate; full Monte Carlo advantages are unbiased but high-variance. Exponentially weighting TD errors with γλ\gamma\lambda interpolates between them.

6. Prerequisite concepts

You need: (a) the policy gradient theorem and the likelihood-ratio estimator ∇log⁡π(a∣s)\nabla\log\pi(a|s); (b) advantage functions and actor–critic baselines (variance reduction); (c) importance sampling and KL divergence, which motivate the trust region; (d) TD errors and generalized advantage estimation; (e) first-order optimization with Adam and gradient clipping, plus the idea of multiple epochs on one batch; (f) PyTorch distributions (Categorical for discrete actions, Normal for continuous) and vectorized gym environments. Understanding TRPO's constrained objective is helpful but not strictly required; the clipped surrogate can be derived without it.

7. Complete mathematical formulation

Policy ratio. rt(θ)=exp⁡(log⁡πθ(at∣st)−log⁡πθold(at∣st))r_t(\theta)=\exp\bigl(\log\pi_\theta(a_t|s_t)-\log\pi_{\theta_{\text{old}}}(a_t|s_t)\bigr). With a categorical policy, log⁡π(a∣s)=log⁡softmax(fθ(s))a\log\pi(a|s)=\log\mathrm{softmax}(f_\theta(s))_a.

Clipped surrogate. LCLIP(θ)=Et[min⁡(rtA^t, clip(rt,1−ε,1+ε)A^t)]L^{\mathrm{CLIP}}(\theta)=\mathbb{E}_t[\min(r_t\hat A_t,\ \mathrm{clip}(r_t,1-\varepsilon,1+\varepsilon)\hat A_t)].

GAE. With δt=rt+γV(st+1)−V(st)\delta_t=r_t+\gamma V(s_{t+1})-V(s_t) (and V(sT)=0V(s_T)=0 at a terminal),

A^tGAE(γ,λ)=∑l=0T−1−t(γλ)lδt+l,\hat A_t^{\mathrm{GAE}(\gamma,\lambda)}=\sum_{l=0}^{T-1-t}(\gamma\lambda)^l\delta_{t+l},

computed by the reverse recursion A^t=δt+γλ(1−dt)A^t+1\hat A_t=\delta_t+\gamma\lambda(1-d_t)\hat A_{t+1}. λ=0\lambda=0 gives the one-step TD advantage; λ=1\lambda=1 gives the Monte Carlo advantage minus V(st)V(s_t).

Objective. L=LCLIP−cv MSE(Vθ,R^)+ceH[πθ]L=L^{\mathrm{CLIP}}-c_v\,\mathrm{MSE}(V_\theta,\hat R)+c_e H[\pi_\theta] with R^t=A^t+V(st)\hat R_t=\hat A_t+V(s_t), typical cv=0.5c_v=0.5, ce=0.01c_e=0.01 (often with entropy annealing).

Trust-region connection. TRPO solves max⁡θg⊤(θ−θold)\max_\theta g^\top(\theta-\theta_{\text{old}}) s.t. 12(θ−θold)⊤F(θ−θold)≤δ\frac12(\theta-\theta_{\text{old}})^\top F(\theta-\theta_{\text{old}})\le\delta, with g=∇θLCPIg=\nabla_\theta L^{\mathrm{CPI}} and Fisher F=E[∇log⁡π∇log⁡π⊤]F=\mathbb{E}[\nabla\log\pi\nabla\log\pi^\top]; the natural step is Δθ=2δ/(g⊤F−1g) F−1g\Delta\theta=\sqrt{2\delta/(g^\top F^{-1}g)}\,F^{-1}g. PPO replaces this by clipping.

Assumptions. On-policy sampling (data from πθold\pi_{\theta_{\text{old}}}), bounded advantages (often normalized), and a policy with full support so ratios are well-defined.

8. Notation dictionary

| Symbol | Meaning | Type / shape | |---|---|---| | πθ(a∣s)\pi_\theta(a|s) | parameterized policy | distribution over actions | | θ,θold\theta,\theta_{\text{old}} | current / behaviour policy parameters | vectors in Rd\mathbb{R}^d | | rt(θ)r_t(\theta) | importance ratio at time tt | positive scalar | | ε\varepsilon | clip range, typically 0.2 | scalar | | A^t\hat A_t | GAE advantage estimate | scalar per timestep | | δt\delta_t | TD error | scalar | | γ,λ\gamma,\lambda | discount and GAE trace decay | scalars in [0,1][0,1] | | Vθ(s)V_\theta(s) | value-network prediction | scalar | | R^t\hat R_t | advantage target return A^t+V(st)\hat A_t+V(s_t) | scalar | | cv,cec_v,c_e | value-loss and entropy coefficients | scalars | | H[π]H[\pi] | policy entropy E[−log⁡π(a∣s)]\mathbb{E}[-\log\pi(a|s)] | scalar | | TT | rollout horizon per environment | integer, e.g. 2048 | | NN | parallel environments | integer, e.g. 8 | | bb | minibatch size | integer, e.g. 256 | | KK | epochs per rollout | integer, e.g. 10 | | FF | Fisher information matrix | Rd×d\mathbb{R}^{d\times d} |

9. Step-by-step derivation

Step 1 — surrogate policy gradient. The policy gradient theorem gives ∇J(θ)=Eτ∼πθ[∑t∇log⁡πθ(at∣st)Aπθ(st,at)]\nabla J(\theta)=\mathbb{E}_{\tau\sim\pi_\theta}[\sum_t\nabla\log\pi_\theta(a_t|s_t)A^{\pi_\theta}(s_t,a_t)]. Using data from πθold\pi_{\theta_{\text{old}}} and the likelihood ratio gives the equivalent surrogate LCPI(θ)=Et[rt(θ)A^t]L^{\mathrm{CPI}}(\theta)=\mathbb{E}_t[r_t(\theta)\hat A_t] whose gradient at θold\theta_{\text{old}} matches the true policy gradient.

Step 2 — bound the update. TRPO's monotonic improvement result uses η(θ)≥LCPI(θ)−4επγ(1−γ)2α2\eta(\theta)\ge L^{\mathrm{CPI}}(\theta)-\frac{4\varepsilon_\pi\gamma}{(1-\gamma)^2}\alpha^2 where α\alpha is the total-variation distance between policies. This motivates constraining KL rather than trusting the surrogate indefinitely.

Step 3 — clip. Define LCLIPL^{\mathrm{CLIP}} as above. Analyse the min term:

  • A^t>0\hat A_t>0, rt>1+εr_t>1+\varepsilon: min⁡(rtA^t,(1+ε)A^t)=(1+ε)A^t\min(r_t\hat A_t,(1+\varepsilon)\hat A_t)=(1+\varepsilon)\hat A_t — zero gradient, preventing further increase.
  • A^t<0\hat A_t<0, rt<1−εr_t<1-\varepsilon: min⁡(rtA^t,(1−ε)A^t)=(1−ε)A^t\min(r_t\hat A_t,(1-\varepsilon)\hat A_t)=(1-\varepsilon)\hat A_t — zero gradient, preventing further decrease.
  • Otherwise the unclipped term is active and the usual policy gradient flows. Hence the objective is a pessimistic lower bound on LCPIL^{\mathrm{CPI}} and creates a "proximal zone" of width 2ε2\varepsilon around the old policy.

Step 4 — GAE derivation. Unroll the Bellman-operator advantage recursion Aπ(s,a)=E[r+γAπ(s′,a′)]A^\pi(s,a)=\mathbb{E}[r+\gamma A^\pi(s',a')] with a λ\lambda-weighted mixture of 1-step, 2-step, … returns:

A^t=(1−λ)∑n≥1λn−1(∑l=0n−1γlrt+l+γnV(st+n)−V(st))=∑l≥0(γλ)lδt+l.\hat A_t=(1-\lambda)\sum_{n\ge1}\lambda^{n-1}\Bigl(\sum_{l=0}^{n-1}\gamma^l r_{t+l}+\gamma^nV(s_{t+n})-V(s_t)\Bigr)=\sum_{l\ge0}(\gamma\lambda)^l\delta_{t+l}.

The telescoping of the value terms is what yields the compact TD-error sum.

Step 5 — combine losses. Regress the value network onto R^t=A^t+V(st)\hat R_t=\hat A_t+V(s_t) and add entropy to discourage premature determinism; optimize all terms jointly with Adam for KK epochs on minibatches of the same rollout.

10. Proofs and proof intuition

Lemma 1 (ratio identity). For any function ff of trajectories, Eπθ[f]=Eπθold[pθ(τ)pθold(τ)f]\mathbb{E}_{\pi_\theta}[f]=\mathbb{E}_{\pi_{\theta_{\text{old}}}}[\frac{p_\theta(\tau)}{p_{\theta_{\text{old}}}(\tau)}f]. Proof. Write the expectation as a sum/integral over trajectories and multiply by pθold/pθold=1p_{\theta_{\text{old}}}/p_{\theta_{\text{old}}}=1. □\square

Lemma 2 (clipped objective is a lower bound). For all r>0r>0 and AA, min⁡(rA,clip(r,1−ε,1+ε)A)≤rA\min(rA,\mathrm{clip}(r,1-\varepsilon,1+\varepsilon)A)\le rA. Proof. The min of two numbers is at most the first. For A>0A>0 the clipped term is even smaller than rArA when rr leaves the interval; for A<0A<0 the inequality is immediate from the min. □\square This gives the pessimistic bound used in the analysis.

Lemma 3 (zero gradient outside the proximal zone). If A>0A>0 and r>1+εr>1+\varepsilon, then ∂LCLIP/∂r=0\partial L^{\mathrm{CLIP}}/\partial r=0; similarly if A<0A<0 and r<1−εr<1-\varepsilon. Proof. Direct case analysis of the min. □\square

Lemma 4 (GAE telescopes). ∑l≥0(γλ)lδt+l=(1−λ)∑n≥1λn−1(∑l=0n−1γlrt+l+γnV(st+n)−V(st))\sum_{l\ge0}(\gamma\lambda)^l\delta_{t+l}=(1-\lambda)\sum_{n\ge1}\lambda^{n-1}\bigl(\sum_{l=0}^{n-1}\gamma^lr_{t+l}+\gamma^nV(s_{t+n})-V(s_t)\bigr). Proof. Expand δt+l=rt+l+γVt+l+1−Vt+l\delta_{t+l}=r_{t+l}+\gamma V_{t+l+1}-V_{t+l} and interchange the sums; the value terms telescope with weights (γλ)l(\gamma\lambda)^l and (1−λ)λn−1(1-\lambda)\lambda^{n-1}. □\square

TRPO monotonicity intuition (Schulman et al. 2015). The performance difference lemma bounds the true return improvement by the surrogate minus a KL-dependent penalty; hence a step satisfying a small KL constraint improves JJ to first order. PPO does not enforce the constraint exactly — its guarantee is heuristic, which is why the clipping range and number of epochs are empirical hyperparameters.

11. Geometric interpretation

In the space of policies, TRPO takes a step of length at most 2δ\sqrt{2\delta} in the Fisher/Riemannian metric: the KL divergence is a local quadratic approximation to the geometry of the policy manifold, so the natural-gradient step is invariant to reparameterization. PPO instead uses ordinary Euclidean gradient steps but deforms the objective: the clipped surface is flat outside a strip r∈[1−ε,1+ε]r\in[1-\varepsilon,1+\varepsilon] in likelihood-ratio space.

Plot LCLIPL^{\mathrm{CLIP}} as a function of rr for fixed AA: for A>0A>0 it rises linearly to (1+ε)A(1+\varepsilon)A at r=1+εr=1+\varepsilon and then becomes a plateau; for A<0A<0 it falls to a floor (1−ε)A(1-\varepsilon)A at r=1−εr=1-\varepsilon and then plateaus. The optimizer has no reason to push further, so repeated epochs on the same batch stay near the old policy in probability space.

GAE's λ\lambda controls a different geometry: in advantage space, λ=0\lambda=0 looks only one step ahead (high bias toward the critic), λ=1\lambda=1 looks to the episode end (high variance). The effective horizon of the advantage estimate is ≈1/(1−γλ)\approx1/(1-\gamma\lambda) steps — about 20 steps for γ=0.99,λ=0.95\gamma=0.99,\lambda=0.95.

12. Visual explanation

Show the clipped surrogate plot: x-axis rtr_t from 0.5 to 1.5, y-axis rtA^tr_t\hat A_t and clip(rt,1−ε,1+ε)A^t\mathrm{clip}(r_t,1-\varepsilon,1+\varepsilon)\hat A_t with two curves for A^=±2\hat A=\pm2; shade the plateau regions and mark ε=0.2\varepsilon=0.2 boundaries at 0.8 and 1.2. The kink at the boundary makes the zero-gradient zones visible.

Second visual: a training curve of mean episode return vs. environment steps, with shaded standard deviation over 3–5 seeds, comparing PPO to vanilla policy gradient (which shows sharp collapses) and TRPO (smoother but slower per wall-clock second).

Third visual: a heat map of A^t\hat A_t over a rollout (time × environment), and a histogram of log⁡rt\log r_t after the update — with clipping working, most values stay in [−0.2,0.2][-0.2,0.2] in log-probability terms.

The Interactive PPO Clip Lab in Practical Labs lets you drag ε\varepsilon and watch the surrogate plateau move and the resulting policy histogram widen or narrow.

13. Numerical worked example

Clipping arithmetic with ε=0.2\varepsilon=0.2:

  • A^=+2\hat A=+2, r=1.5r=1.5: rA^=3.0r\hat A=3.0, clipped =1.2×2=2.4=1.2\times2=2.4, min =2.4=2.4 (gradient zero — the beneficial move is capped).
  • A^=−2\hat A=-2, r=0.7r=0.7: rA^=−1.4r\hat A=-1.4, clipped =0.8×(−2)=−1.6=0.8\times(-2)=-1.6, min =−1.6=-1.6 (capped; further probability reduction stopped).
  • A^=+0.5\hat A=+0.5, r=0.9r=0.9: both terms equal 0.450.45, inside the zone, so the normal gradient flows.

GAE computation for a 3-step episode with rewards (0,0,1)(0,0,1), values V=(0.2,0.4,0.6,0)V=(0.2,0.4,0.6,0), γ=0.99\gamma=0.99, λ=0.95\lambda=0.95, γλ=0.9405\gamma\lambda=0.9405:

δ0=0+0.99(0.4)−0.2=0.196,δ1=0+0.99(0.6)−0.4=0.194,δ2=1+0−0.6=0.400.\delta_0=0+0.99(0.4)-0.2=0.196,\quad \delta_1=0+0.99(0.6)-0.4=0.194,\quad \delta_2=1+0-0.6=0.400.

Reverse recursion: A^2=0.400\hat A_2=0.400; A^1=0.194+0.9405(0.400)=0.5702\hat A_1=0.194+0.9405(0.400)=0.5702; A^0=0.196+0.9405(0.5702)=0.7323\hat A_0=0.196+0.9405(0.5702)=0.7323. With λ=0\lambda=0 we would get A^0=0.196\hat A_0=0.196 (one-step TD); with λ=1\lambda=1, A^0=0.196+0.99(0.194)+0.992(0.4)=0.7746\hat A_0=0.196+0.99(0.194)+0.99^2(0.4)=0.7746.

Rollout sizes. T=2048T=2048 steps × N=8N=8 environments =16,384=16{,}384 transitions per rollout; with minibatch b=256b=256 and K=10K=10 epochs that is 10×16384/256=64010\times16384/256=640 gradient updates per rollout, so each sampled transition is used 10 times — the efficiency gain over a single vanilla gradient step.

14. Real-world analogy

Think of a coach refining a team's strategy based on one tournament. If the team changes its entire playbook after a single lucky win, performance collapses — exactly what a large policy-gradient step does. PPO's rule: "you may adjust each play's usage, but not by more than a factor of about 1.2 per review." Over ten review meetings on the same tournament data, the strategy improves gradually while remaining recognizably the same team. GAE is how the coach judges a play: not just the final score, but a blend of immediate yardage and the likely downstream advantage, with a tunable emphasis on long-term consequences.

15. Algorithm pseudocode

algorithm PPO(actor_critic, T=2048, N=8, K=10, b=256, gamma=0.99, lambda=0.95, eps=0.2, c_v=0.5, c_e=0.01):
    repeat:
        # ---- collect on-policy rollout ----
        for t = 0 .. T-1, for each env n = 0 .. N-1:
            a[t,n] ~ pi_old(.|s[t,n]); store logp_old[t,n], V[t,n], r[t,n], done[t,n]
        # ---- advantages (GAE, reverse recursion) ----
        last <- V(s[T]) if not terminal else 0
        gae <- 0
        for t = T-1 down to 0:
            delta[t] <- r[t] + gamma*(1-done[t])*last - V[t]
            gae <- delta[t] + gamma*lambda*(1-done[t])*gae
            A[t] <- gae ; last <- V[t]
        R[t] <- A[t] + V[t] ; normalise A across the batch
        # ---- optimise for K epochs on minibatches ----
        for k = 1 .. K:
            for each minibatch B of size b:
                ratio <- exp(logpi(theta, a_B|s_B) - logp_old_B)
                L_clip <- mean( min(ratio*A_B, clip(ratio,1-eps,1+eps)*A_B) )
                L_v <- mean( (V(theta,s_B) - R_B)^2 )
                L <- L_clip - c_v*L_v + c_e*entropy(pi(theta,.|s_B))
                ascent step on L with Adam + gradient clipping
        theta_old <- theta
    until convergence

16. Implementation from scratch

import numpy as np

# Toy bandit with 3 actions: demonstrate the clipped surrogate exactly.
logits_old = np.zeros(3)
logits = np.array([0.2, -0.1, 0.4])
actions = np.array([0, 1, 2, 0])
adv = np.array([2.0, -2.0, 0.5, 1.0])
eps = 0.2

def log_softmax(z):
    z = z - z.max()
    return z - np.log(np.exp(z).sum())

def logp(z, a):
    return log_softmax(z)[a]

ratios = np.exp(np.array([logp(logits, a) - logp(logits_old, a) for a in actions]))
clipped = np.clip(ratios, 1-eps, 1+eps)
surr = np.minimum(ratios*adv, clipped*adv)
print("ratios", np.round(ratios, 4))
print("surrogate terms", np.round(surr, 4), "mean", round(surr.mean(), 4))

# Numerical gradient check for d(mean surrogate)/d logits.
def objective(z):
    rr = np.exp(np.array([logp(z, a) - logp(logits_old, a) for a in actions]))
    return np.minimum(rr*adv, np.clip(rr, 1-eps, 1+eps)*adv).mean()

grad_num = np.zeros(3)
h = 1e-6
for i in range(3):
    zp = logits.copy(); zp[i] += h
    zm = logits.copy(); zm[i] -= h
    grad_num[i] = (objective(zp) - objective(zm))/(2*h)
print("gradient", np.round(grad_num, 4))
# Verify the clipping algebra: negative advantage is clipped from below, positive from above.
assert np.allclose(surr, np.minimum(ratios*adv, clipped*adv))
assert abs(surr[1] - clipped[1]*adv[1]) < 1e-12
assert ratios[2] > 1 + eps

17. Professional library implementation

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical
import gymnasium as gym

class ActorCritic(nn.Module):
    def __init__(self, obs_dim=4, n_act=2, hidden=64):
        super().__init__()
        self.actor = nn.Sequential(nn.Linear(obs_dim, hidden), nn.Tanh(),
                                   nn.Linear(hidden, hidden), nn.Tanh(),
                                   nn.Linear(hidden, n_act))
        self.critic = nn.Sequential(nn.Linear(obs_dim, hidden), nn.Tanh(),
                                    nn.Linear(hidden, hidden), nn.Tanh(),
                                    nn.Linear(hidden, 1))
    def logits(self, s): return self.actor(s)               # (b, n_act)
    def value(self, s): return self.critic(s).squeeze(-1)   # (b,)

env = gym.make("CartPole-v1")
model = ActorCritic()
opt = torch.optim.Adam(model.parameters(), lr=3e-4)
T, gamma, lam, eps, K, b = 2048, 0.99, 0.95, 0.2, 10, 256

obs, _ = env.reset()
ob = torch.zeros(T, 4); ac = torch.zeros(T, dtype=torch.long)
lp = torch.zeros(T); rew = torch.zeros(T); val = torch.zeros(T); done = torch.zeros(T)
with torch.no_grad():
    for t in range(T):
        ot = torch.as_tensor(obs, dtype=torch.float32)
        ob[t] = ot
        dist = Categorical(logits=model.logits(ot))
        a = dist.sample()
        ac[t], lp[t], val[t] = a, dist.log_prob(a), model.value(ot)
        obs, r, term, trunc, _ = env.step(int(a))
        rew[t], done[t] = r, float(term or trunc)
        obs = env.reset()[0] if (term or trunc) else obs

with torch.no_grad():
    last = 0.0 if bool(done[-1]) else model.value(torch.as_tensor(obs, dtype=torch.float32))
    adv = torch.zeros(T); gae = 0.0
    for t in reversed(range(T)):
        mask = 1.0 - done[t]
        delta = rew[t] + gamma*mask*last - val[t]
        gae = delta + gamma*lam*mask*gae
        adv[t] = gae
        last = val[t]
    ret = adv + val
    adv = (adv - adv.mean())/(adv.std(unbiased=False) + 1e-8)

for _ in range(K):
    order = torch.randperm(T)
    for start in range(0, T, b):
        mb = order[start:start+b]
        dist = Categorical(logits=model.logits(ob[mb]))
        logp = dist.log_prob(ac[mb])
        ratio = torch.exp(logp - lp[mb])                       # (b,)
        surr = torch.min(ratio*adv[mb],
                         torch.clamp(ratio, 1-eps, 1+eps)*adv[mb])
        policy_loss = -surr.mean()
        value_loss = F.mse_loss(model.value(ob[mb]), ret[mb])
        loss = policy_loss + 0.5*value_loss - 0.01*dist.entropy().mean()
        opt.zero_grad(set_to_none=True)
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), 0.5)
        opt.step()
env.close()

For continuous control replace Categorical with a Gaussian policy: output mean and a learned log_std, use Normal(loc, scale).rsample() and include logp of the squashed action when using bounded action spaces.

18. Code walkthrough

Rollout buffers. ob has shape (T,4), ac and lp shape (T,); the policy and value networks process a single observation during collection (shape (4,)) and a minibatch during optimization (shape (b,4)) — the linear layers accept both. Storing logp (not the probability) avoids underflow; the ratio is recovered as exp(logp_new - logp_old).

GAE loop. The reverse loop maintains gae = delta_t + γλ(1-d_t) gae_next. The mask zeroes the bootstrap at terminal states; last is the value of the state after the final collected step (0 if terminal). The return target ret = adv + val is what the critic regresses to, which keeps the advantage signal consistent with the value baseline.

Optimization. torch.min implements the clipped lower bound; note that when the clipped branch wins, autograd routes zero gradient through the ratio — this is the stabilization mechanism, not an accident. Advantage normalization reduces variance and makes eps behave consistently across tasks. Gradient clipping to norm 0.5 is a safety net; multiple epochs on a stale rollout is the main source of instability if eps or K are too large.

Continuous actions. With log_std as a parameter, dist.log_prob(a) uses the change-of-variables formula if actions are squashed by tanh; forgetting the Jacobian correction silently biases the ratio and the policy gradient.

19. Tensor and memory analysis

Rollout buffers for T=2048T=2048, N=8N=8 parallel environments (the single-env code stores N=1N=1; production vectorized code uses shape (T,N,… )(T,N,\dots)):

  • observations: 2048×8×4=65,5362048\times8\times4=65{,}536 floats = 256 KB;
  • actions (int64), log-probs, rewards, values, dones, advantages, returns: 7 arrays of 16,38416{,}384 floats ≈ 458 KB (actions 128 KB as int64);
  • total rollout memory under 1 MB for CartPole.

Network parameters: actor 4→64→64→24\to64\to64\to2 has (5)(64)+(65)(64)+(65)(2)=320+4160+130=4610(5)(64)+(65)(64)+(65)(2)=320+4160+130=4610; critic has 4609 (single output); total 9,219 floats ≈ 37 KB. Adam moments add ~74 KB.

For image-based agents (e.g. Atari with a CNN) the rollout observations dominate: (T,N,4,84,84)(T,N,4,84,84) uint8 = 2048×8×4×84×84≈5522048\times8\times4\times84\times84\approx552 MB, so implementations store frame indices or use vectorized environments with compressed frames. Minibatch activations scale as b×b\times hidden size: 256×64=16K256\times64=16K floats per layer ≈ 64 KB, negligible for small networks but significant for large transformers in RLHF (where one rollout can hold billions of log-probabilities).

20. Time complexity

Per rollout: T×NT\times N environment steps plus 2TN2TN network forward passes (policy and value). Advantage computation is O(TN)O(TN) (linear reverse scan).

Optimization: KK epochs × ⌈TN/b⌉\lceil TN/b\rceil minibatches; with T=2048T=2048, N=8N=8, b=256b=256, K=10K=10 that is 640640 gradient steps, each with one forward/backward pass for the actor and critic plus a no-grad forward for the old log-probs (precomputed). Cost per step is O(b⋅cost(network))O(b\cdot\mathrm{cost}(\text{network})). Total per rollout ≈O(TN+K⋅TN/b⋅cost)\approx O(TN+K\cdot TN/b\cdot\mathrm{cost}).

Sample efficiency: each transition is reused K=10K=10 times, giving roughly 10×10\times more gradient updates per environment step than a single-step on-policy algorithm, but the data are still discarded after one rollout — PPO remains far less sample-efficient than off-policy methods (DQN, SAC) which reuse entire replay buffers.

Wall-clock: TRPO additionally needs conjugate-gradient iterations (O(d2)O(d^2) memory for Fisher–vector products avoided by implicit products but still several passes); PPO's first-order updates are typically 2–4× faster per gradient step.

21. Space complexity

Memory is dominated by rollout storage O(TN(dim⁡s+dim⁡a+aux))O(TN(\dim s+\dim a+\text{aux})) and network parameters O(d)O(d). For discrete control with small observations this is well under 1 MB; for pixel or language-model policies it can be gigabytes (storing old log-probs and values for every token is required to compute ratios exactly).

Unlike TRPO, PPO needs no Fisher matrix (O(d2)O(d^2)) and no conjugate-gradient workspace, so it scales to very large dd — a key reason it is used for RLHF on multi-billion-parameter language models, where only a forward pass to obtain token log-probs is affordable.

Gradient backpropagation needs O(b×activations)O(b\times\mathrm{activations}) temporary memory; with activation checkpointing this can be reduced at the cost of extra forward passes.

22. Experimental demonstration

  1. Plot the clipped surrogate as a function of rr for A=±2A=\pm2 and verify the plateau at r=1+εr=1+\varepsilon / r=1−εr=1-\varepsilon; confirm numerically that the gradient is exactly zero on the plateau (use the scratch finite-difference check).
  2. Run PPO on CartPole-v1 with K∈{1,4,10,20}K\in\{1,4,10,20\} and ε∈{0.05,0.2,0.5}\varepsilon\in\{0.05,0.2,0.5\}: expect stable improvement at ε=0.2\varepsilon=0.2, slow learning at 0.05, and instability/collapse at 0.5 with large KK.
  3. Compare with a vanilla policy-gradient implementation (same network, one gradient step per rollout): expect sharp drops in return when a large step wipes out good actions; log max⁡t∣log⁡rt∣\max_t|\log r_t| to correlate collapse with ratio excursions.
  4. GAE sweep: λ∈{0,0.95,1}\lambda\in\{0,0.95,1\} on a delayed-reward grid world; λ=0\lambda=0 exhibits value bias (underestimates long paths), λ=1\lambda=1 shows high-variance returns, λ=0.95\lambda=0.95 interpolates.
  5. For continuous control (MuJoCo HalfCheetah), log the fraction of minibatches where the clip is active; with a well-tuned PPO it is typically a few percent early in training and rises if the step size is too large.

23. Benchmark results

Schulman et al. (2017) reported PPO matching or exceeding TRPO, A2C, and GA-EPPO on Atari, MuJoCo, and the Hopper/Walker2d tasks with a simpler implementation. Representative MuJoCo-v2 results after ~1–10M steps (implementation- and seed-dependent): HalfCheetah returns on the order of 1500–2500, Hopper 2000–3500, Walker2d 2000–3000; on CartPole-v1 PPO reliably solves the 195-step criterion within ~105^5 steps.

On Atari, PPO typically need tens of millions of frames per game to approach DQN-level scores; it is not the most sample-efficient choice there. In RLHF, PPO is used because the on-policy ratio computation is feasible for autoregressive token distributions and the clip prevents the policy from drifting far from the reference model (often an additional KL penalty to the SFT model is included).

Treat these as ballpark figures: results vary with observation normalization, reward scaling, network architecture, parallel environments, and evaluation protocol. Always report mean ± std over at least 3 seeds and specify the exact gym version.

24. Limitations

  • On-policy: freshly collected data are discarded after a few epochs; sample efficiency is much worse than off-policy methods.
  • The clipped objective is a heuristic, not an explicit KL constraint; there is no guarantee that the true KL stays below a chosen δ\delta.
  • Sensitive to ε\varepsilon, number of epochs KK, learning rate, advantage normalization, value coefficient, and entropy coefficient; defaults do not transfer perfectly across tasks.
  • A value network must be trained alongside the policy; critic error biases A^t\hat A_t (bias controlled by λ\lambda).
  • Entropy bonus can cause entropy collapse (policy becomes deterministic too early) or prevent convergence if too large.
  • Reward scaling strongly affects the clip fraction and value loss; unnormalized rewards can destabilize training.
  • For very large policies (LLMs), storing old log-probs and computing ratios for every token is memory-intensive; KL estimates can be noisy.

25. Failure scenarios

  1. Policy collapse: a large gradient step makes π\pi nearly deterministic on an action that later proves wrong; recover by reducing lr, increasing epochs with smaller steps, or raising clipping/weakening drift. Once a probability underflows to zero, the ratio cannot recover on that data.
  2. Entropy collapse: entropy term too small or training too long; the policy stops exploring and gets stuck in a local optimum. Monitor H[π]H[\pi] and anneal the coefficient.
  3. Value-function dominance: cvc_v too large or a poorly conditioned critic; the actor gradients are drowned. Track policy vs. value losses separately.
  4. Clip always active: if most ratios are clipped, learning stalls (all gradients zero); reduce lr or KK, or increase ε\varepsilon cautiously.
  5. Wrong GAE terminal handling: bootstrapping across a true terminal inflates advantages; ensure done masks and last=0 at episode boundaries (time-limit truncations are a separate case and may warrant bootstrapping).
  6. Continuous-action log-prob bugs: missing tanh Jacobian correction biases the ratio, breaking the on-policy consistency of PPO.
  7. Advantage scale drift: large rewards make A^\hat A huge, overwhelming the clip; normalize advantages and scale rewards.

26. Common misconceptions

  • "PPO enforces a KL constraint." It uses a clipped surrogate inspired by TRPO; the KL is only indirectly limited and must be monitored empirically.
  • "PPO is off-policy because it reuses old rollout data for 10 epochs." The data are from πθold\pi_{\theta_{\text{old}}}, and ratios correct for the small drift; after the update epoch the data are discarded, so it remains on-policy.
  • "Clipping the ratio always improves performance." Clipping only removes the incentive for beneficial-direction extremes; it can also block a genuinely good large update.
  • "GAE with λ=1\lambda=1 is the true advantage." It is the Monte Carlo return minus V(st)V(s_t), unbiased only if VV is exact; high variance remains.
  • "Entropy bonus is optional and harmless." Too large a coefficient keeps the policy random; too small causes premature determinism.
  • "Advantage normalization changes the policy gradient." It scales all advantages in a batch by a constant (plus centering), changing the effective step size, not the optimum.
  • "PPO always beats DQN in sample efficiency." It is on-policy; off-policy value methods typically need far fewer environment steps.

27. Alternative approaches

  • TRPO: principled KL trust region via natural gradients; stronger monotonicity theory but complex and slower.
  • Adaptive KL PPO: replace clipping with a KL penalty whose coefficient is adjusted to hit a target KL.
  • A2C/A3C: simpler synchronous/asynchronous actor–critic without clipping; less stable.
  • Vanilla policy gradient + baseline: simplest, highest variance.
  • Off-policy actor–critic (DDPG, TD3, SAC): much more sample-efficient, especially for continuous control; SAC adds entropy maximization.
  • REINFORCE with leave-one-out baselines / GRPO: recent LLM-oriented alternatives that avoid a separate value network.
  • Evolution strategies / cross-entropy method: derivative-free, robust but less sample-efficient.

29. Research applications

  • RLHF / alignment: PPO fine-tunes language models against a reward model with a KL penalty to the reference policy; clipped token ratios keep the model close to the supervised starting point.
  • Robotics and sim-to-real: robust sim training with domain randomization; PPO's stability under parallel simulation makes it a default.
  • Game AI: large-scale multi-agent self-play (e.g. Dota/OpenAI Five used PPO variants).
  • Continuous control: MuJoCo-style locomotion and manipulation benchmarks.
  • Algorithm theory: analyses of clipping bias, epoch effects, and trust-region approximations; interplay of value error and policy drift.
  • Efficient variants: token-level clipping alternatives, decoupled value networks, and critic-free methods for LLM training.

30. Important research papers

  • Williams R. J. (1992), Simple statistical gradient-following algorithms for connectionist reinforcement learning, Machine Learning 8:229–256 — REINFORCE.
  • Sutton R. S., McAllester D. A., Singh S., Mansour Y. (2000), Policy Gradient Methods for Reinforcement Learning with Function Approximation, NIPS — policy gradient theorem.
  • Kakade S. (2001), A Natural Policy Gradient, NIPS — Fisher preconditioning.
  • Schulman J., Levine S., Abbeel P., Jordan M., Moritz P. (2015), Trust Region Policy Optimization, ICML — KL trust region.
  • Schulman J., Moritz P., Levine S., Jordan M., Abbeel P. (2016), High-Dimensional Continuous Control Using Generalized Advantage Estimation, ICLR.
  • Schulman J., Wolski F., Dhariwal P., Radford A., Klimov O. (2017), Proximal Policy Optimization Algorithms, arXiv:1707.06347.

31. Further reading

  • Schulman et al. (2017) — the original paper is short and readable; study the pseudocode and the adaptive-KL variant.
  • Schulman et al. (2015) TRPO for the monotonic improvement bound and conjugate-gradient details.
  • Schulman et al. (2016) GAE for the full bias–variance derivation.
  • OpenAI Spinning Up algorithm docs: "PPO" and "TRPO" — spinningup.openai.com.
  • Sutton & Barto (2018), chapter 13 (policy gradient methods).
  • Hugging Face RLHF blog posts and the TRL library implementation for token-level PPO.

32. Practical exercises

  1. Implement the clipped surrogate in NumPy and verify the zero-gradient regions numerically with finite differences.
  2. Derive GAE's equivalence to the λ\lambda-return form on paper; implement both and assert equality on a random 10-step trajectory.
  3. Implement PPO for CartPole from memory (actor/critic, GAE, K epochs); reach the 195-step criterion within 10510^5 steps.
  4. Reproduce the ε\varepsilon/KK sweep and plot the fraction of clipped minibatches against training steps.
  5. Modify the code to use an adaptive KL penalty instead of clipping: adjust the penalty coefficient to target KL≈0.01\mathrm{KL}\approx0.01 and compare curves.
  6. Implement continuous-action PPO with a Gaussian policy and a tanh squash; derive and code the log-probability Jacobian correction.

33. Debugging challenges

  • Mean episode return collapses after a few updates: check advantage normalization, learning rate, and whether ratios exploded; log max |log ratio|.
  • PPO loss is positive or increases while returns improve: expected — you are ascending a surrogate implemented as a negative loss; check sign conventions.
  • Value loss dominates total loss: reduce cvc_v, normalize rewards, or use a separate optimizer/lr for the critic.
  • All ratios equal 1: you forgot to update theta_old at the end of the rollout (or you recomputed old log-probs with the new network).
  • GAE advantages are huge: missing terminal mask or reward scaling; verify last=0 at true terminals and normalize advantages.
  • Continuous actions never improve: check tanh log-prob correction and whether log_std is being optimized.
  • Training is extremely slow: vectorize environments; per-step Python loops with single observations are a major bottleneck.

34. Advanced exercises

  1. Prove the TRPO monotonic improvement bound and derive the natural-gradient step from the KL-constrained linearized objective.
  2. Analyze the bias introduced by clipping: construct a bandit where PPO converges to a suboptimal action because the beneficial update is clipped, and explain the conditions.
  3. Derive GAE for infinite horizons and show its variance as a function of λ\lambda; verify empirically on a synthetic Markov chain.
  4. Implement PPO with a shared actor–critic backbone and separate heads; study how sharing affects value error and policy drift.
  5. Implement token-level PPO for a tiny autoregressive model on a synthetic reward and compare clip behaviour at sequence vs. token level.
  6. Derive the log-probability correction for a tanh-squashed Gaussian and test it by sampling and denormalizing.

35. Interview questions

  • Derive the importance-ratio surrogate and explain why the policy gradient theorem justifies it.
  • Explain precisely when the clipped objective has zero gradient, and why that stabilizes training.
  • Is PPO on-policy or off-policy? Justify using the rollout/epoch structure.
  • Derive GAE from TD errors and explain the bias–variance role of λ\lambda.
  • Compare TRPO and PPO: guarantee, implementation complexity, and computational cost.
  • Why normalize advantages? What does it change and what does it not change?
  • How would you adapt PPO to a continuous action space with bounded actions?
  • Why is PPO popular for RLHF, and what extra term is typically added?

36. Research questions

  • Can we give a non-heuristic performance bound for the clipped surrogate that explains the observed stability across epochs?
  • How does the number of optimization epochs interact with clipping and the effective KL to determinebias and variance?
  • What is the optimal advantage-estimation scheme when the value network is itself imperfect and non-stationary?
  • Can critic-free policy optimization (e.g. GRPO-style group baselines) match PPO's stability at lower memory cost for LLMs?
  • How should the clip range be adapted per token/state based on uncertainty in the reward model?

37. Mastery assessment

To pass: (1) derive the clipped surrogate from the likelihood-ratio policy gradient without notes; (2) explain the zero-gradient case analysis and draw the surrogate curves; (3) derive GAE and compute it numerically on a small trajectory; (4) implement PPO for CartPole from scratch and hit the solved criterion; (5) explain TRPO vs. PPO and the on-policy nature of multi-epoch updates; (6) diagnose collapse, entropy collapse, and clip saturation; (7) answer the interview questions. Complete the linked assessment; reading is not mastery.

38. Implementation submission

Push a repository containing ppo.py (actor–critic, GAE, clipped objective, minibatch epochs), surrogate.py (NumPy clip demonstration with gradient check), experiments.ipynb (CartPole learning curves for ε∈{0.05,0.2,0.5}\varepsilon\in\{0.05,0.2,0.5\} and K∈{1,4,10}K\in\{1,4,10\} over 3 seeds, plus a GAE-lambda sweep), a README.md with derivations and observed clip fractions, and tests asserting the GAE recursion and zero-gradient plateau. Submit the repository URL and exact reproduction command.

39. Completion criteria

All of: every section read; surrogate and GAE derived on paper; implementation passing tests and reaching the CartPole criterion; at least three recorded experiments with plots and seed variance; assessment score ≥80%\ge80\%; one failure case (collapse or saturated clipping) reproduced and explained; one research question answered in a one-page note citing a paper. Only then mark the concept mastered.`

Research papers linked to this concept

Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning 1992
sutton2000 · citation recorded, library entry pending
schulman2015 · citation recorded, library entry pending
schulman2016 · citation recorded, library entry pending
schulman2017 · citation recorded, library entry pending