Lecture 17 · Reinforcement Learning II: Applications to Language Models

Advanced Natural Language Processing · Lecture 17。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 17 (03/17), “Reinforcement Learning II: Applications”; slides anlp-s2026-17-rl-llms.pdf; course code 17_rl_llm/ (sft.py, reverse_ppo.py, evaluate.py, rl_reverse.ipynb). Readings: L. Ouyang et al., Training Language Models to Follow Instructions with Human Feedback (InstructGPT, NeurIPS 2022); DeepSeek-AI, DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning (2025; Nature 2025). Additional: Y. Dubois et al., AlpacaFarm (NeurIPS 2023); P. Christiano et al., Deep Reinforcement Learning from Human Preferences (NeurIPS 2017); D. Ziegler et al., Fine-Tuning Language Models from Human Preferences (2019); R. Rafailov et al., Direct Preference Optimization (NeurIPS 2023). Sources: the public slides and code, the readings, and the papers cited in each section. Every number labelled “measured” comes from code/lecture17/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Numbers from papers are cited as such. Code: code/lecture17/ — five demos, each under two minutes. Reading time: ~100 minutes for the prose; ~25 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Frame text generation as an MDP, one-step or token-level, and name the four key decisions of an RL setup for LMs: initialization, prompts, reward, optimizer settings.
  2. Explain RL with verifiable rewards (RLVR) and GRPO: why supervised fine-tuning comes first, how group-based advantages work, what the PPO loss does per token, and why most groups carry no gradient.
  3. Describe the DeepSeek-R1 recipe and what RL changed in its reasoning.
  4. Explain the three steps of RLHF, derive the Bradley–Terry reward-model loss, and say where a learned reward model is right and wrong.
  5. Explain reward hacking, the KL penalty, its closed-form optimal policy π⋆∝π0 er/β\pi^\star \propto \pi_0\, e^{r/\beta}, and how the KL is estimated from samples.
  6. Derive DPO from that closed form, and compare RLHF, DPO and best-of-N on a reward–KL frontier.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 16: MDPs, the policy gradient, baselines and advantages, PPO’s clip.
    • Lecture 8: supervised and instruction fine-tuning.
    • Lecture 13: pass@k, LLM judges and pairwise comparisons (Bradley–Terry).
  • Scope: the slides’ three examples (string reversal, math, preferences) and the terminology (RLVR, RLHF, GRPO, PPO). DPO comes from the readings.
  • Not in scope:
    • Process reward models and search (Lecture 23).
    • Constitutional AI / RLAIF beyond a mention.
    • Agents (Lecture 18).
    • Distributed RL infrastructure.

0.3 Section → code map

SectionIdeaDemo in code/lecture17/
§2.1–2.5SFT, then GRPO on string reversal; RL from scratch; pass@k01_rlvr_reversal.py
§2.6group advantages, normalization, dead groups, dynamic sampling02_group_advantages.py
§4.3preference data and a Bradley–Terry reward model03_reward_model.py
§4.4KL penalty, closed-form optimum, over-optimization, KL estimators04_rlhf_kl.py
§5best-of-N, DPO, the reward–KL frontier05_dpo_best_of_n.py

0.4 Notation

SymbolMeaning
xx, y=(y1,…,yT)y = (y_1, \dots, y_T)prompt and response
pθ(y∣x)p_\theta(y \mid x) or πθ\pi_\thetathe policy (the language model being trained)
p0p_0 or πref\pi_{\text{ref}}the reference policy, usually the SFT model
r(x,y)r(x, y)a reward: rule-based (“verifiable”) or a learned reward model rϕr_\phi; r⋆r^\star the true reward in demos 03–05
AAan advantage; KK the number of samples per prompt (group size)
β\betastrength of the KL penalty (and DPO’s temperature)
σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z})the logistic function

1. The RL framework for language models

1.1 Three ingredients

The loop of Lecture 16, with a language model in the agent’s seat:

  1. Generate outputs with the model.
  2. Evaluate a reward for each output.
  3. Update the model’s parameters to make high-reward outputs more likely.

1.2 Step 0: frame the problem as an MDP

The slides give two framings:

one-step MDPtoken-level MDP
statethe prompt xxthe prompt and the tokens so far, (x,y<t)(x, y_{<t})
actionthe whole response yythe next token yty_t
policypθ(y∣x)p_\theta(y \mid x)pθ(yt∣y<t,x)p_\theta(y_t \mid y_{<t}, x)
transitionappend the response; doneappend the token
rewardr(x,y)r(x, y) on the full sequencert=0r_t = 0 for t<Tt < T, rT=r(x,y)r_T = r(x, y)

The two are the same optimization problem: log⁡pθ(y∣x)=∑tlog⁡pθ(yt∣y<t,x)\log p_\theta(y \mid x) = \sum_t \log p_\theta(y_t \mid y_{<t}, x), so the policy gradients coincide. They differ in credit assignment. The token-level view can give different tokens different rewards (a per-token KL penalty, a process reward) and different advantages (a value function per prefix). The one-step view gives every token of a response the same advantage.

With either view, Lecture 16’s algorithm applies directly:

  • given a pre-trained or fine-tuned model, a set of prompts and a reward function, loop:
    1. generate outputs y^∼pθ(⋅∣x)\hat y \sim p_\theta(\cdot \mid x);
    2. compute the rewards and advantages AtA_t;
    3. minimize L=−∑tAtlog⁡pθ(y^t∣y^<t,x)\mathcal L = -\sum_t A_t \log p_\theta(\hat y_t \mid \hat y_{<t}, x) (or PPO’s clipped version) and update.

1.3 Key decisions

The slides organize everything that follows around four decisions:

  1. Fine-tune first or not. Where does the policy start?
  2. The dataset of inputs. Which prompts, how hard, how many.
  3. The reward function. Rule-based (“verifiable”), or a learned model of human judgments.
  4. Policy-optimization settings. How advantages are computed, which loss, hyperparameters.

2. Example 1: reversing a string (RLVR + GRPO)

The course code fine-tunes SmolLM2-135M to reverse names (“hello” → “olleh”), then improves it with RL. The demos rebuild the pipeline at laptop scale (reverse_task.py):

  • 8,000 generated names of 3–10 letters (“tusnikthu”, “zailha”, …);
  • a 2-layer character Transformer from Lecture 5;
  • prompts of the form <s> _ _ _ k a m o r u |, answered by u r o m a k </s>.

2.1 Fine-tuning before RL (“cold start”)

Given a pretrained model pθ0p_{\theta_0}, it often helps to fine-tune first, pθ0→pθSFT→pθRLp_{\theta_0} \to p_{\theta_{\text{SFT}}} \to p_{\theta_{\text{RL}}}. The slides list pros and cons:

proscons
teaches the task formatrequires a dataset of (x,y)(x, y) examples
uses the supervision in the datamay narrow or bias the output distribution
the model then encounters high-reward outputs

The third pro is the decisive one. Measured (demo 01):

  • SFT on 1,000 pairs (600 steps) gives 66.0% exact reversals on held-out names. The course’s SmolLM2 reached 64.8%. Accuracy falls with length: 100% on 3-letter names, 28.7% on 10-letter ones.
  • RL from a randomly initialized model produced 0 correct answers in 2,560 samples. Every group of samples has the same reward (0), every advantage is 0, and there is no gradient. This is Lecture 16’s sparse-reward problem (one success per 11,122 random episodes in Key Quest) in its purest form.

“Cold start” in recent papers means exactly this initial SFT. DeepSeek-R1-Zero showed that a strong enough pretrained model can skip it for math (§3), because its samples are already sometimes right.

2.2 Rule-based (“verifiable”) rewards

A verifiable reward checks a property of the output with a program:

  • reversal: 1 if the output is the reversed input, else 0;
  • math: 1 if the final answer equals the reference answer, else 0;
  • code: the fraction of test cases passed.

There is no learned model to fool: what is checked is what is wanted, as long as the checker is right. RL with such rewards is now called RLVR (RL with verifiable rewards).

2.3 Group-based advantages

For each input x(i)x^{(i)}, generate KK outputs y(i,1),…,y(i,K)y^{(i,1)}, \dots, y^{(i,K)}, then subtract the group’s mean reward and optionally divide by its standard deviation ZZ:

A(i,k)=r(i,k)−mean(r(i,1),…,r(i,K))Z.A^{(i,k)} = \frac{r^{(i,k)} - \mathrm{mean}(r^{(i,1)}, \dots, r^{(i,K)})}{Z}.

The slides’ example (demo 02 reproduces it), for the prompt “reverse hello”:

outputollhollhollholleh
reward0001
advantage, no normalization−0.25−0.25−0.250.75
advantage, ZZ = group std−0.50−0.50−0.501.50

This is Lecture 16’s leave-one-out baseline in another form. Each sample is judged against other samples for the same prompt, so an easy prompt and a hard one are compared only with themselves.

  • Pros: no learned value function, which for an LLM would be another LLM-sized network.
  • Cons:
    • it is less clear how to assign advantages to non-terminal states (every token of a response gets the same advantage);
    • generating KK outputs per prompt is expensive.

2.4 The PPO loss, per token

The policy-gradient loss is LPG=Atlog⁡pθ(yt∣y<t,x)\mathcal L_{\text{PG}} = A_t \log p_\theta(y_t \mid y_{<t}, x). PPO (Lecture 16) replaces it with the clipped ratio to the policy that generated the samples:

LPPO=min⁡(pθ(yt∣y<t,x)pθold(yt∣y<t,x) At, clip(pθpθold, 1−ϵ, 1+ϵ) At).\mathcal L_{\text{PPO}} = \min\Big(\frac{p_\theta(y_t \mid y_{<t}, x)}{p_{\theta_{\text{old}}}(y_t \mid y_{<t}, x)}\, A_t,\ \mathrm{clip}\Big(\frac{p_\theta}{p_{\theta_{\text{old}}}},\, 1 - \epsilon,\, 1 + \epsilon\Big)\, A_t\Big).

The course’s reverse_ppo.py:

  • takes 3 gradient steps per batch;
  • clips to the asymmetric range [0.8, 2.0] (“clip-higher”, as in DAPO), which lets rarely chosen tokens with positive advantage grow faster;
  • averages the loss over each response’s tokens, then over responses;
  • normalizes advantages by the batch’s standard deviation.

GRPO (Shao et al., 2024) is precisely this combination: the PPO-style loss plus group-based advantages, often with a KL penalty to a reference model (§4.4).

2.5 Measured: GRPO on string reversal

Demo 01 runs GRPO from the SFT model: 16 prompts × 8 samples per update, clip [0.8, 2.0], 2 epochs, Adam 3e-4:

RL updatestrain rewarddead groupstest accuracy
0 (SFT)––66.0%
10071.4%74.4%66.6%
30077.9%80.1%76.7%
60085.8%87.1%83.8%
name length345678910
SFT100%63%65%91%83%70%51%29%
SFT + GRPO100%90%90%98%93%87%78%57%
  • RL improves exactly where SFT was weak. Long names gain 27 points on average. The course reported 64.8% → 92.6% after an hour on an A100; our scale gets 66.0% → 83.8% in about a minute on a CPU.
  • Most groups carry no signal. A “dead” group has 8 identical rewards: all right on easy names, all wrong on hard ones. Their advantages are all 0. Dead groups rise from 74.4% to 87.1% of prompts as the model improves, so learning slows as it succeeds.
  • The learning rate decides everything. In prototypes, 2e-3 collapsed the policy and 1e-3 barely moved it; 3e-4 gave the steady climb above.

Sharpening or new skills? pass@k from 32 samples per name:

modelpass@1pass@4pass@16
SFT65.1%73.3%77.6%
SFT + GRPO83.2%88.1%90.1%

RL sharpens: the gap between pass@16 and pass@1 shrinks from 12.5 to 6.9 points, so what the model can find in a few tries it now finds first. But here it also extends: pass@16 itself rises by 12.5 points. Yue et al. (2025) found the opposite on math, where RL-trained models fall below their base models at large kk. Whether RL teaches new skills or only reweights existing ones depends on the task and the starting point. It is a measurement to make, not a law.

2.6 Policy-optimization settings, measured

Normalizing by the group’s standard deviation re-weights prompts (demo 02). For a group of 8 with cc correct answers:

correct in the groupadvantage of a right / wrong answer, mean onlytotal weight ∑∣A∣\sum \lvert A \rvertwith std: right / wrongtotal weight
1 of 8+0.875 / −0.1251.75+2.475 / −0.3544.95
4 of 8+0.500 / −0.5004.00+0.935 / −0.9357.48
7 of 8+0.125 / −0.8751.75+0.354 / −2.4754.95

Dividing by the std flattens the difference between prompts the model almost never solves and prompts it solves half the time. Liu et al. (2025, “Dr. GRPO”) call this a difficulty bias and drop it. GRPO’s per-response length averaging introduces a similar length bias, which they also remove.

Dead groups vs group size. At the SFT model, 43.2% of names are always right in 32 tries and 15.8% never. The expected share of dead groups:

group size KK2481632
dead groups92.0%85.2%78.3%71.5%65.3%

Larger groups help only slowly, at proportionally more generation.

Dynamic sampling (DAPO; Yu et al., 2025) oversamples prompts, discards dead groups and trains only on live ones. At an equal number of generated responses (25,600; 2 seeds each):

  • dynamic sampling has 7.4 live groups per update vs 3.6;
  • but it makes half as many updates;
  • it ends at 73.0% vs 75.0% for plain GRPO.

Whether filtering pays depends on what is expensive. When generation dominates the cost, as here, it does not. Compare methods at equal compute (Lecture 14).


3. Example 2: solving math problems (DeepSeek-R1)

The slides’ second example is the case study that made RLVR famous:

  • task: math problems with a checkable final answer;
  • input: the problem statement; output: a chain of thought, then the answer.

The recipe of DeepSeek-R1-Zero (DeepSeek-AI, 2025):

  • Model: a pretrained base model (DeepSeek-V3-Base), with no SFT. A strong pretrained model already solves some problems by sampling, so the cold-start problem of §2.1 does not arise.
  • MDP: one-step: the prompt in, the whole reasoning plus answer out.
  • Reward: rule-based. An accuracy reward (is the final answer right?) and a format reward (is the reasoning inside <think> … </think> tags?). No neural reward model, deliberately, to avoid reward hacking (§4.4).
  • Algorithm: GRPO, with a KL penalty to the reference model.

What the paper reports:

  • AIME 2024 pass@1 rose from 15.6% to 71.0% over training (86.7% with majority voting over 64 samples).

  • The average response length grew steadily: the model learned on its own to “think longer”, including reflection and re-checking (“aha moment”).

  • R1-Zero’s outputs were hard to read and mixed languages. DeepSeek-R1 therefore added stages:

    1. a small cold-start SFT on long chains of thought;
    2. RL;
    3. rejection sampling to build a larger SFT set;
    4. SFT;
    5. a final RL stage, also on general (preference-rewarded) tasks.

    R1 reports 79.8% pass@1 on AIME 2024.

  • Distillation of R1’s outputs into smaller dense models worked better than running RL on those small models directly.

Lessons that match the measurements above:

  • RL with a verifiable reward needs a starting policy that sometimes succeeds. A large pretrained model can provide one; our tiny model could not (§2.1).
  • The training signal comes only from prompts of intermediate difficulty, so data selection matters: all-right and all-wrong prompts are dead groups (§2.6).
  • Length and behavior can change substantially under RL even with a simple reward. Monitor them; Lecture 23 returns to controlling the length of chains of thought.

4. Example 3: alignment with human preferences (RLHF)

4.1 The key challenge: evaluating the reward

“Generate a chat completion that human users find good” has no checker. The reward must be learned:

  • Direct assessment models: r(x,y)→Rr(x, y) \to \mathbb R or [0,1][0, 1], e.g. a classifier for “helpful” or “safe” (the slides show a toxicity classifier).
  • Preference models: it is often easier for people to say which of two responses is better than to assign absolute scores. The reward is learned from pairwise comparisons.

4.2 RLHF’s three steps

  1. Supervised fine-tuning (SFT) on DSFT={(x(n),y(n))}D_{\text{SFT}} = \{(x^{(n)}, y^{(n)})\}. Examples:
    • Alpaca: 52,000 model-generated (prompt, response) pairs;
    • AI2’s Tulu 3: about 900k prompts, 57% from open data and 43% generated for instruction following, math and code, with responses from proprietary models and skill-specific mixtures.
  2. Reward modeling. Train rϕ(x,y)r_\phi(x, y) on preference data Dpref={(x,y+,y−)}D_{\text{pref}} = \{(x, y^+, y^-)\}:
    • prompts reused from SFT or new (AlpacaFarm held out 10k of Alpaca’s 52k);
    • responses generated by the SFT model or others;
    • preference ratings from hired human labelers, or from a strong LLM (AlpacaFarm used GPT-4 as the annotator; Lecture 13’s LLM-as-a-judge).
  3. Reinforcement learning. Fine-tune the SFT model p0p_0 with RL against rϕr_\phi on prompts {x(n)}\{x^{(n)}\}, typically with PPO. This is InstructGPT’s pipeline (Ouyang et al., 2022).

4.3 The Bradley–Terry reward model

The Bradley–Terry model (1952) gives the probability that item ii beats item jj in a comparison as pi/(pi+pj)p_i/(p_i + p_j). Set pi=exp⁡(rθ(yi))p_i = \exp(r_\theta(y_i)) and divide by exp⁡(rθ(yi))\exp(r_\theta(y_i)):

P(yi≻yj)=erθ(yi)erθ(yi)+erθ(yj)=11+e−[rθ(yi)−rθ(yj)]=σ(rθ(yi)−rθ(yj)).P(y_i \succ y_j) = \frac{e^{r_\theta(y_i)}}{e^{r_\theta(y_i)} + e^{r_\theta(y_j)}} = \frac{1}{1 + e^{-[r_\theta(y_i) - r_\theta(y_j)]}} = \sigma\big(r_\theta(y_i) - r_\theta(y_j)\big).

Maximizing the likelihood of all observed preferences gives the reward-model loss

LNLL(θ)=−∑(y+,y−)∈Dlog⁡σ(rθ(y+)−rθ(y−)).\mathcal L_{\text{NLL}}(\theta) = -\sum_{(y^+, y^-) \in D} \log \sigma\big(r_\theta(y^+) - r_\theta(y^-)\big).

Only differences of rewards are identified. Adding a constant changes nothing, which is why Lecture 16’s baselines are indispensable with reward models.

Measured in Reply World (demo 03). The world is a toy chat task:

  • four multiple-choice questions;
  • replies of up to 4 tokens from {A, B, C, D, because, please}, i.e. 1,555 possible replies;
  • a hidden true reward r⋆r^\star (+2 for the right letter, +1 for one explanation, +0.3 for one “please”, penalties for wrong letters, repetition and verbosity; best reply “A because please” = 3.3);
  • an SFT model whose expected true reward is 1.004.

Annotators compare two SFT replies and pick one with probability σ(r⋆(y1)−r⋆(y2))\sigma(r^\star(y_1) - r^\star(y_2)).

  • The labels are noisy. In 2,000 pairs the annotator picked the truly worse reply 16.8% of the time, and 10.1% of pairs were ties. The Bayes ceiling, the expected accuracy of a perfect reward model, is 79.2%. A reward model’s accuracy must be read against that, not 100%.
  • A linear reward model over five counts (right letter present, wrong letters, “because”s, “please”s, length) reaches 76.7% with 2,000 pairs. With 200 pairs it gets 74.7%; with 20,000, 76.9%. More data barely helps, because the limit is what five counts can express.
  • A tabular reward model (a free score per reply) reaches 71.7% with 2,000 pairs and 77.0% with 20,000. It is flexible but needs data for every reply: with 2,000 pairs, 24.2% of held-out pairs involve a reply it never saw.

Where is the reward model right?

pairs of repliesthe linear RM orders them like r⋆r^\star
replies the SFT model writes91.4%
all 1,555 replies, uniformly92.2%
the RM’s own 50 favorite replies52.6%

Its weights explain the blind spot: “because” +0.68 and “please” +0.72 per occurrence, length −0.63 per token. Counts cannot express “one is good, three are bad”. Its favorite reply to question 0 is “A please please please” (RM 2.51, true 0.8). The truly best reply, “please A because”, scores 2.38.

A reward model is accurate where its training data was, which is the SFT model’s replies, and near chance among the replies it likes most. Those are exactly where RL will push the policy.

4.4 Reward hacking and the KL penalty

Reward hacking: models overfit to patterns in the reward. The slides’ quiz: if r(x,y)r(x, y) measures how non-offensive an output is, the policy that maximizes it is the empty response. Real reward models have subtler versions: length, flattery, repetition, formatting.

The mitigation is to keep the policy close to the SFT model:

max⁡θ Ex, y∼pθ[r(x,y)]−β DKL(pθ ∥ p0).\max_\theta\ \mathbb E_{x,\, y \sim p_\theta}[r(x, y)] - \beta\, D_{\mathrm{KL}}(p_\theta \,\|\, p_0).

  • Higher β\beta: more pressure to stay close to p0p_0.
  • Lower β\beta: more freedom to maximize reward.

It is usually implemented as a modified reward that needs a frozen copy of the reference model:

rKL(x,y)=r(x,y)−βlog⁡pθ(y∣x)p0(y∣x),r_{\mathrm{KL}}(x, y) = r(x, y) - \beta \log \frac{p_\theta(y \mid x)}{p_0(y \mid x)},

a single-sample Monte Carlo estimate of the penalty, since DKL=Ey∼pθ[log⁡pθ(y∣x)/p0(y∣x)]D_{\mathrm{KL}} = \mathbb E_{y \sim p_\theta}[\log p_\theta(y \mid x) / p_0(y \mid x)].

The closed-form optimum (Korbak et al., 2022; Rafailov et al., 2023). For each prompt, the objective is ∑yp(y) r(y)−β∑yp(y)log⁡p(y)p0(y)\sum_y p(y)\, r(y) - \beta \sum_y p(y) \log \frac{p(y)}{p_0(y)}. Rewrite it as

−β DKL(p ∥ 1Z p0 er/β)+βlog⁡Z,-\beta\, D_{\mathrm{KL}}\Big(p \,\Big\|\, \frac{1}{Z}\, p_0\, e^{r/\beta}\Big) + \beta \log Z,

which is maximized when the KL term is zero:

p⋆(y∣x)=1Z(x) p0(y∣x) exp⁡ ⁣(1β r(x,y)).p^\star(y \mid x) = \frac{1}{Z(x)}\, p_0(y \mid x)\, \exp\!\Big(\frac{1}{\beta}\, r(x, y)\Big).

The optimal policy reweights the reference model. It never puts mass where p0p_0 has none, and β\beta is a temperature on the reward.

Measured: over-optimization in closed form (demo 04, Part A). Reply World’s response space is small enough to compute p⋆p^\star exactly for the learned reward model and for the true reward:

βKLproxy (RM) rewardtrue rewardmost likely reply to question 0oracle (r⋆r^\star): KL / true
30.0901.5131.620A (0.22)0.116 / 1.736
10.4302.0772.225A (0.28)0.585 / 2.505
0.20.8942.3352.481A (0.22)2.072 / 3.200
0.052.0012.4312.314please please A because (0.06)2.872 / 3.299
0.015.2552.5081.005please please please A (0.43)2.899 / 3.300

As β\beta falls:

  • the proxy reward rises monotonically;
  • the true reward peaks at 2.481 (β=0.2\beta = 0.2, KL 0.89), then falls back to 1.005, no better than the SFT model.

This is Goodhart’s law (“when a measure becomes a target, it ceases to be a good measure”) and Gao et al.’s (2023) over-optimization curve. With the true reward, the same KL would buy 3.2–3.3.

Measured: during training (Part B). A policy-gradient learner on rKLr_{\mathrm{KL}}: 8 samples per prompt, leave-one-out baseline, 2,000 updates.

updateno penalty: KLproxytrueβ = 0.2: KLproxytrue
500.692.0502.1330.592.0432.166
2002.212.3112.5510.912.2382.408
8005.422.4502.3970.902.3012.477
20006.402.4832.0020.912.3182.473
  • Without the penalty, the true reward peaks early and then falls while the proxy keeps rising. The policy ends on “A please because please” with probability 1.00.
  • With β=0.2\beta = 0.2, it settles at KL 0.91 with true reward 2.473, only 0.100 nats from the closed-form pβ⋆p^\star_\beta.

Early stopping on the true reward would work, but in practice the true reward is unobserved. The KL penalty is the principled substitute.

Estimating the KL from samples (Part C). The slides’ estimate k1=log⁡(pθ/p0)k_1 = \log(p_\theta/p_0) is unbiased but noisy and can be negative. Schulman’s k3=(ρ−1)−log⁡ρk_3 = (\rho - 1) - \log \rho, with ρ=p0/pθ\rho = p_0/p_\theta, is unbiased and never negative (GRPO uses it). Measured over 40,000 samples:

policyestimatormeanstd per samplenegative
near p0p_0 (exact KL 0.0899)k1k_10.09180.39327.1%
k3k_30.08860.1140%
far from p0p_0 (exact KL 0.8943)k1k_10.89280.5040.5%
k3k_30.46612.8070%

k3k_3 is far better near the reference. Far from it, rare samples with huge ρ\rho (the largest was 225) make it unreliable even with 40,000 samples. Per-token KLs in LLM training are small, which is why k3k_3 works there.

4.5 The algorithm in practice

InstructGPT used PPO with GAE (Lecture 16) on the token-level MDP:

  • the reward is the reward model’s score at the last token, minus a per-token KL penalty;
  • a value network (usually initialized from the reward model) estimates per-prefix values;
  • four models are in memory: policy, reference, reward model, value network.

GRPO removes the value network by using group-mean advantages (§2.3). That is a large saving at LLM scale, and one reason GRPO became the default for RLVR.


5. Using preferences without RL: best-of-N and DPO

5.1 Best-of-N

The simplest way to use a reward model: sample NN responses from the SFT model and return the one rϕr_\phi scores highest (rejection sampling; WebGPT, Nakano et al., 2021). There is no training at all. Its KL from p0p_0 is bounded by log⁡N−(N−1)/N\log N - (N - 1)/N (Beirami et al., 2024).

Measured exactly (demo 05):

NN12481664256
KL00.1910.6301.1911.8173.1034.212
bound00.1930.6361.2041.8353.1754.549
true reward1.0041.8412.3712.5262.4542.1391.598
oracle best-of-N (with r⋆r^\star)1.0041.8952.5292.9023.1283.2923.300

Best-of-N over-optimizes too: past N=8N = 8 the reward model’s errors dominate. Lecture 23 studies best-of-N with verifiers as a test-time scaling method.

5.2 Direct Preference Optimization

DPO (Rafailov et al., 2023) turns the closed form of §4.4 around. If p⋆=p0 er/β/Zp^\star = p_0\, e^{r/\beta}/Z, then the reward is determined by the policy:

r(x,y)=βlog⁡p⋆(y∣x)p0(y∣x)+βlog⁡Z(x).r(x, y) = \beta \log \frac{p^\star(y \mid x)}{p_0(y \mid x)} + \beta \log Z(x).

Substitute into the Bradley–Terry likelihood. The intractable βlog⁡Z(x)\beta \log Z(x) is the same for both responses of a pair and cancels:

LDPO(θ)=−∑(x,y+,y−)log⁡σ(βlog⁡pθ(y+∣x)p0(y+∣x)−βlog⁡pθ(y−∣x)p0(y−∣x)).\mathcal L_{\text{DPO}}(\theta) = -\sum_{(x, y^+, y^-)} \log \sigma\Big(\beta \log \frac{p_\theta(y^+ \mid x)}{p_0(y^+ \mid x)} - \beta \log \frac{p_\theta(y^- \mid x)}{p_0(y^- \mid x)}\Big).

This is a classification loss on the preference pairs, with no reward model, no sampling and no RL. In the paper’s phrase, the language model is “secretly a reward model”: its implicit reward is βlog⁡(pθ/p0)\beta \log(p_\theta/p_0).

Measured (demo 05, β = 0.1, full-batch training on the same 2,000 pairs):

epochKLtrue rewardimplicit-reward accuracymean log-prob: chosen / rejected
250.7122.22670.3%−4.15 / −6.86
1001.3252.53472.8%−6.32 / −14.55
2001.9452.59372.9%−8.89 / −21.66
6004.1702.51371.9%−18.58 / −39.62

(For p0p_0: chosen −4.00, rejected −4.45.)

  • DPO works, and it over-optimizes too. The true reward peaks at 2.593 and then declines as the KL grows: DPO’s β\beta does not stop it from drifting, only early stopping does (Azar et al., 2023).
  • Likelihood displacement. DPO lowers the probability of the chosen replies (−4.00 → −18.58), just more slowly than the rejected ones. The loss only needs the gap. The mass goes to the few replies that win most often, which end with 99.9% of it (Razin et al., 2024; Pal et al., 2024).
  • The implicit reward is a reward model. It orders held-out pairs 72.9% right, less accurately than the linear reward model (76.3% on the same pairs), yet DPO reaches a higher true reward (next section).

5.3 The reward–KL frontier

The best true reward each method reaches within a KL budget (demo 05):

methodKL ≤ 0.5KL ≤ 1KL ≤ 2KL ≤ 4
oracle: pβ⋆p^\star_\beta with r⋆r^\star2.0082.7203.1003.300
RLHF: pβ⋆p^\star_\beta with the reward model2.2252.4842.4842.484
best-of-N with the reward model1.8412.3712.5262.526
DPO (checkpoints)–2.3102.5932.593
  • Everything stops far below the oracle. 2,000 noisy preferences do not pin down the true reward; better data, not a better optimizer, is the main lever.
  • DPO edges out RLHF here, despite its lower held-out accuracy. Its implicit reward is per reply rather than five counts, so it is less wrong where the policy goes. Held-out accuracy on the SFT model’s replies is not what matters (§4.3). With a well-specified reward model the ranking could flip: the comparison depends on the reward model, not only on the algorithm.

6. The landscape of methods

The slides classify methods by three choices:

methodlossrewardadvantages
GRPOPPO loss + KL-penalty lossany (typically rule-based)group-based, std-normalized
PPOPPO lossanyany (typically GAE)
PPO as applied in RLHFPPO lossmodel-based preference reward + KL penaltyGAE with a value network

Many recent variants tweak one of these:

  • RLOO uses leave-one-out advantages;
  • Dr. GRPO removes the std and length normalizations;
  • DAPO adds clip-higher, dynamic sampling and token-level loss averaging;
  • DPO and its relatives (IPO, KTO, SimPO) remove the RL loop altogether.

Practical tools (the slides): Hugging Face TRL (SFT, reward modeling, PPO, GRPO, DPO trainers) and verl (Volcano Engine’s distributed RL framework for LLMs).


7. Summary

  1. RL for LMs = generate, reward, update. Frame it as a one-step or token-level MDP, then decide the initialization, prompts, reward and optimizer settings.
  2. Fine-tune first when the model rarely succeeds. Measured: RL from scratch saw 0 rewards in 2,560 samples; SFT gave 66.0%.
  3. RLVR + GRPO: verifiable 0/1 rewards, group-mean (± std) advantages, PPO’s clipped loss. Measured:
    • 66.0% → 83.8%, mostly on long names;
    • most groups are dead (78% at K = 8) and more become dead as the model improves;
    • pass@k rose at every k here.
  4. DeepSeek-R1: GRPO with accuracy and format rewards from a base model; reasoning length grows; cold-start SFT and distillation in the full pipeline.
  5. RLHF: SFT → Bradley–Terry reward model → RL with a KL penalty. Measured:
    • the reward model is 91% right on the SFT model’s replies and 53% among its own favorites;
    • over-optimization shows in closed form (true reward 2.481 → 1.005 as β → 0) and during training;
    • the KL penalty keeps the policy near pβ⋆p^\star_\beta.
  6. Without RL: best-of-N (peaks at N = 8) and DPO (the policy is the reward model; likelihood displacement). All methods stop far below the oracle frontier.

Common pitfalls

  • Starting RL where the policy never succeeds. No reward, no gradient; fine-tune first or choose easier prompts.
  • Ignoring dead groups. Report the share of zero-advantage groups; it tells you how much of your generation budget teaches nothing.
  • Comparing RL variants at equal updates instead of equal compute. Dynamic sampling looks better per update and worse per generated response.
  • Trusting a reward model’s held-out accuracy. It measures agreement on the SFT model’s outputs, not where the policy will go.
  • Training against a learned reward without a KL penalty or early stopping. The proxy keeps rising while the true reward falls.
  • Using k3k_3 (or any single-sample KL estimate) far from the reference. Heavy tails make it unreliable.
  • Reading DPO’s falling chosen-response likelihood as a bug. It is how the loss works, and it can push mass onto unintended outputs.
  • Concluding “DPO beats RLHF” (or the reverse) from one setting. The reward model, the data and the KL budget decide.

Exercises

  1. Two MDPs, one gradient. Show that the policy gradient of Ey∼pθ[r(x,y)]\mathbb E_{y \sim p_\theta}[r(x, y)] in the one-step MDP equals the token-level policy gradient with rt=0r_t = 0 for t<Tt < T and rT=r(x,y)r_T = r(x, y) (no discounting, no baseline). What changes when a per-token KL penalty is added to the rewards?

    AnswerOne-step: $\mathbb E[r\,\nabla\log p_\theta(y \mid x)] = \mathbb E[r \sum_t \nabla \log p_\theta(y_t \mid y_{
  2. Group advantages. For a group of 4 with rewards (1, 1, 1, 0), compute the advantages with and without std normalization. What happens to a group (1, 1, 1, 1)? Why does GRPO add a small ϵ\epsilon to the std?

    AnswerMean 0.75: without std (0.25, 0.25, 0.25, −0.75). Unbiased std = 0.5: (0.5, 0.5, 0.5, −1.5). All-ones: every advantage is 0 (dead group, no gradient). Its std is 0, so without $\epsilon$ the normalization would divide 0 by 0; $\epsilon$ keeps it at 0.
  3. Bradley–Terry. A reward model gives r(y1)=2.0r(y_1) = 2.0, r(y2)=0.5r(y_2) = 0.5. What probability does it assign to y1≻y2y_1 \succ y_2? If every reward is shifted by +10, what changes? If they are multiplied by 2?

    Answer$\sigma(1.5) \approx 0.818$. Shifting changes nothing (only differences enter): reward models are identified only up to a constant, hence baselines. Doubling gives $\sigma(3.0) \approx 0.953$: the scale is identified by the data's noise level, and it interacts with $\beta$ in the KL penalty (only $r/\beta$ matters for $p^\star$).
  4. The closed form. Derive p⋆=p0er/β/Zp^\star = p_0 e^{r/\beta}/Z by writing the objective as −β DKL(p ∥ p0er/β/Z)+βlog⁡Z-\beta\,D_{\mathrm{KL}}(p \,\|\, p_0 e^{r/\beta}/Z) + \beta\log Z. What does p⋆p^\star become as β→∞\beta \to \infty and as β→0\beta \to 0?

    Answer$\sum_y p(r - \beta\log\frac{p}{p_0}) = -\beta\sum_y p\log\frac{p}{p_0 e^{r/\beta}} = -\beta\sum_y p \log\frac{p}{p_0e^{r/\beta}/Z} + \beta\log Z$. KL ≥ 0 with equality iff $p = p_0e^{r/\beta}/Z$. As $\beta \to \infty$, $p^\star \to p_0$. As $\beta \to 0$, $p^\star$ concentrates on $\arg\max_y r(x, y)$ among responses with $p_0 > 0$: pure reward maximization, which is where Reply World's true reward fell to 1.005.
  5. DPO’s cancellation. Show that Z(x)Z(x) cancels in the Bradley–Terry likelihood when r=βlog⁡(p⋆/p0)+βlog⁡Zr = \beta\log(p^\star/p_0) + \beta\log Z. Why would it not cancel in a loss that scores single responses (e.g. regressing r(x,y)r(x, y) on a rating)?

    Answer$r(y^+) - r(y^-) = \beta\log\frac{p^\star(y^+)}{p_0(y^+)} + \beta\log Z - \beta\log\frac{p^\star(y^-)}{p_0(y^-)} - \beta\log Z$: the $Z$ terms are equal (same prompt) and cancel. A loss on a single response's absolute reward would need $\beta\log Z(x)$, a sum over all responses: intractable. DPO relies on Bradley–Terry using only differences, which is also why only pairwise (or ranked) preferences work directly.
  6. Best-of-N’s KL. For a continuous reward with no ties, the KL of best-of-N from p0p_0 is exactly log⁡N−(N−1)/N\log N - (N-1)/N. Why is Reply World’s exact KL slightly below the bound (3.103 vs 3.175 at N=64N = 64)?

    AnswerWith ties, best-of-N must break them among equally scored responses. It then keeps their relative probabilities from $p_0$, which costs less KL than the no-ties formula assumes. Reply World's linear reward model gives many replies identical scores (same counts), so the exact KL is lower. Beirami et al. (2024) show the formula is an upper bound in general.
  7. Reward hacking by design. In Reply World the linear reward model gives “please” +0.723 per occurrence and length −0.626 per token. Which replies does it rank above “A because please”? What single feature would fix it?

    AnswerEach extra "please" adds 0.723 − 0.626 = +0.097, so "A please please please" (2.51) beats "A because please" (2.38): more "please"s at the cost of the explanation. A feature like "at least one 'please'" (an indicator instead of a count), or a penalty for repeats, lets the model express "one is good, more is bad". In practice reward models are neural nets whose blind spots are not so easy to name; this is why one monitors outputs and keeps a KL penalty.
  • Assignment 3 (literature review, proposal, baseline reproduction) and Assignment 4 (project): RL fine-tuning of small models is a feasible project, with TRL or verl and a verifiable reward. Plan to measure:

    • the share of dead groups;
    • pass@k before and after;
    • the KL to the reference;
    • comparisons at equal generated tokens, not equal updates.

    If you use a learned reward, check it on the outputs your policy produces, not only on held-out preference pairs. These notes do not provide assignment code.

Further reading

  • L. Ouyang et al., “Training Language Models to Follow Instructions with Human Feedback”, NeurIPS 2022 (course reading); DeepSeek-AI, “DeepSeek-R1”, 2025 / Nature 2025 (course reading).
  • P. Christiano et al., “Deep Reinforcement Learning from Human Preferences”, NeurIPS 2017; D. Ziegler et al., “Fine-Tuning Language Models from Human Preferences”, 2019; N. Stiennon et al., “Learning to Summarize from Human Feedback”, NeurIPS 2020; R. Nakano et al., “WebGPT”, 2021.
  • Y. Dubois et al., “AlpacaFarm: A Simulation Framework for Methods that Learn from Human Feedback”, NeurIPS 2023; N. Lambert et al., “Tulu 3”, 2024.
  • R. Rafailov et al., “Direct Preference Optimization: Your Language Model is Secretly a Reward Model”, NeurIPS 2023; M. Azar et al., “A General Theoretical Paradigm to Understand Learning from Human Preferences” (IPO), 2023; N. Razin et al., “Unintentional Unalignment: Likelihood Displacement in Direct Preference Optimization”, 2024.
  • Z. Shao et al., “DeepSeekMath” (GRPO), 2024; Z. Liu et al., “Understanding R1-Zero-Like Training: A Critical Perspective” (Dr. GRPO), 2025; Q. Yu et al., “DAPO”, 2025; A. Ahmadian et al., “Back to Basics” (RLOO), ACL 2024; Y. Yue et al., “Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model?”, 2025.
  • L. Gao, J. Schulman, J. Hilton, “Scaling Laws for Reward Model Overoptimization”, ICML 2023; T. Korbak, E. Perez, C. Buckley, “RL with KL Penalties is Better Viewed as Bayesian Inference”, 2022; A. Beirami et al., “Theoretical Guarantees on the Best-of-n Alignment Policy”, 2024; J. Schulman, “Approximating KL Divergence” (blog), 2020.
  • R. Bradley, M. Terry, “Rank Analysis of Incomplete Block Designs”, Biometrika 1952.

Preview of Lecture 18 — Language-model-based agents

So far the “environment” was a single prompt and a single response. Lecture 18 (a guest lecture by Zora Wang) makes the language model act over many steps in an environment:

  • observations (files, web pages as HTML or accessibility trees, screenshots);
  • actions (clicks, typing, tool and API calls, self-induced skills);
  • internal state (memory, reflection, workflows);
  • how agents are benchmarked and trained.

The demos build a small web shop where a learned agent’s success, step count and failure modes can be measured, and come back to Lecture 16’s exposure bias and to RL from outcome rewards.


术语表 (Glossary, English → 中文)

English中文
one-step MDP / token-level MDP单步马尔可夫决策过程 / 词元级马尔可夫决策过程
credit assignment信用分配
cold start / supervised fine-tuning (SFT)冷启动 / 监督微调
verifiable reward / rule-based reward / format reward可验证奖励 / 基于规则的奖励 / 格式奖励
RL with verifiable rewards (RLVR)基于可验证奖励的强化学习
group relative policy optimization (GRPO)组相对策略优化
group-based advantage / dead (zero-advantage) group组内优势 / 零优势组
clip-higher / dynamic sampling上界放宽截断 / 动态采样
difficulty bias / length bias难度偏差 / 长度偏差
pass@k / sharpening前 k 次通过率 / 分布锐化
chain of thought / reasoning model思维链 / 推理模型
distillation蒸馏
reinforcement learning from human feedback (RLHF)基于人类反馈的强化学习
direct assessment / preference model直接评分模型 / 偏好模型
Bradley–Terry model / pairwise preference布拉德利-特里模型 / 成对偏好
reward model / proxy reward / true reward奖励模型 / 代理奖励 / 真实奖励
Bayes ceiling / label noise贝叶斯上限 / 标签噪声
reward hacking / over-optimization / Goodhart’s law奖励作弊 / 过度优化 / 古德哈特定律
KL penalty / reference policyKL 惩罚 / 参考策略
closed-form optimal policy / partition function闭式最优策略 / 配分函数
KL estimator (k1, k3)KL 估计量
best-of-N / rejection samplingN 选一 / 拒绝采样
direct preference optimization (DPO) / implicit reward直接偏好优化 / 隐式奖励
likelihood displacement似然位移
reward–KL frontier奖励-KL 前沿
← 返回课程目录