Trust regions, PPO and RL for language models
Before this lesson: lesson 07 (the policy gradient theorem, REINFORCE and baselines), lesson 08 (advantages, GAE and the soft-greedy policy ) and the importance ratio of lesson 04. KL divergence: information theory 03 and, for forward vs reverse KL, information theory 06. The Fisher matrix and natural gradient (optional): optimization 10. The full LLM training pipeline (SFT, reward models, DPO) is outside this track. Time: about 95 minutes, plus the notebook.
Why this matters #
- PPO is the default on-policy deep RL algorithm. It is simple, works with shared actor-critic networks, and reuses each batch for several epochs. It trained OpenAI Five (Dota 2) and many robotics and game agents.
- RLHF. InstructGPT (Ouyang et al., 2022) fine-tuned GPT-3 with PPO on the score of a reward model learned from human preferences, plus a per-token KL penalty to the supervised model. This recipe made chat assistants follow instructions.
- RL with verifiable rewards. GRPO (DeepSeekMath, 2024) removes the critic and uses a group of sampled answers as the baseline. As of 2025 it and its variants (Dr. GRPO, DAPO and others) are a standard way to train reasoning models such as DeepSeek-R1 on math and code, where a program checks the answer.
- One idea behind all of them: distribution shift. The trust region (TRPO, PPO), the KL penalty (RLHF) and the behaviour constraint of offline RL (lesson 06) all keep the policy where the data, or the reward model, can be trusted.
1. Predict first #
2. The picture #
Why big steps fail. Think of climbing a hill in fog. You can see the slope only near your feet. A small step uphill is safe. A long jump in the same direction can land you lower than before. In RL the "fog" is the data: every sample was collected by the old policy . To judge a new policy with old samples, we reweight each sample by the probability ratio
the importance weight of lesson 04. This corrects for the actions. It does not correct for the states: a new policy also visits other states, and the old batch has no information about how often. This error is small for small steps and large for large steps.
A small example where this matters. An agent has two states, (the start) and , and three actions. It cannot tell the two states apart (they look the same to it), so one softmax policy with acts in both. This is the normal situation with function approximation: one parameter vector serves many states. Rewards and next states, with :
| (forward) | (wait) | (back) | |
|---|---|---|---|
| , go to | , stay in | , stay in | |
| , stay in | , stay in | , go to |
The old policy is uniform (). It spends a lot of time in , where "back" is very good (advantage ). So the policy gradient says: more "back", less "forward". But "back" is slightly bad in (advantage ). A policy that almost always goes back never reaches again, so it spends all its time in , where "back" earns nothing.
Predict, then slide. Move the step size along the policy gradient. The blue curve is the true improvement , computed exactly. The violet curve is the surrogate , the improvement predicted from old data. Near they agree (same value, same slope). Far away the surrogate keeps rising while the true improvement falls below zero. The lower chart shows the KL from the old policy (solid) and its Fisher approximation (dashed). The shaded band is the trust region .
This answers question 1. The first small steps help almost as predicted: at the surrogate predicts and the true gain is . But the true gain peaks near (about ) and becomes negative after , while the surrogate keeps growing to above . A trust region of size stops at , with a true gain of , close to the best possible on this line.
PPO's rule, as a picture. PPO does not compute any KL during the update. For each sample it looks at and the advantage estimate (from GAE, lesson 08). If , the update wants to make the action more likely, so grows. Once , PPO stops rewarding further growth: that sample's gradient becomes zero. If , the same happens once . Here (typically ) is the clip range; it is not the exploration rate of earlier lessons.
Drag the orange point along the curve (or use the slider), then switch the sign of . The solid orange curve is PPO's per-sample objective ; the dashed line is the unclipped . In the magenta region the curve is flat, so the gradient is zero. Notice that the flat part is only on one side: a sample that moved the wrong way keeps its full gradient.
PPO with . Which sample gives zero gradient?
With the objective is . For this is the constant , so the gradient is zero: the action is already 30% more likely, which is enough. For , the action became less likely although it was good; is the unclipped term, so the full gradient pushes it back up. For , the bad action became more likely; is unclipped, so it keeps its gradient.
3. Definitions and main results #
3.1 Setup and notation #
We use the notation of the track. is the expected discounted return from the start distribution . is the advantage. The discounted visitation of a policy is
It is unnormalised; is a probability distribution. Three policies appear in this lesson. Keep them apart:
| Symbol | What it is | Where it appears |
|---|---|---|
| the policy we are training | everywhere | |
| the policy that collected the current batch; fixed during one update | in the ratio | |
| a frozen copy of the starting model (in LLMs: the supervised model) | in the KL penalty of RLHF |
3.2 The performance difference lemma #
The first result says exactly how much better a new policy is than an old policy , using the old advantages.
Theorem (performance difference lemma; Kakade and Langford, 2002). For any two policies and , with bounded rewards and ,
In words: run the new policy, and add up the old policy's advantages of the actions it takes.
Why this is true (intuition). measures how much better action is than following from . The new policy is a sequence of such "deviations" from , one per step. Each deviation changes the return by its advantage, and the changes add up.
Proof.
- Fix a start state and a trajectory of . Because is bounded and , the sum telescopes (neighbouring terms cancel) and equals . Write out the first terms to see it: .
- is the expected return of . Add the zero-sum identity of step 1 inside the expectation: .
- Condition on . The next state comes from the environment, , which does not depend on the policy. So , and term has expectation .
- Average over . Then group the terms by state: the weight of state is , and the action there is drawn from .
The lemma is exact, but it has a problem: it needs states from , the new policy's visitation. We cannot sample those before we have chosen .
3.3 The surrogate objective and TRPO #
Replace by and write the inner sum with importance weights. This gives the surrogate objective
Every term can be estimated from the old batch: states and actions come from , and only appears in the ratio. In practice is the sample mean of (up to the constant ).
Theorem (first-order agreement). For a differentiable policy with : , and .
Proof.
- Value: for every , so .
- Gradient: .
- Since , we have , so we may replace by without changing the sum.
- is exactly by the policy gradient theorem of lesson 07.
Why replacing by is a second-order error. The difference between the lemma and the surrogate is . Both factors are zero when , and both grow linearly with a small change of . Their product grows like the square of the step. So is accurate near and can be badly wrong far away, as the first figure showed.
Theorem (TRPO lower bound; Schulman et al., 2015, Theorem 1). With ,
The right side is at . So if each update maximizes the right side, the true never decreases (a minorize-maximize scheme). We do not prove the bound here; the proof is in the TRPO paper (§3 and Appendix A).
In practice is huge (in the example above ), and the penalized steps would be tiny. TRPO therefore solves a constrained problem with a chosen radius (for example ):
Here is the average over the batch, and the max over states is replaced by an average.
The KL is locally a quadratic form. Near , with ,
where is the Fisher information matrix. The value and the gradient of the KL are zero at , so the first term of its Taylor series is the quadratic one, and its Hessian is . For a softmax over logits, and .
The natural gradient, conjugate gradient and line search
Maximize the linear model ( is the policy gradient) subject to . The Lagrangian condition gives , the natural gradient, and the constraint fixes the length:
For a network with millions of parameters, cannot be stored. TRPO computes with about 10 steps of conjugate gradient, which needs only Fisher-vector products (two backward passes, no matrix). Because the quadratic model is only approximate, TRPO then runs a backtracking line search: it halves the step until the true sample KL is at most and the surrogate improves. For a softmax, is singular along (adding a constant to all logits does not change ), so one uses the pseudo-inverse or a small damping .
Numerical check. , : the exact KL is and . The natural gradient and K-FAC are in optimization 10 and optimization 12.
3.4 PPO: the clipped surrogate #
TRPO needs second-order machinery. PPO (Schulman et al., 2017) gets most of its benefit with first-order SGD. With and advantage estimates :
The derivative of with respect to is , because . The four cases:
| Case | Term chosen by the min | Gradient w.r.t. |
|---|---|---|
| , | (push up) | |
| , | , a constant | |
| , | (push down) | |
| , | , a constant |
Zero-gradient condition. The gradient is zero only when the sample has already moved by more than in the direction that helps ( or ). A sample that moved the wrong way keeps its full gradient.
Pessimistic bound. Since , every term satisfies , so . The clipped objective is a lower bound on the unclipped surrogate. It ignores gains beyond the clip range but keeps every loss. At (the start of each update) the two agree, and the gradient of is the ordinary policy gradient .
Why is for every ?
for any numbers . Apply it term by term with ; the mean of smaller numbers is smaller. This holds for both signs of . For example, with and : , the clipped term is , and the min is below . Clipping does not change the ratios themselves; it only changes the objective.
The full PPO update. A PPO iteration:
- Run for steps in parallel environments. Store and .
- Compute advantages with GAE and value targets (lesson 08).
- For epochs (typically 3–10), shuffle the batch into minibatches and take gradient steps on the loss below, with a value-loss weight (for example ) and an entropy bonus weight (for example ).
- Set and repeat.
The loss of step 3 is
Implementation details that matter (Huang et al., The 37 implementation details of PPO):
- Advantage normalization per minibatch: . The step size then does not depend on the reward scale.
- Value loss, often clipped like the policy, with its own weight. Entropy bonus: keeps the policy from becoming deterministic too early.
- Several epochs of shuffled minibatches: this data reuse is the reason to have a trust region.
- Approximate-KL monitoring and early stopping: stop the epochs when the estimated KL passes a target (for example –). The clip does not bound the KL (see below).
- Global gradient-norm clipping (for example ) and learning-rate annealing.
Estimating the KL from samples. During the update we only have the sampled actions, drawn from . With :
Both are unbiased for . For this is the definition: . For , add . Each term can be negative, but each term is , because . So usually has lower variance (Schulman's note "Approximating KL divergence").
The clip does not bound the KL. The clip only removes the incentive for samples that are already outside the range in the helpful direction. Other samples keep moving the shared parameters, and those changes also move the clipped samples and the actions that were never sampled. Ratios often end far outside , and the KL keeps growing with more epochs or a larger learning rate. The notebook shows this on a 10-action problem: after 10 epochs with , over half of the ratios are outside , the largest is , and the KL is more than ten times its value after the first epoch.
You run PPO with for 10 epochs on one batch. What can you say about at the end?
The clip only zeroes the gradient of samples that already moved in the helpful direction. Shared parameters keep changing through the other samples, so ratios drift outside the range and the KL grows with epochs and learning rate. Clipping usually keeps the KL much smaller than the unclipped objective would, but it is not a bound. That is why PPO implementations track an approximate KL.
3.5 RL for language models #
The token-level MDP. A language model generates a response to a prompt one token at a time. As an MDP:
- State : the prompt and the tokens so far.
- Action : the next token. The action space is the vocabulary (for example 100 000 tokens).
- Transition: deterministic, append the token. The episode ends at the end-of-sequence token or a length limit.
- Reward: usually one number for the whole response, given at the last token, from a reward model or a checker. Usually .
Because the transition is known and deterministic, the same problem can also be seen as a contextual bandit: the context is , the action is the whole response , and .
A reward model from preferences. Humans compare two responses (preferred) and to the same prompt. The Bradley–Terry model says , with the logistic function . The reward model (a language model with a scalar head) is trained by minimizing over the comparisons. Only reward differences are learned, so is defined up to a constant per prompt.
The KL-regularized objective (InstructGPT style):
with a KL coefficient . The penalty keeps the policy near , where the reward model was trained and is reliable, and keeps the text fluent.
The per-token reward, from the chain rule. Because ,
The second line takes, at each step , the expectation over the token given first.
The sequence KL is the expected sum of per-token log-ratios (the chain rule for KL). So PPO-based RLHF gives every token the reward
The sum over the response is . A token-level critic and GAE then turn these rewards into per-token advantages.
Pick a response and move the sliders. The tree shows a toy model that writes two tokens from . Each edge shows the policy probability and the reference probability . For the chosen response, the panel lists the per-token log-ratios, the KL rewards and the reward-model score. Check that the per-token rewards add up to , and that the sequence KL equals the sum of the per-token KLs.
In PPO-based RLHF with , a token has and . What is the sign of its KL reward (ignore the final score)?
The per-token reward is times the log-ratio. Here the policy makes the token less likely than the reference, so the log-ratio is negative and the reward is positive. Only the expected penalty per state, , is always .
The optimum of the KL-regularized objective has a closed form. Fix a prompt and allow any distribution over responses.
Theorem. Let . The unique maximizer of is
and the maximum value is .
Proof.
- From the definition of , take logs: for every .
- Put this into : .
- The terms cancel: .
- , with equality only for (Gibbs' inequality, information theory 03).
So the KL-regularized optimum reweights the reference model by . Small : almost all mass on the best response (but only among responses that can produce). Large : almost . With a uniform reference this is the soft-greedy policy of lesson 08, with : the KL to a uniform distribution is , so the KL penalty becomes an entropy bonus.
Step 1 also says: at the optimum, the penalized reward equals for every response. All responses look equally good, so every advantage is zero and the gradient vanishes.
Move and drag the reward dots. Grey bars are ; orange bars are the optimum ; the aqua dots are the rewards . The lower chart shows, for every , the expected reward (aqua) and (magenta). Predict first: what happens to when ? Can put mass on a response with ?
Direct preference optimization (DPO)
Step 1 of the proof can be read backwards: for the optimal policy, the reward is . Put this into the Bradley–Terry model. The term is the same for both responses and cancels:
DPO (Rafailov et al., 2023) fits a policy in place of directly to the preference data by minimizing of this expression. It needs no reward model, no sampling and no RL loop, only log-probabilities of fixed pairs. The cost: it learns only from the given pairs (it is an offline method), and it is exact only if the optimum is reachable.
3.6 Critic-free methods: RLOO and GRPO #
PPO for RLHF needs four large models in memory: the policy, the reference, the reward model and a value model about as large as the policy. The value model must assign credit to single tokens from one reward at the end, which is hard. LLMs offer a cheaper baseline: sample responses to the same prompt, with rewards , and compare them.
- RLOO (REINFORCE leave-one-out; Ahmadian et al., 2024):
The baseline of response does not use ; it depends only on the other, independent samples. So : this is unbiased REINFORCE with a per-prompt baseline (lesson 07). In the paper the KL penalty is part of the sequence reward, .
- GRPO (Group Relative Policy Optimization; Shao et al., DeepSeekMath, 2024):
the same advantage for every token of . It is used inside a PPO-style clipped ratio per token, and the KL to is a separate loss term, not part of the reward. It is estimated per token with the form, . Dividing by the std is not unbiased: it gives more weight to prompts whose rewards vary little. As of 2025, variants differ: sample or population std, and Dr. GRPO (Liu et al., 2025) drops both the std and the division by the response length.
Drag the reward bars, then compare the advantages. The aqua bars are the rewards of responses to one prompt. Below are three advantages per response: (grey), RLOO and GRPO. Try "one correct of four" and "all equal": when every reward is the same, every advantage is 0 and the prompt gives no learning signal.
Why they fit LLMs. The dynamics are known and deterministic, so sampling several responses per prompt is cheap and needs no simulator. The reward comes once per sequence, so a per-prompt Monte Carlo baseline is a good baseline. No value network saves memory and removes a hard regression problem. Ahmadian et al. report RLOO matching or beating PPO for RLHF.
RL with verifiable rewards (RLVR). For math and code, a program can check the final answer: the reward is 1 if correct and 0 if not. There is no reward model to over-optimize, only the risk of gaming the checker (for example, an answer format it accepts by mistake). GRPO with such rewards trained DeepSeek-R1 (2025).
Four responses to one prompt get rewards . What are the RLOO advantages?
For response 1 the baseline is the mean of the other three, , so . For response 2 the others are with mean , so . Check with . The first option is (the mean baseline including ); the third is GRPO with the population std .
3.7 Reward over-optimization #
The reward model is only a proxy for what people want. If we optimize it hard, the policy finds responses that score high but are not better, for example longer answers or flattering text (reward hacking, an example of Goodhart's law). Gao et al. (2022) measured this with a large "gold" reward model playing the role of humans and smaller proxy reward models. With the distance from the initial policy, the proxy reward keeps rising, while the gold reward rises and then falls. For RL they fit the gold reward as , with constants that depend on the reward-model size.
The KL penalty keeps the policy near , where the proxy is more reliable. It does not make the proxy correct. In Gao et al.'s setup, the penalty acted like early stopping: it changed how far training went, but not the gold reward reached at a given KL distance. Other protections: early stopping on held-out human or gold evaluations, larger or ensembled reward models, new preference data from the current policy, and verifiable rewards where possible.
Answers to section 1. (1) No. The true improvement agrees with the surrogate only to first order. In the example, the gain grows more slowly than the step, peaks, and then becomes negative, while the surrogate keeps rising. (2) Yes. Clipping removes the incentive only for samples that are already outside the range in the helpful direction; other samples and shared parameters keep moving the policy. That is why PPO monitors the KL and stops early. (3) Lower. The log-ratio of that response is positive, so is added to .
4. Worked example #
(a) PPO with on three samples , with and :
| Sample | min | Gradient w.r.t. its | ||
|---|---|---|---|---|
| (clipped constant) | ||||
| (unclipped) | ||||
| (inside the range) |
. The unclipped mean is . The clipped value is lower, as the pessimistic bound says. The first sample already moved enough and is ignored. The second sample was good but became less likely; its gradient pushes back up.
(b) Per-token RLHF reward. A 4-token response has log-ratios , , and reward-model score .
- Token 1: .
- Token 2: .
- Token 3: .
- Token 4: .
Sum: . Check: the sequence log-ratio is , and .
(c) RLOO and GRPO. Three responses with rewards ; mean .
- RLOO: ; ; . Check: .
- GRPO with the population std : . With the sample std : .
(d) The closed-form optimum. Three responses with , rewards and .
- Weights : , , .
- , so .
- and .
- Objective: ✓.
- Penalized reward of response 1: ; of response 3: . The same for all responses, as the theorem says.
With the optimum is almost with KL (all mass on response 3, which had ). With it is , close to .
(e) Sequence KL = sum of per-token KLs. A toy model writes two tokens from . Policy: first token ; second token after a 0 and after a 1. Reference: first ; second after a 0 and after a 1.
- First-token KL: .
- Second-token KL after a 0: ; after a 1: .
- Chain rule: .
- Directly over the four sequences, with and : ✓.
5. In code #
NumPy checks of the worked examples. The notebook for this lesson has these cells and the exercises.
import numpy as np
from scipy.special import softmax
# (a) PPO clipped objective and its gradient w.r.t. log pi
rho, A, eps = np.array([1.5, 0.6, 1.1]), np.array([1.0, 1.0, -2.0]), 0.2
terms = np.minimum(rho * A, np.clip(rho, 1 - eps, 1 + eps) * A)
grad = np.where(rho * A <= np.clip(rho, 1 - eps, 1 + eps) * A, rho * A, 0.0) / len(rho)
print(terms.mean(), (rho * A).mean()) # -0.1333 -0.0333
print(grad) # [ 0. 0.2 -0.7333]
# (b) per-token RLHF reward
log_ratio, beta, score = np.array([0.2, -0.1, 0.4, 0.0]), 0.05, 0.8
r_tok = -beta * log_ratio
r_tok[-1] += score
print(r_tok, r_tok.sum()) # [-0.01 0.005 -0.02 0.8 ] 0.775
# (c) RLOO and GRPO
r = np.array([0.8, 0.2, 0.5]); K = len(r)
print(K / (K - 1) * (r - r.mean())) # [ 0.45 -0.45 0. ]
print((r - r.mean()) / r.std()) # [ 1.2247 -1.2247 0. ] (population std)
# (d) closed-form optimum of E[r] - beta KL(pi || pi_ref)
p_ref, rew, beta = np.array([0.5, 0.3, 0.2]), np.array([0.0, 1.0, 2.0]), 1.0
w = p_ref * np.exp(rew / beta); Z = w.sum(); p_star = w / Z
kl = np.sum(p_star * np.log(p_star / p_ref))
print(p_star, p_star @ rew - beta * kl, beta * np.log(Z)) # [0.179 0.2919 0.5291] 1.0272 1.0272
print(rew - beta * np.log(p_star / p_ref)) # [1.0272 1.0272 1.0272]
# Fisher approximation of the KL for a softmax policy
theta, delta = np.array([0.5, -0.2, 0.1]), np.array([0.03, -0.02, 0.01])
p, q = softmax(theta), softmax(theta + delta)
F = np.diag(p) - np.outer(p, p)
print(np.sum(p * np.log(p / q)), 0.5 * delta @ F @ delta) # 1.918e-04 1.927e-04
# (e) sequence KL = sum of per-token KLs (toy two-token model)
pol = {"first": np.array([0.7, 0.3]), "second": np.array([[0.9, 0.1], [0.4, 0.6]])}
ref = {"first": np.array([0.5, 0.5]), "second": np.array([[0.5, 0.5], [0.2, 0.8]])}
seq = lambda m, a, b: m["first"][a] * m["second"][a, b]
kl = lambda u, v: np.sum(u * np.log(u / v))
kl_seq = sum(seq(pol, a, b) * np.log(seq(pol, a, b) / seq(ref, a, b)) for a in (0, 1) for b in (0, 1))
kl_tok = kl(pol["first"], ref["first"]) + sum(pol["first"][a] * kl(pol["second"][a], ref["second"][a]) for a in (0, 1))
print(kl_seq, kl_tok) # 0.3713 0.3713
6. Where it shows up #
- Deep RL benchmarks and games. PPO with GAE is the default baseline in libraries such as Stable-Baselines3 and CleanRL, and trained OpenAI Five. Its clipped ratio also appears in multi-agent RL (MAPPO).
- RLHF. InstructGPT and many later chat models: a reward model from human comparisons, then PPO with a learned value model and a per-token KL penalty to the supervised model.
- Reasoning models and RLVR. GRPO and its 2025 variants (Dr. GRPO, DAPO) with rewards from answer checkers, unit tests or proof checkers; DeepSeek-R1 is the best-known example.
- Preference optimization without RL. DPO and its variants use the closed-form optimum of the KL-regularized objective to fit preferences directly.
- ML for science. Policy-gradient fine-tuning with a penalty for leaving a prior model steers generative models toward a computed property. REINVENT trains a molecule generator toward a scoring function (for example predicted activity) while keeping it close to the prior generator, and DDPO (Black et al., 2023) fine-tunes diffusion models with a PPO-style clipped ratio. The penalty has the same role as in RLHF: the property score is often a learned proxy, and the prior keeps samples realistic.
7. Common mistakes #
- Mixing up the three policies. is trained, generated the batch and appears in the ratio, is the frozen starting model and appears in the KL penalty. In PPO-RLHF all three exist at the same time.
- "Clipping bounds the KL." It does not. Measure the approximate KL and stop the epochs early.
- Zero-gradient cases reversed. The gradient vanishes for and for . A sample that moved the wrong way keeps its gradient.
- Forgetting that the surrogate uses the old states. The ratio corrects the action distribution, not the state distribution. This is why big steps are dangerous even with exact ratios.
- Std normalization of an all-equal group. If all rewards are equal, all GRPO and RLOO advantages are 0 (GRPO needs a small constant in the denominator to avoid ). Such prompts give no signal.
- Counting the KL twice. PPO-RLHF puts it in the per-token reward; GRPO adds it as a separate loss term. Use one or the other.
- Believing the KL penalty fixes reward hacking. It limits how far the policy moves; it does not make the reward model right.
- Reward timing. We write for the reward after ; Sutton and Barto write . In the token MDP the score belongs to the last token.
8. Check yourself #
- Why can the surrogate use instead of ?
Answer
Because it agrees with the true improvement to first order at : the same value (0) and the same gradient (the policy gradient). The error is a product of two terms that both vanish at , so it is second order in the step, and TRPO's theorem bounds it by a multiple of the maximum KL. So the surrogate is accurate inside a small trust region. - A sample has and , with . Does it give a gradient?
Answer
No. and ; the min is , the clipped constant. The probability of this bad action has already fallen by more than , in the helpful direction. - Show that the RLOO advantage equals .
Answer
, so . - Prove that is an unbiased estimator of with , and that each term is non-negative.
Answer
, so and . Each term is because for . - For the KL-regularized objective with , rewards and , find .
Answer
Weights and ; ; . This is for the first response. - What does the KL penalty not fix in reward over-optimization?
Answer
The proxy reward is still wrong; the penalty only limits how far the policy moves from . Gao et al. found that it acted like early stopping, with no better gold reward at a given KL distance.
State the performance difference lemma.
.
What is the surrogate objective, and how does it differ from the exact improvement?
: the same as the lemma but with the old visitation instead of .
Write PPO's clipped objective.
with .
For which samples is the PPO gradient zero?
For with , and for with : the sample already moved more than in the helpful direction.
Why does PPO still monitor the KL?
The clip only zeroes some samples' gradients; shared parameters keep moving, ratios leave the clip range, and the KL can grow without bound over epochs.
Give the estimator of and its two properties.
with . It is unbiased, and every term is .
What is the per-token reward in PPO-based RLHF?
for every token, plus the reward-model score at the last token.
What is the maximizer of ?
, with ; the maximum value is .
Compute the RLOO advantages for rewards .
; in general .
What is the GRPO advantage, and what does Dr. GRPO change?
for every token of response . Dr. GRPO drops the std division and the length normalization.
9. Interview angle #
- "Walk me through PPO's loss." The ratio ; the clipped surrogate with the min (a pessimistic bound; zero gradient only after enough movement in the helpful direction); the value loss; the entropy bonus; advantage normalization; several epochs of minibatches; KL monitoring and early stopping.
- "Why not just take bigger policy-gradient steps?" The data come from the old policy. The performance difference lemma shows the surrogate uses the old state distribution, so it is only valid near the old policy; large steps can make the policy worse.
- "TRPO vs PPO?" TRPO: a hard KL constraint, natural gradient by conjugate gradient, line search; more principled, harder to implement, awkward with shared actor-critic networks. PPO: first-order, clipped ratio, simpler and usually as good.
- "PPO vs GRPO vs RLOO for LLMs?" PPO needs a value model and GAE for per-token credit. RLOO and GRPO use samples per prompt as the baseline; less memory, no critic to train, but more samples per prompt. RLOO is unbiased; GRPO's std division reweights prompts.
- "Derive the optimal policy of the KL-regularized objective." Write with . Mention that DPO inverts this to get the reward from the policy.
- "What is reward hacking, and what do you do about it?" Over-optimizing a proxy. KL penalty and early stopping, better or ensembled reward models, fresh human data, verifiable rewards.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
- Write
ppo_clip_objectiveandppo_clip_grad, and check the gradient by finite differences. - Write
approx_kl( and ); show by sampling that both are unbiased and that . - Run PPO for several epochs on one batch of a 10-action softmax problem and track the KL and the fraction of ratios outside the clip range; compare with the unclipped objective.
- Compute per-token KL rewards on the two-token toy model and check the chain rule (sequence KL = sum of per-token KLs).
- Write
rloo_advantages,grpo_advantagesand the closed-form optimum; train the toy model with RLOO plus a KL penalty and check that it converges to .
11. Watch and read #
- Schulman, Levine, Moritz, Jordan, Abbeel, Trust Region Policy Optimization (2015): §2–3 (the performance difference identity and Theorem 1) and Appendix C (conjugate gradient).
- Schulman, Wolski, Dhariwal, Radford, Klimov, Proximal Policy Optimization Algorithms (2017): §3 (the clipped objective) and §5 (the algorithm).
- Kakade and Langford, Approximately Optimal Approximate Reinforcement Learning (ICML 2002): the original performance difference lemma.
- Huang et al., The 37 Implementation Details of Proximal Policy Optimization (ICLR blog track, 2022).
- John Schulman, Approximating KL Divergence: the , , estimators.
- OpenAI Spinning Up: TRPO and PPO pages, with pseudocode.
- Ouyang et al., Training language models to follow instructions with human feedback (InstructGPT, 2022): §3.5 (reward model and PPO with a per-token KL penalty).
- Nathan Lambert, Reinforcement Learning from Human Feedback (free online book): chapters on reward models, policy gradients (PPO, RLOO, GRPO) and direct alignment (DPO).
- Ahmadian et al., Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs (RLOO, 2024).
- Shao et al., DeepSeekMath (GRPO, 2024), §4; Liu et al., Understanding R1-Zero-Like Training: A Critical Perspective (Dr. GRPO, 2025).
- Gao, Schulman, Hilton, Scaling Laws for Reward Model Overoptimization (2022).
- Rafailov et al., Direct Preference Optimization: Your Language Model is Secretly a Reward Model (2023).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.