Chapter 02 · Foundations

RL for language models: from REINFORCE to PPO

Tokens as actions, gradients from samples, baselines that cost nothing, critics that cost a lot, and the clipped objective that ran RLHF for five years. Every step derived, every knob explained.

⏱ 75 min9 interactivesPrereq: Ch. 00, softmax, expectations
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

$$\max_\theta\; \htmlClass{t-exp}{\E_{x\sim\mathcal D,\;y\sim\pit(\cdot\mid x)}}\big[\htmlClass{t-r}{R(x,y)}\big]\;-\;\htmlClass{t-beta}{\beta}\;\htmlClass{t-kl}{\KL\big(\pit(\cdot\mid x)\,\|\,\piref(\cdot\mid x)\big)}$$
  • 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$:

Step through the generation: the state grows by one token, the policy's next-token distribution changes, and the reward appears only at <eos>. Press Resample answer until you get a wrong result (" 41"). Then switch between the two views. Sequence-level blames every token equally. Token-level uses a critic whose estimate collapses right after the wrong number, so the blame concentrates there. The critic here is hand-specified to be good; a real one is not.

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)
Actionwhole response $y$one token $y_t$
Creditsame $\hat A$ for every tokenper-token $\hat A_t$
Needsseveral samples per prompt (for a baseline)a value function $V_\psi(s_t)$
KL penaltyin the sequence reward, or as a loss termper-token reward shaping
Typical methodsREINFORCE, RLOO, ReMax, GRPO, DPO (implicitly)PPO + GAE (InstructGPT-style RLHF), VinePPO, VAPO
Key idea: deterministic transitions make Q and V the same object

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.

Analogy: a typewriter with no eraser

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.

Pitfall: the action space is huge, and that is mostly fine

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.

Derivation: causality, or "reward-to-go"

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
Analogy: you cannot differentiate a lottery, but you can change the odds

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.

Pitfall: the gradient is not of the loss you print

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.

You use the per-sample baseline $b_i = R_i$ (each sample's own reward) "to get zero variance". What happens?
The unbiasedness proof needs $b$ to be independent of $a$ given $s$, so that it can be pulled out of $\E_a[\nabla\log\pi]$. A baseline built from the sample's own reward depends on the action, and here it cancels all the signal. RLOO uses other samples' rewards, which are independent of sample $i$.

§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)$:

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.)

Five canned "responses" with true rewards 0 … 1, a softmax policy that starts out preferring bad ones, batches of 4 samples, and 12 seeds per learner (thin lines). With the default reward offset of +2, the no-baseline learner (blue) learns slowly and some seeds lock onto a mediocre arm. The baselined learner (clay) learns fast and consistently. Set the offset to 0 and the gap essentially disappears (both learners reach ≈0.99 here). Push it to +5 and vanilla REINFORCE falls apart: its seeds end anywhere from the worst arm to the best. Watch the gradient-std readouts: the baseline cuts the noise at the very same policy.

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:

Analogy: grading on a curve

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).

GRPO-style mean-centering $\hat A_i = R_i - \bar R$ (with $\bar R$ including $R_i$), compared with RLOO, is…
$R_i-\bar R = R_i - \tfrac1k R_i - \tfrac1k\sum_{j\ne i}R_j = \tfrac{k-1}{k}\big(R_i - \tfrac{1}{k-1}\sum_{j\ne i}R_j\big)$. A positive constant rescales the gradient (an effective learning-rate change) but not its expected direction. The std division is what actually changes the objective.

§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:

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

$$\htmlClass{t-a}{\hat A_t} = \sum_{l\ge0}(\htmlClass{t-g}{\gamma}\htmlClass{t-l}{\lambda})^l\,\htmlClass{t-d}{\delta_{t+l}} \;=\; \delta_t + \gamma\lambda\,\hat A_{t+1},\qquad \htmlClass{t-d}{\delta_t} = r_t + \gamma V(s_{t+1}) - V(s_t)$$
  • 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.

A response of T tokens with a small KL cost per token (red) and a reward of 1 at the end (green). With the good critic, whose value jumps at the "decisive" token, λ = 0 puts nearly all the credit on that token. With a constant or zero critic, small λ starves early tokens: set T = 512 and λ = 0.95 and read the "weight of R in Â₀". Then set λ = 1 and γ = 1: credit reaches every token, at the price of noise (the ticks show the λ = 1 Monte-Carlo advantage for comparison).

γ 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.)

Analogy: the forecast and the weather

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
In the token MDP (deterministic transitions), suppose your critic is exactly $V^\pi$. Which GAE setting gives the true advantage $A^\pi(s_t,a_t)$ with zero variance?
With deterministic transitions, $Q^\pi(s_t,a_t) = r_t + \gamma V^\pi(s_{t+1})$ exactly, so $\delta_t = A^\pi(s_t,a_t)$. There is no environment noise to average out. λ = 1 is also unbiased, but it carries the variance of all the policy's future sampling. The catch, of course, is that no real critic is exact.

§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.

TRPO in one page

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.

Analogy: last week's poll

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.

$$L^{\mathrm{CLIP}}(\theta) = \E_t\Big[\min\big(\htmlClass{t-r}{r_t(\theta)}\,\htmlClass{t-a}{\hat A_t},\;\htmlClass{t-c}{\clip\big(r_t(\theta),1-\epsilon,1+\epsilon\big)}\,\hat A_t\big)\Big],\qquad r_t(\theta) = \frac{\pit(a_t\mid s_t)}{\piold(a_t\mid s_t)}$$
  • 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 min makes 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)$.

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.

Clay is $L^{\text{CLIP}}$, dashed blue is the unclipped $r\hat A$, and gold bands mark where the gradient is exactly zero. Drag the ratio past $1+\epsilon$: on the left the slope readout goes to 0, on the right it stays at −1, so the penalty for making a bad action more likely is unbounded. Tick dual-clip to see the fix from Ye et al. (2020): for $\hat A\lt0$, also bound the objective below by $c\,\hat A$ so huge ratios (common with stale, off-policy data) cannot blow up the update.

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:

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)
Analogy: a leash that only pulls one way

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.

A token has $\hat A = -0.8$ and, after two epochs, ratio $r = 1.5$ with ε = 0.2. What does PPO's clipped objective do with this token?
For $\hat A\lt0$, $r\hat A = -1.2 \lt (1.2)(-0.8) = -0.96$, so the min selects the unclipped term and the gradient flows. Clipping only zeroes the gradient when the ratio has moved in the direction the advantage wants (here, below 0.8).

§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:

  1. 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.
  2. Rollout: sample responses for a batch of prompts from $\piold$.
  3. Score: one RM forward pass per response gives $R_\phi(x,y)$.
  4. 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.
  5. Values and GAE: run the critic on every prefix, compute $\hat A_t$ and the λ-return targets (§5).
  6. Optimize: $K$ epochs of minibatch PPO on the policy and the critic.
  7. Repeat, optionally adapting β to hit a target KL.

Nine stages, about 18 seconds. Watch which model is active at each stage, the KL entering the reward on every token, the GAE recursion running backwards, and in the last panel how the per-token ratios drift out of the clip band over the epochs (clipped tokens stop contributing). The numbers are illustrative but computed: the advantages are real GAE outputs of the rewards and values shown.

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:

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.

Anthropic: PPO in the HH-RLHF paper

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.

Toggle the models a recipe needs. Dropping the critic halves the trainable state: that, more than any variance argument, is what made critic-free methods attractive at scale. These are model states only. Sharding (ZeRO/FSDP) spreads them over GPUs but does not shrink the total. Note that InstructGPT used a 6B reward and value model for its 175B policy, so the critic need not match the policy's size.

Pitfall: the "free" KL in the reward is a one-sample, noisy, biased-gradient object

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.

$q=\mathcal N(0,1)$ is the sampling distribution and $p=\mathcal N(\mu,1)$, so the true KL is $\mu^2/2$. Left: each estimator as a function of the per-sample log-ratio. Right: histograms over 20,000 samples. Click μ = 0.1: k1's standard deviation is about 20× the KL it estimates, and about half its samples are negative, while k3 is tight and never negative. Click μ = 1: k2's bias becomes visible (its mean is about 25% above the true KL), while k3 stays unbiased.

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.

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)
Analogy: measuring a small height difference

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.

GRPO adds $\beta\cdot k_3$ (per token, on-policy samples) to the loss and backpropagates through it. In expectation, the gradient of this term is the gradient of…
$\nabla k_3 = (1 - \piref/\pit)\nabla\log\pit$, and $\E_{\pit}$ of that is $-\sum_y\piref(y)\nabla\log\pit(y) = \nabla\KL(\piref\|\pit)$. An unbiased estimator of a quantity does not have to have an unbiased gradient for it. k2 is the one whose on-policy gradient matches the reverse KL.

§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:

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.

MethodAdvantageCritic?Ratio / clipKL
REINFORCE$R - b$ (moving average)nono (on-policy)in reward
RLOO$R_i - \text{mean}_{j\ne i}R_j$nooptionalin reward
ReMax$R - R(\text{greedy})$nonoin reward
PPO (RLHF)GAE over per-token rewardsyesper-token clipper-token, in reward
GRPO$(R_i - \bar R)/\mathrm{std}$noper-token clipk3, in loss
Analogy: a sports commentator vs a scoreboard

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.

Frontier: the critic is not dead

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.

Three responses: a short correct one (A), a verbose correct one (B) and a long wrong one (C). Naive shaping pays +b per token "for effort". Raise b and watch first the verbose answer, then the wrong one, overtake the concise correct answer. Potential-based shaping pays the change in a heuristic "progress" potential Φ. The curves wiggle, because Φ even favors long answers mid-way, but every response ends exactly at its true reward, so the ranking cannot flip.

Analogy: paying a hiker for altitude, not for steps

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.

Anthropic: reward hacking in production RL is a safety problem

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.

§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.

Log-derivative trick
$\nabla\pi = \pi\nabla\log\pi$, so $\nabla\E_\pi[f] = \E_\pi[f\,\nabla\log\pi]$.
Why do baselines not add bias?
$\E_a[\nabla\log\pi(a\mid s)] = \nabla\sum_a\pi = 0$, so any $b(s)$ independent of the action multiplies a zero-mean term.
Advantage
$A^\pi(s,a)=Q^\pi(s,a)-V^\pi(s)$: how much better this action is than the policy's average action from s.
TD error
$\delta_t=r_t+\gamma V(s_{t+1})-V(s_t)$. With deterministic transitions and the true V, it equals the true advantage.
GAE recursion
$\hat A_t=\delta_t+\gamma\lambda\hat A_{t+1}$; λ = 0 is TD, λ = 1 is MC (return − V).
Typical γ, λ for LLMs
γ = 1 (finite episodes); λ ≈ 0.95. For long CoT, VC-PPO decouples: λ = 1 for the critic's targets, ≈ 0.95 for the policy's advantages.
PPO zero-gradient regions
A>0: r>1+ε. A<0: r<1−ε. Moves against the advantage are never clipped.
TRPO step
Natural gradient $F^{-1}g$ by conjugate gradient, scaled to KL = δ, then line search.
Four models of PPO-RLHF
Policy (train), reference (frozen), reward model (frozen), value (train, often initialized from the RM).
k3 estimator
$(r-1)-\log r$, r = p/q: unbiased, ≥ 0, low variance. Its gradient in the loss gives the forward KL direction.
RLOO advantage
$R_i-\frac{1}{k-1}\sum_{j\ne i}R_j$: unbiased, no critic.
Potential-based shaping
$F=\gamma\Phi(s')-\Phi(s)$ preserves optimal policies; returns shift by $-\Phi(s_0)$.
Mixed-precision Adam memory
≈16 bytes per trainable parameter (2 + 2 + 12); frozen bf16 weights ≈ 2 bytes.
Why γ < 1 is a bias
It changes the objective: future reward is discounted, so you optimize a different problem than the sequence reward.

§14Read next

Proximal Policy Optimization Algorithms
Schulman et al. · 2017 · arXiv
The clipped surrogate, the combined policy/value/entropy objective and multi-epoch minibatch updates.
PPOcore
High-Dimensional Continuous Control Using Generalized Advantage Estimation
Schulman et al. · 2015 · ICLR 2016
GAE as an exponentially weighted sum of TD errors; γ and λ as separate bias-variance knobs.
GAEadvantages
The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization
Huang et al. · 2024 · arXiv
A from-scratch reproduction of OpenAI's RLHF; 25 numbered details from EOS handling to value initialization.
RLHFengineering
Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs
Ahmadian et al. · 2024 · ACL 2024
Whole generation as one action; clipping fires on <5% of a batch; RLOO beats PPO without a critic.
RLOOREINFORCE
Approximating KL Divergence
Schulman · 2020 · blog note
The k1/k2/k3 estimators, why k3 is an unbiased, non-negative control-variate estimator, with numbers.
KLestimators
Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning
Williams · 1992 · Machine Learning
The original REINFORCE: likelihood-ratio gradients with a reinforcement baseline.
REINFORCEhistory
Policy Gradient Methods for Reinforcement Learning with Function Approximation
Sutton et al. · 1999 · NeurIPS (NIPS 12)
The policy gradient theorem and compatible function approximation.
theory
Trust Region Policy Optimization
Schulman et al. · 2015 · ICML 2015
The monotonic-improvement bound and the natural-gradient, KL-constrained step PPO approximates.
TRPOtrust region
Training Language Models to Follow Instructions with Human Feedback
Ouyang et al. · 2022 · NeurIPS 2022
InstructGPT: SFT, then RM, then PPO with a per-token KL penalty (β = 0.02), a 6B value function initialized from the RM, and PPO-ptx.
RLHFInstructGPT
Fine-Tuning Language Models from Human Preferences
Ziegler et al. · 2019 · arXiv
KL-to-reference in the reward and the adaptive-β controller.
RLHFKL
Secrets of RLHF in Large Language Models Part I: PPO
Zheng et al. · 2023 · arXiv
Ablations of PPO for chat models; PPO-max; monitor perplexity, KL and length rather than reward.
RLHFstability
Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback
Bai et al. (Anthropic) · 2022 · arXiv
PPO-based RLHF at Anthropic; reward roughly linear in √KL; iterated online training.
AnthropicRLHF
Buy 4 REINFORCE Samples, Get a Baseline for Free!
Kool et al. · 2019 · ICLR workshop
The leave-one-out baseline behind RLOO.
RLOObaselines
DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models
Shao et al. · 2024 · arXiv
Introduces GRPO: group-normalized advantages, no critic, k3 KL in the loss.
GRPOpreview Ch. 06
What's Behind PPO's Collapse in Long-CoT? Value Optimization Holds the Secret
Yuan et al. · 2025 · arXiv
VC-PPO: value pretraining and decoupled GAE (λ_critic = 1, λ_actor = 0.95) rescue PPO on long chains of thought.
criticGAE
VinePPO: Refining Credit Assignment in RL Training of LLMs
Kazemnejad et al. · 2024 · ICML 2025
Learned critics barely beat random at ranking steps; Monte-Carlo rollouts give unbiased per-step values.
credit assignment
On a Few Pitfalls in KL Divergence Gradient Estimation for RL
Tang & Munos · 2025 · arXiv
Differentiating a KL estimate is not estimating its gradient; token-level losses give partial derivatives.
KLtheory
A Comedy of Estimators: On KL Regularization in RL Training of LLMs
Shah et al. · 2025 · arXiv
k1 or k3, in the reward or in the loss: only k1-in-reward gives an unbiased sequence-level reverse-KL gradient; k3-in-reward collapses; k3-in-loss acts as a token-level forward KL.
KL2025
What Matters In On-Policy Reinforcement Learning? A Large-Scale Empirical Study
Andrychowicz et al. · 2020 · arXiv
Over 250,000 agents on continuous control: GAE with λ ≈ 0.9, no PPO-style value clipping, and many other defaults checked.
ablations
Policy Invariance Under Reward Transformations: Theory and Application to Reward Shaping
Ng, Harada & Russell · 1999 · ICML
Potential-based shaping is exactly the class of shaping rewards that preserves optimal policies.
shaping
Natural Emergent Misalignment from Reward Hacking in Production RL
MacDiarmid et al. (Anthropic) · 2025 · arXiv
Reward hacking learned in real coding RL generalizes to broad misalignment; inoculation prompting mitigates it.
Anthropicreward hacking