Part III · RL for LLMs · Chapter 11
The language model as a policy
Tokens as actions, prompts as states. Pretraining → SFT → RL, and why a KL leash to the reference model.
Here is a small experiment you will run in this chapter’s lab. A tiny transformer, about 100,000 parameters, has been trained on roughly 22,000 worked examples of two-digit addition: “37+48=” followed by “85”. Ask it a fresh problem and let it answer greedily (the top-scoring digit at every step), and it is right about 80% of the time. Let it sample instead, and it is right only a little over half the time. Most of its mistakes are near misses: in about four out of five wrong answers exactly one digit is off, “86” instead of “85”.
How do you make it better? One option is more of the same: more worked examples. The other is to let the model try, check each answer, and nudge it toward the attempts that worked. The checking is cheap: a one-line program can verify a sum. That second option is reinforcement learning, and it is how reasoning models, chat assistants and coding agents are post-trained. To do it you need to see the language model as what Part I and Part II called a policy: something that picks actions in states and can be improved with a reward. This chapter builds that view carefully. It also answers a question that every later chapter depends on. When we do RL on a language model, we almost always add a leash, a penalty for moving away from where the model started. Why, and what exactly does the leash do?
Logits, softmax, and a distribution over the next token
A language model reads a sequence of tokens (pieces of words, digits, punctuation; a real model’s vocabulary has about 100,000 of them, Llama 3’s tokenizer about 128,000) and outputs one real number per vocabulary entry, the logits , where is the vocabulary size. The softmax turns them into a probability distribution over the next token:
Here is the prompt, the tokens the model has written so far, and is the transformer. This is the softmax policy of Chapter 7, with a neural network computing the logits from the state. Nothing new is needed to call it a policy: it maps a situation to a distribution over actions.
A worked example. After the prompt “37+48=”, suppose the model’s logits for the three most plausible first digits are for “8”, “7” and “9” (pretend the other tokens have logits so low they don’t matter). Then
A response is a product; its log is a sum
The model writes a response one token at a time, feeding each sampled token back in, until it emits an end-of-sequence token <eos>. By the chain rule of probability, the probability of the whole response is the product of the next-token probabilities:
Continue the example. If the model then puts probability 0.9 on “5” after “8”, and 0.98 on <eos> after “85”, then
Everyone works with the log-prob, the sum, rather than the product, for two reasons. The first is numerical. A 1,000-token response whose tokens each have probability 0.9 has probability , which is exactly zero in 32-bit floating point. Its log-prob, , is a perfectly ordinary number. The second reason matters more for RL: the gradient of a sum is a sum. The policy gradient of Chapter 7 needs , and that is a sum of per-token gradients, each computed by the same backward pass you would use for ordinary training.
Temperature
When you sample from a language model you can set a temperature . The sampler divides the logits by before the softmax:
(Here is the state, the prompt plus the tokens so far; the MDP section below makes this official.) The second form says that temperature raises every probability to the power and renormalizes. With the logits from above:
| 0.5 | 0.867 | 0.117 | 0.016 |
| 1 (the model as trained) | 0.665 | 0.245 | 0.090 |
| 2 | 0.506 | 0.307 | 0.186 |
As the sampler becomes greedy (always the top token). As it becomes uniform. You have seen this before in statistical mechanics: is a Boltzmann distribution with energies at temperature , and the softmax denominator is the partition function. Lower temperature freezes the system into its ground state, the most likely token.
Two other knobs truncate the distribution before sampling. Top-k keeps only the most likely tokens. Top-p or nucleus sampling (Holtzman et al., 2020) keeps the smallest set of tokens whose probabilities add up to at least . Both cut off the long tail of unlikely tokens, where a single bad draw can derail a response. They matter for RL in one way: the policy you sampled from is the truncated, temperature-scaled one, and every importance ratio and log-prob in training should refer to that policy. That is one reason RL rollouts are often sampled at with no truncation (DeepSeek-R1-Zero used temperature 1, for example), and why some systems record the truncation mask and reapply it in training (Chapter 20).
Quick check You halve the sampling temperature, from T = 1 to T = 0.5. Two tokens have logits that differ by 1. What happens to the ratio of their probabilities?
The ratio of two softmax probabilities is exp((z_a − z_b)/T). At T = 1 that is e¹; at T = 0.5 it is e². In general, π_T ∝ π^(1/T), so every ratio is raised to the power 1/T. Check it against the table: 0.867/0.117 = 7.4.
Three stages: pretraining, SFT, RL
A modern assistant is trained in three stages. Each one can be written as an objective over the same policy .
Pretraining. Take trillions of tokens of text and maximize the likelihood of each next token given the ones before it:
This is maximum likelihood, and through the RL lens it is behavior cloning (Chapter 10) where the “expert” is everyone who ever wrote on the internet. The result, the base model, can continue any text plausibly. It has no particular wish to be helpful, correct or brief.
Supervised fine-tuning (SFT). Collect demonstrations, pairs of a prompt and a good response written by a person (or a stronger model), and run the same loss on them, counting only the response tokens:
Still behavior cloning, now of a narrower expert. The model learns the format and style of an assistant. The SFT model is usually the starting point of RL and the reference model that the leash ties it to.
Reinforcement learning. Now the model writes its own responses, something scores them, and we maximize the expected score:
The reward can come from a model trained on human preferences (Chapter 12), from an AI judge, or from a program that checks the answer (Chapter 14, Chapter 15).
Put the gradients side by side and the stages look strikingly similar. By the log-derivative trick of Chapter 7:
Both push up the log-probability of some responses. SFT pushes up responses someone else wrote, all with weight 1. RL pushes up the model’s own samples, weighted by how good they were, and with a baseline subtracted (Chapter 7) it pushes the bad ones down. Halfway between sits a simple, widely used method: sample several responses, keep only the correct ones, and fine-tune on them. It goes by names like rejection-sampling fine-tuning, expert iteration or STaR (Zelikman et al., 2022). For each prompt, that is REINFORCE with a 0/1 reward and no baseline, up to a scale factor: the fraction of samples that were correct (Exercise 11.1 asks you to check this).
Why RL after SFT?
If RL and SFT use the same machinery, why bother with RL at all? Why not just collect more demonstrations? There are four good reasons.
1. RL can learn from mistakes. SFT only ever sees good responses. It raises their probability, and the softmax lowers everything else a little, spread over the whole vocabulary. It never looks at what this model actually gets wrong. RL samples the model’s actual answers, so if the model likes to answer “86” to “37+48=”, RL sees “86”, sees reward 0, and with a baseline pushes exactly that answer down. This is the negative example that SFT never gets.
2. It is often easier to judge than to demonstrate. A person can tell which of two summaries is better more easily than they can write a better one. A unit test can check a program that nobody has written yet. A math checker confirms “85” without knowing how to solve harder problems. RL needs only a judgment of each response, which lets you train on tasks where good demonstrations are expensive or don’t exist.
3. RL trains on the model’s own distribution. In SFT the model always continues a human-written prefix. At generation time it continues its own, and one odd early token can lead it into territory no demonstration covers. Chapter 10 called this covariate shift and showed that behavior cloning’s errors can compound with the length of the episode. For text it has a name, exposure bias (Ranzato et al., 2015): the model is never exposed to its own mistakes during training. RL fixes this by construction: every training response is one the model itself wrote, mistakes included, and it is the consequences of those mistakes that the reward judges.
4. RL can go beyond the demonstrator. The best SFT can do is reproduce the distribution of its demonstrations, warts and all. RL’s objective has no such ceiling. A model can discover a solution strategy, or a style of reasoning, that no demonstration contained, as long as it samples it sometimes and the reward recognizes it. AlphaGo’s journey from imitating human games to beating the people it imitated is the classic example (Chapter 10).
Two ways to see the MDP
Chapters 3–9 framed RL as an agent moving through states. To use them, you have to say what the states, actions, transitions and rewards of text generation are. There are two natural answers. They are not rival theories: they describe the same process at two levels of detail, and different algorithms work at different levels.
View 1: the token-level MDP
Treat each token as one decision.
| MDP piece | For a language model |
|---|---|
| state | the prompt plus the tokens so far, |
| action | the next token , one of vocabulary entries |
| policy | the model’s next-token distribution |
| transition | deterministic: append the token, |
| episode end | the model emits <eos> (or hits a length limit) |
| reward | usually 0 for every token except the last, which gets |
| discount | : the episode is short and finite, and nothing is gained by discounting |
Three things make this MDP unusual. The state is the full history, so it is Markov by construction (Chapter 3). The transition function is known exactly and is trivial, which removes one of RL’s usual difficulties (learning or sampling the environment) and leaves only the policy’s own randomness. And the reward is sparse: a single number at the very end. With and one terminal reward, the return from every token is the same number, . The hard question becomes credit assignment: which of the 300 tokens in a response made it good? A critic that predicts the eventual reward from a half-finished response is one answer, used by PPO-based RLHF (Chapter 8, Chapter 12).
View 2: the contextual bandit
Zoom out until the whole response is one action.
| Bandit piece | For a language model |
|---|---|
| context | the prompt |
| arm (action) | the entire response |
| policy | |
| reward | , then the episode is over |
This is the contextual bandit of Chapter 2, with an astronomically large set of arms: with 100,000 tokens and responses of 1,000 tokens there are of them. Nobody keeps a table of arms. But the bandit view is often the more honest one, because rewards really are given to whole responses, not to tokens.
Same gradient, different bookkeeping
The two views agree on the most important thing. The bandit’s REINFORCE gradient is
and the right-hand side is exactly the token-level REINFORCE gradient, , with for every token. Where the views part ways is everything you add on top:
- What baseline or advantage each token gets. Token level: a different advantage per token, from a critic. Bandit level: one advantage for the whole response, shared by its tokens.
- Where importance ratios and clipping live. Per token () or per response ().
- Where the KL penalty enters. As a small per-token reward, or as one number per response.
| Method | Reward and advantage | Ratio, clip, KL | Chapter |
|---|---|---|---|
| PPO-based RLHF (InstructGPT, Ouyang et al. 2022) | token level: value head, per-token GAE | per token; KL penalty per token in the reward | 12 |
| RLOO (Ahmadian et al. 2024) | bandit: one reward per response, leave-one-out baseline | KL folded into the response’s reward | 16 |
| GRPO (Shao et al. 2024) | bandit: one group-normalized advantage per response | per token: ratio, clip and KL term | 15 |
| GSPO (Qwen team, 2025) | bandit | per response: one sequence-level ratio | 16 |
| DPO (Rafailov et al. 2023) | derived in the bandit view, no sampling at all | none (offline) | 13 |
GRPO is a hybrid: its reward and advantage are per response, while its PPO machinery is per token. GRPO and its variants are the workhorses of 2025–26 reasoning-model training, so this hybrid is the view you will meet most often. Exercise 11.3 works both views on a two-token example.
Quick check In the token-level MDP of a language model, with a single reward r(x, y) at the end of the response and γ = 1, what is the return G_t from token t?
The return is the sum of rewards from t to the end. Every reward is 0 except the final one, and γ = 1 means it is not discounted, so every token's return is the same number, r(x, y). That is why the token-level and bandit REINFORCE gradients coincide, and why the interesting question becomes which tokens deserve the credit.
The KL-regularized objective
Here is the objective that RLHF optimizes, and that almost every method in Part III either optimizes, approximates or modifies:
with . In words: get as much reward as you can, but pay for every nat of divergence (a nat is the unit of KL computed with natural logarithms) from the reference model (the SFT model, frozen). We call this the KL-regularized objective and the KL coefficient.
The best possible policy, in closed form
You have already solved this problem. In Chapter 10 you maximized over distributions on a finite set of actions, and found the Gibbs distribution. In the bandit view, each prompt is one such problem, and its “actions” are the responses . So the optimum is
and for every other policy, (the Gibbs identity), so nothing beats . In words: take the reference model and tilt it, multiplying the probability of each response by . Large : barely tilt, stay at . Small : tilt hard, toward the highest-reward response. A response with stays impossible.
∂ The optimum in four lines (a recap of Chapter 10)
Fix a prompt and drop from the notation. Define by the formula above. Taking logs, . Substitute this into the objective for an arbitrary :
(The third line uses .) KL is non-negative and zero only when the two distributions are equal, so is maximized exactly at , where it equals . Chapter 10 has the Lagrange-multiplier route and the free-energy interpretation.
A worked example. Here is a toy language model whose responses are always exactly two tokens long, from the vocabulary . You will meet it again in the demo and the lab. The reference model and the rewards are:
| response | ||||
|---|---|---|---|---|
| aa | 0.7 | 0.6 | 0.42 | 0 |
| ab | 0.7 | 0.4 | 0.28 | 1 |
| ba | 0.3 | 0.5 | 0.15 | 0 |
| bb | 0.3 | 0.5 | 0.15 | 2 |
The best response, “bb”, is the least likely one, and it starts with the less likely first token. The reference’s expected reward is . With :
- Tilted weights : , , , . Their sum is .
- for aa, ab, ba, bb.
- , and nats.
- . Check: .
Compare the alternatives at the same . Copying the reference gives . Always answering “bb” gives reward 2 but costs , so . The tilted policy is far better than either.
The optimum, one token at a time
Now look at the same through the token-level lens. What is its probability for the first token? Add up the responses: and . The reference put 0.7 on ; the optimum prefers . But the token itself earns no reward. It is tilted up because of what can follow it: after , the model can write “bb”, worth 2.
Here is the precise version. Define the soft value of a prefix as the log-sum-exp of the rewards of what can follow it, working backwards from the end. For our two-token responses:
is a “soft maximum” of the rewards reachable after : it lies between their -weighted average (large ) and their maximum (small ). In physics language, is minus the free energy of the subtree below , at temperature with energies . Then the optimum’s next-token probabilities are the reference’s, tilted by the soft value of where each token leads:
With : and . So and , giving after dividing by their sum, , as before. The second-token probabilities come out as and .
∂ Why the token-level product equals the sequence-level π* (any length)
Let and let be the state after appending . Define soft values backwards: at a finished response, ; at any unfinished prefix,
where is the state after appending (a finished response if is <eos>). Define . It sums to 1 over by the definition of . Multiply along a response of length :
The sum telescopes, leaving the value of the finished response, , minus the value at the start, . Since the product sums to 1 over all responses, . That is the sequence-level .
Why not just compute and be done? Because and the soft values are sums over every possible continuation, and there are of them. Everything in Part III is a way around that sum. RL methods (Chapters 12, 15, 16) climb the KL-regularized objective with sampled responses. DPO (Chapter 13) notices that cancels when you compare two responses to the same prompt. Best-of- sampling (Chapter 17) approximates a tilted distribution by brute force.
Token view (tree) and response view (bars): the same policy, seen two ways
reference π_ref optimum π* π_ref sampled at temperature T · edge labels: π_ref → π* for that token; V = soft value of the node
Reward–KL plane: every policy is a point (KL from π_ref, expected reward)
π* as β varies (the frontier) π_ref at temperature T as T varies true reward of π* (the reward model is wrong on "cc")
What to try: (1) In the worked example at β = 1, check the numbers against the text: π* = 0.172, 0.312, 0.062, 0.454; V(a) = 0.52, V(b) = 1.43; J(π*) = β log Z = 0.892. Note the first-token edge to b rises from 0.30 to 0.52 although b earns nothing by itself. (2) Sweep β from right to left and watch the accent dot run along the frontier, from π_ref (KL = 0) toward the greedy answer bb. (3) Move the temperature slider. In the worked example, lowering T moves the green dot down: the likeliest responses are not the best ones, and temperature can't know that. Switch to 'Likely answers are good answers': now lowering T helps, but its curve still stays below the frontier, and J(π_ref at T) never beats J(π*). (4) In 'Reward model with a blind spot', the reward model wrongly scores the rare response cc at 1.6 (true value 0). Lower β slowly: the true reward (dashed red) rises, peaks near β ≈ 0.4, then collapses as π* piles onto cc.
Quick check In the worked example, the first token b has no reward of its own, yet π* raises its probability from 0.30 to 0.52. Why?
π*(y₁) ∝ π_ref(y₁)·exp(V(y₁)/β), and V(b) = ln(0.5 + 0.5e²) = 1.43 is a soft maximum over the rewards reachable after b (0 and 2). The optimal policy looks ahead. A method that only adjusted the last token, or rewarded tokens myopically, would leave the first token at 0.7 / 0.3 and fall short of π*.
Why a leash?
Why not set and maximize reward outright? Four reasons, from most to least important.
1. The reward model is only trustworthy near its training data. A reward model (Chapter 12) is trained on responses sampled from (roughly) , labeled by people. On responses like those it is reasonably accurate. On responses unlike anything it saw, its scores are guesses, and an optimizer will find the guesses that are too high. The demo’s third scenario is the smallest possible version: the reward model is right everywhere except on one rare response, and a weak leash lets the policy find it. With real reward models, Gao, Schulman and Hilton (2022) measured the same shape: as the KL from the initial policy grows, the true reward first rises, then falls, while the learned reward keeps climbing. This is reward overoptimization, Goodhart’s law with a learned reward, and Chapter 19 is about it. The KL term keeps the policy where the reward is still a good proxy for what we want.
2. It preserves what the reward doesn’t measure. With , puts all its mass on the single highest-reward response per prompt. Every other skill the reference had, fluency, variety, knowledge the reward never asks about, is up for grabs. The leash keeps the policy a reweighting of the reference, so it keeps the reference’s breadth except where the reward argues otherwise. Korbak, Perez and Buckley (2022) push this view all the way: the KL-regularized optimum is a Bayesian posterior, with as the prior and as the likelihood.
3. It stops degenerate exploits. Many reward hacks are text that no sensible model would write: repeated phrases, odd formatting, keyword stuffing. Such text has very low probability under , so reaching it costs a lot of KL.
4. It keeps training stable. A policy far from its starting point produces long, strange rollouts and huge gradients. Staying near a known-good model is a safety margin.
How strong is the leash in practice? It varies a lot, and the trend has been toward weaker leashes when the reward is a reliable checker. DeepSeekMath’s GRPO run used a KL coefficient of 0.04, and DeepSeek-R1-Zero used 0.001. Many 2025 recipes for RL with verifiable rewards (DAPO and Dr. GRPO among them) drop the KL term entirely, arguing that a verifier can’t be fooled the way a learned reward model can and that reasoning models should move far from the reference. Others keep it, or periodically reset to the current policy. Chapter 16 treats the KL term as one of the knobs of the algorithm zoo. One sanity check the demo shows: whatever you do, a policy’s reward is only meaningful together with how far it has moved. When comparing methods, compare them on the reward–KL plane, not on reward alone.
Estimating the KL from samples
The objective needs , a sum over all responses, which we can’t compute. Two facts make it manageable.
The KL of a sequence is a sum of per-token KLs. Because both models factor into next-token probabilities, the log-ratio of a response is a sum over its tokens, and so
The second equality is the chain rule for KL: take the expectation over each token given its prefix. (In the worked example at : first-token KL 0.101, plus second-token KL 0.121 after or 0.328 after , weighted by and , gives , the sequence KL from before.) That is why it is natural to charge the KL per token.
We only need samples. During RL you already have responses sampled from , and for each token both log-probabilities, and (one extra forward pass through the frozen reference). Write the sampled token’s log-ratio as
John Schulman’s note “Approximating KL divergence” (2020) compares three per-token estimators of built from it:
| Estimator | Formula | Unbiased? | Can be negative? |
|---|---|---|---|
| yes | yes | ||
| no (small bias near ) | no | ||
| yes | no |
- is the definition of KL with the expectation replaced by a sample. Unbiased, but a single token’s value is negative whenever the sampled token is less likely under than under , although KL is never negative. Its variance can be large compared with the KL itself.
- is always non-negative and usually low-variance, but biased. Its expectation is a different divergence that agrees with KL to second order when , so the bias is small near the reference and grows as the policy moves.
- adds , with , to ‘s . Since , the added term has mean zero, so is still unbiased. It is a control variate, like the baselines of Chapter 7. And since for all (the log lies below its tangent line at 1), every single value is .
A worked example. One position, three tokens, and . The exact KL is .
| sampled token | prob. under | ||||
|---|---|---|---|---|---|
| 1 | 0.6 | 0.405 | 0.405 | 0.082 | 0.072 |
| 2 | 0.3 | −0.288 | −0.288 | 0.041 | 0.046 |
| 3 | 0.1 | −0.693 | −0.693 | 0.240 | 0.307 |
| mean under | 0.0877 | 0.0858 | 0.0877 | ||
| std. dev. | 0.405 | 0.055 | 0.074 |
and hit the exact value on average; is 2% low. A single sample has a standard deviation almost five times the KL itself, while ‘s is about the size of the KL.
Each curve is what one sampled token contributes, as a function of its log-ratio ℓ = log π_θ/π_ref. Dots on the axis: the 8 tokens, sized by how often π_θ samples them. k₁ = ℓ k₂ = ℓ²/2 k₃ = e^(−ℓ) − 1 + ℓ
| mean of estimates | bias | std. dev. | single tokens < 0 | |
|---|---|---|---|---|
| k₁ | ||||
| k₂ | ||||
| k₃ |
What to try: (1) Press Play with the default settings (π_θ a little flatter than π_ref, N = 16). All three histograms center near the dashed exact KL, but k₁'s is several times wider, and about half of the single k₁ values are negative. k₃ is never negative. (2) Drag the slider far to the right (π_θ much flatter, KL ≈ 1). k₂'s solid line separates from the dashed one: it is biased upward by about 45%. (3) Now drag far to the left (π_θ much sharper than π_ref). k₃'s histogram becomes skewed: most batches land below the true KL, with rare large values pulling the mean back. Its std. dev. overtakes k₁'s. (4) Set N = 1 and N = 256 and compare the spreads: they shrink like 1/√N for all three.
The penalty in the reward, or a term in the loss?
There are two places to put the KL, and they are not equivalent.
In the reward. Subtract from the reward of every token, treat it as a fixed number (no gradient flows through it), and let the usual policy-gradient machinery do the rest. Per token, with the task reward at the end:
Here is 1 for the last token and 0 otherwise. This is how InstructGPT-style PPO does it (Chapter 12), and RLOO does the same at the level of whole responses, with . The score-function gradient of this shaped reward is an unbiased estimate of the gradient of the KL-regularized objective (when the samples come from the current policy). Exercise 11.6 shows why.
In the loss. GRPO (Shao et al., 2024) instead keeps the reward clean and adds times the average per-token to the loss, then differentiates it directly. That is convenient: the advantage stays a simple function of the task reward. But the gradient of an estimate is not, in general, an estimate of the gradient. For one position, differentiating and averaging over gives
the gradient of the KL with its arguments swapped. Near the two KLs agree to second order, so this still pulls the policy toward the reference, and in practice it works. But it is not the gradient of the objective written on the page, and the difference grows as the policy moves away. Tang and Munos (2025) point out this and a second pitfall (ignoring how the KL of later tokens depends on earlier ones) in several open-source implementations. Shah et al. (2025) compare the placements systematically. In their on-policy experiments, in the reward gave unbiased gradients and trained stably, in the loss (GRPO’s choice) was biased but stable, and used as a reward led to collapse. Exercise 11.6 derives the expected gradient of each estimator used as a loss.
Quick check You add β·k₁ (the plain log-ratio, log π_θ − log π_ref of the sampled token) to the loss and backpropagate through it. On average over tokens sampled from π_θ, what does that term contribute to the gradient?
∇θ k₁ = ∇θ log π_θ(y_t | s_t), and the expected score is zero: Σ π ∇log π = ∇Σ π = ∇1 = 0. Used as a loss term, k₁ does nothing on average. Its value estimates the KL perfectly well, but its gradient doesn't. Used as a reward instead, multiplied by the score function, it gives the correct gradient.
Log-probs in practice: the shift and the mask
Every algorithm in Part III starts by computing, for a batch of sampled responses, the log-probability of each response token under the policy (and under the reference, and sometimes under the old policy). It looks trivial. It is also where much of the debugging time in real RL code goes. Here is one row of a TinyLM batch: the 7-column prompt <bos> 3 7 + 4 8 = (shorter prompts in the batch would be padded on the left so that all prompts end in the same column, ), followed by a 4-token response budget, of which “85<eos>” used three:
column: 0 1 2 3 4 5 6 | 7 8 9 10
ids: <bos> 3 7 + 4 8 = | 8 5 <eos> <pad>
prompt | response
logits col t predicts the token in col t+1: col 6 -> "8", col 7 -> "5",
col 8 -> <eos>, col 9 -> <pad>
response mask: | 1 1 1 0
Three rules:
- Shift by one. The logits at column are the model’s prediction for the token in column . So the log-probs of the response tokens come from logits columns to the second-to-last column, matched with token columns to the end.
- Mask the prompt. Prompt tokens are given, not chosen by the policy. They are not actions, and they must get no gradient (if they did, you would be training the model to write prompts).
- Mask the padding. Tokens after
<eos>were never generated. Exclude them, and do it withwhere, not by multiplying by 0: a padding position can hold , and is NaN.
logits = model(ids) # (B, L_total, V)
logp = log_softmax(logits[:, :-1], dim=-1) # column t predicts token t+1
tok_logp = gather(logp, ids[:, 1:]) # (B, L_total - 1): log-prob of the actual next token
tok_logp = tok_logp[:, L - 1:] # keep only the response tokens
seq_logp = where(mask, tok_logp, 0).sum(dim=-1) # log π(y | x), one number per response
Real systems add details (attention masks so padding is never attended to, position ids that skip padding, packing several sequences into one row), but these three rules are where the bugs live. One more decision hides in the last line: when you turn per-token quantities into a loss, do you sum over a response’s tokens, average them per response, or average over all tokens in the batch? The choice changes how much long and short responses count, and Chapter 16 shows it creates a length bias. The lab’s Task 1 is exactly this code, with tests that catch each of the three bugs.
Summary
- A language model is a policy: logits → softmax → next-token distribution. A response’s probability is the product of its token probabilities, and its log-prob is the sum of their logs.
- Temperature divides the logits by : , a Boltzmann distribution. Low trades diversity for the model’s favorite answers; it does not know about the reward. Top-k and top-p truncate the tail.
- Pretraining and SFT are behavior cloning; RL maximizes a reward on the model’s own samples. The REINFORCE gradient is SFT on your own samples, weighted by reward. RL adds negative examples, learns from judgments instead of demonstrations, fixes exposure bias, and can exceed the demonstrator, but it can only reinforce what the model samples.
- Two MDP views: the token-level MDP (state = prompt + prefix, action = token, deterministic transitions, reward at the end, ) and the contextual bandit (action = whole response). They give the same REINFORCE gradient; algorithms differ in where advantages, ratios and the KL live.
- The KL-regularized objective is maximized by the tilted reference . Token by token, tilts each token by the soft value of what can follow it: the optimum looks ahead.
- The leash exists because learned rewards are only trustworthy near the data (overoptimization), and to keep the reference’s breadth and block degenerate exploits. With reliable verifiers, many recent recipes weaken or drop it.
- Per-token KL estimators from sampled tokens: (unbiased, noisy, can be negative), (biased, low variance), (unbiased, non-negative, usually low variance, but heavy-tailed when is much sharper than ). in the reward gives the right gradient; in the loss (GRPO) gives the gradient of the reversed KL.
- Computing log-probs: shift by one, mask the prompt, mask the padding (with
where).
Exercises
(a) A model answers “37+48=” with “86<eos>”, with token probabilities 0.665, 0.08 and 0.97. Compute the response’s probability and log-prob. Which token contributes most to the log-prob?
(b) Show from the chain rule of probability that .
(c) Rejection-sampling fine-tuning: for each prompt, sample responses from , keep the correct ones, and take an SFT step on them (average gradient of over the kept responses). Show that, for a single prompt, this gradient points in the same direction as the REINFORCE estimate with . What is the scale factor between them, and what is missing compared with REINFORCE with a baseline?
Solution
(a) . (and ). The unlikely second digit “6” contributes 85% of the total. That’s typical: a response’s log-prob is dominated by its few surprising tokens.
(b) For any random sequence, , the chain rule, applied conditionally on . A language model defines exactly these conditionals, so , and the log of a product is the sum of the logs.
(c) Let be the set of kept (correct) responses, . The SFT step’s gradient is . Since for and otherwise, REINFORCE gives . Same direction, scale factor (the fraction correct), so rejection sampling takes relatively larger steps on hard prompts where few samples are correct. What’s missing is the baseline: wrong answers get weight 0 rather than a negative weight, so rejection sampling never pushes a specific mistake down. Its only route to lowering wrong answers is the indirect one through normalization.
Let .
(a) Show that .
(b) For logits , find the temperature at which the top token has probability 0.95.
(c) Write (the inverse temperature). Show that the entropy satisfies . Conclude that entropy increases with temperature, strictly unless all logits are equal.
Hint
Solution
(a) , so . The factor is the same for every , so .
(b) , so . With : , so , , and . Check: logits give .
(c) with . Then . Differentiate: , and . So
Entropy falls as rises, so it rises with . It is strict unless , which (since gives every token positive probability) means all logits are equal. In thermodynamic language, is proportional to a heat capacity, which is never negative.
Use the worked example’s reference model: , , , with rewards , , , .
(a) Suppose the first-token distribution is a softmax with logits (and the second-token distributions don’t depend on these parameters). In the bandit view, compute the exact policy gradient at , where .
(b) In the token-level view, compute as and check that you get the same number. Then redo it with a per-token baseline: the value of the state before the first token, . Does the answer change?
(c) Use the chain rule for KL to compute at from the token-level numbers in the text, and check that it matches the sequence-level 0.329.
Hint
Solution
(a) . With and :
(b) Every token’s return is . Only involves . So the gradient is :
- responses starting with (probability 0.7, mean reward 0.4): , contributing ;
- responses starting with (probability 0.3, mean reward 1.0): , contributing .
Total , the same. With the baseline , the weights become and : . Unchanged in expectation, as Chapter 7 proved; only the variance of the single-sample estimates changes.
(c) First-token KL: . Second token after : . After : . Total: . It matches.
Samples ; ; .
(a) Prove for every sample, with equality only when .
(b) Prove . Which assumption about the supports of the two distributions do you need?
(c) Take and . Compute the exact KL, the values of and for each token, and their standard deviations.
(d) You estimate the KL by averaging over sampled tokens. What is the probability that no rare token appears, and what is the estimate in that case? Compare with .
Hint
Solution
(a) has , negative for and positive for , and . So is strictly convex with its unique minimum at , where . Hence , with equality only at . (Equivalently: , the log lies below its tangent at 1.)
(b) . First, . This equals 1 if puts no mass where has none. For softmax policies every token has positive probability, so the condition holds. Second, . So . (If had zero mass on some tokens where has mass, and would underestimate.)
(c) .
- Common token: , so and .
- Rare token: , so and .
Check the means: : . : . Both unbiased. Standard deviations: : . : , ten times larger.
(d) . In that case the estimate is , less than a third of the true 0.637, and the estimate is , 7% high. So 85% of the time underestimates by a factor of 3.4. When exactly one rare token appears, the estimate jumps to , almost five times too high. Unbiased on average, but in a single batch it is usually far too low. The same thing happens with TinyLM in the lab when the sampler is much sharper than the reference. The lesson: is excellent when is close to or broader than it, and treacherous when has become much more confident, which is what RL tends to do. Exact per-position KL over the whole vocabulary avoids the problem at the cost of more computation (some recent systems do this).
(a) Without looking back, derive as the maximizer of over distributions on a finite set, using a Lagrange multiplier for .
(b) Redo the worked example at : compute , , , the first-token probabilities of , and .
(c) What happens to as and as ? Express your answer in terms of .
Hint
Solution
(a) Setting the derivative to zero: , so . The last factor doesn’t depend on ; normalization fixes it to . The objective is concave (linear term plus times a convex function), so this stationary point is the global maximum. (Chapter 10 gives the full argument.)
(b) With , :
- .
- .
- , and .
- and .
- , so .
Check against the sequence level: . (The demo shows the same numbers at β = 0.5.)
(c) As , expand : the soft value tends to the plain average, , and . Both stay finite, so and . As , the soft max becomes a hard max: (over continuations with ), and concentrates on the first token(s) with the largest . Here: , because after is 2 and after only 1. The first token’s fate is decided by the best thing that can follow it, not the average.
Consider one position with a softmax policy over a finite vocabulary and a fixed reference . Tokens are sampled and . Write for the score. In this setting , the one in the objective, is called the reverse KL, and , with the arguments swapped, the forward KL.
(a) Show that the true gradient of the reverse KL is .
(b) “KL in the reward”: treat as a fixed number and use the score-function estimator . Show it is unbiased for the gradient in (a).
(c) “KL in the loss”: compute when you differentiate the estimator itself, for , and . Which KL, if any, does each one differentiate?
Hint
Solution
(a) , and both factors depend on . Product rule: . The first sum is . In the second, (the reference doesn’t depend on ), so it is . Hence .
(b) Its expectation is , the right-hand side of (a). Unbiased. This is why ” as a per-token reward, no gradient through it” implements the KL-regularized objective correctly on-policy. (The full sequence version needs the KL of later tokens to be included in each token’s return, which reward-to-go does automatically; that’s the sequential pitfall of Tang and Munos.)
(c) Differentiate through the sampled value, keeping fixed:
- : , and . Zero expected gradient. As a loss term, does nothing on average (it only adds noise).
- : , with expectation . The correct reverse-KL gradient, although ‘s value is biased. (This is the argument REINFORCE++ makes for in the loss.)
- with : . Expectation: . From the hint, that is . The gradient of the forward KL, with the arguments swapped.
So, used as a loss: is useless, is right, and (GRPO’s choice) optimizes a different divergence. Near both KLs have the same second-order expansion (Fisher metric), so the three options that do something ( in the reward, or in the loss) push toward the reference in about the same way, which is why GRPO’s choice works in practice. Far from the reference they differ: the forward KL is “mass-covering” (it heavily penalizes putting tiny probability on tokens likes), the reverse KL is “mode-seeking”.
(a) Fix and define the sequence-level power distribution . Show that is the KL-regularized optimum for the reward , and find as a function of .
(b) Ordinary sampling at temperature applies to each next-token distribution separately. Show by example that this is not the same distribution over responses as . Use a reference with , uniform over two tokens, and putting all its mass on one token, at .
(c) Explain the difference using soft values.
Hint
Solution
(a) . This is when , that is . For example corresponds to with “reward = the reference’s own log-likelihood”. Lowering the temperature is a KL-regularized optimization toward likely text: no outside reward involved. ( gives , no change; gives , the single most likely response.)
(b) Reference response probabilities: , , .
- Power distribution at : square and renormalize: , divided by : .
- Token-level temperature: the first token is vs , still ; after it stays uniform; after it stays deterministic. Responses: , unchanged from the reference.
Different distributions. Token-level sharpening can’t see that choosing leads to a confident continuation.
(c) Under (as an instance of with , ), the soft value of a first token is , which is larger after (one continuation with all the mass) than after (mass split two ways). The power distribution looks ahead, exactly like the tilted optimum in the text; per-token temperature doesn’t. Karan and Du (2025) sample from the sequence-level power distribution of base models with an MCMC method, and report reasoning gains approaching those of RL-trained models without any training, which is one reason this distinction has attracted recent attention.
A reward model was trained on comparisons between responses sampled from the SFT model.
(a) Explain in two or three sentences why its errors are likely to be largest on responses that the SFT model rarely produces, and why an RL optimizer with will find those responses.
(b) In the demo’s “blind spot” scenario, the reference gives the response “cc” probability 0.02 and the reward model scores it 1.6 instead of its true 0. The best honest response, “bb”, has reference probability 0.24 and reward 1.0. Using the tilted form , find the at which puts equal mass on “bb” and “cc”. What happens to the true reward for well below that value?
(c) Give two reasons, other than reward-model errors, to keep , and one reason recent RL-with-verifiers recipes give for setting .
(d) In one sentence each: what does PPO’s clip keep close to, and what does the KL term keep it close to? Why would you want both?
Hint
Solution
(a) The reward model learned from examples near ‘s typical outputs; on unusual responses it is extrapolating, and nothing in its training penalized wrong scores there. An optimizer looks for the highest score anywhere, and among many responses with noisy scores, the highest is very likely one whose error is large and positive (the same “max of noisy estimates” effect as maximization bias in Chapter 5). With nothing stops it from moving all its mass there.
(b) Equal mass when , i.e. , so . Above that, “bb” dominates the two; below it, “cc” does, and as , and the true reward falls toward 0, below even the reference’s 0.46. In the demo the true reward peaks around at about 0.63 and is 0.03 at . (The peak comes well before the crossover at 0.241: below , “bb” stops gaining mass, at about 0.5, while “cc”, already at 18%, keeps growing.)
(c) Keep to preserve what the reward doesn’t measure (fluency, diversity, general knowledge: as , collapses onto one response per prompt), to make degenerate exploits expensive (text with tiny costs a lot of KL), and for stability. Reason to drop it: a programmatic verifier is much harder to fool than a learned reward model, and for long reasoning the model should move far from the SFT model; recipes like DAPO argue the KL term just slows that down.
(d) PPO’s clip keeps close to , the policy that collected the current batch, so each update is a trustworthy small step. The KL term keeps it close to , the fixed starting model, which changes what the final answer is. One makes each step safe; the other decides how far the whole journey may go.
(a) In “Tilting a toy language model”, worked scenario, set and check your answers to Exercise 11.5(b) against the readouts and the tree.
(b) Still in the worked scenario, find a temperature at which “π_ref at temperature T” has the same KL from as at (KL ≈ 0.08). Compare the two expected rewards. Then push to its maximum. Why can’t temperature reach the frontier in either direction?
(c) Switch to “Reward model with a blind spot”. Find the that maximizes the true reward (dashed red). What is the KL there? How much proxy reward does have at that point, and how much at ?
(d) In “Three ways to estimate a KL”, set the slider to the far left (sharper) and . After a few thousand batches, what fraction of the histogram lies below the true KL? Which estimator has the smallest standard deviation now?
Solution
(a) At : , , , , , matching Exercise 11.5. The slider’s nearest setting is , so the readouts may differ in the third decimal (, ).
(b) Around the KL reaches about 0.08, and the expected reward there is about 0.40, far below ‘s 0.887 at the same KL (and below the reference’s 0.58: lowering favors “aa”, the likeliest response, which earns 0). At the maximum, , the KL is only about 0.05 and the reward about 0.70, while at that KL earns about 0.81. Temperature reshapes the distribution using only ‘s own probabilities; it has no information about the reward, so it can’t move mass specifically toward “ab” and “bb”. is by construction the best policy at each KL (the Gibbs identity), so every other policy lies on or below the frontier.
(c) The true reward peaks at about 0.63 near , where nats and the proxy reward is about 0.90. (The peak is flat: anywhere from to the true reward is within 0.01 of it.) At the proxy reward is about 1.58 while the true reward is about 0.03. More “reward”, much worse model: overoptimization in miniature.
(d) Roughly 70% of the batch estimates fall below the true KL (the mean still matches it, pulled up by a long right tail). has the smallest standard deviation but is now clearly biased low; has a smaller standard deviation than in this regime, the reverse of the “flatter” side.
Do the lab 11-llm-as-policy (download below). In policy.py:
- Task 1a
response_logprobsand Task 1bsequence_logprob: the shift, the gather, and the mask. - Task 2
sample_with_temperature, used by the providedgenerateto run the token-level MDP on TinyLM. - Task 3
kl_estimators: , , . - Task 4
tilted_optimumandkl_objective: over all responses of the toy LM, in log space. - Task 5
token_level_optimum: the same from soft values.
Then run run.py. In panel 2, at which temperatures do and disagree, and which one agrees with the exact (full-vocabulary) value? Connect your answer to Exercise 11.4.
Hint
test_task1_shift_on_a_hand_example. Task 1b: torch.where(mask.bool(), tok_logp, torch.zeros_like(tok_logp)). Task 4: np.errstate(divide="ignore") around np.log(ref_probs), then subtract the max before exponentiating.Solution
The key lines (full code in solutions/policy.py):
# Task 1a
logp = F.log_softmax(logits[:, :-1], dim=-1) # column t predicts token t+1
tok = logp.gather(-1, ids[:, 1:].unsqueeze(-1)).squeeze(-1)
return tok[:, prompt_len - 1:]
# Task 1b
return torch.where(mask.bool(), tok_logp, torch.zeros_like(tok_logp)).sum(-1)
# Task 2
if temperature == 0: return logits.argmax(-1)
return torch.multinomial(F.softmax(logits / temperature, -1), 1, generator=generator).squeeze(-1)
# Task 3
l = logp - ref_logp; return l, 0.5 * l**2, torch.exp(-l) - 1 + l
# Task 4
logw = np.log(ref_probs) + rewards / beta; m = logw.max(); w = np.exp(logw - m)
return w / w.sum(), m + np.log(w.sum())
# Task 5
V = beta * np.logaddexp.reduce(np.log(second) + rewards / beta, axis=1)
V0 = beta * np.logaddexp.reduce(np.log(first) + V / beta)
return first * np.exp((V - V0) / beta), second * np.exp((rewards - V[:, None]) / beta), V, V0In run.py’s panel 2, the two estimators agree with each other and with the exact value for (within their error bars). At , is far below the exact value, by much more than its error bar, while matches it; at both are noisy and is again on the low side. A sampler at low temperature is much sharper than the model, so the tokens where is huge are almost never drawn: exactly the situation of Exercise 11.4(d). At high temperature the sampler is flatter than the reference, the ratio stays bounded, and behaves well.
Files: README.md, policy.py, toylm.py, tinylm.py, test_policy.py, run.py
cd 11-llm-as-policy
python -m pytest -q # your code: tests fail until you fill in the TODOs
RL_SOLUTIONS=1 python -m pytest -q # reference solutions: all passFirst time? See Exercises & setup.
Further reading
- Schulman (2020), Approximating KL Divergence. Two pages that define , , , with a small numerical comparison. The source of the estimator names used everywhere.
- Ouyang et al. (2022), Training language models to follow instructions with human feedback. InstructGPT: the pretraining → SFT → RL pipeline and the KL-penalized reward, in the paper that made it standard. Section 3.5 states the KL-penalized RL objective.
- Rafailov, Hejna, Park & Finn (2024), From r to Q*: Your Language Model is Secretly a Q-Function. Works out the token-level MDP view of the KL-regularized objective that this chapter sketched with soft values, and connects it to DPO.
- Korbak, Perez & Buckley (2022), RL with KL penalties is better viewed as Bayesian inference. Short and clarifying: as a posterior with as the prior, and why plain reward maximization collapses the distribution.
- Shah et al. (2025), A Comedy of Estimators: On KL Regularization in RL Training of LLMs, and Tang & Munos (2025), On a few pitfalls in KL divergence gradient estimation for RL. Where the KL goes (reward or loss) and which estimator you differentiate change the gradient you actually get; the first paper also tests the consequences on 4–8B models.
- Holtzman et al. (2020), The Curious Case of Neural Text Degeneration. Why pure sampling and greedy decoding both fail for open-ended text, and nucleus (top-p) sampling.
- Lambert, Reinforcement Learning from Human Feedback (online book). A practitioner’s tour of the whole pipeline, with a chapter on regularization; good to read alongside Part III.
Next, Chapter 12 puts all of this to work: a reward model learned from human comparisons, and PPO climbing the KL-regularized objective, one token at a time.