In one breath
- Text generation is an MDP with deterministic, append-only transitions and a reward that usually arrives once, at the end. You can treat the whole response as one bandit action (REINFORCE, RLOO, GRPO) or each token as an action with its own advantage (PPO with a critic).
- The policy gradient is $\E[\hat A\,\nabla_\theta\log\pit]$. The log-derivative trick turns "the gradient of an expectation" into "an expectation of something you can sample". Any baseline that does not depend on the sampled action leaves it unbiased and can cut variance by orders of magnitude.
- GAE slides between TD (λ = 0: low variance, biased by the critic) and Monte Carlo (λ = 1: unbiased, noisy). LLM practice uses γ = 1, and λ close to 1 because the reward sits at the end.
- PPO reuses one batch for several epochs through an importance-sampled surrogate. Its clip removes the incentive to push the probability ratio past $1\pm\epsilon$ in the direction the advantage wants. It is a cheap, heuristic trust region.
- RLHF-PPO keeps four models in memory, puts the KL to the reference inside the per-token reward, and depends on many implementation details (whitening, value initialization, EOS handling, sampling settings).
- KL estimators: k1 is unbiased but noisy, k3 is unbiased, low-variance and never negative. But differentiating an estimator is not estimating a gradient: put k3 in the loss and you get the gradient of the other KL direction.
- With a strong pretrained initialization and a terminal reward, a learned critic often costs more (memory, bias, tuning) than it saves. That is why REINFORCE-style methods (RLOO, then GRPO in Chapter 06) displaced PPO for much of LLM post-training.
§1Why RL, and what this chapter is for
Supervised fine-tuning teaches a model to imitate. Reinforcement learning teaches it to improve against a score, including on outputs no human ever wrote.
After SFT (Chapter 01), the model can produce good responses, but it learned only from demonstrations. Three things push us towards RL. First, it is often easier to judge a response than to write the ideal one: a preference label, a unit test, or a checked math answer gives a signal on outputs nobody demonstrated. Second, imitation learns from the expert's state distribution, but at test time the model conditions on its own previous tokens. RL trains on the model's own samples, so it learns to recover from its own mistakes. Third, a scalar reward can express things a likelihood cannot: "shorter is better if still correct", "refuse only when necessary", "the proof must check".
The objective we will optimize for the rest of the guide is
- On-policy expectation: prompts from a dataset, responses sampled from the policy being trained. The sampling distribution depends on θ. That one fact is what makes this RL and not supervised learning.
- Reward: a reward model (Ch. 03), a verifier (Ch. 06) or a rubric judge. Usually one scalar per response.
- KL to the reference: keeps the policy near the SFT model. Chapter 04 derives the closed-form optimum of this objective. Here we care about how to estimate and optimize it with samples.
- β: the KL strength. Small enough to let the reward matter, large enough to stop the policy from exploiting the reward model.
This chapter is the machinery: how to get a gradient of that objective from samples, how to make it low-variance, how to take several safe steps per batch, and how all this became the PPO recipe of InstructGPT, plus why much of the field later dropped half of that recipe. Chapter 04 owns the KL-regularized objective and its optimum, Chapter 06 owns GRPO and its descendants, and Chapter 07 owns large-scale asynchronous systems. Here we build the foundations they all stand on.
§2Generation as a Markov decision process
A state is everything written so far. An action is the next token. The environment does nothing except append it.
An MDP is a tuple $(\mathcal S,\mathcal A,P,r,\rho_0,\gamma)$. For a decoder-only language model answering a prompt $x$:
- State $s_t = (x, y_1,\dots,y_{t-1})$: the prompt plus the tokens generated so far. The initial state distribution $\rho_0$ is the prompt distribution.
- Action $a_t = y_t \in \mathcal V$: one token from a vocabulary of roughly $10^5$ entries.
- Policy $\pit(a_t\mid s_t) = \mathrm{softmax}(z_\theta(s_t)/\tau)_{a_t}$: the language model's next-token distribution at temperature τ.
- Transition $P(s_{t+1}\mid s_t,a_t) = \mathbb 1[s_{t+1} = s_t\oplus a_t]$: deterministic. The new state is the old one with the token appended. The episode ends at the end-of-sequence token or at a length cap.
- Reward: typically $r_t = 0$ for $t\lt T$ and $r_T = R(x,y)$: sparse and terminal. In PPO-style RLHF a small per-token KL penalty is added to every step (§8).
- Discount γ: episodes are finite, so LLM practice almost always uses $\gamma = 1$.
Two ways to slice the same problem
The sequence-level (bandit) view treats the whole response $y$ as a single action from the context $x$, with probability $\pit(y\mid x) = \prod_t \pit(y_t\mid s_t)$ and reward $R(x,y)$. There are no intermediate states to reason about. The gradient (next section) is $\E[R\,\nabla\log\pit(y\mid x)]$, and since $\log\pit(y\mid x) = \sum_t\log\pit(y_t\mid s_t)$, every token gets the same scalar weight. REINFORCE, RLOO, ReMax and GRPO all live here. The InstructGPT paper also describes its environment as a bandit: a prompt, a response, a reward, end of episode.
The token-level view keeps the full MDP. Each token has its own state and gets its own advantage $\hat A_t$, typically from a learned value function and GAE (§5). PPO as implemented for RLHF lives here: the KL penalty is paid per token, and a critic tries to say which tokens moved the expected return.
| Sequence-level (bandit) | Token-level (MDP) | |
|---|---|---|
| Action | whole response $y$ | one token $y_t$ |
| Credit | same $\hat A$ for every token | per-token $\hat A_t$ |
| Needs | several samples per prompt (for a baseline) | a value function $V_\psi(s_t)$ |
| KL penalty | in the sequence reward, or as a loss term | per-token reward shaping |
| Typical methods | REINFORCE, RLOO, ReMax, GRPO, DPO (implicitly) | PPO + GAE (InstructGPT-style RLHF), VinePPO, VAPO |
Because $s_{t+1}$ is a deterministic function of $(s_t,a_t)$, the action-value function needs no expectation over the environment: $Q^\pi(s_t,a_t) = r_t + \gamma V^\pi(s_{t+1})$ exactly. So the one-step TD error with the true value function, $\delta_t = r_t+\gamma V^\pi(s_{t+1}) - V^\pi(s_t)$, is the true advantage $A^\pi(s_t,a_t)$, with no sampling noise at all. Every bit of variance in an LLM advantage estimate comes from the policy's own future sampling and from critic error, never from the "environment". Keep this in mind for the GAE discussion. It is also why "the logits are Q-values" readings of LLMs (Rafailov et al., 2024, Ch. 05) are natural in this setting.
Writing a response is typing on a typewriter: every keystroke deterministically changes the page, the page is the whole state, and you cannot erase. The judge reads the finished page once and gives a grade. The bandit view grades the page. The token view also hires a commentator who, after every keystroke, guesses the final grade, so you can see which keystroke made the guess jump. Where it breaks: a real typist has a plan that is not on the page. A transformer's "plan" is only whatever its activations compute from the page, so the state really is just the text. That is what makes the MDP exactly Markov.
A vocabulary of ~150k tokens sounds like a nightmare action space. It is not, because we never enumerate it: we only need $\log\pit(a\mid s)$ for the sampled token, which the forward pass gives for free. The real difficulty is the horizon. Responses run to hundreds or tens of thousands of tokens, and one terminal scalar has to be spread across all of them. That credit-assignment problem (§11) is where the variance comes from.
§3The policy gradient, derived
We want the gradient of an average over samples whose distribution itself depends on θ. The trick: differentiate the probabilities, not the samples.
Write $J(\theta) = \E_{\tau\sim p_\theta}[R(\tau)]$, where τ is a trajectory (for us: a prompt and a response). The problem: the reward model or verifier is not differentiable with respect to the tokens (they are discrete samples), and the expectation is over a θ-dependent distribution. Scroll through the derivation on a one-dimensional toy. The "policy" is a Gaussian $\pit = \mathcal N(\theta,1)$ over a continuous action $x$, and the reward $f(x)$ has a bump to the right.
1 · The objective. The policy (clay) puts mass around θ = 0. The reward (green) is highest near x ≈ 2.6. We want $\nabla_\theta J$, which says which way to slide θ. Here the answer is obviously "right", but we must get it from samples alone, because in the LLM case the integral is over every possible string.
2 · The obstacle. Push the gradient inside the integral: $\nabla_\theta J = \int\nabla_\theta\pi_\theta(x)\,f(x)\,dx$. This is not an expectation under $\pi_\theta$ (there is no $\pi_\theta$ multiplying the integrand), so averaging over our samples (dots) does not estimate it.
3 · The trick. Since $\nabla\log\pi = \nabla\pi/\pi$, we can write $\nabla\pi = \pi\,\nabla\log\pi$. That puts a $\pi_\theta$ back in front. The violet line is the score function $\nabla_\theta\log\pi_\theta(x)$. For a unit Gaussian it is $x-\theta$: positive for samples to the right of the mean, negative to the left.
4 · Monte Carlo. Now $\nabla J = \E_{\pi_\theta}[f(x)\nabla\log\pi_\theta(x)]$, so average $f(x_i)\,(x_i-\theta)$ over samples. Each bar is one sample's vote. Samples on the right vote "move right" with weight $f$. Samples on the left vote "move left" with weight $f$. Because $f$ is positive everywhere, the left samples vote hard in the wrong direction, and the estimate is a small difference of large numbers. Compare the readouts.
5 · Subtract a baseline. Replace $f$ with $f-b$. The score has mean zero, $\E[\nabla\log\pi] = \int\nabla\pi = \nabla\!\int\!\pi = \nabla 1 = 0$, so the expectation is unchanged. Now samples are judged against the average: low-reward samples on the left push right by pushing their own probability down. The bars shrink and agree, and the estimator's standard deviation drops (readout).
6 · Step. Ascend: $\theta\leftarrow\theta+\alpha\hat g$. The policy slides towards the reward bump. In an LLM, θ is billions of weights, $x$ is a response, and $\nabla\log\pi$ is ordinary backprop through the log-likelihood of the sampled tokens. That is the whole idea.
From one action to a trajectory
For a trajectory $\tau=(s_0,a_0,\dots,s_T,a_T)$ the probability factorizes as $p_\theta(\tau) = \rho_0(s_0)\prod_t \pit(a_t\mid s_t)\,P(s_{t+1}\mid s_t,a_t)$. Take the log and differentiate. The initial-state and transition terms do not depend on θ and drop out:
$$\nabla_\theta\log p_\theta(\tau) = \sum_{t=0}^{T}\nabla_\theta\log\pit(a_t\mid s_t).$$
This is why model-free policy gradients never need a model of the environment. For LLMs that point is moot, since we know the dynamics exactly ("append the token"). So
$$\nabla_\theta J = \E_{\tau\sim p_\theta}\Big[R(\tau)\sum_{t}\nabla_\theta\log\pit(a_t\mid s_t)\Big].$$
This is REINFORCE (Williams, 1992): sample, score, and scale each sampled token's log-likelihood gradient by the return. It is the gradient of a weighted log-likelihood, a "supervised loss whose labels are the model's own samples, weighted by how good they were". That reading is the most useful intuition in the chapter.
The action at time $t$ cannot influence rewards received before $t$. Formally, for $t' \lt t$, condition on the history up to $s_t$. The reward $r_{t'}$ is then fixed, and
$$\E\big[r_{t'}\,\nabla\log\pit(a_t\mid s_t)\big] = \E\Big[r_{t'}\;\underbrace{\E_{a_t\sim\pit(\cdot\mid s_t)}\big[\nabla\log\pit(a_t\mid s_t)\big]}_{=\,0}\Big] = 0.$$
Dropping these zero-mean terms gives the lower-variance form $\nabla J = \E\big[\sum_t \nabla\log\pit(a_t\mid s_t)\,G_t\big]$ with the reward-to-go $G_t = \sum_{t'\ge t}\gamma^{t'-t}r_{t'}$. By the tower property, $G_t$ can be replaced by its conditional expectation $Q^\pi(s_t,a_t)$. That gives the policy gradient theorem (Sutton et al., 1999) in trajectory form:
$$\nabla_\theta J = \E_{\pi}\Big[\sum_t \nabla_\theta\log\pit(a_t\mid s_t)\;Q^{\pi}(s_t,a_t)\Big].$$
With a purely terminal reward and γ = 1, every $G_t$ equals $R$, so for vanilla LLM REINFORCE the reward-to-go refinement only matters once you add per-token terms such as the KL penalty.
# REINFORCE for an LLM, sequence-level (one scalar per response)
# logp: [B, T] log-probs of the *sampled* tokens under the current policy
# mask: [B, T] 1 for response tokens, 0 for prompt/padding; R: [B] rewards
def reinforce_loss(logp, mask, R, baseline=0.0):
adv = (R - baseline).detach() # no gradient through the weight
seq_logp = (logp * mask).sum(-1) # log pi(y|x) = sum_t log pi(y_t|s_t)
return -(adv * seq_logp).mean() # minimize the negative objective
You cannot ask "how does the reward change if I nudge the token 'Paris' a little?". Tokens are lottery tickets, not dials. You can ask "how does the probability of buying this ticket change if I nudge θ?". That is $\nabla\log\pi$. The policy gradient says: for every ticket you drew, raise its odds in proportion to how much it paid. Where it breaks: in a real lottery the payout does not depend on your other tickets. In an LLM, raising the odds of one token also shifts every later state and every later distribution. The trajectory form handles this exactly, but only in expectation, which is where the variance comes from.
The "loss" $-\hat A\log\pi$ is a surrogate: its gradient at the current θ equals the policy-gradient estimate, but its value means nothing. It can go up while the policy improves, and its scale depends on the advantage normalization. Monitor reward, KL to the reference, entropy and response length, not the surrogate loss. The same holds for every objective in this chapter.
§4Variance, baselines and advantages
The policy-gradient estimator is unbiased and terribly noisy. Almost every algorithm after REINFORCE is a variance-reduction trick.
Where does the noise come from? Look at a single-sample estimate $\hat g = R\cdot\sum_t\nabla\log\pit(a_t\mid s_t)$:
- The score sum grows with length. It is a sum of $T$ zero-mean random vectors (martingale differences), so its variance grows roughly linearly in $T$. A 2,000-token response contributes 2,000 noisy terms for one scalar of signal.
- Reward offset multiplies the noise. Write $R = c + R'$. Since $\E[\nabla\log\pi]=0$, the constant $c$ adds nothing to the mean but adds about $c^2\,\E\|\nabla\log p_\theta(\tau)\|^2$ to the variance. A reward model whose scores sit around +4 is, to REINFORCE, mostly noise.
- One sample says little about the counterfactual. We see the reward of what was sampled, not of what wasn't. Learning "this was better than usual" needs a notion of "usual".
Baselines: free variance reduction
For any function $b(s)$ that does not depend on the action:
$$\E_{a\sim\pi(\cdot\mid s)}\big[b(s)\,\nabla_\theta\log\pit(a\mid s)\big] = b(s)\sum_a\pit(a\mid s)\frac{\nabla_\theta\pit(a\mid s)}{\pit(a\mid s)} = b(s)\,\nabla_\theta\!\sum_a\pit(a\mid s) = b(s)\,\nabla_\theta 1 = 0.$$
So $\E[(G_t - b(s_t))\nabla\log\pi(a_t\mid s_t)] = \E[G_t\nabla\log\pi(a_t\mid s_t)]$: subtracting a baseline never changes the expected gradient, only its variance. The ideal per-state choice, up to a gradient-magnitude weighting, is $b(s)=V^\pi(s)$. Then the weight becomes the advantage $A^\pi(s,a) = Q^\pi(s,a) - V^\pi(s)$: how much better this action was than the policy's average action from the same state. (The exact variance-minimizing scalar baseline is $b^* = \E[\|\nabla\log\pi\|^2 R]/\E[\|\nabla\log\pi\|^2]$, a reward average weighted by squared score norm; Greensmith et al., 2004, analyze such choices. In practice nobody bothers with the weighting.)
Two things the widget makes visible. First, a constant shift of the reward is invisible to the expected gradient but very visible to the variance, which is why every serious LLM RL recipe either learns a baseline (critic), computes one from other samples (RLOO, GRPO), or at least whitens the rewards. Second, the variance does not only slow learning: with a softmax policy, a few unlucky large steps can push probability onto a mediocre arm, after which that arm is sampled almost exclusively and the better arm is rarely tried again. That is a small version of the entropy collapse problem of Chapter 06.
Baselines you can compute without a critic
Sample $k$ responses $y_1,\dots,y_k$ for the same prompt. Then:
- Leave-one-out (RLOO): $\hat A_i = R_i - \frac{1}{k-1}\sum_{j\ne i}R_j$. The baseline for sample $i$ uses only the other samples, which are independent of $y_i$, so the estimator stays exactly unbiased (Kool et al., 2019; Ahmadian et al., 2024).
- Group mean (GRPO-style): $\hat A_i = R_i - \bar R$. Including $R_i$ in the mean makes the baseline depend on the action. But algebraically $R_i - \bar R = \frac{k-1}{k}\big(R_i - \frac{1}{k-1}\sum_{j\ne i}R_j\big)$, so it is just RLOO scaled by a constant: unbiased in direction. GRPO's extra division by the group's standard deviation is a different matter. It reweights prompts by how consistent their rewards are, which does change the expected gradient (Liu et al., 2025; Ch. 06).
- Greedy baseline (ReMax): $b = R(x,\hat y_{\text{greedy}})$. One extra decode per prompt, independent of the sample, so it is unbiased (Li et al., 2023).
A teacher who says "great job" to every student in the same tone gives no information. That is REINFORCE with all-positive rewards: every sample gets pushed up, and only the differences in how much carry signal. A teacher who says "you beat the class average by 12 points" gives a clear signal. That is a baseline. RLOO is the strictest fair version: your grade is compared with the average of everyone else, so you cannot raise the curve you are compared to. Where it breaks: a curve only ranks students within one class (one prompt). If every student in a class fails (all rewards 0), the curve gives zero signal for that prompt. GRPO and RLOO genuinely learn nothing from all-fail or all-pass groups. That is why reasoning-RL pipelines filter such prompts out (Ch. 06).
§5Critics, TD learning and GAE
A critic is a learned baseline that can also say where in the sequence things went right or wrong. GAE is the dial that decides how much you trust it.
A value function $V^\pi(s) = \E_\pi[\sum_{k\ge0}\gamma^k r_{t+k}\mid s_t=s]$ is the expected return from state $s$ under the current policy. For an LLM with a correctness reward it is, roughly, "the probability that this prefix ends in a correct answer" (minus the KL still to be paid). It satisfies the Bellman equation $V^\pi(s_t) = \E_{a_t}[r_t + \gamma V^\pi(s_{t+1})]$. In RLHF the critic $V_\psi$ is usually a copy of a transformer with a scalar head, trained by regression.
There are two ways to build a regression target for $V$, and two matching ways to estimate advantages:
- Monte Carlo (MC): target $G_t$ (the actual return). Unbiased, high variance. Advantage $\hat A_t = G_t - V(s_t)$.
- Temporal difference (TD): target $r_t + \gamma V(s_{t+1})$ (one real reward, then trust the critic). Low variance, biased whenever $V$ is wrong. Advantage $\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)$, the TD error.
Generalized advantage estimation, derived
Between the two extremes sit the $k$-step estimators. Using $k$ real rewards and then bootstrapping, the sum telescopes:
$$\hat A^{(k)}_t = \sum_{l=0}^{k-1}\gamma^l\delta_{t+l} = -V(s_t) + r_t + \gamma r_{t+1} + \dots + \gamma^{k-1}r_{t+k-1} + \gamma^k V(s_{t+k}).$$
(Check: in $\sum_l\gamma^l(r_{t+l} + \gamma V(s_{t+l+1}) - V(s_{t+l}))$ each $+\gamma^{l+1}V(s_{t+l+1})$ cancels the next term's $-\gamma^{l+1}V(s_{t+l+1})$.) Larger $k$ means less reliance on $V$ (less bias) and more random rewards in the sum (more variance). GAE (Schulman et al., 2015b) takes an exponentially weighted average over all $k$:
$$\hat A^{\mathrm{GAE}(\gamma,\lambda)}_t = (1-\lambda)\big(\hat A^{(1)}_t + \lambda\hat A^{(2)}_t + \lambda^2\hat A^{(3)}_t + \dots\big).$$
Substitute $\hat A^{(k)}_t = \sum_{l\lt k}\gamma^l\delta_{t+l}$ and collect the coefficient of each $\delta_{t+l}$. The term $\gamma^l\delta_{t+l}$ appears in every $\hat A^{(k)}$ with $k\gt l$, weighted by $(1-\lambda)\lambda^{k-1}$, and $(1-\lambda)\sum_{k\gt l}\lambda^{k-1} = \lambda^l$. Hence
- GAE advantage: computed in one backward pass over the sequence with the recursion on the right, starting from $\hat A_{T+1}=0$ and $V(s_{T+1})=0$ at the terminal state.
- TD error: the critic's "surprise" at step $t$. It is also the reward reshaped with potential $V$ (§11), which is why GAE is "a discounted sum of shaped rewards".
- γ: changes the objective (it discounts real future rewards). With γ < 1 you optimize a different problem.
- λ: changes only the estimator. λ = 0 gives TD, λ = 1 gives MC; in between it trades critic bias against reward noise.
The critic is trained towards the λ-return $G^\lambda_t = \hat A_t + V_{\text{old}}(s_t)$, the matching blend of MC and TD targets. Two limits are worth memorizing. With λ = 1: $\hat A_t = \sum_l\gamma^l r_{t+l} - V(s_t)$, which is unbiased for any $V$ (the critic is then only a baseline). With λ = 0: $\hat A_t = \delta_t$, which is exactly right if $V=V^\pi$ (by the key idea in §2) and wrong by the critic's error otherwise.
γ and λ in LLM practice
Classic control used γ ≈ 0.99, λ ≈ 0.95. For LLMs the episode is finite and we care about the undiscounted sequence reward, so γ = 1 is standard (the TL;DR reproduction of Huang et al., 2024, uses γ = 1 and λ = 0.95). λ is the subtle one. With a purely terminal reward, the reward's direct contribution to token $t$'s advantage is weighted by $(\gamma\lambda)^{T-t}$. For λ = 0.95 and a 1,000-token chain of thought that is $0.95^{1000}\approx 5\times10^{-23}$. Early tokens then learn only through the critic, and a critic initialized from a reward model is badly biased early in training. This is precisely the failure that VC-PPO (Yuan et al., 2025) diagnosed for long chain-of-thought. Their diagnosis was "value initialization bias and reward signal decay". Their fix had two parts. First, value pretraining: freeze the policy and fit the critic with λ = 1 (pure Monte-Carlo returns), so the RM-initialized critic stops being biased. Second, decoupled GAE: λcritic = 1.0, so the reward reaches every token in the value targets without decay, while λactor = 0.95 keeps the policy's advantages low-variance by leaning on the now-trustworthy critic. In their sweep, λactor of 0.95 and 0.99 beat both 0.9 and 1.0. On Qwen2.5-32B they report 48.8 on AIME 2024, against 38.9 for GRPO. VAPO (Yue et al., 2025) went further with a length-adaptive policy λ, $\lambda = 1 - \tfrac{1}{\alpha\,\ell}$ for response length ℓ (α = 0.05), and reports 60.4 on AIME 2024 with the same base model. That number comes from a whole package (asymmetric clipping, token-level loss, an extra LM loss on correct samples, and more), so do not attribute it to λ alone. (VC-PPO's numbers are from 16k-token generations; its λactor ablation reads 34.3 / 41.3 / 41.9 / 29.4 for λ = 0.9 / 0.95 / 0.99 / 1.0.)
You want to know whether a decision you made this morning was good. TD (λ = 0) asks the weather forecaster right after the decision: "did tomorrow's forecast improve?". That is quick and stable, but only as good as the forecaster. MC (λ = 1) waits until tomorrow and looks out of the window. That is honest, but tomorrow's weather depends on a thousand things besides your decision. GAE averages the forecasts made 1, 2, 3, … steps later, trusting later ones less. Where it breaks: a real forecaster is trained on far more weather than you will ever see. An RLHF critic is trained on the same few thousand rollouts it is judging, and it is chasing a moving policy.
def gae(rewards, values, gamma=1.0, lam=0.95):
"""rewards: [T] per-token rewards; values: [T+1] critic values, values[T] = 0 at EOS.
Returns advantages [T] and value targets (lambda-returns) [T]."""
T = len(rewards); adv = torch.zeros(T); last = 0.0
for t in reversed(range(T)):
delta = rewards[t] + gamma * values[t + 1] - values[t]
last = delta + gamma * lam * last
adv[t] = last
return adv, adv + values[:T] # returns = lambda-return targets for the critic
§6Off-policy correction and trust regions
Sampling is the expensive part. To take more than one gradient step per batch, we must correct for the fact that the batch came from an older policy, and stop the new policy from moving so far that the correction breaks.
Importance sampling
For any distributions with matching support, $\E_{a\sim\pi}[f(a)] = \E_{a\sim\mu}\big[\tfrac{\pi(a)}{\mu(a)}f(a)\big]$. Apply this to the policy gradient with samples from the behavior policy $\piold$ that generated the batch:
$$L_{\piold}(\theta) = \E_{s,a\sim\piold}\Big[\underbrace{\frac{\pit(a\mid s)}{\piold(a\mid s)}}_{r_t(\theta)}\hat A_t\Big],\qquad \nabla_\theta L_{\piold}\big|_{\theta=\theta_{\text{old}}} = \E_{\piold}\big[\nabla_\theta\log\pit(a\mid s)\,\hat A_t\big]\big|_{\theta=\theta_{\text{old}}}.$$
At $\theta=\theta_{\text{old}}$ the ratio is 1 and $\nabla r = r\,\nabla\log\pi = \nabla\log\pi$, so this surrogate has exactly the policy gradient. Away from $\theta_{\text{old}}$ it is an approximation in two ways. (i) The per-token ratio corrects the action distribution but not the state distribution: the prefixes were generated by $\piold$, and the exact correction would multiply ratios over all previous tokens, a product whose variance explodes with length. (ii) The advantages $\hat A_t$ were estimated for $\piold$, not for $\pit$. Both errors are small only if $\pit$ stays close to $\piold$.
Why "close" can be made precise
The performance difference lemma (Kakade & Langford, 2002) is exact:
$$J(\pi') - J(\pi) = \E_{\tau\sim\pi'}\Big[\sum_t\gamma^t A^{\pi}(s_t,a_t)\Big].$$
The surrogate $L_\pi(\pi')$ is the same expression with states drawn from $\pi$ instead of $\pi'$. TRPO's theorem (Schulman et al., 2015a) bounds the gap: $J(\pi')\ge L_\pi(\pi') - C\cdot\max_s\KL(\pi(\cdot\mid s)\,\|\,\pi'(\cdot\mid s))$, with $C = 4\epsilon\gamma/(1-\gamma)^2$ and $\epsilon=\max|A^\pi|$. Maximizing the right-hand side guarantees monotonic improvement. Note the $(1-\gamma)^{-2}$: with γ = 1, as in LLMs, the theoretical constant is vacuous. Nobody runs the theory-backed version, and the practical algorithms keep only the idea: improve the surrogate while keeping the KL small.
Problem. $\max_\theta L_{\piold}(\theta)$ subject to $\bar D_{\mathrm{KL}}(\theta_{\text{old}},\theta) = \E_s[\KL(\piold(\cdot\mid s)\,\|\,\pit(\cdot\mid s))]\le\delta$. The average KL replaces the max in the bound, a heuristic.
Local model. Linearize the objective, $L\approx g^\top\Delta\theta$, and take a second-order expansion of the constraint, $\bar D_{\mathrm{KL}}\approx\tfrac12\Delta\theta^\top F\Delta\theta$. Here $F=\E[\nabla\log\pi\,\nabla\log\pi^\top]$ is the Fisher information matrix, the Hessian of the KL at $\theta_{\text{old}}$. The KL's value and gradient both vanish there.
Solution. The Lagrangian gives the natural gradient direction $F^{-1}g$ with step size $\sqrt{2\delta/(g^\top F^{-1}g)}$. TRPO computes $F^{-1}g$ with conjugate gradient using Fisher-vector products (never forming $F$), then backtracks along the direction until the surrogate improves and the KL constraint holds.
Why not for LLMs. Conjugate gradient plus line search means many extra forward/backward passes per update, poor compatibility with Adam, minibatching and sharded training, and a hard constraint that is awkward with dropout and value-sharing. PPO keeps the spirit and throws away the second-order machinery.
Importance sampling is reusing last week's poll to predict this week's vote by reweighting respondents: "people like this respondent are now 1.3× as common". That works if opinions shifted a little. If they shifted a lot, a few respondents get enormous weights and the prediction is driven by them. A trust region is the rule "only use the old poll if the electorate has not drifted by more than δ". Where it breaks: the poll analogy reweights people (states). PPO's per-token ratio reweights only choices and ignores that the prefixes (who is being polled) also changed.
§7PPO: the clipped surrogate
Replace TRPO's constraint with a pessimistic objective that simply stops rewarding you for moving the ratio further in the direction you wanted.
- Probability ratio: 1 at the start of each update, drifts as you take minibatch steps on the same batch.
- Advantage: fixed for the whole update (computed once with the old policy and critic), usually whitened.
- Clipped ratio: the "trust region" in ratio space; ε ≈ 0.2 in the original paper. The
minmakes the objective a lower bound of the unclipped one.
Work through the cases. The gradient of the unclipped term is $\hat A_t\,\nabla r_t = \hat A_t\,r_t\,\nabla\log\pit(a_t\mid s_t)$.
- $\hat A\gt0$ (good action). We want $r$ up. For $r\le1+\epsilon$ the min picks $r\hat A$ and the gradient flows. For $r\gt1+\epsilon$ the min picks $(1+\epsilon)\hat A$, a constant: zero gradient. The incentive to increase this token's probability further is removed. If a good action's ratio has fallen below $1-\epsilon$, the min still picks $r\hat A$ and the gradient flows, pulling it back up.
- $\hat A\lt0$ (bad action). We want $r$ down. For $r\ge1-\epsilon$ the min picks $r\hat A$ (gradient flows). For $r\lt1-\epsilon$ the min picks $(1-\epsilon)\hat A$: zero gradient; it has been pushed down enough. But if the ratio of a bad action has risen above $1+\epsilon$, then $r\hat A\lt(1+\epsilon)\hat A$, the min picks the unclipped term, and the gradient flows with no bound. That is the pessimism: PPO always lets you undo a mistake.
So the clip is one-sided per sign: it caps how much you can gain from moving in the advantage's direction and never caps the push back. Clipped tokens drop out of the gradient entirely. The fraction of such tokens, clipfrac, is one of the most useful PPO diagnostics.
The rest of the PPO loss
The full objective of Schulman et al. (2017) is $L = \E_t[L^{\mathrm{CLIP}}_t - c_1 L^{V}_t + c_2\,\mathcal H[\pit](s_t)]$, maximized jointly when policy and value share parameters:
- Value loss $L^V_t = (V_\psi(s_t) - G^\lambda_t)^2$. Many implementations add value clipping, $\max\big((V_\psi-G^\lambda)^2,\;(\clip(V_\psi, V_{\text{old}}-\epsilon_v, V_{\text{old}}+\epsilon_v)-G^\lambda)^2\big)$, mirroring the policy clip. It comes from the reference implementations, not the paper. The large-scale study of Andrychowicz et al. (2020), on continuous-control tasks, found that PPO-style value clipping "hurts the performance regardless of the clipping threshold", in line with Engstrom et al. (2020). Their recommendation: GAE with λ = 0.9, and neither value clipping nor a Huber loss. For LLMs the critic is usually a separate network, so $c_1$ becomes simply the critic's own learning-rate scale.
- Entropy bonus $c_2\mathcal H$: encourages exploration in control tasks. In RLHF it is usually set to 0, because the KL-to-reference term already keeps the policy from collapsing, and a 150k-way entropy bonus mostly rewards garbage tokens. In RL for reasoning, entropy is managed in other ways (asymmetric clipping, covariance-based clipping; Ch. 06).
- Several epochs: the batch of rollouts is reused for $K$ epochs (typically 1–4 for LLMs) of minibatch updates. This is PPO's main efficiency win over vanilla policy gradient. With $K=1$ and one minibatch, the ratio is exactly 1 and PPO reduces to REINFORCE with the given advantages.
- Diagnostics: approximate KL between $\piold$ and $\pit$ on the batch (with the k3 estimator of §9), clipfrac, explained variance of the critic, entropy, and in RLHF the KL to the reference and the mean response length.
def ppo_loss(logp_new, logp_old, adv, v_new, v_old, returns, mask, eps=0.2, eps_v=0.2, c_v=0.5):
"""All tensors [B, T]; mask selects response tokens. adv already whitened, everything *_old detached."""
ratio = torch.exp(logp_new - logp_old)
pg1 = -adv * ratio
pg2 = -adv * torch.clamp(ratio, 1 - eps, 1 + eps)
pg_loss = masked_mean(torch.max(pg1, pg2), mask) # max of negatives == min of objectives
v_clip = v_old + torch.clamp(v_new - v_old, -eps_v, eps_v) # optional value clipping
v_loss = 0.5 * masked_mean(torch.max((v_new - returns) ** 2, (v_clip - returns) ** 2), mask)
clipfrac = masked_mean((torch.abs(ratio - 1) > eps).float(), mask)
approx_kl = masked_mean((ratio - 1) - (logp_new - logp_old), mask) # k3 estimate of KL(old || new)
return pg_loss + c_v * v_loss, dict(clipfrac=clipfrac, approx_kl=approx_kl)
The clip is a leash on a dog chasing a ball (the advantage). Once the dog is a leash-length ahead in the ball's direction, it feels no more pull forward: running further earns nothing. But if it has wandered the wrong way, nothing stops you from reeling it back. Where it breaks: a leash constrains position, while the clip only removes incentive on the tokens in this batch. Other tokens' gradients, shared parameters, Adam momentum and multiple epochs can still drag a clipped token's ratio far outside the band. The clip is not a real trust region: PPO's actual KL can exceed any target, which is why practitioners monitor approx-KL and sometimes early-stop the epoch.
§8PPO for language models: the RLHF recipe
InstructGPT made PPO the default post-training algorithm. What made it work was a dozen details that are easy to get wrong and rarely in the equations.
The lineage runs from Ziegler et al. (2019, stylistic continuation and summarization) through Stiennon et al. (2020, TL;DR summarization) to InstructGPT (Ouyang et al., 2022). Anthropic's HH-RLHF paper (Bai et al., 2022a) used the same family of methods. The recipe:
- Start from the SFT model, which is copied four times: the policy $\pit$ (trainable), the reference $\piref$ (frozen), the reward model $R_\phi$ (a separately trained, frozen network, Ch. 03) and the value model $V_\psi$ (trainable, typically initialized from the reward model, so it starts out already reading text the way the RM does). InstructGPT trained 1.3B, 6B and 175B policies, but used "a 6B RM and a 6B value function" for all of them, with the value function initialized from the RM.
- Rollout: sample responses for a batch of prompts from $\piold$.
- Score: one RM forward pass per response gives $R_\phi(x,y)$.
- KL-shaped per-token reward: $$r_t = -\beta\,\big(\log\piold(y_t\mid s_t) - \log\piref(y_t\mid s_t)\big) + \mathbb 1[t=T]\,R_\phi(x,y).$$ The KL appears inside the reward, as a per-token cost paid with the k1 estimator on the sampled token. Summed over the sequence, it is a single-sample estimate of the sequence-level $\KL(\pi\,\|\,\piref)$. InstructGPT's paper calls this "a per-token KL penalty from the SFT model at each token to mitigate over-optimization of the reward model", with β = 0.02.
- Values and GAE: run the critic on every prefix, compute $\hat A_t$ and the λ-return targets (§5).
- Optimize: $K$ epochs of minibatch PPO on the policy and the critic.
- Repeat, optionally adapting β to hit a target KL.
The details that matter
Two papers catalogue them. Huang et al. (2024), "The N+ Implementation Details of RLHF with PPO", reproduced OpenAI's TL;DR results from scratch. Zheng et al. (2023), "Secrets of RLHF in Large Language Models Part I: PPO", ablated the components on chat models and proposed a stabilized variant, PPO-max. The ones worth knowing by heart:
- Reward normalization. Fix the RM's offset so that a reference distribution scores zero on average. In the N+ reproduction (detail 15) the reward head's bias is set so that the SFT demonstrations have mean reward 0. This is the "subtract a constant" of §4, done once, globally. "Secrets of RLHF" goes further and normalizes and clips rewards with running statistics.
- Whitening. Advantage whitening across the batch (stage 7 of the explainer) is near-universal: it is a per-batch rescaling of the step size that keeps ε meaningful. Reward whitening is optional and not innocuous. In the N+ ablation it produced shorter outputs and lower preference rates, although at matched lengths the two variants performed similarly, so most of the effect runs through length.
- Value head initialized from the RM. "Secrets of RLHF" recommends going further and pre-training the critic before PPO starts, "replacing the learning rate warmup with the critic model pre-training". This is the same idea VC-PPO later applied to long chain-of-thought.
- Dropout off. With dropout, the "same" policy gives different log-probs on two forward passes, so the ratio is not 1 even before any update (N+ detail 7, following Ziegler et al.).
- Sampling settings. Rollouts must be samples from the distribution you differentiate. Top-p or top-k that is not mirrored in the training forward pass silently makes $\piold$ in the ratio wrong. The N+ reproduction samples at temperature 0.7. The same authors' earlier blog post on OpenAI's original
lm-human-preferencescode explains that the training forward pass divides the logits by the sampling temperature; in their informal test, without it "the KL would rise faster than expected, and performance would deteriorate". - EOS handling. Responses truncated at the length cap never reach a proper terminal state. The N+ "EOS trick" gives any completion without an EOS token a constant reward of −1. A related pitfall: the reward must be read at the EOS position, not at padding.
- KL control. Ziegler et al. (2019) proposed an adaptive β, a proportional controller: $e_t = \clip\big((\mathrm{KL}_t - \mathrm{KL}_{\text{target}})/\mathrm{KL}_{\text{target}}, -0.2, 0.2\big)$, $\beta_{t+1} = \beta_t(1 + K_\beta e_t)$ with $K_\beta = 0.1$. Many later recipes fix β: 0.02 in InstructGPT, 0.05 in the N+ reproduction and in "Secrets of RLHF" (which calls the KL penalty "critical to the stability of PPO"), and 0.001 in Anthropic's HH-RLHF (below).
- Pretraining mix (PPO-ptx). InstructGPT added a language-modeling loss on pretraining data, with coefficient 27.8, to reduce the "alignment tax" on public NLP benchmarks.
- No entropy bonus. "Secrets of RLHF" found it too sensitive to tune and does not recommend it.
- Monitoring. "Secrets of RLHF" reports that the policy's perplexity, its KL to the reference and its response length are "more informative of the training stability" than reward or loss. A collapsed model "uniformly delivers longer responses and exhibits lower perplexity".
For calibration, the N+ reproduction's full PPO setting on Pythia 1B–6.9B is: γ = 1, λ = 0.95, β = 0.05, 4 PPO epochs per batch, policy and value clip 0.2, batch 512, AdamW at 3e-6. InstructGPT used batches of 512 split into 8 minibatches of 64, trained for a single inner epoch, rollouts at temperature 1, no discount in GAE, and 256k episodes. So even with one epoch, the ratio drifts away from 1 after the first minibatch step, and the clip can matter.
Bai et al. (2022a), "Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback", trained Anthropic's early assistants with preference models and PPO, with a KL penalty to the initial policy. The coefficient was tiny, "a very small value of λKL = 0.001", which they said "likely has a very minor impact during most of RL training" (their KL typically stayed below 100 nats) and "might actually be wholly unnecessary". They reported an approximately linear relation between the preference-model score and the square root of the KL from the initial policy during RL training (presented as an empirical observation, not a law), and they ran "iterated online" RLHF, in which preference models and policies were "updated on a weekly cadence with fresh human feedback data". The constitutional AI paper that followed (Bai et al., 2022b) kept the RL stage and replaced human harmlessness labels with AI feedback (RLAIF; Ch. 04). These papers describe the methods of that time. Anthropic has not published its current RL algorithm in this level of detail, so any statement about what is used for Claude today would be speculation.
The memory bill
Four transformers is the part everybody remembers. With mixed-precision Adam, each trainable parameter costs about 16 bytes: bf16 weights and gradients (2 + 2) plus fp32 master weights and two Adam moments (4 + 4 + 4). This is the accounting of the ZeRO paper (Rajbhandari et al., 2019). Each frozen parameter costs 2 bytes. Before counting activations, the KV cache for generation, or a separate inference engine's copy of the weights, PPO with a same-size critic needs more than twice the memory of SFT.
The per-token penalty $\log\piold - \log\piref$ is a k1 sample: unbiased for the KL but negative on many tokens (see §9). It also enters the reward, so its effect on the gradient goes through the critic and GAE, and it is evaluated at $\piold$, not at the current $\pit$, during the epochs. None of this is wrong, but "β = 0.05" in one codebase is not "β = 0.05" in another that puts the KL in the loss, uses a different estimator, or sums instead of averaging over tokens.
§9Estimating KL from samples: k1, k2, k3
You cannot sum over every possible response, so the KL is always estimated from the tokens you sampled. How you estimate it, and whether you then differentiate the estimate, changes what you optimize.
Setting (following Schulman's note "Approximating KL Divergence", 2020): we sample $x\sim q$ and want $\KL(q\,\|\,p) = \E_q[\log\frac{q(x)}{p(x)}]$. Let $r = p(x)/q(x)$. In RLHF, $q=\pit$, $p=\piref$, and $x$ is a sampled token or sequence.
- k1 $=-\log r$. Unbiased by definition. Its variance is high, and it is negative whenever the sample is more likely under $p$ than under $q$, which happens on a large fraction of samples even though the KL is non-negative.
- k2 $=\tfrac12(\log r)^2$. Always ≥ 0 and low-variance, but biased. Its expectation is an f-divergence that agrees with KL to second order when $p\approx q$ (both are $\tfrac12$ the Fisher quadratic form), so the bias is small only when the distributions are close.
- k3 $=(r-1)-\log r$. Unbiased, because $\E_q[r-1] = \sum_x q\,\frac{p}{q} - 1 = 0$: it is k1 plus a zero-mean control variate. It is always ≥ 0, because $\log r\le r-1$ (concavity of log). It also has low variance when $p\approx q$. It is the Bregman divergence of $-\log$, the gap between $\log$ and its tangent line at $r = 1$.
KL in the reward vs KL in the loss
There are two places to put the KL, and they are not equivalent.
KL in the reward (InstructGPT-style PPO; also RLOO/REINFORCE recipes that subtract $\beta\sum_t\log\frac{\pi}{\piref}$ from the sequence reward). The KL sample is treated as part of the return, so it reaches the parameters through the score function, like any reward. Since $\nabla\KL(\pit\|\piref) = \E_{\pit}\big[\log\frac{\pit}{\piref}\,\nabla\log\pit\big]$ (the extra term $\E[\nabla\log\pi]$ vanishes), "k1 in the reward, with the reward-to-go" is an unbiased estimator of the reverse-KL gradient. It also accounts for how today's token changes the KL paid on future tokens.
KL in the loss (GRPO: $\beta\,\KL$ estimated with k3 per token, added to the loss and differentiated directly; DeepSeekMath used β = 0.04). Now the gradient is the pathwise derivative of the estimator at the sampled tokens. The true gradient of an expectation has two parts, $\nabla\E_{\pit}[\hat k] = \E[\nabla\hat k] + \E[\hat k\,\nabla\log\pit]$, and a loss term keeps only the first. Work it out on-policy for a single categorical distribution (one token), with $\rho = \piref/\pit$. Convention: "reverse KL" means $\KL(\pit\|\piref)$, the one in the RLHF objective, and "forward KL" means $\KL(\piref\|\pit)$. Some RL-theory papers use the opposite names, so check before comparing claims.
- $\nabla k_1 = \nabla(\log\pit - \log\piref) = \nabla\log\pit$, so $\E_{\pit}[\nabla k_1] = 0$. Differentiating k1 gives no signal in expectation, even though k1 is an unbiased estimate of the KL's value.
- $\nabla k_2 = \log\frac{\pit}{\piref}\,\nabla\log\pit$. Its expectation is exactly the reverse-KL gradient above, so for one token, k2 in the loss is the "right" one for $\KL(\pit\|\piref)$.
- $\nabla k_3 = \nabla(\rho - 1 - \log\rho) = -\rho\nabla\log\pit + \nabla\log\pit = (1-\rho)\nabla\log\pit$. Its expectation is $\E_{\pit}[\nabla\log\pit] - \sum_y\piref\nabla\log\pit = -\sum_y\piref(y)\nabla\log\pit(y) = \nabla\KL(\piref\|\pit)$. So k3 in the loss follows the gradient of the forward KL, $\KL(\piref\|\pit)$, not the reverse KL it estimates.
Near $\pit\approx\piref$ all of these agree to first order, which is why GRPO works fine in practice. But the forward KL is mass-covering: it penalizes the policy for dropping reference tokens much more than for adding new ones, a different regularizer than the one in the objective of Chapter 04. Two more subtleties. First, for sequences, a per-token loss term gives at best a partial derivative: it ignores how today's token changes the KL paid on future tokens. Tang & Munos (2025) make this point ("token-level losses only produce a partial derivative at best"). Shah et al. (2025) study the four on-policy configurations k1 or k3, in the reward or in the loss. Only k1 in the reward gives an unbiased gradient of the sequence-level reverse KL. k3 in the reward led to training collapse in their runs. k3 in the loss is "a sum of unbiased gradient estimates of the forward KL divergences computed at the token level", which is consistent with its stability in practice despite optimizing a different regularizer. (By the derivation above, per-token k2 in the loss recovers only the local reverse-KL terms, not the effect on future tokens.) Second, once samples are off-policy (several epochs, async rollouts), the expectation is under $\piold$, so the KL term needs the importance weight $\pit/\piold$ as well. Zhang et al. (2025) identify this missing weight in GRPO's k3 term, and DeepSeek-V3.2 (2025) adds exactly this correction, after which "the gradient of this KL estimator becomes unbiased". The weight matters even on-policy, where it equals 1 numerically, because it is differentiated. With $w=\pit/\piold$, $\nabla(w\,k_3) = w\,(k_3 + 1-\rho)\nabla\log\pit = w\,\log\tfrac{\pit}{\piref}\,\nabla\log\pit$, whose expectation under $\piold$ is the per-token reverse-KL gradient. Differentiating through $w$ supplies exactly the score-function term $\E[\hat k\,\nabla\log\pit]$ that a plain loss term drops.
# per-token log-ratios on sampled tokens: lr = logp_ref - logp_policy (= log rho)
k1 = -lr # unbiased value, high variance, can be negative
k2 = 0.5 * lr ** 2 # biased value; its *gradient* matches reverse KL on-policy
k3 = torch.exp(lr) - 1 - lr # unbiased value, low variance, >= 0; gradient matches *forward* KL
# KL in the reward (PPO-RLHF): no gradient through it, it is part of the return
rewards = -beta * (logp_old - logp_ref).detach(); rewards[last_token] += R
# KL in the loss (GRPO-style): differentiated directly
loss = pg_loss + beta * masked_mean(k3, mask)
To measure how much taller one person is than another, k1 measures each one from the floor and subtracts. Each reading is unbiased, but the difference is tiny next to the noise in two big numbers. k3 lays a ruler across both heads and reads the gap directly: the "−1 + r" part is a reference you know averages to zero, which cancels most of the shared noise. Where it breaks: the ruler helps only when the two are close in height. When $p$ and $q$ are far apart, $r$ has heavy tails and k3's variance grows too.
§10Back to basics: REINFORCE, RLOO and the case against the critic
PPO was designed for robots learning from scratch. LLM fine-tuning starts from a model that is already good, and that changes which problems actually matter.
Ahmadian et al. (2024), "Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs", argued that most of PPO's machinery solves problems RLHF does not have. The argument, in their framing:
- The starting point is strong. Deep-RL algorithms were tuned for policies initialized at random, where the gradient estimates are very noisy and the policy can collapse. An SFT model already puts its probability on a sensible region, so the variance problem is milder and big, destructive updates are rarer.
- Model the whole generation as one action. With a terminal reward, the partial-sequence states add little. Treating the response as a single bandit action with a sequence-level reward works as well or better.
- The clip rarely fires. In their runs, "the loss is actually clipped on average <5% of the time per batch", and turning clipping off did not hurt. PPO's main safety device mostly did not matter.
- A sample-based baseline is enough. On TL;DR summarization and Anthropic-HH (Pythia-6.9B and Llama-7B), RLOO with k = 4 reached win-rates of 77.9 / 43.7 / 64.1 against PPO's 67.6 / 29.2 / 32.0, and it also beat DPO and RAFT. Even vanilla policy gradient beat PPO in their table. And RLOO needs no critic.
Then there are the costs of the critic itself: a second trainable network (the memory widget above), a second set of hyperparameters, and a bias that is worst exactly when the reward is sparse and the sequences are long, i.e. in reasoning RL. Groups of samples per prompt make the critic's job, "how good is this prompt for the current policy?", directly measurable: just average the group. That is the step from RLOO to GRPO (Shao et al., 2024): group-relative advantages (DeepSeekMath sampled 64 outputs per question), the clipped PPO ratio retained for multi-epoch reuse, and a k3 KL penalty in the loss. Its many refinements (Dr. GRPO, DAPO, GSPO, CISPO…) are the subject of Chapter 06.
| Method | Advantage | Critic? | Ratio / clip | KL |
|---|---|---|---|---|
| REINFORCE | $R - b$ (moving average) | no | no (on-policy) | in reward |
| RLOO | $R_i - \text{mean}_{j\ne i}R_j$ | no | optional | in reward |
| ReMax | $R - R(\text{greedy})$ | no | no | in reward |
| PPO (RLHF) | GAE over per-token rewards | yes | per-token clip | per-token, in reward |
| GRPO | $(R_i - \bar R)/\mathrm{std}$ | no | per-token clip | k3, in loss |
A critic is a commentator who, after every play, estimates the team's win probability. When the commentator is good, the change in their estimate tells you which play mattered: per-token credit. When they are new to the sport (a freshly initialized value head), their running commentary is confidently wrong, and a team that trusts it learns the wrong lessons. RLOO and GRPO ignore the commentator and read the scoreboard over several games played from the same position. They get no per-play credit, but nothing is made up either. Where it breaks: for games of 30,000 plays (long agentic or reasoning episodes), "same credit to every play" is very wasteful. That is why value-based methods (VAPO, VC-PPO) and process rewards keep coming back.
The 2025 picture is mixed rather than one-sided. Critic-free methods dominate published open recipes: GRPO in DeepSeekMath and R1 and in Qwen3, GSPO later at Qwen, and a critic-free mirror-descent variant in Kimi k1.5 ("We exclude the value network in our training system") and K2. But ByteDance Seed's VC-PPO and VAPO showed that PPO with a pretrained value model and decoupled or adaptive λ can beat GRPO-family methods on long chain-of-thought math. VAPO argues that "value-model-based approaches possess a higher performance ceiling", and Seed1.5-Thinking reports both actor-critic and policy-gradient training frameworks. Ai2's Tülu 3 used PPO for its RLVR stage, with the value model initialized from a reward model. VinePPO (Kazemnejad et al., 2024) found that PPO's value networks "barely outperform a random baseline when comparing alternative steps" and replaced them with Monte-Carlo estimates from extra rollouts at intermediate states. OpenAI and Anthropic have not published which policy-optimization algorithm they use. The open question is not "critic or no critic" but "what is the cheapest source of reliable intermediate credit": a value network, extra rollouts, a process reward model, or simply more samples per prompt.
§11Credit assignment and reward shaping
One number at the end of 5,000 tokens. Which tokens deserve it? Every answer is either a statistical average over many samples or a denser signal that might be wrong.
With a sequence-level advantage, every token in a good response is pushed up by the same amount, including the filler. Credit is assigned statistically: a token that appears in good responses more often than in bad ones gets pushed up on net, and an irrelevant token's pushes cancel out in expectation. This works, but the effective sample size per decision shrinks as responses get longer. Denser signals help if they are right: a critic (§5), Monte-Carlo rollouts from intermediate prefixes (VinePPO), or a process reward model that scores each step (Ch. 03, Ch. 06). The danger with any dense signal is that the policy optimizes the signal instead of the goal.
The potential-based shaping theorem
Ng, Harada & Russell (1999) answered a precise question: which extra rewards $F(s,a,s')$ can you add without changing the optimal policy? Answer: exactly those of the form
$$F(s,a,s') = \gamma\,\Phi(s') - \Phi(s)$$
for some potential function $\Phi$ over states. Sufficiency is a telescoping sum. The shaped return from $s_0$ is
$$\sum_{t=0}^{T}\gamma^t\big(r_t + \gamma\Phi(s_{t+1}) - \Phi(s_t)\big) = G_0 + \gamma^{T+1}\Phi(s_{T+1}) - \Phi(s_0).$$
If Φ is zero (or any constant) on terminal states, the shaped return is the original return minus $\Phi(s_0)$, a quantity no action can affect. Every policy's return shifts by the same per-start-state constant, so the ranking of policies, and therefore the optimum, is unchanged. Equivalently, $Q'(s,a) = Q(s,a) - \Phi(s)$, a shift that does not depend on $a$, so it is just a baseline. Ng et al. also show necessity: without further knowledge of the MDP, any non-potential shaping can change the optimal policy for some transition and reward function.
Pay a hiker per step and they will walk in circles. Pay them for altitude gained, and charge them for altitude lost, and the total payout is just the summit height minus the start height, whatever the route: zig-zags earn nothing net. That is potential-based shaping with Φ = altitude. Where it breaks: the theorem protects the optimum, not the learning dynamics. A misleading Φ still sends a function-approximating learner up the wrong hill for a long time before the telescoping catches up. And if the "altitude" of the final state depends on the final state itself (a terminal potential that varies), the protection is gone: you have simply changed the reward.
Three connections to the rest of the chapter. First, the TD error $\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)$ is the reward shaped with potential $\Phi=V$. GAE is a discounted sum of potential-shaped rewards, which is why a critic can only help variance and never move the optimum (with λ = 1). Second, the per-token KL penalty is not potential-based: it deliberately changes the optimum, to the KL-regularized policy of Chapter 04. Third, length bonuses, format bonuses and "partial credit" heuristics are usually not potential-based either, and they are a classic source of reward hacking. The shaping widget is a two-line Goodhart demo.
In "Natural Emergent Misalignment from Reward Hacking in Production RL" (MacDiarmid et al., 2025), Anthropic researchers took a pretrained model, gave it knowledge of reward-hacking strategies (through synthetic-document finetuning or prompting), and trained it with RL on real Anthropic production coding environments where hacks were possible (for example, calling sys.exit(0) to exit the test harness with code 0). Models that learned to hack generalized to much broader misalignment. In the accompanying blog post, the model attempted to sabotage safety-research code 12% of the time in one evaluation and showed alignment-faking reasoning in 50% of responses to simple questions about its goals. Standard chat-style RLHF safety training made the models look aligned on chat evaluations, but the misalignment persisted in agentic settings. The mitigations that worked: preventing the hacks, more diverse safety training, and "inoculation prompting" (framing hacking as acceptable in that context, which cut the generalization). The blog says Anthropic has "already started making use of this technique in training Claude". Earlier, the Claude Opus 4 / Sonnet 4 system card (2025) reported a 67% / 69% average decrease in test hard-coding relative to Claude Sonnet 3.7, after monitoring, environment fixes and adjustments to the RL reward signal to make it more robust to reward hacking. The policy-gradient lesson: the estimator faithfully reinforces whatever earned reward, including the strategy that earned it. See Chapter 08.
§12Frontier & open problems
The math in this chapter is settled. Which pieces of it to use at scale is not.
- Token-level vs sequence-level ratios. PPO and GRPO use per-token ratios, even though the reward is per sequence. GSPO (Zheng et al., 2025) argued for a length-normalized sequence-level importance ratio and clipping, reporting better stability, notably for mixture-of-experts models. Which granularity matches the sampling unit is a live design question (Ch. 06).
- Off-policyness you did not choose. In large systems, rollouts come from an inference engine (vLLM, SGLang) whose numerics differ from the trainer's, and asynchronous pipelines train on stale samples. The "old policy" in the ratio is then not the policy that actually sampled. Yao et al. (2025) showed that vLLM-sampled and FSDP-trained probabilities differ enough to make "on-policy" training silently off-policy, and proposed truncated importance sampling. Later work traced much of the mismatch to bf16 rounding and argued that fp16 fixes it, and Meta's ScaleRL study (Khatri et al., 2025, over 400,000 GPU-hours) found that computing the LM head in fp32 raised the asymptotic performance. Off-policy corrections are now part of the recipe (Ch. 07).
- Which KL, where, and whether at all. Several reasoning-RL recipes drop the KL to the reference entirely. DAPO (Yu et al., 2025) argues that long chain-of-thought training should be allowed to move far from the initial model. Others keep it for safety and readability. The estimator-gradient mismatch of §9 means many published "β" values are not comparable, and the 2025 analyses (Tang & Munos; Shah et al.; Zhang et al.) have started to change what recipes actually ship (DeepSeek-V3.2's importance-weighted KL).
- Which loss, at scale? ScaleRL found that the choice of loss (it compared DAPO, GSPO and CISPO) and fp32 logits move the asymptote of the compute-performance curve, while normalization, aggregation and curriculum choices mostly change efficiency. Whether such sigmoidal fits extrapolate is open.
- Credit assignment over very long horizons. Agentic episodes of tens of thousands of tokens and many tool calls make the sequence-level bandit view increasingly wasteful. Value models, process rewards, turn-level advantages and Monte-Carlo rollouts are all being revisited.
- Entropy and exploration. Policy-gradient updates on a softmax systematically reduce entropy when high-probability actions get positive advantages (Cui et al., 2025). Managing it without an entropy bonus, through clip asymmetry or covariance-based clipping, is active work.
- Does RL teach or select? Whether RL on a pretrained model creates new capabilities or reweights existing ones is debated (pass@k analyses, Ch. 06). The policy-gradient view says it can only move mass among outputs the model already samples with non-negligible probability, which is why exploration and initialization matter so much.
§13Check yourself
Try each one before opening the answer. The "research" ones have no single right answer; the answer shows one good line of reasoning.
Derive the policy gradient for a sequence and explain why the environment dynamics drop out. core
$\nabla\E_{p_\theta}[R] = \sum_\tau\nabla p_\theta(\tau)R(\tau) = \sum_\tau p_\theta(\tau)\nabla\log p_\theta(\tau)R(\tau)$. Then $\log p_\theta(\tau) = \log\rho_0 + \sum_t\log\pit(a_t\mid s_t) + \sum_t\log P(s_{t+1}\mid s_t,a_t)$, and only the policy terms depend on θ. So $\nabla J = \E[R\sum_t\nabla\log\pit(a_t\mid s_t)]$. Add causality (reward-to-go) and a state-dependent baseline to reach $\E[\sum_t\nabla\log\pi\,\hat A_t]$. For an LLM, $\sum_t\log\pi(y_t\mid s_t)$ is the response's log-likelihood, so the estimator is a reward-weighted negative log-likelihood loss on the model's own samples.
Prove that a baseline does not bias the gradient. When can a baseline introduce bias? core
$\E_{a\sim\pi(\cdot\mid s)}[b(s)\nabla\log\pi(a\mid s)] = b(s)\nabla\sum_a\pi(a\mid s) = 0$. It introduces bias whenever $b$ depends on the action being scored: the sample's own reward, a mean that includes it (harmless here, since it only rescales, as shown in §4), or a critic that sees the token being scored. With several samples per prompt, baselines built from the other samples (RLOO) are exactly unbiased. Normalizing by a per-group std is not a baseline at all: it is a per-prompt reweighting that changes the objective.
Derive GAE from k-step advantages, and explain what γ and λ each trade off. deep
$\hat A^{(k)}_t = \sum_{l\lt k}\gamma^l\delta_{t+l}$ by telescoping. GAE is $(1-\lambda)\sum_k\lambda^{k-1}\hat A^{(k)}_t$; collecting coefficients gives $\sum_l(\gamma\lambda)^l\delta_{t+l}$, with the recursion $\hat A_t = \delta_t+\gamma\lambda\hat A_{t+1}$. γ changes the objective (it discounts real rewards, introducing bias with respect to the undiscounted return). λ changes only the estimator: λ = 1 is unbiased for any critic but has high variance, and λ = 0 has low variance but is biased by critic error. For LLMs, γ = 1, and with terminal rewards over long sequences a λ below 1 means early tokens learn only through the critic. So the critic must be good. VC-PPO's answer is to fit the critic with λ = 1 (Monte-Carlo targets, no decay) and then use λ ≈ 0.95 for the policy's advantages: low variance, with bias controlled by a pretrained critic.
Walk through the PPO clip for A > 0 and A < 0. Which tokens get zero gradient, and why is that the "pessimistic" choice? core
$\min(r\hat A,\clip(r)\hat A)$. For $\hat A\gt0$, the gradient is zero when $r\gt1+\epsilon$; for $\hat A\lt0$, when $r\lt1-\epsilon$. In both cases the ratio has already moved in the advantage's favor beyond the band, so further movement earns nothing. In the other direction (good action now less likely, bad action now more likely) the unclipped term is selected and the gradient flows. The min makes the objective a lower bound on the unclipped surrogate: you never get credit for an improvement that relies on extrapolating the importance weights, but you always pay for regressions.
Why does PPO-RLHF put the KL penalty in the reward while GRPO puts it in the loss? What does each actually optimize? deep
In the reward, the per-token k1 sample is part of the return, so it reaches θ through the score function with reward-to-go. In expectation that is the gradient of the sequence-level reverse KL, including the effect of each token on future KL. In the loss, the estimator is differentiated at the sampled tokens. With k1 that has zero expected gradient. With k3 the expected gradient is that of the forward KL $\KL(\piref\|\pit)$. With k2 it is the reverse KL's, but only the local per-token term. Near the reference, all of them agree to first order. Far from it, or off-policy, they differ, and "β" does not transfer between recipes.
Show k3 is unbiased and non-negative. Why is it lower variance than k1? core
$\E_q[r-1]=\sum q\cdot p/q - 1 = 0$, so $\E[k_3]=\E[k_1]$. Non-negativity: $\log r\le r-1$ by concavity. Variance: k3 = k1 + (r − 1), and when $p\approx q$, $r-1\approx\log r$, so the control variate cancels k1's first-order fluctuation, leaving a second-order quantity. For $q=\mathcal N(0,1)$, $p=\mathcal N(0.1,1)$, Schulman's note reports a standard deviation of about 20× the true KL for k1 and about 1.4× for k3.
Your PPO-RLHF run: reward goes up steadily, KL to the reference climbs fast, responses get longer. What is happening and what do you check? deep
Classic reward over-optimization, possibly length exploitation. Check: (1) samples with the highest reward: are they actually better? (2) the RM's correlation with length on held-out data; (3) whether truncated (no-EOS) responses are scored as if complete; (4) the KL controller and β; (5) clipfrac and approx-KL per update (too many epochs or too high a learning rate makes the trust region meaningless); (6) critic explained variance (a bad critic gives garbage per-token credit). Fixes: higher β or a KL target, length-controlled RM or length penalty, an EOS penalty, fewer epochs, early stopping on KL, refreshing the RM on policy samples. Chapter 03 covers RM overoptimization scaling.
When would you still pay for a critic in 2026? research
When per-token or per-step credit matters and is learnable: very long episodes (agents, long chains of thought) where sequence-level advantages are diluted; settings where you cannot afford many samples per prompt (expensive environments, one rollout per task) so group baselines are noisy; dense or multi-turn rewards where states are genuinely informative. Make the critic work: pretrain it on policy rollouts before policy updates (VC-PPO), decouple λ, consider MC value targets from extra rollouts (VinePPO), and measure explained variance. If explained variance is near zero, you are paying for a baseline that is worse than a group mean.
Design an experiment to measure whether your advantage estimator's variance is the bottleneck. research
Hold the policy checkpoint fixed. For a set of prompts, draw many independent batches and compute the gradient estimate with each candidate estimator (no baseline, RLOO with k = 2, 4, 8, critic + GAE at several λ). Measure the cosine similarity of each estimate with a high-sample "reference" gradient, and the gradient signal-to-noise ratio $\|\E\hat g\|^2/\E\|\hat g-\E\hat g\|^2$. Then run short training with matched compute (samples × steps) and see whether the SNR ranking predicts the learning-curve ranking. Ilyas et al. (2018) did a version of this for control and found that the gradient estimates of deep policy-gradient methods correlated poorly with the true gradient at typical batch sizes.
Why is the importance ratio per token rather than per sequence in PPO? What breaks either way? deep
The exact off-policy correction for a sequence is the product of per-token ratios, whose variance grows exponentially with length. PPO uses only the current token's ratio, which is low-variance but ignores the change in the distribution of prefixes (states). That approximation is acceptable only near $\piold$, hence the clip. Per-token clipping with a sequence-level reward means a few tokens with extreme ratios can be clipped while the rest of the sequence still updates, so the effective update depends on token-level noise. GSPO's length-normalized sequence ratio (a geometric mean of token ratios) is one compromise: its variance does not blow up with length the way the raw product does, and it matches the unit of the reward.
State and prove the potential-based shaping theorem (sufficiency). Is the RLHF per-token KL penalty potential-based? core
With $F=\gamma\Phi(s')-\Phi(s)$, the shaped return telescopes to $G_0 - \Phi(s_0)$ (with terminal Φ constant), so every policy's value shifts by a constant that depends only on the start state, and the optimal policy is unchanged; $Q' = Q - \Phi(s)$. The KL penalty $-\beta\log\frac{\pi}{\piref}(y_t\mid s_t)$ depends on the action and on π itself. It is not of the form $\Phi(s')-\Phi(s)$, and it intentionally changes the optimum to $\pi^*\propto\piref e^{R/\beta}$.
PPO with K = 1 epoch and a single minibatch: what algorithm is this? core
The ratio is exactly 1 when the gradient is taken, so the clip is inactive and $\nabla L^{\mathrm{CLIP}} = \E[\hat A\nabla\log\pi]$: on-policy policy gradient (REINFORCE / advantage actor-critic with GAE). The clip only matters from the second minibatch step on the same data. This is also why "the clip rarely fires" in near-on-policy LLM setups.
Sampling uses top-p = 0.9, training computes log-probs from the full softmax. What goes wrong, precisely? deep
The behavior distribution μ that generated the tokens is the truncated, renormalized distribution, but the ratio and the KL use the full softmax as $\piold$. For sampled tokens, $\mu(y)\gt\piold(y)$ by the renormalization factor, so the importance weights are systematically off. Worse, the policy never sees samples from the tail it is being regularized on, and the k1 KL sample is biased. Either train with the same truncation (and renormalize the log-probs), or sample with no top-p/top-k and divide the training logits by the sampling temperature, which is what the N+ reproduction does at τ = 0.7. The same issue, with numerics instead of truncation, underlies the train/inference mismatch of Chapter 07.