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.
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:
The clipped surrogate objective is
typically with . The advantage estimates come from generalized advantage estimation (GAE), and the full objective adds a value-function loss and an entropy bonus:
PPO collects a rollout, runs 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
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 leaves 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: . Sutton et al. (2000) proved the policy gradient theorem , 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 . 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 using samples collected from , while:
- avoiding destructive updates (a large step can permanently remove useful actions once );
- making efficient use of each rollout (multiple gradient epochs without leaving the region where importance sampling is valid);
- keeping advantage estimates low-variance but not overly biased;
- 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 ,
can be rewritten with the per-step ratio . The surrogate has gradient equal to the policy gradient at .
Fact 2 — unconstrained maximization breaks the surrogate. If , maximizing drives (probability 1 for that action); if , it drives . Both are catastrophic when is a noisy estimate and the batch is finite.
Fact 3 — clipping removes the incentive for extremes. With , once and , the clipped term is constant , so the min selects it and the gradient is zero. Similarly for and . 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 are low-variance but biased by the value estimate; full Monte Carlo advantages are unbiased but high-variance. Exponentially weighting TD errors with interpolates between them.
6. Prerequisite concepts
You need: (a) the policy gradient theorem and the likelihood-ratio estimator ; (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. . With a categorical policy, .
Clipped surrogate. .
GAE. With (and at a terminal),
computed by the reverse recursion . gives the one-step TD advantage; gives the Monte Carlo advantage minus .
Objective. with , typical , (often with entropy annealing).
Trust-region connection. TRPO solves s.t. , with and Fisher ; the natural step is . PPO replaces this by clipping.
Assumptions. On-policy sampling (data from ), bounded advantages (often normalized), and a policy with full support so ratios are well-defined.
8. Notation dictionary
| Symbol | Meaning | Type / shape | |---|---|---| | | parameterized policy | distribution over actions | | | current / behaviour policy parameters | vectors in | | | importance ratio at time | positive scalar | | | clip range, typically 0.2 | scalar | | | GAE advantage estimate | scalar per timestep | | | TD error | scalar | | | discount and GAE trace decay | scalars in | | | value-network prediction | scalar | | | advantage target return | scalar | | | value-loss and entropy coefficients | scalars | | | policy entropy | scalar | | | rollout horizon per environment | integer, e.g. 2048 | | | parallel environments | integer, e.g. 8 | | | minibatch size | integer, e.g. 256 | | | epochs per rollout | integer, e.g. 10 | | | Fisher information matrix | |
9. Step-by-step derivation
Step 1 — surrogate policy gradient. The policy gradient theorem gives . Using data from and the likelihood ratio gives the equivalent surrogate whose gradient at matches the true policy gradient.
Step 2 — bound the update. TRPO's monotonic improvement result uses where is the total-variation distance between policies. This motivates constraining KL rather than trusting the surrogate indefinitely.
Step 3 — clip. Define as above. Analyse the min term:
- , : — zero gradient, preventing further increase.
- , : — 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 and creates a "proximal zone" of width around the old policy.
Step 4 — GAE derivation. Unroll the Bellman-operator advantage recursion with a -weighted mixture of 1-step, 2-step, … returns:
The telescoping of the value terms is what yields the compact TD-error sum.
Step 5 — combine losses. Regress the value network onto and add entropy to discourage premature determinism; optimize all terms jointly with Adam for epochs on minibatches of the same rollout.
10. Proofs and proof intuition
Lemma 1 (ratio identity). For any function of trajectories, . Proof. Write the expectation as a sum/integral over trajectories and multiply by .
Lemma 2 (clipped objective is a lower bound). For all and , . Proof. The min of two numbers is at most the first. For the clipped term is even smaller than when leaves the interval; for the inequality is immediate from the min. This gives the pessimistic bound used in the analysis.
Lemma 3 (zero gradient outside the proximal zone). If and , then ; similarly if and . Proof. Direct case analysis of the min.
Lemma 4 (GAE telescopes). . Proof. Expand and interchange the sums; the value terms telescope with weights and .
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 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 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 in likelihood-ratio space.
Plot as a function of for fixed : for it rises linearly to at and then becomes a plateau; for it falls to a floor at 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 controls a different geometry: in advantage space, looks only one step ahead (high bias toward the critic), looks to the episode end (high variance). The effective horizon of the advantage estimate is steps — about 20 steps for .
12. Visual explanation
Show the clipped surrogate plot: x-axis from 0.5 to 1.5, y-axis and with two curves for ; shade the plateau regions and mark 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 over a rollout (time × environment), and a histogram of after the update — with clipping working, most values stay in in log-probability terms.
The Interactive PPO Clip Lab in Practical Labs lets you drag and watch the surrogate plateau move and the resulting policy histogram widen or narrow.
13. Numerical worked example
Clipping arithmetic with :
- , : , clipped , min (gradient zero — the beneficial move is capped).
- , : , clipped , min (capped; further probability reduction stopped).
- , : both terms equal , inside the zone, so the normal gradient flows.
GAE computation for a 3-step episode with rewards , values , , , :
Reverse recursion: ; ; . With we would get (one-step TD); with , .
Rollout sizes. steps × environments transitions per rollout; with minibatch and epochs that is 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 , parallel environments (the single-env code stores ; production vectorized code uses shape ):
- observations: floats = 256 KB;
- actions (int64), log-probs, rewards, values, dones, advantages, returns: 7 arrays of floats ≈ 458 KB (actions 128 KB as int64);
- total rollout memory under 1 MB for CartPole.
Network parameters: actor has ; 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: uint8 = MB, so implementations store frame indices or use vectorized environments with compressed frames. Minibatch activations scale as hidden size: 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: environment steps plus network forward passes (policy and value). Advantage computation is (linear reverse scan).
Optimization: epochs × minibatches; with , , , that is 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 . Total per rollout .
Sample efficiency: each transition is reused times, giving roughly 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 ( 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 and network parameters . 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 () and no conjugate-gradient workspace, so it scales to very large — 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 temporary memory; with activation checkpointing this can be reduced at the cost of extra forward passes.
22. Experimental demonstration
- Plot the clipped surrogate as a function of for and verify the plateau at / ; confirm numerically that the gradient is exactly zero on the plateau (use the scratch finite-difference check).
- Run PPO on CartPole-v1 with and : expect stable improvement at , slow learning at 0.05, and instability/collapse at 0.5 with large .
- 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 to correlate collapse with ratio excursions.
- GAE sweep: on a delayed-reward grid world; exhibits value bias (underestimates long paths), shows high-variance returns, interpolates.
- 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 ~10 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 .
- Sensitive to , number of epochs , 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 (bias controlled by ).
- 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
- Policy collapse: a large gradient step makes 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.
- Entropy collapse: entropy term too small or training too long; the policy stops exploring and gets stuck in a local optimum. Monitor and anneal the coefficient.
- Value-function dominance: too large or a poorly conditioned critic; the actor gradients are drowned. Track policy vs. value losses separately.
- Clip always active: if most ratios are clipped, learning stalls (all gradients zero); reduce lr or , or increase cautiously.
- Wrong GAE terminal handling: bootstrapping across a true terminal inflates advantages; ensure
donemasks andlast=0at episode boundaries (time-limit truncations are a separate case and may warrant bootstrapping). - Continuous-action log-prob bugs: missing tanh Jacobian correction biases the ratio, breaking the on-policy consistency of PPO.
- Advantage scale drift: large rewards make 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 , 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 is the true advantage." It is the Monte Carlo return minus , unbiased only if 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
- Implement the clipped surrogate in NumPy and verify the zero-gradient regions numerically with finite differences.
- Derive GAE's equivalence to the -return form on paper; implement both and assert equality on a random 10-step trajectory.
- Implement PPO for CartPole from memory (actor/critic, GAE, K epochs); reach the 195-step criterion within steps.
- Reproduce the / sweep and plot the fraction of clipped minibatches against training steps.
- Modify the code to use an adaptive KL penalty instead of clipping: adjust the penalty coefficient to target and compare curves.
- Implement continuous-action PPO with a Gaussian policy and a
tanhsquash; 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 , normalize rewards, or use a separate optimizer/lr for the critic.
- All ratios equal 1: you forgot to update
theta_oldat 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=0at true terminals and normalize advantages. - Continuous actions never improve: check tanh log-prob correction and whether
log_stdis being optimized. - Training is extremely slow: vectorize environments; per-step Python loops with single observations are a major bottleneck.
34. Advanced exercises
- Prove the TRPO monotonic improvement bound and derive the natural-gradient step from the KL-constrained linearized objective.
- 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.
- Derive GAE for infinite horizons and show its variance as a function of ; verify empirically on a synthetic Markov chain.
- Implement PPO with a shared actor–critic backbone and separate heads; study how sharing affects value error and policy drift.
- Implement token-level PPO for a tiny autoregressive model on a synthetic reward and compare clip behaviour at sequence vs. token level.
- 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 .
- 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 and 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 ; 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.`