04 · PPO

What you're learning

How to take the policy-gradient machinery from lessons 01–03 and make it stable enough to actually train large policies — including the LLMs behind RLHF. By the end you should be able to derive PPO-Clip from the trust-region idea, explain exactly why the min-of-clipped surrogate does what it does, and map every term onto the RLHF-PPO loop (reward model, KL-to-reference, value head, GAE).

This is the capstone of the foundations tier. Everything downstream — 05-rl-on-token-sequences, GRPO, DPO — is either an application of PPO or a deliberate simplification of it.


1. Learning map

graph TD
    A["Policy gradient<br/>(lesson 02)<br/>∇J = E[∇log π · Â]"] --> B["Instability:<br/>one big step wrecks π"]
    A --> C["On-policy staleness:<br/>data dies after 1 update"]
    B --> D["Trust region idea:<br/>bound the policy change"]
    C --> E["Importance sampling ratio<br/>r_t(θ) = π_θ / π_old"]
    D --> F["TRPO<br/>max surrogate s.t. KL ≤ δ<br/>(natural gradient, CG)"]
    E --> F
    F --> G["Too heavy:<br/>2nd-order, Fisher-vector products"]
    G --> H["PPO-Clip<br/>L^CLIP = E[min(rÂ, clip(r)Â)]"]
    E --> H
    F --> I["PPO-Penalty<br/>adaptive-β KL penalty"]
    H --> J["Full PPO loss:<br/>clip + value + entropy"]
    J --> K["Training loop:<br/>rollout → GAE → K epochs SGD"]
    K --> L["RLHF-PPO<br/>policy=LLM, reward=RM − β·KL_ref"]
    L --> M["Foreshadow: DPO (07)<br/>GRPO (09)"]

    style H fill:#4a4,color:#fff
    style L fill:#44a,color:#fff
    style D fill:#a64,color:#fff

Prerequisites (assumed): MDPs and returns (01-mdps-and-the-rl-objective), the policy-gradient theorem and REINFORCE (02-policy-gradients), actor-critic and generalized advantage estimation (03-actor-critic-and-gae).


2. Why this matters: the two failure modes of vanilla PG

Recall the policy-gradient estimator from lesson 02, written with an advantage baseline from lesson 03:

You estimate this from a batch of rollouts, take a gradient ascent step, throw the data away, and roll out again. This works on toy problems, but it is brutally fragile at scale for two coupled reasons.

Failure mode 1 — a too-large step destroys the policy.
The gradient is only a local linear approximation of . It tells you the ascent direction, but nothing about how far you can trust it. The mapping from parameter space to policy space is wildly non-isometric: a small can produce a huge change in the distribution (and vice versa). If a single SGD step moves too far, the new policy visits a completely different part of the state space, the old advantage estimates become meaningless, and performance can collapse irrecoverably — there is no supervised “ground truth” to snap back to. This is the signature pathology of policy gradient: monotonic-improvement is not guaranteed, and a bad step is often unrecoverable.

Failure mode 2 — on-policy data is single-use.
The expectation above is taken under — the current policy. The instant you update , your batch was drawn from , so it is off-policy and the estimator is biased. Vanilla PG therefore does exactly one gradient step per batch of environment interaction. When a rollout is expensive (a robot episode, or — foreshadowing — an LLM generating thousands of tokens against a reward model), throwing the batch away after one step is ruinously sample-inefficient.

The unifying want

Both failures point to the same fix: limit how far the policy is allowed to move per update. If the step is small in policy space (not parameter space), (a) the linear approximation stays valid so improvement is roughly monotone, and (b) so we can reuse the batch for several steps before it goes stale. This is the trust region idea, and PPO is the cheap, robust way to enforce it.


3. The importance-sampling ratio: reusing off-policy data

To take multiple gradient steps on one batch, we must evaluate the current policy on data collected under . Importance sampling gives the correction. For any function ,

Define the probability ratio

The surrogate objective — the thing TRPO and PPO both maximize — replaces the log-prob gradient with this ratio:

(“CPI” = conservative policy iteration.1) Note — at this is exactly the vanilla policy gradient. So the surrogate is a legitimate stand-in: maximizing it locally is maximizing , but now it is written in a form we can evaluate for and thus optimize for several epochs.

The surrogate is only trustworthy near

is an approximation to the true improvement whose error grows with how far drifts from . Maximizing it without a constraint is precisely failure mode 1 in disguise: the optimizer will happily drive to enormous values on actions with positive advantage, producing an excessively large policy update. The whole game of TRPO/PPO is how to keep this honest.

The theory behind “how far is too far” is the surrogate-improvement bound: the true return satisfies

for a constant depending on the advantage magnitude and .2 The penalty term says: trust the surrogate only to the extent the policies stay KL-close. Everything else is a way to operationalize this bound cheaply.


4. TRPO: the correct-but-heavy trust region

TRPO takes the bound literally but turns the penalty into a hard constraint (a fixed penalty coefficient from the theory is far too conservative — steps would be tiny).2 It solves, each iteration:

This is a constrained optimization in a trust region of radius measured in KL (policy space), not (parameter space) — which is exactly the fix from §2.

How it’s solved (the heavy part). Linearize the objective and quadratically approximate the constraint around :

where and is the Fisher information matrix (the Hessian of the KL, a metric on policy space). The closed-form solution is the natural gradient

You never form explicitly (it is ). Instead you compute with conjugate gradient, using Fisher-vector products obtained via a second backprop through the KL. A backtracking line search then shrinks the step until the KL constraint holds and the surrogate actually improved (guarding against the quadratic approximation being wrong).

TRPO's one-sentence legacy

It proved you can get near-monotonic improvement by constraining the step in KL — but at the cost of conjugate gradient + Fisher-vector products + line search per update, which is second-order, memory-hungry, hard to implement, and awkward to combine with parameter sharing (e.g. a shared actor-critic trunk) or with architectures like dropout/RNNs. PPO’s thesis: get 90% of TRPO’s stability with only first-order SGD.


5. PPO-Clip: the main event

PPO throws away the explicit constraint and the second-order machinery. Instead it bakes the trust region directly into the objective so that ordinary first-order SGD cannot move the ratio too far. The clipped surrogate is3:

with pinning the ratio to (typically ). Two things are happening — the clip and the min — and both are essential. Let’s derive why.

5.1 Case analysis: what clip alone does

Consider one term and the two signs of the advantage.

Positive advantage (). The action was better than baseline; we want to increase its probability, i.e. push up. The unclipped term grows without bound as — an unlimited incentive to make this action near-certain. The clipped term flattens once : no further reward for pushing the probability higher. Gradient there is zero.

Negative advantage (). The action was worse than baseline; we want to decrease its probability, pushing down. Now is negative and becomes more negative as — an unlimited incentive to crush the probability to zero. The clip floors at , so the term flattens once .

In both cases: once the ratio has moved a factor in the beneficial direction, the objective stops rewarding further movement. That is the trust region — enforced pointwise, per sample, with a clip and no KL computation.

5.2 Why the min? The subtle part

Clipping alone is not enough, and this is the most misunderstood point in PPO. The min takes the smaller (more pessimistic) of the unclipped and clipped terms, making a lower bound (a pessimistic estimate) on the unclipped surrogate. Its job is to handle the case where the ratio moves in the wrong direction.

Suppose but the current update has pushed (the policy got worse at this good action — maybe because a shared network moved to help other samples). We must retain a gradient to pull it back up. With clip-only, if we clipped here we’d zero the gradient and get stuck. The min resolves it:

  • If : , and since the smaller product is (unclipped). Gradient is active — it pulls back toward 1. Good.
  • If : clipped value , smaller product is (clipped, flat). Gradient zero. Good — don’t reward overshoot.

The asymmetry is the whole design. Writing it out fully:

Sign of Ratio regionTerm chosen by minGradient?Effect
unclipped activepull ratio back up
either (equal)activenormal ascent
clipped, flatzerostop rewarding overshoot
unclipped activepush ratio back down
either (equal)activenormal descent
clipped, flatzerostop rewarding over-suppression

The clean statement

The clip removes the incentive to move the ratio beyond the trust region in the helpful direction. The min ensures that when the ratio has already left the region in the unhelpful direction, the penalty is not itself clipped away — you keep a corrective gradient. Together: bounded reward for good moves, unbounded corrective pressure for bad ones. That asymmetry is precisely a pessimistic lower bound on improvement.

What clipping does not guarantee

A single term’s gradient being zeroed does not bound the total KL across an update. Clip acts per-sample and per-coordinate; a minibatch can still push the aggregate KL past your intended over epochs, especially early in training. PPO-Clip is a heuristic trust region, not a certified one — which is why practical PPO monitors KL and often early-stops (see §8). Don’t over-trust alone.

5.3 PPO-Penalty (adaptive KL) — the other variant

The original PPO paper also proposed a penalty form that stays closer to TRPO’s Lagrangian3:

with adapted between updates to hit a target KL : if the measured , double ; if , halve it. Clip generally matched or beat this and needs no per-run KL target, so PPO-Clip became the default. Keep KLPEN in mind, though — the idea of an adaptive KL coefficient reappears verbatim in RLHF (§7), just against a frozen reference policy rather than .


6. The full PPO objective and training loop

Actor-critic (lesson 03) shares structure between the policy and a value function (often a shared trunk with two heads). PPO’s total per-step objective combines three terms3:

We maximize this (equivalently minimize its negation). Term by term:

Value loss — regress the critic toward the empirical returns (GAE targets from lesson 03, ):

Many implementations use a clipped value loss mirroring the policy clip, to stop the critic from moving too far in one update4:

Entropy bonus; maximizing it keeps the policy stochastic, preventing premature collapse to a deterministic (and possibly wrong) policy early in training. is small (e.g. 0.0–0.01).

Advantage normalization is doing more than you think

Almost every strong PPO implementation normalizes advantages to zero mean / unit variance per minibatch before the clip term. This makes scale-invariant across tasks and reward magnitudes. Omitting it is one of the most common reasons a “correct” PPO reimplementation silently underperforms — a lesson from the “PPO implementation details” literature (Engstrom et al.; Huang et al.).4

The loop

flowchart TD
    A["Initialize policy π_θ,<br/>value V_φ (shared trunk + 2 heads)"] --> B
    B["<b>Collect rollouts</b><br/>run π_θ_old for T steps<br/>store s_t, a_t, r_t,<br/>log π_θ_old(a_t|s_t), V(s_t)"] --> C
    C["<b>Compute advantages</b><br/>GAE(λ): Â_t = Σ (γλ)^l δ_{t+l}<br/>returns R_t = Â_t + V(s_t)<br/>normalize Â_t"] --> D
    D["<b>K epochs of minibatch SGD</b>"] --> E
    subgraph inner ["for K epochs, over shuffled minibatches"]
        E["compute r_t(θ)=π_θ/π_θ_old"] --> F["L = L^CLIP − c1·L^VF + c2·H"]
        F --> G["Adam step on θ, φ"]
        G --> H{"KL(π_old‖π_θ)<br/>> target?"}
        H -- "yes" --> I["early-stop epochs"]
        H -- "no" --> E
    end
    D --> inner
    I --> J["θ_old ← θ"]
    inner --> J
    J --> B

    style B fill:#334,color:#fff
    style C fill:#343,color:#fff
    style D fill:#433,color:#fff

The key structural point vs. vanilla PG: one batch of rollouts is reused for epochs () of minibatch updates. The ratio starts at 1 for the whole batch (since at the first epoch) and drifts as epochs proceed; the clip keeps that drift bounded. After the epochs, and you collect fresh data.


7. LLM connection: PPO is the classic RLHF optimizer

This is the bridge to the rest of the curriculum. RLHF (InstructGPT5, and the early GPT-/Claude-style alignment pipelines) is PPO applied to language generation, where the “environment” is degenerate — it’s just the token sequence itself. Map the RL abstractions onto an LLM:

RL conceptRLHF instantiation
Policy The LLM being fine-tuned (init from the SFT model)
State Prompt + tokens generated so far
Action The next token from the vocabulary
Episode / trajectoryOne full generated response
RewardReward-model score at EOS, minus a per-token KL penalty (below)
Value A value head on the LLM (lesson 03), predicting return-to-go per token
Advantage GAE over the per-token rewards (lesson 03)

The reward: RM score minus KL-to-reference

The reward model (trained separately on human preference comparisons) outputs a scalar for the whole response, available only at the final token. If you optimized that alone, PPO would find degenerate high-reward gibberish — reward hacking / over-optimization of an imperfect . The fix is a per-token KL penalty to a frozen reference policy (the SFT model, held fixed). The per-token reward is:

The bracketed term is a single-sample estimate of at position . So the total objective PPO maximizes is:

Two different KLs — don't conflate them

There are two KL terms in RLHF-PPO, and they do different jobs:

  1. The PPO trust-region KL — between and , enforced implicitly by the clip. Keeps each optimization step stable. Changes every update ( is refreshed).
  2. The RLHF reference KL — between and the frozen , added explicitly into the reward with coefficient . Keeps the model from drifting away from fluent, sensible language over the whole run and anchors it against reward-model exploitation. never moves.

Why the reference KL is load-bearing: the reward model is a learned, imperfect proxy for human preference. Its errors are largest exactly in the regions of output space the SFT model rarely visits — so an unconstrained optimizer marches straight into ‘s blind spots and produces text that scores high but is degenerate. The term is a leash: it makes drifting into those under-trained regions costly, trading a little reward for staying in the distribution where is trustworthy. Tuning is the central reward–fluency knob of the whole pipeline; some pipelines adapt it exactly like PPO-Penalty’s adaptive- scheme from §5.3.

Why RLHF-PPO is operationally painful

A full RLHF-PPO setup keeps four models in play: the policy (trainable), the value/critic head (trainable, often a second full copy the size of the policy), the frozen reference , and the frozen reward model .5 That’s roughly 2× the memory of the policy just for the critic and reference, plus a separate RM. It’s also notoriously sensitive to , the KL controller, advantage normalization, and reward-scaling. This operational weight is exactly what the next methods attack.

Foreshadowing: why GRPO and DPO exist

  • 09-rl-for-reasoning (critic-free) — removes the value head/GAE entirely. GRPO samples a group of responses per prompt and uses their mean/std reward as the baseline (a Monte-Carlo advantage), keeping the PPO-style clipped ratio objective but deleting the second trainable model.6 Motivation: kill the critic’s memory and instability.
  • 07-dpo-and-rl-free-preference-optimization (RL-free) — removes PPO, the reward model, and the sampling loop. DPO shows the RLHF objective (reward + reference-KL) has a closed-form optimum, letting you fit the policy directly on preference pairs with a simple classification-style loss.7 Motivation: skip online RL altogether when you have preference data.

Both are best understood as deliberate deletions from the PPO recipe you now hold in full — which is why PPO is the foundations capstone.


8. Hyperparameters and failure modes

The PPO pitfalls checklist

  • (clip) too large → effectively no trust region; you’re back to unstable vanilla PG and can collapse. Too small → glacial learning. Default ; RLHF often uses smaller.
  • epochs too high → by the last epoch has drifted far from , most samples are clipped (zero gradient) and the surviving importance weights are high-variance and stale. Symptom: KL spikes, entropy craters, reward collapses. Fix: fewer epochs (3–4) or KL early-stopping.
  • KL blowup → the policy KL (to or, in RLHF, to ) runs away in a single update. Because clip is only a heuristic bound, always monitor KL and either early-stop the epoch loop when or raise the penalty .
  • No advantage normalization becomes task/reward-scale-dependent; training is fragile and non-portable (§6).
  • Value clipping / value-loss scale () → an over-eager critic destabilizes the shared trunk and corrupts the advantages the actor depends on; clip the value update and keep . In RLHF, a common choice is to not share the trunk (separate value model) precisely to decouple this.
  • Reward/return scaling → unnormalized rewards make the advantage magnitudes (and thus the effective learning rate through ) unpredictable; use running return normalization.
  • Entropy collapse → without the entropy bonus (or with too small ) the policy goes deterministic too early and stops exploring. In RLHF this shows up as mode-collapse / repetitive outputs.

Typical starting points (continuous control / Atari-scale): , , GAE , , , Adam LR , minibatch 32–256, rollout length 2048/env.3 RLHF differs: much smaller LR (), , small , and the dominant knob is (reference-KL), tuned to a target KL of a few nats over the response.5


9. Quizzes


10. Practice problems


11. Reading order

Work through these in order:

  1. Primary source (start here): Proximal Policy Optimization Algorithms — Schulman et al., 2017 (arXiv:1707.06347) — short and readable; §3 (clipped surrogate) and §5 (the loss with value + entropy) are the core. Note Figure 1’s per-sample plot of the clipped objective vs. — it is §5.2 in a picture.
  2. The trust-region backstory: Trust Region Policy Optimization — Schulman et al., 2015 (arXiv:1502.05477) — read for the surrogate-improvement bound and the natural-gradient/CG machinery PPO is simplifying. You can skim the proofs; internalize the constrained objective.
  3. Best pedagogical treatment + code: OpenAI Spinning Up — PPO — clean derivation of the clip intuition and a minimal reference implementation; do the “you should be able to…” exercises.
  4. The RLHF instantiation: Training language models to follow instructions with human feedback (InstructGPT) — Ouyang et al., 2022 (arXiv:2203.02155) — read §3.5 and Appendix for the exact RM-score-minus-KL reward and the value-head/PPO setup; this is §7 of this lesson in the wild.
  5. Production reference: HuggingFace TRL — PPOTrainer docs — see the concrete four-model setup (policy, ref, reward, value), KL controller, and the config knobs from §8. The best bridge from theory to a real training run.
  6. (Optional but worth it): “The 37 Implementation Details of PPO” (Huang et al.) and “Implementation Matters in Deep RL” (Engstrom et al.) — why advantage normalization, value clipping, and reward scaling matter more than the headline algorithm.

12. What’s next

Two threads, in order:

  1. 05-rl-on-token-sequences — makes the §7 mapping rigorous: how an autoregressive LM is an MDP, per-token vs. sequence-level rewards, credit assignment across a response, and the exact plumbing of value heads and GAE over tokens. This is where PPO becomes RLHF for real.
  2. Circle back to 03-actor-critic-and-gae — reread the GAE section now that you’ve seen the value head and per-token advantages in action; the knob and the bias–variance trade-off will land differently.

Then the two “deletions from PPO”: 09-rl-for-reasoning (drop the critic) and 07-dpo-and-rl-free-preference-optimization (drop the RL loop entirely).


References


Topic hub: rl-for-llms | Reference page: ppo | Filed: 2026-09-02

Footnotes

  1. Kakade & Langford (2002). “Approximately Optimal Approximate Reinforcement Learning.” ICML 2002, pp. 267–274. Origin of Conservative Policy Iteration (CPI) and the surrogate objective that TRPO and PPO build on.

  2. Schulman, Levine, Abbeel, Jordan, Moritz (2015). “Trust Region Policy Optimization.” arXiv:1502.05477. Source for the surrogate-improvement bound, the KL-constrained trust-region objective, and the natural-gradient / conjugate-gradient / Fisher-vector-product solution. 2

  3. Schulman, Wolski, Dhariwal, Radford, Klimov (2017). “Proximal Policy Optimization Algorithms.” arXiv:1707.06347. Source for the clipped surrogate (§3), the adaptive-KL penalty variant (§5), the combined clip+value+entropy objective (§5), and the continuous-control/Atari default hyperparameters (§3 uses ). 2 3 4

  4. Engstrom et al. (2020), “Implementation Matters in Deep Policy Gradients: A Case Study on PPO and TRPO,” arXiv:2005.12729; and Huang et al. (2022), “The 37 Implementation Details of Proximal Policy Optimization,” ICLR Blog Track (https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/). Document value-loss clipping and per-minibatch advantage normalization as code-level optimizations that account for much of PPO’s practical performance. 2

  5. Ouyang et al. (2022). “Training language models to follow instructions with human feedback” (InstructGPT). arXiv:2203.02155. The canonical RLHF-PPO instantiation: LLM policy initialized from SFT, per-token reward = terminal RM score minus KL-to-frozen-reference penalty, value head, and the policy/critic/reward/reference model setup; also the RLHF-side hyperparameter regime. 2 3

  6. Shao et al. (2024). “DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models.” arXiv:2402.03300. Introduces GRPO (Group Relative Policy Optimization): removes the value network, using the standardized group-mean reward as the baseline while keeping the PPO-style clipped ratio objective. [recent]

  7. Rafailov et al. (2023). “Direct Preference Optimization: Your Language Model is Secretly a Reward Model.” arXiv:2305.18290. Shows the RLHF reward-plus-reference-KL objective has a closed-form optimal policy, enabling direct fitting on preference pairs with a classification-style loss (no reward model, no sampling loop). [recent]