Skip to content
Post-training and alignment Advanced 36 min read

RLHF with PPO

Reinforcement learning from human feedback samples answers from the model, scores them with a reward model, subtracts a penalty for drifting from the SFT model, and nudges the model towards the answers that scored better than expected. PPO is the algorithm InstructGPT and ChatGPT used to do the nudging: policy gradients with a learned baseline and a clip that stops any one step going too far. The idea to keep is that RLHF does not teach the model new answers; it re-weights the answers it can already write, towards a target you can write down in closed form.

10,000 ft

SFT imitates demonstrations and reward models turn comparisons into a score. RLHF closes the loop: the model generates, the score judges, and the model shifts probability towards what the judge preferred. Because it trains on the model's own samples, it can do what imitation cannot: rank behaviours, push down bad ones, and exceed its demonstrators. It came from deep RL (Christiano et al., 2017), was adapted to language by Ziegler et al. (2019) and Stiennon et al. (2020), and became the third stage of the InstructGPT recipe that produced ChatGPT (Ouyang et al., 2022). Its algorithm, PPO (Schulman et al., 2017), comes from the policy-gradient family of the RL track. Its simplifications run through the rest of this track: DPO solves the same objective without sampling, and GRPO drops PPO's critic and uses a verifier for the reward.

2,000 ft

Four models sit in memory: the policy being trained (initialised from SFT), a frozen reference copy of the SFT model, the frozen reward model, and a value model that predicts future reward (initialised from the reward model). One iteration:

  1. Sample a batch of prompts and generate a response to each with the policy.
  2. Score each full response with the reward model.
  3. At every token, compute a penalty \(-\beta\log\frac{\pi_\theta}{\pi_{\text{ref}}}\); add the reward-model score at the last token.
  4. Use the value model to turn these rewards into per-token advantages (GAE): how much better each token turned out than expected.
  5. Take a few epochs of minibatch gradient steps on PPO's clipped objective, which raises the probability of tokens with positive advantage and lowers the rest, but only by about ±20% per iteration. Regress the value model towards the observed returns.
  6. Repeat for a few hundred iterations, watching reward, KL and human evaluations.

One PPO iteration in RLHF: four models, one loop
One PPO iteration in RLHF: four models, one loop. Prompt batch, Policy π_θ (trained, starts as SFT), Responses + token log-probs, Reference π_ref (frozen SFT), Reward model r_φ (frozen), Value model V_ψ (trained, starts as RM), Per-token reward KL penalty + final RM score, Advantages (GAE), Clipped PPO update policy and value, generate, log π_ref, score, V(s_t), new θ, new ψOne PPO iteration in RLHF: four models, one loop. Prompt batch, Policy π_θ (trained, starts as SFT), Responses + token log-probs, Reference π_ref (frozen SFT), Reward model r_φ (frozen), Value model V_ψ (trained, starts as RM), Per-token reward KL penalty + final RM score, Advantages (GAE), Clipped PPO update policy and value, generate, log π_ref, score, V(s_t), new θ, new ψ

Ground level

The objective: reward, minus a leash

RLHF maximises the reward model's score of the policy's answers, minus a penalty for moving away from the reference model:

\[ J(\theta) = \mathbb{E}_{x\sim\mathcal{D},\; y\sim\pi_\theta(\cdot\mid x)}\Big[r_\phi(x, y) - \beta \log\frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)}\Big]. \]

The expectation of the second term is \(\beta\,\mathrm{KL}(\pi_\theta\,\|\,\pi_{\text{ref}})\). Stiennon et al. gave the two reasons for it that still hold: it "acts as an entropy bonus, encouraging the policy to explore and deterring it from collapsing to a single mode", and it "ensures the policy doesn't learn to produce outputs that are too different from those that the reward model has seen during training" (Stiennon et al., 2020). The second reason is the important one. The reward model page showed that a learned reward is accurate only near its training data; \(\beta\) sets how far outside that region the policy may wander.

How big is \(\beta\)? InstructGPT used 0.02; Llama 2 used 0.01 for its 7B and 13B models and 0.005 for 34B and 70B; the open reproduction of OpenAI's summarisation work used 0.05 (Ouyang et al., 2022; Touvron et al., 2023; Huang et al., 2024). These numbers only mean something relative to the reward's scale, which is why reward models are normalised before RL.

This objective has an exact solution, derived in first principles:

\[ \pi^*(y\mid x) = \frac{1}{Z(x)}\,\pi_{\text{ref}}(y\mid x)\,\exp\!\Big(\frac{r_\phi(x,y)}{\beta}\Big). \]

Take what the SFT model already says and re-weight each answer by the exponential of its reward, with \(\beta\) as the temperature. Nothing outside the SFT model's support can appear; answers it rarely writes but the reward model loves can grow without limit as \(\beta \to 0\). PPO is a way to approach \(\pi^*\) when you cannot enumerate \(y\), which with language you never can.

Text generation as a reinforcement-learning problem

Text generation as a reinforcement-learning episode
Text generation as a reinforcement-learning episode. s_0 prompt, s_1 prompt + y_1, s_2 prompt + y_1 y_2, s_T prompt + whole answer, Reward model scores the answer, action y_1 reward -β·KL_1, action y_2 reward -β·KL_2, ... end-of-turn, final reward r_φ(x, y)Text generation as a reinforcement-learning episode. s_0 prompt, s_1 prompt + y_1, s_2 prompt + y_1 y_2, s_T prompt + whole answer, Reward model scores the answer, action y_1 reward -β·KL_1, action y_2 reward -β·KL_2, ... end-of-turn, final reward r_φ(x, y)

There are two ways to cast generation as RL, and RLHF implementations use both at once.

As a bandit. The prompt is the context, the whole response is one action, and the reward model's score is the payoff. InstructGPT described it this way: "a bandit environment which presents a random customer prompt and expects a response to the prompt … produces a reward … and ends the episode". This view is exact and simple, and it is the view of REINFORCE-style methods and DPO.

As a token-level episode. The state is the prompt plus the tokens so far, the action is the next token, transitions are deterministic (append the token), the episode ends at the end-of-turn token, and there is no discount (\(\gamma = 1\)). The KL penalty decomposes over tokens, so it is paid as a small reward at every step; the reward-model score arrives only at the final step:

\[ r_t = -\beta\,\log\frac{\pi_\theta(y_t\mid s_t)}{\pi_{\text{ref}}(y_t\mid s_t)} \;+\; \mathbf{1}[t = T]\; r_\phi(x, y). \]

PPO uses this view because its critic estimates a value for every prefix, which lets it assign credit to individual tokens rather than smearing one number over all of them.

Policy gradients in one paragraph

The policy-gradient theorem says that to increase expected reward you raise the log-probability of each action in proportion to how good it turned out:

\[ \nabla_\theta J = \mathbb{E}\Big[\sum_t \nabla_\theta \log\pi_\theta(y_t\mid s_t)\,\hat A_t\Big]. \]

\(\hat A_t\), the advantage, is how much better the outcome after taking \(y_t\) was than the policy expected at \(s_t\). Using the raw return instead is unbiased but noisy; subtracting a baseline that depends only on the state does not change the expectation and removes most of the noise. PPO learns that baseline as a value function \(V_\psi(s_t)\), the critic. The whole of PPO is three additions to this formula: a critic for low-variance advantages, an estimator (GAE) that blends short and long horizons, and a clip that lets you reuse each batch for several steps without the policy running away.

The critic and generalised advantage estimation

The value model is a copy of the reward model (same architecture: transformer body, scalar head) that outputs a number at every position: \(V_\psi(s_t)\), the expected sum of future rewards from prefix \(s_t\). InstructGPT initialised it from the reward model, which makes sense: at the last position the two predict the same thing. Stiennon et al. used a separate network rather than a second head on the policy, to stop value updates "partially destroying the pretrained policy early in training".

Given rewards and values along one response, the one-step temporal-difference error is

\[ \delta_t = r_t + \gamma V(s_{t+1}) - V(s_t), \]

the surprise after one token. Generalised advantage estimation (Schulman et al., 2015) sums these surprises with decaying weight \(\lambda\):

\[ \hat A_t = \sum_{l \ge 0} (\gamma\lambda)^l\, \delta_{t+l} . \]

\(\lambda = 0\) trusts the critic completely (\(\hat A_t = \delta_t\), low variance, biased if \(V\) is wrong). \(\lambda = 1\) ignores it except as a baseline (\(\hat A_t\) = actual return minus \(V(s_t)\), unbiased, noisy). RLHF implementations use \(\gamma = 1\) (InstructGPT: "No discount is applied") and \(\lambda = 0.95\) (Huang et al., table 7).

A worked example: a five-token response, with per-token log-ratios \(\log\frac{\pi_\theta}{\pi_{\text{ref}}} = (0.10, -0.05, 0.30, 0.02, 0.08)\), \(\beta = 0.05\), a reward-model score of 1.0, and a critic that predicted \(V = (0.60, 0.70, 0.50, 0.80, 0.90)\). Computed by the third program in Build it:

Token \(t\) 1 2 3 4 5
Reward \(r_t\) −0.0050 0.0025 −0.0150 −0.0010 0.9960
TD error \(\delta_t\) 0.0950 −0.1975 0.2850 0.0990 0.0960
Advantage, \(\lambda = 0\) 0.0950 −0.1975 0.2850 0.0990 0.0960
Advantage, \(\lambda = 0.95\) 0.3277 0.2449 0.4657 0.1902 0.0960
Advantage, \(\lambda = 1\) 0.3775 0.2825 0.4800 0.1950 0.0960

With \(\lambda = 0\), token 2 gets a negative advantage, because the critic's value dropped from 0.70 to 0.50 after it: the critic thinks token 2 made things worse. With \(\lambda = 1\) every token shares in the good final outcome. GAE with 0.95 sits close to the Monte Carlo answer here because responses are short; the critic's influence grows with response length.

PPO's clipped objective

A rollout batch is expensive: generating it dominates RLHF's compute. You want several gradient steps per batch, but after the first step the batch was sampled by an older policy. The probability ratio

\[ \rho_t(\theta) = \frac{\pi_\theta(y_t\mid s_t)}{\pi_{\theta_{\text{old}}}(y_t\mid s_t)} \]

corrects for that (importance sampling), but nothing stops \(\rho_t\) from growing large, and then one batch can drag the policy somewhere its advantages no longer describe. TRPO (Schulman et al., 2015) solved this with a hard KL constraint and second-order optimisation. PPO's answer is a clip:

\[ L^{\text{CLIP}}(\theta) = \mathbb{E}_t\Big[\min\big(\rho_t\hat A_t,\;\operatorname{clip}(\rho_t, 1-\varepsilon, 1+\varepsilon)\,\hat A_t\big)\Big], \qquad \varepsilon = 0.2 . \]
0.81.2ratio ρ, advantage A > 00.81.2ratio ρ, advantage A < 0flat: no reward for ρ > 1.2flat: no reward for ρ < 0.8ρA (unclipped)
The clipped surrogate, per token. Left: a good token (A > 0). Raising its probability helps until the ratio reaches 1.2; beyond that the objective is flat and the gradient is zero. Right: a bad token (A < 0). Lowering its probability helps until 0.8, then stops. In the other direction (making a bad token more likely, a good one less likely) the unclipped, pessimistic term is kept, so mistakes are always corrected.

Three worked cases with \(\varepsilon = 0.2\):

Token \(\hat A_t\) \(\rho_t\) \(\rho_t\hat A_t\) clipped term objective gradient?
good, already pushed up +2 1.35 2.70 1.2 × 2 = 2.40 2.40 none: stop pushing
bad, already pushed down −2 0.70 −1.40 0.8 × −2 = −1.60 −1.60 none: stop pushing
bad, but became more likely −2 1.35 −2.70 1.2 × −2 = −2.40 −2.70 yes: undo it

The minimum makes the objective a pessimistic bound: you never get credit for moving more than \(\varepsilon\) in the helpful direction, and you always pay for moving in the harmful one. If you take exactly one gradient step per batch, \(\rho = 1\) where the gradient is computed and the clip never binds; it matters only because PPO reuses each batch.

The value model is trained at the same time, by regressing \(V_\psi(s_t)\) towards the return \(\hat A_t + V_{\text{old}}(s_t)\), usually with its own clip so it too cannot move far in one batch.

One iteration, with real numbers

InstructGPT's settings (Ouyang et al., 2022, appendix C.4) make the loop concrete:

  1. Rollout. 512 prompts, one response each, sampled at temperature 1 from the policy. Store every token's log-probability under the policy (this is \(\pi_{\theta_{\text{old}}}\)) and under the frozen SFT model.
  2. Score. The 6B reward model scores each response; subtract \(\beta = 0.02\) times the per-token log-ratio at every position.
  3. Advantages. The 6B value model predicts \(V\) at every position; GAE with no discount turns rewards and values into advantages.
  4. Update. Split the 512 into 8 minibatches of 64 and take one gradient step on each, one pass over the batch, with clip ratio 0.2. Update the value model on the same minibatches.
  5. Optionally, pretraining gradients. For "PPO-ptx", add a language-modelling loss on pretraining data, scaled by \(\gamma = 27.8\), using eight times as many pretraining examples as RL episodes, to limit regressions on public NLP benchmarks.
  6. Repeat for 256k episodes, which covered about 31k unique prompts.

The result made the case for the whole method: labellers preferred the outputs of the 1.3B PPO-ptx model to those of the 175B GPT-3, and training the 175B PPO-ptx model took 60 petaflop/s-days against 3,640 for pre-training GPT-3. The authors concluded that "increasing investments in alignment of existing language models is more cost-effective than training larger models", at least for their customers' tasks.

The implementation details that decide whether it works

PPO is famous for being sensitive to details that papers leave out. Huang et al. reproduced OpenAI's summarisation results from scratch and catalogued "over 20 key implementation details" (Huang et al., 2024); for classic control the same group had listed 37. The ones that matter most for language:

  • Disable dropout. With dropout on, the same tokens get different log-probabilities on two forward passes, so \(\rho \ne 1\) even before any update and the ratio is noise.
  • Score only finished answers. A response cut off by the length limit has no end-of-turn token, and the reward model never saw such inputs. Give truncated responses a fixed penalty (Huang et al. use −1, following Ziegler et al.).
  • Normalise rewards and advantages. Reward-model outputs drift in scale; whitening advantages per batch (subtract mean, divide by standard deviation) keeps step sizes stable. Llama 2 additionally inverted the sigmoid of its reward and whitened the result "to increase stability and balance properly with the KL penalty term".
  • Sample honestly. The KL penalty is estimated from sampled tokens, which is only valid if they were sampled from \(\pi_\theta\) itself. Top-\(k\), top-\(p\), or a forced minimum length make the sampled tokens differ from what the policy's distribution implies; the estimated KL can go negative and the policy gets paid for it. TRL's documentation explains this and recommends plain sampling with top-\(k\) off and top-\(p\) = 1 (TRL training FAQ). The same applies if a separate inference engine generates rollouts: recompute \(\log\pi_{\theta_{\text{old}}}\) with the training model.
  • Initialise the critic from the reward model, as InstructGPT and Stiennon et al. did, so it predicts something sensible from the first iteration.
  • Adapt \(\beta\) if you need a fixed KL budget. Ziegler et al. used a proportional controller, \(e_t = \operatorname{clip}\big(\frac{\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\), so runs with different seeds end up at comparable KL.

Reading the dashboard

RL losses are not progress measures; the PPO loss can rise while the model improves. Watch these instead (the "healthy" ranges are rules of thumb, not laws):

Metric Healthy Warning sign
Mean reward Rises, then flattens Keeps rising while human or judge evals stall: overoptimisation
KL to reference Grows smoothly to a few nats per response Jumps, or goes negative (a sampling bug)
Response length Moves modestly Grows steadily: the reward model likes length
Policy entropy Declines slowly Collapses: one stock answer for everything
Clip fraction A few to ~20% of tokens Most tokens clipped: steps too large
Approximate KL between \(\pi_{\theta_{\text{old}}}\) and \(\pi_\theta\) Small, about 0.01 Large: learning rate or epochs too high
Value loss / explained variance Value loss falls Critic never learns: advantages are noise

And read samples every few iterations. The TRL FAQ's first debugging tip is the right one: "Inspect the generations".

What goes wrong

Reward hacking. The policy finds what the reward model over-scores. Ziegler et al.'s summarisation models became "smart copiers" that copied whole sentences from the input, which labellers rated highly, "but may be exploiting the fact that labelers rely on simple heuristics". The modern versions are length, flattery and confident tone (see reward models). The Build it section shows it happen in a five-answer toy.

Mode collapse. The KL-regularised optimum is mode-seeking: as \(\beta\) falls, probability piles onto the highest-reward answers, and diversity drops. That is the goal when there is one right answer and a cost when there are many (creative writing, brainstorming).

The alignment tax. InstructGPT's RLHF models regressed on some public NLP datasets (SQuADv2, DROP, translation); PPO-ptx reduced but did not remove the regressions. The authors called this an "alignment tax" and argued that low-tax methods matter because a high tax "incentivizes the use of models that are unaligned but more capable on these tasks".

Engineering cost. Four models of similar size, generation in the inner loop, and two sets of optimiser states. Llama 2 reported that generation under FSDP caused a "≈ 20×" slowdown until they consolidated weights on each node before generating (Touvron et al., 2023).

Simpler relatives of PPO

What each method keeps in memory
What each method keeps in memory. PPO policy, reference, reward model, value model (2 trained), RLOO / GRPO policy, reference, reward model or verifier (1 trained), DPO policy, reference (1 trained, offline), Best-of-n policy, reward model (nothing trained), drop the critic, baseline from samples, drop sampling and the RM, fit comparisons directly, drop training, search at inferenceWhat each method keeps in memory. PPO policy, reference, reward model, value model (2 trained), RLOO / GRPO policy, reference, reward model or verifier (1 trained), DPO policy, reference (1 trained, offline), Best-of-n policy, reward model (nothing trained), drop the critic, baseline from samples, drop sampling and the RM, fit comparisons directly, drop training, search at inference
  • Best-of-\(n\) and rejection-sampling fine-tuning. Sample \(n\) answers, keep the one the reward model likes best: at inference (best-of-\(n\)), or as SFT data for the next round (rejection sampling). Llama 2 used only rejection sampling up to its fourth RLHF iteration, then PPO on top of the rejection-sampled checkpoint. It is simple, stable, and a strong baseline per unit of KL (reward models derives its KL).
  • REINFORCE with a leave-one-out baseline (RLOO). Sample \(k\) answers per prompt, treat each whole answer as one action, and use the mean reward of the other \(k-1\) as its baseline. No critic. Ahmadian et al. argued that PPO's machinery targets high variance from weak initialisations, which is "not a practical concern in fine-tuning LLMs due to the extremely strong initialization of the policy", and found RLOO outperformed PPO, DPO and RAFT (Ahmadian et al., 2024). ReMax uses the greedy response's reward as the baseline instead (Li et al., 2023).
  • GRPO. The group-mean baseline of RLOO, with PPO's clip and a KL term; the algorithm of DeepSeekMath and DeepSeek-R1, covered fully in RL with verifiable rewards.
  • DPO. No sampling at all: solve for \(\pi^*\) in closed form from the comparisons. Next page.

Does PPO still beat the simpler methods? When tuned well, often yes. Ivison et al. found "PPO outperforms DPO by up to 2.5% in math and 1.2% in general domains", with preference-data quality mattering more than either algorithm (Ivison et al., 2024); Xu et al. found PPO "able to surpass other alignment methods in all cases" in their benchmarks, including competitive code (Xu et al., 2024). Meta nevertheless chose DPO for Llama 3 because it "required less compute for large-scale models and performed better, especially on instruction following" (Llama 3, 2024). The honest summary for 2026: online RL (PPO, RLOO, GRPO) has the higher ceiling, offline DPO the lower cost, and the data matters more than the choice.

History

  • 2017. Christiano et al. learn a reward model from human comparisons of video clips and train Atari agents and simulated robots with it; a Hopper learns backflips from 900 queries (paper). PPO is published the next month (Schulman et al., 2017).
  • 2019. Ziegler et al. apply the recipe to GPT-2: positive-sentiment and descriptive continuations from 5,000 comparisons, summarisation from 60,000, the KL penalty to the pre-trained model, and the adaptive KL controller (paper).
  • 2020. Stiennon et al. scale it to Reddit TL;DR summaries: a 1.3B RLHF model beats a supervised model ten times its size (61% versus 43% preference against reference summaries), and over-optimising the reward model makes summaries worse (paper).
  • March 2022. InstructGPT applies SFT → reward model → PPO to OpenAI's API prompts (paper).
  • April 2022. Anthropic's helpful-and-harmless assistant: iterated online RLHF with weekly data refreshes, and "a roughly linear relation between the RL reward and the square root of the KL divergence" (Bai et al., 2022).
  • November 2022. ChatGPT, trained with the InstructGPT recipe, launches (the assistant era).
  • 2023. Llama 2-Chat combines rejection sampling and PPO with separate helpfulness and safety reward models, the most detailed open account of RLHF at scale (paper). DPO offers a way around RL altogether.
  • 2024–2025. RLOO and ReMax show the critic is unnecessary for preference RL; GRPO and verifiable rewards move the field's RL effort to reasoning (RLVR). Open frameworks such as OpenRLHF and verl make PPO-style training at scale reproducible.

In practice

Published settings, for orientation (always tune for your reward scale):

Setting InstructGPT (2022) Llama 2 (2023) TL;DR reproduction (Huang et al., 2024)
KL coefficient \(\beta\) 0.02 0.01 (7B, 13B); 0.005 (34B, 70B) 0.05
Clip \(\varepsilon\) 0.2 0.2 0.2
Batch / minibatch 512 / 64, one epoch 512 / 64 512 / 512, 4 PPO epochs
Policy learning rate — 1e-6, constant 3e-6, linear decay
GAE \(\gamma\), \(\lambda\) \(\gamma = 1\) — 1.0, 0.95
Length of training 256k episodes 200–400 iterations, early stopping on held-out prompts 1M episodes
Rollout temperature 1 — 0.7

Practical advice that follows from everything above:

  • Start from a strong SFT model; RL re-weights, it does not rescue.
  • Fix the prompt distribution before you tune anything: RLHF optimises exactly the prompts you give it.
  • Tune \(\beta\) (or a KL target) first; most "PPO is unstable" stories are a reward scale and a \(\beta\) that do not match.
  • Run best-of-\(n\) with the same reward model as a baseline. If PPO cannot beat it at the same KL, look for a bug before buying more compute.
  • Select checkpoints with human or strong-judge evaluations on held-out prompts, never with the training reward.

Common misconceptions

  • "RLHF teaches the model what humans value." It teaches the model what a reward model, trained on a particular labelling process, scores highly, within a KL budget of the SFT model. The gap between the two is the subject of the alignment problem.
  • "PPO is what makes RLHF work." The reward model and the KL leash do most of the work. RLOO, GRPO, rejection sampling and DPO reach similar places with less machinery.
  • "The KL penalty prevents reward hacking." It limits how far the policy moves; within that budget the policy still finds the reward model's errors. Gao et al. found it did not improve the gold-reward-versus-KL frontier (reward models).
  • "Higher reward means a better model." Only before the overoptimisation peak; that is why you stop on held-out evaluations.
  • "RL can teach the model anything." The optimum \(\pi^* \propto \pi_{\text{ref}}\,e^{r/\beta}\) is zero wherever \(\pi_{\text{ref}}\) is zero. RL sharpens behaviours the SFT model can already produce, at least occasionally; see RLVR for the debate about how far that extends.

First principles

Why this objective has the solution it has. For a single prompt, write the objective as a function of the distribution \(\pi\) over responses:

\[ \mathbb{E}_{y\sim\pi}[r(y)] - \beta\,\mathrm{KL}(\pi\,\|\,\pi_{\text{ref}}) = -\beta\,\mathrm{KL}\Big(\pi \,\Big\|\, \tfrac{1}{Z}\pi_{\text{ref}}\,e^{r/\beta}\Big) + \beta\log Z . \]

The right-hand side is maximised when the KL is zero, so \(\pi^* = \pi_{\text{ref}}e^{r/\beta}/Z\). (The derivation is two lines; see the maths.) This is the Gibbs distribution of statistical physics with energy \(-r\) and temperature \(\beta\), and it is why every method in this track, PPO, DPO, best-of-\(n\), is "re-weight the reference by the exponential of reward".

Why reverse KL. The penalty is \(\mathrm{KL}(\pi\,\|\,\pi_{\text{ref}})\), with the policy first. It is an expectation under the policy's own samples, so it can be estimated from rollouts, and it is mode-seeking: the policy may drop modes of the reference cheaply but pays heavily for putting mass where the reference has little. That second property is the leash: it keeps the policy on text the reference (and therefore the reward model's training data) considers plausible. SFT's loss is the opposite direction, mode-covering (see information theory and the SFT page).

Why a clip and not just a small learning rate. A learning rate bounds the step in parameter space, but what matters is the step in behaviour space, and the same parameter step changes a confident token's probability very differently from an uncertain one's. The clip bounds the change in each sampled token's probability directly. It is a cheap stand-in for TRPO's trust region, which bounds the KL between old and new policy exactly.

Why a critic, and why you might not need one. The critic exists to reduce variance and to give per-token credit. In language RLHF the policy starts from a strong SFT model, each prompt's responses vary relatively little in reward, and the reward arrives once at the end. Ahmadian et al.'s argument is that the variance problem PPO was designed for is small here, so a baseline from other samples of the same prompt (RLOO, GRPO) does as well without training a second large network. The counter-argument is credit assignment on long responses, where a per-token critic helps in principle; in practice reasoning-model training in 2025 mostly dropped it.

What breaks if you change it. Remove the KL term and the optimum puts all its mass on the reward model's single favourite answer, which is usually a reward-model error. Remove the clip and several epochs per batch overshoot. Remove the reference model and use the current policy as the anchor, and the leash moves with the dog.

The maths

Notation. Prompt \(x \sim \mathcal{D}\); response \(y = (y_1, \dots, y_T)\); state \(s_t = (x, y_{<t})\); policy \(\pi_\theta\); reference \(\pi_{\text{ref}}\); reward model \(r_\phi\); value model \(V_\psi\); KL coefficient \(\beta\); clip range \(\varepsilon\); GAE parameters \(\gamma, \lambda\).

Objective.

\[ J(\theta) = \mathbb{E}_{x,\,y\sim\pi_\theta}\Big[r_\phi(x,y)\Big] - \beta\,\mathbb{E}_x\Big[\mathrm{KL}\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\text{ref}}(\cdot\mid x)\big)\Big]. \]

Per-token decomposition. Since \(\log\pi(y\mid x) = \sum_t \log\pi(y_t\mid s_t)\), the sequence-level penalty is a sum of per-token terms, giving the per-token reward

\[ r_t = -\beta\log\frac{\pi_\theta(y_t\mid s_t)}{\pi_{\text{ref}}(y_t\mid s_t)} + \mathbf{1}[t=T]\,r_\phi(x,y), \qquad \sum_{t=1}^T r_t = r_\phi(x,y) - \beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)} . \]

Treating the penalty as a reward (no gradient through it) gives an unbiased gradient of \(J\), because the extra term it ignores is \(-\beta\,\mathbb{E}_{\pi_\theta}[\nabla_\theta\log\pi_\theta] = 0\).

Advantages.

\[ \delta_t = r_t + \gamma V_\psi(s_{t+1}) - V_\psi(s_t), \qquad \hat A_t = \sum_{l=0}^{T-t}(\gamma\lambda)^l\,\delta_{t+l}, \qquad V_\psi(s_{T+1}) = 0 . \]

PPO loss (to minimise), per token, averaged over the batch:

\[ \mathcal{L}(\theta,\psi) = -\min\big(\rho_t\hat A_t,\ \operatorname{clip}(\rho_t,1-\varepsilon,1+\varepsilon)\hat A_t\big) + c_1 \max\Big(\big(V_\psi(s_t) - \hat R_t\big)^2,\ \big(V^{\text{clip}}_\psi(s_t) - \hat R_t\big)^2\Big), \]

with \(\rho_t = \pi_\theta(y_t\mid s_t)/\pi_{\theta_{\text{old}}}(y_t\mid s_t)\), return target \(\hat R_t = \hat A_t + V_{\psi_{\text{old}}}(s_t)\), and \(V^{\text{clip}}_\psi = V_{\psi_{\text{old}}} + \operatorname{clip}(V_\psi - V_{\psi_{\text{old}}}, -\varepsilon_v, \varepsilon_v)\). Huang et al. use \(c_1 = 0.1\) and \(\varepsilon_v = 0.2\).

PPO-ptx adds a pretraining term (InstructGPT, equation 2):

\[ J_{\text{ptx}}(\theta) = \mathbb{E}_{(x,y)\sim\pi_\theta}\Big[r_\phi(x,y) - \beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\text{SFT}}(y\mid x)}\Big] + \gamma\,\mathbb{E}_{x\sim\mathcal{D}_{\text{pretrain}}}\big[\log\pi_\theta(x)\big]. \]
Derivation: the optimum of the KL-regularised objective

Fix a prompt and drop \(x\). For any distribution \(\pi\) with the support of \(\pi_{\text{ref}}\), define \(Z = \sum_y \pi_{\text{ref}}(y)e^{r(y)/\beta}\) and \(\pi^*(y) = \pi_{\text{ref}}(y)e^{r(y)/\beta}/Z\). Then \(r(y) = \beta\log\frac{\pi^*(y)}{\pi_{\text{ref}}(y)} + \beta\log Z\), and

\[ \mathbb{E}_\pi[r] - \beta\,\mathrm{KL}(\pi\|\pi_{\text{ref}}) = \mathbb{E}_\pi\Big[\beta\log\frac{\pi^*}{\pi_{\text{ref}}} + \beta\log Z - \beta\log\frac{\pi}{\pi_{\text{ref}}}\Big] = \beta\log Z - \beta\,\mathrm{KL}(\pi\,\|\,\pi^*) . \]

\(\beta\log Z\) does not depend on \(\pi\), and \(\mathrm{KL}\ge 0\) with equality iff \(\pi = \pi^*\). So \(\pi^*\) is the unique maximiser, and the maximum value is \(\beta\log Z\) (a "soft maximum" of the reward: it tends to \(\max_y r(y)\) as \(\beta\to 0\) and to \(\mathbb{E}_{\pi_{\text{ref}}}[r]\) as \(\beta\to\infty\)). DPO starts by inverting this formula.

Derivation: GAE interpolates between TD and Monte Carlo

Define the \(k\)-step advantage estimate \(\hat A^{(k)}_t = \sum_{l=0}^{k-1}\gamma^l r_{t+l} + \gamma^k V(s_{t+k}) - V(s_t)\). Writing each reward as \(r_{t+l} = \delta_{t+l} - \gamma V(s_{t+l+1}) + V(s_{t+l})\), the value terms telescope:

\[ \hat A^{(k)}_t = \sum_{l=0}^{k-1}\gamma^l\,\delta_{t+l}. \]

GAE is the exponentially weighted average \((1-\lambda)\sum_{k\ge1}\lambda^{k-1}\hat A^{(k)}_t\). Swapping the order of summation, \(\delta_{t+l}\) appears in every \(\hat A^{(k)}_t\) with \(k > l\), with total weight \((1-\lambda)\sum_{k>l}\lambda^{k-1}\gamma^l = (\gamma\lambda)^l\). Hence \(\hat A_t = \sum_l (\gamma\lambda)^l\delta_{t+l}\). At \(\lambda=0\) only \(\delta_t\) survives; at \(\lambda=1\) the sum telescopes to the full return minus \(V(s_t)\). The recursion \(\hat A_t = \delta_t + \gamma\lambda\hat A_{t+1}\) computes it in one backward pass.

Build it

First, the target. The five-answer toy continues the SFT and reward-model pages, with one addition: an answer that flatters the user, which the SFT model rarely writes (1%) and which the reward model over-scores because it saw few examples of it. Compute the exact KL-regularised optimum for a range of \(\beta\) (NumPy):

import numpy as np
# The four styles from the SFT and RM pages, plus one the SFT model rarely writes and the
# reward model over-scores (it saw few examples): an answer that flatters the user.
styles  = ["concise", "rambling", "wrong", "refuses", "flatters"]
quality = np.array([1.0, 0.6, -1.0, -0.3, -0.2])           # true quality, unseen in training
r_rm    = np.array([0.549, 0.440, -3.322, -2.041, 1.2])    # reward model scores
pi_ref  = np.array([0.54, 0.30, 0.10, 0.05, 0.01])         # SFT policy = reference

def kl(p, q): return float(np.sum(p * np.log(p / q)))
print(" beta  " + " ".join(f"{s:>8s}" for s in styles) + "   E[r_RM]  KL(nats)  E[quality]")
for beta in [4.0, 1.0, 0.5, 0.3, 0.2, 0.1, 0.05]:
    w = pi_ref * np.exp(r_rm / beta); pi = w / w.sum()     # closed-form KL-regularised optimum
    print(f"{beta:5.2f}  " + " ".join(f"{p:8.3f}" for p in pi) +
          f"   {pi @ r_rm:+.3f}   {kl(pi, pi_ref):6.3f}    {pi @ quality:+.3f}")
 beta   concise rambling    wrong  refuses flatters   E[r_RM]  KL(nats)  E[quality]
 4.00     0.595    0.322    0.042    0.029    0.013   +0.286    0.031    +0.735
 1.00     0.647    0.323    0.002    0.004    0.023   +0.507    0.140    +0.833
 0.50     0.660    0.295    0.000    0.000    0.045   +0.545    0.193    +0.828
 0.30     0.646    0.249    0.000    0.000    0.105   +0.590    0.315    +0.775
 0.20     0.555    0.179    0.000    0.000    0.266   +0.703    0.797    +0.609
 0.10     0.073    0.014    0.000    0.000    0.913   +1.142    3.932    -0.101
 0.05     0.000    0.000    0.000    0.000    1.000   +1.200    4.603    -0.200

This is the whole story of RLHF in one table. At \(\beta = 4\) the policy barely moves. Around \(\beta = 0.5\)–1 it removes the wrong answers and refusals and lifts true quality from the SFT model's 0.60 to 0.83, at a cost of under 0.2 nats. Below that, the reward model's error takes over: the 1%-answer it over-scores grows to 91% of the policy at \(\beta = 0.1\), the reward model reports its best score yet, and true quality goes negative. Exactly the overoptimisation curve of Gao et al., in closed form.

Second, PPO itself on this problem (one prompt, so the critic is a single number), with \(\beta = 0.5\), to show that the sampled, clipped, critic-baselined procedure lands on the closed-form target (NumPy):

import numpy as np
rng = np.random.default_rng(0)
r_rm   = np.array([0.549, 0.440, -3.322, -2.041, 1.2])     # same five styles as above
pi_ref = np.array([0.54, 0.30, 0.10, 0.05, 0.01])
beta, eps, lr = 0.5, 0.2, 0.1                              # KL coef, clip range, step size
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()

theta = np.log(pi_ref).copy()          # policy logits, initialised AT the SFT policy
v = 0.0                                # value "network": one number, since there is one prompt
for it in range(300):
    pi_old = softmax(theta)
    y = rng.choice(5, size=512, p=pi_old)                       # 1. rollouts
    R = r_rm[y] - beta * np.log(pi_old[y] / pi_ref[y])          # 2. reward minus KL penalty
    A = R - v                                                   # 3. advantage with critic
    A = (A - A.mean()) / (A.std() + 1e-8)                       #    whitened
    v += 0.5 * (R.mean() - v)                                   #    critic regression step
    clipped = 0
    for epoch in range(4):                                      # 4. several clipped epochs
        for mb in np.split(rng.permutation(512), 4):
            pi = softmax(theta); rho = pi[y[mb]] / pi_old[y[mb]]
            active = ~(((A[mb] > 0) & (rho > 1 + eps)) | ((A[mb] < 0) & (rho < 1 - eps)))
            clipped += (~active).sum()
            c = rho * A[mb] * active               # d(rho*A)/dtheta = rho*A*(onehot(y) - pi)
            g = np.bincount(y[mb], weights=c, minlength=5) - pi * c.sum()
            theta += lr * g / len(mb)
    if it in (0, 9, 49, 149, 299):
        pi = softmax(theta); kl = np.sum(pi * np.log(pi / pi_ref))
        print(f"iter {it+1:2d}  pi={np.round(pi, 3)}  E[r_RM]={pi @ r_rm:+.3f}"
              f"  KL={kl:.3f}  clipped={clipped / 2048:.0%}")
w = pi_ref * np.exp(r_rm / beta)
print(f"closed form pi* = {np.round(w / w.sum(), 3)}")
iter  1  pi=[0.581 0.297 0.074 0.039 0.009]  E[r_RM]=+0.134  KL=0.007  clipped=8%
iter 10  pi=[0.69  0.287 0.01  0.008 0.005]  E[r_RM]=+0.463  KL=0.116  clipped=0%
iter 50  pi=[0.716 0.242 0.001 0.001 0.04 ]  E[r_RM]=+0.542  KL=0.196  clipped=21%
iter 150  pi=[0.704 0.253 0.    0.    0.042]  E[r_RM]=+0.547  KL=0.201  clipped=51%
iter 300  pi=[0.661 0.292 0.    0.    0.046]  E[r_RM]=+0.546  KL=0.194  clipped=18%
closed form pi* = [0.66  0.295 0.    0.    0.045]

PPO arrives at \(\pi^*\) (0.661 against 0.660 for the concise answer, 0.046 against 0.045 for the flattering one). Note the wandering in between: near the optimum the true advantages are close to zero, so whitening divides sampling noise by a tiny standard deviation and the clip fraction jumps. That is a real phenomenon, and one reason large runs watch the clip fraction and use small learning rates.

Third, GAE on one response, the numbers in the worked example (NumPy):

import numpy as np
# One 5-token response. Per-token log(pi/pi_ref) at the sampled tokens, the reward model's
# score for the whole response, and the value head's predictions V(s_t) before each token.
log_ratio = np.array([0.10, -0.05, 0.30, 0.02, 0.08])
rm_score, beta = 1.0, 0.05
V = np.array([0.60, 0.70, 0.50, 0.80, 0.90])

r = -beta * log_ratio                    # per-token KL penalty ...
r[-1] += rm_score                        # ... plus the RM score on the final token
V_next = np.append(V[1:], 0.0)           # value after the last token is 0 (episode ends)

def gae(r, V, V_next, gamma=1.0, lam=0.95):
    delta = r + gamma * V_next - V       # one-step TD errors
    A, running = np.zeros_like(r), 0.0
    for t in reversed(range(len(r))):    # A_t = delta_t + gamma*lam*A_{t+1}
        running = delta[t] + gamma * lam * running
        A[t] = running
    return delta, A

delta, A95 = gae(r, V, V_next)
print("rewards r_t     ", np.round(r, 4))
print("TD errors delta ", np.round(delta, 4))
for lam in [0.0, 0.95, 1.0]:
    _, A = gae(r, V, V_next, lam=lam)
    print(f"advantages lam={lam:<4}", np.round(A, 4), "  value targets", np.round(A + V, 4))
rewards r_t      [-0.005   0.0025 -0.015  -0.001   0.996 ]
TD errors delta  [ 0.095  -0.1975  0.285   0.099   0.096 ]
advantages lam=0.0  [ 0.095  -0.1975  0.285   0.099   0.096 ]   value targets [0.695  0.5025 0.785  0.899  0.996 ]
advantages lam=0.95 [0.3277 0.2449 0.4657 0.1902 0.096 ]   value targets [0.9277 0.9449 0.9657 0.9902 0.996 ]
advantages lam=1.0  [0.3775 0.2825 0.48   0.195  0.096 ]   value targets [0.9775 0.9825 0.98   0.995  0.996 ]

Finally, the PPO loss for a batch of language-model rollouts in PyTorch (standard code; not run here). All tensors are \((B, T)\) over response tokens, with mask = 1 on real tokens:

import torch

def ppo_loss(logp, logp_old, adv, values, values_old, returns, mask,
             clip=0.2, vclip=0.2, vf_coef=0.1):
    ratio = torch.exp(logp - logp_old)
    pg = -torch.min(ratio * adv, torch.clamp(ratio, 1 - clip, 1 + clip) * adv)
    v_clipped = values_old + torch.clamp(values - values_old, -vclip, vclip)
    vf = 0.5 * torch.max((values - returns) ** 2, (v_clipped - returns) ** 2)
    masked_mean = lambda x: (x * mask).sum() / mask.sum()
    stats = {"clipfrac": masked_mean(((ratio - 1).abs() > clip).float()),
             "approx_kl": masked_mean(0.5 * (logp - logp_old) ** 2)}
    return masked_mean(pg) + vf_coef * masked_mean(vf), stats

Things to try

  • In the first program, give the flattering answer an SFT probability of 0.001 instead of 0.01. Which \(\beta\) now maximises true quality, and how much KL does reward hacking need?
  • In the PPO program, set eps = 10 (effectively no clip) and lr = 0.5. What happens to the trajectory? Then remove advantage whitening.
  • Replace the critic with the leave-one-out mean of four samples per "prompt" (RLOO). Does it converge to the same \(\pi^*\)?
  • Run TRL's PPO or RLOO trainer on a 0.5B model with a small reward model. Plot reward, KL and response length together, and read 20 samples at the start, middle and end.

Check yourself

Write the per-token reward used in RLHF-PPO and explain why the reward-model score appears only once.

\(r_t = -\beta\log\frac{\pi_\theta(y_t\mid s_t)}{\pi_{\text{ref}}(y_t\mid s_t)}\) for every token, plus \(r_\phi(x,y)\) at the final token. The reward model judges complete answers (it reads the end-of-turn position), so its score exists only once the answer is finished. The KL term decomposes over tokens because sequence log-probabilities are sums of token log-probabilities.

Why is the value model initialised from the reward model rather than from the policy?

At the final position the value model should predict the reward model's score, so starting from the reward model gives a sensible critic immediately. Keeping it as a separate network (rather than a head on the policy) also stops value-loss gradients disturbing the policy's weights early in training, which Stiennon et al. found harmful.

A token has advantage −1.5 and its probability ratio is already 0.75. What gradient does the clipped objective give for it, and why?

None. With \(\varepsilon = 0.2\), \(\operatorname{clip}(0.75) = 0.8\); the terms are \(0.75 \times -1.5 = -1.125\) and \(0.8 \times -1.5 = -1.2\), and the minimum is the clipped, constant \(-1.2\). The token is already 25% less likely than under the old policy, past the 20% limit, so PPO stops pushing it down for this batch.

Your mean reward rises steadily but the KL to the reference is negative. What is happening?

A per-token KL estimate \(\log\frac{\pi_\theta}{\pi_{\text{ref}}}\) on sampled tokens can only average below zero if the tokens were not sampled from \(\pi_\theta\): top-\(k\)/top-\(p\), a forced minimum length, or log-probabilities computed by a different engine. The policy is being rewarded through the penalty term. Sample from the full distribution and recompute log-probabilities with the training model.

Why do RLHF implementations use γ = 1?

Episodes are short and finite, and the main reward arrives at the end. Discounting would make early tokens care less about the final score, which is the wrong inductive bias: the first sentence of an answer matters as much as the last. Variance control comes from \(\lambda\) and the critic, not from \(\gamma\).

Hard: show that maximising E[r] − β KL(π‖π_ref) is equivalent to minimising KL(π‖π*) and use it to explain why reward hacking needs only a small KL when the reward model over-scores a rare answer.

The derivation above gives \(\mathbb{E}_\pi[r]-\beta\mathrm{KL}(\pi\|\pi_{\text{ref}}) = \beta\log Z - \beta\mathrm{KL}(\pi\|\pi^*)\). The optimum multiplies each answer's reference probability by \(e^{r/\beta}\). An answer with reference probability \(p\) and an over-score of \(\Delta\) above the alternatives gets weight \(p\,e^{\Delta/\beta}\); it dominates once \(e^{\Delta/\beta} \gtrsim 1/p\), i.e. \(\beta \lesssim \Delta/\log(1/p)\). Moving most of the mass onto it costs about \(\log(1/p)\) nats: 4.6 nats for a 1% answer. Rare answers are cheap to reach and are where reward models are least trained, which is the worst combination.

Hard: Ahmadian et al. say PPO's variance-reduction machinery is unnecessary for RLHF. Give the argument, and one situation where you would still want a critic.

PPO was designed for RL from weak initialisations, where gradients are high-variance and destructive. An SFT-initialised language model concentrates probability on a few tokens at each step, so samples for a prompt are similar and sequence-level REINFORCE with a good baseline (other samples of the same prompt) has manageable variance; the critic's bias and cost are not worth paying. A critic still helps when responses are very long and the reward is sparse, or in multi-turn and tool-using episodes, where per-step credit assignment matters and a sequence-level baseline cannot tell which step caused the outcome.

Go deeper

Papers

Videos and lectures

Articles

Books

Code

Where this leads