Lecture 09: Reinforcement learning and policy optimization
Week 9, November 4, 2026. Sections 1–8 consolidate REINFORCE and PPO. Sections 9–11 collect GRPO and DPO as supplementary material. Instructor update, November 11: these topics have now been covered across Lectures 8–10 and serve as review for the remaining course. This coverage update does not change the published Quiz 4 scope.
These notes adapt the instructor's November 4 reference, Policy optimization for LLMs: REINFORCE, PPO, GRPO and DPO, with consistent notation and small checked examples. We maximize and minimize . Logarithms are natural.
1. An autoregressive policy as a decision process
A prompt is sampled from a specified distribution. At step , the state is , the action is the next token , and the transition appends it to the prefix. The response ends at EOS or a declared horizon. Padding is not an action. The model is a policy .
For a trajectory of actions indexed from zero, define
The initial state distribution, environment transitions, and reward function are fixed in this derivation. For a language-model example with one terminal score and , every response token has the same return . Equivalently, the entire response can be viewed as one contextual-bandit action. This equivalence does not imply that PPO should use a full-response ratio.
The value averages future outcomes under the policy. The action value additionally conditions on the next action. The advantage is . The terminal state's value is zero when it is truly terminal.
2. The score-function identity
Differentiating an observed reward number does not capture how the policy changes the probability of observing that outcome. Instead, use
For differentiable positive probabilities on fixed support, this gives
Only the policy factors depend on under the stated assumptions, so
The probability already determines the sampling distribution. Do not multiply each Monte Carlo sample by its policy probability a second time.
Past rewards have zero expected contribution to a later action's score. Removing them gives the return-to-go form
The outer belongs to this discounted trajectory-sum convention. For our language-model examples we set explicitly. This avoids silently dropping a factor while claiming to optimize a discounted objective.
3. Baselines and REINFORCE
A baseline that does not depend on the current sampled action has zero expected score contribution:
Thus can replace without changing the expected gradient. A well-chosen baseline can reduce variance; an arbitrary one need not. Bootstrapping with an approximate critic can introduce a separate estimation bias.
For trajectories generated at , construct the local loss
Here means stop-gradient. At , the negative gradient estimates the desired policy gradient. Reusing the same unweighted batch for many updates does not keep it on-policy as changes.
Binary-action check
Let be the chance of action 1, with rewards 1 and 0 for actions 1 and 0. Then and . The scores of the two actions are and respectively. At ,
Subtracting a fixed baseline leaves this mean unchanged. The sample-level gradient contributions can change substantially, which is how a baseline can change variance while preserving the expected update.
Reading: Williams (1992).
4. The old policy and the reference policy
The old policy generated the current rollout batch. Its cached log probabilities stay fixed during inner updates. The reference policy is a persistent anchor, often the SFT model, used to penalize unwanted drift. Refreshing the old policy does not mean replacing the reference.
At a fixed sampled state and action, define
This corrects an action expectation at a fixed state. Correcting an entire trajectory distribution would generally require a product of ratios. PPO uses a local surrogate based on old-policy state visitation and token-level ratios; it does not make a full new-policy trajectory expectation exact.
The denominator must describe the distribution that actually generated the tokens. Temperature changes or top-p filtering alter that distribution. For the derivations here, sample directly from the stated policy without such transformations. Otherwise account for them explicitly and check support.
5. PPO's clipped surrogate
For a fixed estimated advantage and , PPO maximizes
The minimum picks the less optimistic contribution. The clipping behavior depends on the sign of the advantage:
| Advantage | Region where this sample's policy term is flat | Region still receiving a gradient |
|---|---|---|
| Positive | Ratio above | Ratios below that upper threshold |
| Negative | Ratio below | Ratios above that lower threshold |
| Zero | Everywhere | None from this sample's reward advantage |
With , consider four synthetic cases:
| Advantage | Ratio | Unclipped value | Clipped objective contribution |
|---|---|---|---|
| 1.3 | 2.6 | 2.4 | |
| 0.7 | 1.4 | 1.4 | |
| 0.7 | -1.4 | -1.6 | |
| 1.3 | -2.6 | -2.6 |
The first and third cases are flat with respect to their ratio away from the kink. Other samples or auxiliary losses can still move shared parameters. PPO does not force all probability ratios into the clipping interval and does not impose a hard KL bound. Monitor actual policy changes separately.
Reading: Schulman et al. (2017), Section 3 and Algorithm 1.
6. Returns, the critic, and GAE
A fixed rollout-time critic produces . The temporal-difference residual is
Generalized advantage estimation uses
For a true terminal episode, set . A segment truncated from a continuing episode needs an appropriate bootstrap; do not treat every batch boundary as a terminal event. At , the estimate is one residual. At with a true terminal state, it is the Monte Carlo return minus the value.
For rewards , values , , and , the residuals are . Backward recursion gives advantages and value targets . At , the advantages become .
Reading: Generalized Advantage Estimation, Section 3.
7. A PPO iteration for a language model
- Freeze the rollout snapshot and collect responses. Cache old-policy and reference log probabilities, rollout-time critic values, and completion masks.
- Score responses with a fixed reward model or verifier. In one common RLHF construction, add token rewards and place the response score at the final action.
- Compute detached advantages and value targets, with explicit EOS and truncation handling. Declare whether the loss averages tokens or responses.
- Recompute current-policy log probabilities on the batch. Minimize the negative clipped surrogate and a critic regression loss, with any entropy term documented separately. Keep cached denominators and targets fixed.
- After the chosen inner epochs, collect a new rollout batch. Keep the reference anchor fixed in this standard setup.
At the first update, the actor equals the rollout snapshot and ratios are one. Later updates on that same batch activate the ratio and clipping behavior. Detach old log probabilities and actor advantages, but keep gradients through the current log probabilities and the critic predictions used by its own loss.
Check reward, held-out task performance, length, reference KL, entropy, clip fraction, and critic error. Reward growth alone does not establish improvement.
8. Three useful implementation distinctions
Objective versus gradient contribution. A detached weighted log-probability loss can reproduce a first-order gradient at a particular point. It is not generally identical to the original objective over later updates. In ordinary PPO, differentiate the minimum and clipping operations themselves.
Sequence sum versus token mean. For terminal reward and , a sequence score is a sum of token scores. Dividing each response by its length changes its relative weight when response lengths differ. Padding should never change either declared reduction.
Value estimate versus reward model. The critic predicts expected remaining return under a policy and reward convention. The reward model predicts a score for a candidate response. Replacing one with the other changes the algorithm.
9. Supplement: GRPO and within-prompt groups
For review of the Lectures 8–10 sequence, outcome-based GRPO draws responses for one prompt and standardizes their rewards:
We use the population standard deviation in this example. Other conventions change the scale. Every response token receives its response's group advantage, but each token retains its own policy ratio. The method removes the learned value critic; it does not remove reward evaluation or the rollout cost.
Rewards give advantages approximately . If all rewards agree, the relative reward signal is zero. A separate regularizer can still contribute a gradient. This makes group size and reward difficulty important.
The original outcome-based GRPO surrogate uses a mean across responses and a token mean within each response, plus a sampled reference penalty. Define and . Then a version matching that convention is
where is the PPO clipped contribution. Response lengths and group statistics are fixed during an inner update. Name the precise variant when implementing GRPO; later implementations can change normalization, clipping, and KL treatment.
The group mean includes the current sample. It is therefore correlated with that sample's score. Even without standardization, the centered group estimator has expectation times the raw reward gradient under independent draws. A leave-one-out mean avoids that particular correlation. Standardization, clipping, and length weighting introduce further differences: do not claim that the complete GRPO update is an unbiased REINFORCE estimator.
Also distinguish the KL estimator's value from its gradient. Under actions drawn from the current policy, . Differentiating on a fixed old-policy batch gives a surrogate gradient; it does not include the score term from changing the sampling distribution.
Reading: DeepSeekMath, Section 4.1 and Appendix A.
10. Supplement: direct preference optimization
DPO fits fixed preference pairs directly. It does not require an explicit reward-model fit or fresh policy rollouts during standard offline training. Its motivation starts with a KL-regularized response distribution at a fixed prompt. For a known reward and positive reference support,
Rearrange to obtain . The prompt-only partition term cancels in a same-prompt reward difference. Substituting into the Bradley–Terry likelihood motivates the margin
Use sums of response-token log probabilities, with a consistent EOS convention and no prompt or padding targets. Length-normalizing each sequence produces a different objective. Keep the reference fixed and retain gradients through the policy margin. Compute the log-sigmoid stably.
For a margin of , the predicted preference is and the corrective coefficient for ascent is . At a margin of , that coefficient is . Incorrectly ranked pairs receive stronger corrective pressure.
The ideal optimum derivation does not say that finite-data DPO and PPO have identical trajectories or outcomes. DPO's gradient is a preference-likelihood gradient over a fixed dataset. A log-probability derivative alone does not identify an algorithm as reinforcement learning: SFT also has one.
Reading: Rafailov et al., Section 4.
11. Comparing the learning problems
| Method | Data used for an update | Feedback | Main qualification |
|---|---|---|---|
| SFT | Fixed demonstrations | Target response tokens | Learns demonstrated behavior |
| REINFORCE | Current-policy samples | Return, optional baseline | Monte Carlo policy-gradient estimator |
| PPO | Fixed batch from a rollout snapshot | Detached advantages | Local clipped surrogate; monitor policy drift |
| GRPO | Groups from a rollout snapshot | Relative group scores | Variant and normalization matter |
| DPO | Fixed preference pairs | Winner/loser labels | Direct preference likelihood |
The companion notebook checks REINFORCE arithmetic, PPO's sign-dependent clipping, GAE recursion, and old/reference roles. Optional P01–P02 check GRPO group statistics and DPO margins. All examples run offline on CPU and are ungraded. The post-training reading guide offers longer courses and implementation references.