18.6 PPO with a critic and generalized advantage estimation
Concepts from other sections (11)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- PPO: a policy gradient method that clips the new-to-old probability ratio to keep updates small. Read more: 4.4 World models, multiple agents, and RLHF
- clipped surrogate: the minimum of and , which removes the incentive to move a sample’s probability beyond the clip range. Read more: 18.3 Group relative policy optimization with verifiable rewards
- Regularization: penalizing model complexity to trade bias for lower variance. Read more: Chapter 1: Statistical Learning
- Entropy: , the average surprise of a distribution. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
- Standard deviation: , the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics in Mathematics
- chat template: the byte-level protocol that renders a list of role-tagged messages into one token sequence. Read more: 18.1 Supervised fine-tuning: chat rendering, assistant-only loss, packing
- Dropout: randomly zeroing activations during training to approximate an ensemble of subnetworks. Read more: Chapter 2: Deep Learning
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller in Mathematics
- Compute budget: the training FLOP available, , which fixes the trade between parameters and tokens . Read more: A.1 Capstone: TinyStories, owned end to end
- Task success: whether an agent accomplished its objective end to end; the agent metric that matters most. Read more: Chapter 29: LLM Evaluation
- Reward exploitation: improving a proxy score by behavior that misses the intended outcome. Read more: 18.7 Rewards, preference models, and independent evaluation
PPO alternates between collecting rollouts and taking a limited number of gradient updates on them. The actor chooses actions; a critic predicts future return so the actor can compare an outcome with what was expected. This part derives the quantities needed for a small language-model RLHF loop. Read on-policy and off-policy learning first.
Learning objectives
- Compute token rewards, temporal-difference residuals, and GAE.
- Evaluate both signs of PPO’s clipped surrogate.
- Separate critic fitting, actor clipping, KL regularization, and stopping criteria.
Four roles, not necessarily four full models
Section titled “Four roles, not necessarily four full models”The actor is trainable. A frozen old snapshot supplies rollout probabilities. A frozen reference anchors behavior. A reward model or checker scores outcomes, and a trainable value head or critic estimates returns. Implementations can share a backbone, cache scores, or swap weights, so count resident tensors and optimizer states instead of multiplying “model size” by a fixed number. Shared actor/critic parameters also couple their gradients.
For generated token and history , an illustrative RLHF reward is
Here the first term is a sampled reference-KL shaping reward, fixed with this rollout batch. Individual log ratios may be negative; their expectation under the old policy is its KL to the reference. Other recipes place an explicit KL penalty in the actor loss. Define which formulation you use so the penalty is not accidentally counted twice. A length cap needs an explicit termination convention; it does not automatically mean the task reached a terminal state.
Derive the advantage
Section titled “Derive the advantage”The critic predicts discounted return. With discount , define
The bootstrap mask is zero at a true terminal and one when a next-state value is legitimate. The trace mask is zero where a collected trajectory ends, so advantages cannot propagate into another episode or packed example. At an artificial truncation one may bootstrap () while stopping the trace (). A recipe that treats length-capped text as a terminal uses there instead. State and test the choice.
This recurrence is generalized advantage estimation. trades shorter bootstrapped estimates against longer return estimates. gives a one-step residual; with appropriate terminal handling yields return minus value. LLM recipes often use , but discounting is a task decision. See GAE, section 3.
Work it by hand. Rewards are , old values , the final next value is zero, and the last action truly terminates. With , , residuals are . Backward recursion gives advantages . Fixed critic targets are . These are detached targets, not numbers recomputed through the changing critic on every minibatch.
Derive the clipped actor objective
Section titled “Derive the clipped actor objective”At each valid action token, the ratio is
Maximize the mean of
With , the four cases below expose the sign handling:
| Advantage | Ratio | Raw term | Clipped term | Minimum |
|---|---|---|---|---|
| 1.5 | 1.5 | 1.2 | 1.2 | |
| 0.5 | 0.5 | 0.8 | 0.5 | |
| 1.5 | -1.5 | -1.2 | -1.5 | |
| 0.5 | -0.5 | -0.8 | -0.8 |
The clip removes the incentive for excessive movement in the favorable direction; it retains penalties for harmful movement. It is not a hard bound on parameters, probability ratios for unseen actions, or full-policy KL. The clipped formulation and combined policy/value/entropy objective come from PPO, equations 7 and 9.
A simple minimized loss is
Use completion masks for actor, critic, and entropy reductions; mask padding and prompt-only positions. Some implementations clip the value update as well; this is an extra design choice. Advantage normalization changes optimization scale. Record its scope and do not divide by the standard deviation of a singleton without an epsilon and a defined convention.
One complete update round
Section titled “One complete update round”freeze rollout revision and old token log probabilitiescollect prompts → generate completions → score rewardscompute frozen reference scores and old valuesbuild terminal/truncation masks → compute GAE and return targetsfor a bounded number of minibatch epochs: score recorded action tokens under the current actor compute masked clipped actor, critic, and optional entropy loss backward → finite-gradient check → clip norm → optimizer step measure old/current KL and stop early if the drift budget is exceededdiscard or archive the batch; collect fresh rolloutsAt initialization, for matching behavior and learner computations. Compare the rollout and teacher-forced scoring paths before training; a systematic mismatch can come from filtering, chat templates, dropout, quantization, or batch-dependent kernels. Never replace the actual behavior denominator simply to make ratios look like one.
Controls and failure evidence
Section titled “Controls and failure evidence”| Control | Mechanism | Evidence to inspect |
|---|---|---|
| Clip range, update epochs, learning rate | Limit how strongly one batch changes the actor | Ratio tails, old/current KL, clip fraction, held-out return |
| Reference KL coefficient | Penalize drift from the anchor | Reference KL and behavior changes, separately from old/current KL |
| Value-loss weight and critic learning rate | Fit return predictions | Value error and explained variance on nonconstant targets |
| , , reward scaling | Change credit assignment and gradient scale | Length-conditioned reward, advantage variance, terminal correctness |
| Rollout budget and lag limit | Control sample cost and policy mismatch | Accepted fresh tokens/sec, stale fraction, reward per compute budget |
If reward rises while independent task success falls, investigate reward exploitation. If KL spikes immediately, inspect behavior probabilities and update scale. If the critic predicts a constant, inspect masks, terminal rewards, and target construction before adding capacity. A loss scalar alone does not diagnose these failures.
Key terms
Section titled “Key terms”- Critic: a learned estimate of value or return.
- Advantage: estimated improvement over the state’s baseline value.
- GAE: an exponentially weighted combination of temporal-difference residuals.
- Clip fraction: a defined count of ratios outside the clipping interval; it is not the fraction of all gradients that are zero.
Summary
Section titled “Summary”PPO needs valid rollout probabilities, fixed advantages and targets, correct episode boundaries, and controlled reuse. Critic fitting and policy improvement must both be checked against independent outcomes.
Review questions
Section titled “Review questions”-
Why does the negative-advantage, ratio-1.5 row use -1.5?
Answer
Increasing the probability of a bad action is harmful. The minimum retains that penalty rather than hiding it with the clipped -1.2 term. -
Why are truncation and terminal masks separate?
Answer
A rollout can stop collecting while the underlying task remains nonterminal. Bootstrap from that final state if the task definition permits it, but stop the trace at the collection boundary.
Checks
Section titled “Checks”Learning checks verifies the four clipping cases, the GAE example, and terminal versus truncated bootstrapping. It checks arithmetic and boundary conventions, not convergence of a trained policy. Continue with reward design, then compare the critic-free GRPO objective.