15.8 Reinforcement Learning for Sequence Generation
Every language model in this book was trained to imitate text, which is behavior cloning (Section 14.5) of whoever wrote the corpus. The models people use today are trained further, on a signal that no corpus contains: a checker says whether the final answer of a solution is right, or a reader says which of two responses is better. The score arrives once, after a whole response that the model wrote itself, with no target token to copy. Section 14.7 and Section 14.8 trained a policy in this setting, on four arithmetic prompts and a checker.
The idea is older than these models. Christiano et al. (2017) fitted a reward to human comparisons and optimized it with a policy gradient; Ouyang et al. (2022) did so for a large language model, with a penalty for drifting from the supervised model; Shao et al. (2024) replaced the value network by a group of samples, and DeepSeek-AI (2025) the learned reward by a checker.
What does the token-by-token view add when the reward is one number per response, and how far does the penalty of Section 15.3 hold back a policy that has found a loophole? The answers assemble the post-training update from the group weight of Section 14.8, the ratio and clip of Section 15.2, and that penalty.
15.8.1 A Response as a Trajectory#
15.8.1.1 One Gradient, Two Views#
A response to a prompt is a trajectory whose actions are tokens (Table 15.8.1). The state before token is the prefix , and appending leads to with probability one, so the response probability is the product of the token probabilities, , and
| Language modeling | Reinforcement learning |
|---|---|
| prompt | start state |
| token | action |
| prefix | state |
| complete response | trajectory |
| prefix ending in EOS, | terminal state |
| next-token distribution | policy |
| verifier or reward-model score | terminal reward |
The left side of (15.8.1) treats the response as one action, the right side as token actions. With one reward at the end and no discount, every token's reward-to-go is , so both views multiply every token's score by the same response weight , for any baseline of the prompt alone.
15.8.1.2 Credit within a Response#
The response weight is unbiased, but it treats every token alike, and some tokens of a wrong answer are right. Let the prompt 3*4 be answered by a tens digit and a units digit , each uniform over . Only 12 is correct, so , , and for every other tens digit. The response 13 scores and receives the weight on both tokens, which pushes its correct tens digit down. The token advantages of Section 14.8 condition on the prefix instead: the tens digit gets and the units digit . The function token_credit computes , the response weight and both advantages for all one hundred responses :
def token_credit(p1, p2, r):
"""For two-digit responses y = 10 a1 + a2: pi(y | x), the response
weight r - V(x) and the token advantages A(s_1, a1), A(s_2, a2)."""
a1, a2 = np.divmod(np.arange(100), 10)
prob = p1[a1] * p2[a2]
V_x, V_xa = prob @ r, r.reshape(10, 10) @ p2 # V(x), V(x, a1)
return prob, r - V_x, V_xa[a1] - V_x, r - V_xa[a1]We print the three weights of three responses, check that the response weight and the tens digit's advantage give the same expected gradient for the tens digit (whose score is ), and compare the variances of the weights, all of mean zero:
y = np.arange(100) # the response y = 10 a1 + a2
r = (y == 12).astype(float) # the verifier of 3*4
uniform = np.full(10, 0.1)
prob, w, A1, A2 = token_credit(uniform, uniform, r)
print('response r - V(x) A(s_1, a_1) A(s_2, a_2)')
for k in (12, 13, 52):
print(f'{k:8d} {w[k]:10.2f} {A1[k]:13.2f} {A2[k]:13.2f}')
S1 = np.eye(10)[y // 10] - uniform # the tens digit's score
print('same expected gradient for the tens digit:',
np.allclose(prob * w @ S1, prob * A1 @ S1))
print(f'variance: r - V(x) {prob @ w**2:.4f}, A(s_1, a_1) {prob @ A1**2:.4f}'
f', A(s_2, a_2) {prob @ A2**2:.4f}')response r - V(x) A(s_1, a_1) A(s_2, a_2)
12 0.99 0.09 0.90
13 -0.01 0.09 -0.10
52 -0.01 -0.01 0.00
same expected gradient for the tens digit: True
variance: r - V(x) 0.0099, A(s_1, a_1) 0.0009, A(s_2, a_2) 0.0090
The response weight has eleven times the variance of the tens digit's advantage. It telescopes, , and the two terms are uncorrelated because the second has mean zero given any prefix, so their variances add: . Every token's score carries the noise of all the other tokens, terms for tokens.
15.8.1.3 Necessary and Optional Components#
Known transitions and one terminal reward make much of the chapter unnecessary: responses are finite, so ; no transition model is learned, and generation can restart from any prefix; nothing is bootstrapped off-policy, so the deadly triad of Section 15.4 does not arise. A critic is optional, because the response weight is unbiased and the group mean of Section 14.8 is a baseline without a network, as in RLOO (Ahmadian et al., 2024) and GRPO; a value head on every prefix (Ouyang et al., 2022), or continuations sampled from the prefix as in VinePPO (Kazemnejad et al., 2025), buys per-token credit. What remains necessary is the score with a baseline, a bound on each step, and protection against errors in the reward (Figure 15.8.1).
The token MDP. Top: states are prefixes, actions are tokens, every transition appends the chosen token with probability one, and the reward arrives once, when EOS enters the terminal state. Bottom: one draw scored by , with the same gradient by (15.8.1). Right: the components this makes unnecessary, and the optional prefix value.
15.8.2 Verifiers, Reward Models and Their Loopholes#
The reward comes from a model fitted to human comparisons (Section 15.3), least reliable where the comparisons never went, or from a check such as a test harness or an exact-match grader. Training against checks, reinforcement learning from verifiable rewards (RLVR), is how recent reasoning models are trained (DeepSeek-AI, 2025). A checker is exact for the property it checks, which may not be the property intended.
15.8.2.1 The KL-Penalized Group Step#
On the verifier task of Section 14.1 no ordinary candidate answers 8*8 or 9*9, and the ninth candidate, the hedge "one of 4, 12, 64 or 81", has times the reference probability of each ordinary one. sloppy_checker accepts any response that contains the answer, so it pays the hedge on every prompt:
def sloppy_checker(task):
"""A lenient checker: 1 if the answer appears anywhere in response y."""
return lambda x, y: float(task.answers[x] in task.resp[y])
task = d2l.VerifierTask()
sloppy = sloppy_checker(task)
print(f'reference: exact score {task.success(task.pi_ref):.3f}, '
f'lenient score {task.success(task.pi_ref, sloppy):.3f}')reference: exact score 0.062, lenient score 0.065
Training against the lenient checker will find the hedge. The penalty of Section 15.3 can be folded into the reward, scoring each sampled response by . The REINFORCE estimate stays unbiased, because differentiating the inside adds . For tokens the log-ratio is a sum of per-token log-ratios, which turns the terminal reward into a reward at every token, so each token's weight may keep only the log-ratios from that token on (exercise 5c). kl_group_step passes the penalized reward to the group step d2l.group_step of Section 14.8:
def kl_group_step(task, theta, K, reward, rng, beta, lr=2.0):
"""d2l.group_step with the reward r - beta log(pi(y|x) / pi_ref(y|x))."""
pi = task.policy(theta) # the policy that samples
def penalized(x, y):
return reward(x, y) - beta * np.log(pi[x, y] / task.pi_ref[x, y])
return d2l.group_step(task, theta, K, penalized, rng, lr)How large must be? The optimum is the reference tilted by the reward, (Section 15.3). On 8*8 the lenient checker pays only the hedge, so its odds against an ordinary candidate rise from to : the hedge is the more probable exactly when , and at it is times as probable. On 2+2 and 3*4 the correct answer is paid too, the odds stay at , and there is no threshold.
15.8.2.2 The Sweep against the Closed Form#
We train with for updates at five values of , average the last policies, and print the lenient score, the exact score and the mean probability of the hedge, beside the same numbers for the tilted optimum (in preferences, the reference plus the reward divided by ):
R = task.reward_table(sloppy) # sloppy(x, y) for every pair
def scores(task, pi, reward):
"""Expected reward, exact score, mean probability of the hedge."""
return task.success(pi, reward), task.success(pi), pi[:, -1].mean()
print('beta trained: lenient exact hedge optimum: lenient exact hedge')
for beta in (0.0, 0.1, 0.2, 0.3, 0.5):
rng, theta, avg = np.random.default_rng(0), task.theta_ref.copy(), 0
for step in range(400):
theta = kl_group_step(task, theta, 32, sloppy, rng, beta)
if step >= 300: # average the last 100 policies
avg = avg + task.policy(theta) / 100
row = '{:4.1f} {:18.2f} {:6.2f} {:6.2f}'.format(
beta, *scores(task, avg, sloppy))
if beta > 0: # the tilted optimum in preferences
pi_star = task.policy(task.theta_ref + R / beta)
row += '{:18.2f} {:6.2f} {:6.2f}'.format(*scores(task, pi_star, sloppy))
print(row)beta trained: lenient exact hedge optimum: lenient exact hedge
0.0 1.00 0.50 0.50
0.1 0.99 0.50 0.49 0.99 0.49 0.50
0.2 0.60 0.48 0.12 0.60 0.47 0.14
0.3 0.44 0.40 0.04 0.43 0.39 0.04
0.5 0.25 0.23 0.01 0.27 0.25 0.01
At the policy earns the full lenient score but only under exact evaluation, with all of its probability on the hedge on 8*8 and 9*9. The hedge stays favored at and . Above it is not: at it is about half as probable as each ordinary candidate on 8*8, as predicts. The price is useful learning: at the exact score falls to about a quarter. The trained rows lie within about of the optimum, a small systematic gap: near the penalized rewards of a group become nearly equal, and standardization enlarges the step just where the iterate should settle. The penalty prices the loophole at every ; it never closes it.
15.8.3 The Post-Training Update#
15.8.3.1 Ratios for Stale Samples#
Every update so far used a fresh group once. Large-scale post-training does not: an inference engine whose kernels and precision differ from the trainer's generates the responses, and several gradient steps share each batch. The samples come from an older policy , so token is weighted by the ratio and clipped as in Section 15.2. A whole response has the ratio and its geometric mean ,
The product is the exact correction, but its logarithm sums noisy terms and spans many orders of magnitude for long responses. Group Sequence Policy Optimization (GSPO) clips instead, one number per response whose scale does not grow with the length (Zheng et al., 2025).
15.8.3.2 Asymmetric Clipping Bands#
A band of fixed width in ratio space permits different changes in probability: at a token at gains nothing by rising above , a token at nothing above . Over a vocabulary of tens of thousands of mostly rare tokens, useful rare tokens grow slowly and the entropy falls, so DAPO raises only the upper bound, to with (Yu et al., 2025) (exercise 6).
15.8.3.3 Group Relative Policy Optimization#
Group Relative Policy Optimization (GRPO) (Shao et al., 2024) assembles the pieces. It samples responses per prompt from and gives every token of response the standardized weight of Section 14.8, where and are the mean and the standard deviation of the group's rewards. It then maximizes, for several epochs on the same group,
where is the length of response and is evaluated at the sampled token. The minimum drops a sample's gradient once its ratio is past the band on the favorable side. The clip compares with the sampling policy and limits each update; the penalty compares with the frozen reference and changes the optimum.
grpo_step implements this objective on the verifier task, where every response is one token. Each of its num_epochs passes computes the ratios against the sampling policy, keeps the samples whose clipped term still depends on (live), and takes one ascent step; the gradients of and of are and times the score :
def grpo_step(task, theta, K, reward, rng, beta=0.04, epsilon=0.2,
num_epochs=4, lr=2.0):
"""One group of K responses per prompt, reused for num_epochs clipped
ascent steps with the k3 penalty; returns theta and each epoch's ratios."""
pi_old, n = task.policy(theta), len(task.resp)
ys = np.stack([rng.choice(n, K, p=p) for p in pi_old]) # (prompts, K)
A = np.stack([d2l.standardize(np.array([reward(x, y) for y in ys[x]]))
for x in range(len(ys))])
rows, onehot, ratios = np.arange(len(ys))[:, None], np.eye(n)[ys], []
for _ in range(num_epochs):
pi = task.policy(theta)
rho = pi[rows, ys] / pi_old[rows, ys]
live = np.where(A > 0, rho < 1 + epsilon, rho > 1 - epsilon)
u = live * A * rho - beta * (1 - task.pi_ref[rows, ys] / pi[rows, ys])
theta = theta + lr * np.einsum('xk,xkn->xn', u, onehot - pi[:, None]) / K
ratios.append(rho)
return theta, ratiosWe reuse one group of responses per prompt for four epochs, print each epoch's range of ratios and fraction outside the band , and compare with a single step on the same group:
epsilon = 0.2 # grpo_step's half-width of the band
theta, ratios = grpo_step(task, task.theta_ref, 32, task.verify,
np.random.default_rng(0), epsilon=epsilon)
for epoch, rho in enumerate(ratios, 1):
print(f'epoch {epoch}: ratios from {rho.min():.2f} to {rho.max():.2f}, '
f'{np.mean(abs(rho - 1) > epsilon):.0%} outside the band')
theta_1, _ = grpo_step(task, task.theta_ref, 32, task.verify,
np.random.default_rng(0), num_epochs=1)
print(f'exact score: reference {task.success(task.pi_ref):.3f}, one epoch '
f'{task.success(task.policy(theta_1)):.3f}, four epochs '
f'{task.success(task.policy(theta)):.3f}')epoch 1: ratios from 1.00 to 1.00, 0% outside the band
epoch 2: ratios from 0.81 to 1.97, 5% outside the band
epoch 3: ratios from 0.74 to 2.23, 14% outside the band
epoch 4: ratios from 0.75 to 2.39, 30% outside the band
exact score: reference 0.062, one epoch 0.111, four epochs 0.137
At the first epoch every ratio is , because the policy has not moved. After one step the correct answers' ratios already exceed : the clip does not bound a step, it only stops rewarding growth beyond the band. The fraction outside the band then grows, and on almost every group it is larger at the fourth epoch than at the second. Over forty groups, four epochs always ended with a higher exact score than one.
The term restrains the policy differently from the folded penalty. Its expectation under is , but differentiated with the samples held fixed it has the expected gradient of the forward divergence (Tang and Munos, 2025) (exercise 5). The two directions of Section 15.3.3.5 differ sharply on a loophole: on 8*8 at the reverse optimum keeps the hedge at , the forward optimum at . The forward divergence charges for neglecting the reference's ordinary candidates, not for moving probability onto one it rarely chose.
Two widely used variants adjust these choices. DAPO drops the penalty, raises the upper clip, and discards groups whose rewards are all equal (Yu et al., 2025). Dr. GRPO removes the division by and by the response length (Section 14.8.3.4) (Liu et al., 2025).
15.8.3.4 Direct Preference Optimization#
Read backwards, the tilted optimum gives the reward
so every policy defines the reward for which it is optimal, up to a term of the prompt that comparisons cannot see. Substituting it into the Bradley-Terry likelihood turns reward fitting into a classification loss on the policy itself, with no sampling and no reward model: Direct Preference Optimization (DPO) (Rafailov et al., 2023). Its data are a fixed set of comparisons, so it inherits the questions of Section 15.7.
Everything here rests on one turn and one terminal reward, which make the problem a contextual bandit over whole responses (Section 14.4); tool calls, feedback from an environment and conversations of several turns bring back the transition kernel, and with it the critic and the credit problem. The Language Models part takes up post-training at scale, and Section 15.9 collects variants and a project.
The chapter began with a pendulum that needed a few hundred thousand steps. On CartPole the one-step critic did not save steps, four PPO epochs per batch halved them, and DQN needed 35 to 45 thousand; on Pendulum soft actor-critic needed a few thousand and a learned model a few hundred, paid for in computation; an offline learner takes no new step at all, and four epochs on a group moved a policy further on the same samples. Each saving rests on an estimate that can be wrong: a critic, a stale batch, a model, a log or a checker.
15.8.4 Summary#
A response is a trajectory of tokens, and both views give one gradient. One terminal score gives every token the weight , whose variance sums the token advantages' variances; prefix values give each token its own credit at the cost of a critic or restarts, and because the response weight is unbiased, the critic is optional. A KL penalty prices a checker's loophole at the rate its tilted optimum predicts, threshold included. GRPO combines the group weight, the clipped ratio and the penalty, whose gradient is that of the forward divergence, which barely restrains the hedge.
15.8.5 Exercises#
- Tool outputs in the trajectory. A model that calls a tool emits
tokens , receives the tool's output
, which does not depend
on , and then emits tokens . The verifier scores
once, with reward .
- Write the probability of and the gradient of its logarithm. Which tokens contribute score terms?
- A training loop that evaluates log-probabilities on the whole sequence adds the term , with the model's own probability of the tool's output. Show that it has a nonzero expectation in general, even for a constant weight, and say which step of the argument that a score has mean zero fails. What does the term train the model to do?
- Two-digit responses. Let the two digits of
Section 15.8.1.2 be drawn from distributions
and , each a softmax of its own preferences,
and let the verifier pay for the correct answer only.
- Show that the response weight and the token advantages give the same expected gradient for the preferences of each position. Which conditional expectation makes them agree?
- Show that and are uncorrelated, and state the analogous result for a response of tokens.
- Call
token_creditat the policy that gives probability to the digit in the first position and to the digit in the second, and to every other digit. How much does replacing the response weight by now reduce the variance of the tens digit's update, and why less than at the uniform policy?
- Two thresholds for the hedge. Let be the tilted optimum
for the reward
sloppyand the referencetask.pi_ref.- On
8*8and9*9the hedge is the only response thatsloppyrewards. Write its probability under as a function of . At which is it as probable as each of the other eight responses, and at which does it hold half of the probability? Which of the two is the threshold of the text? - On
2+2and3*4the correct response and the hedge are both rewarded. What probability does give the hedge as ? - At training put almost no mass on the hedge on
2+2and3*4, although every split of the probability between the two rewarded responses maximizes the unregularized objective. Which property of the update ind2l.group_stepselects the split that training reached?
- On
- [code] DPO on the finite instance. ● Let preferences between two
responses to the same prompt, both drawn from
task.pi_ref, follow the Bradley-Terry model with the rewardsloppy. Write and for the preferred and the rejected response, and .- Substitute (15.8.3) into the Bradley-Terry model and show that the negative log-likelihood of one pair is , where is the logistic function. Why does not appear?
- Show that with infinitely many pairs the expected loss is minimized by the tilted optimum. What does this imply for the thresholds of exercise 3a?
- Draw labeled pairs per prompt and minimize the mean loss at
by gradient descent with step size on the
preference table, starting from
task.theta_ref. Over five seeds, report the probability of the hedge on each prompt after , and steps. What happens on prompts where the hedge never loses a comparison, and why does not prevent it?
- The KL term as a loss. ●● GRPO subtracts at every
sampled token and differentiates it with the tokens held fixed
(Shao et al., 2024); Tang and Munos (2025) analyze what such
losses optimize.
- For one-token responses, write and compare the losses , and . Show that, for , the expected gradient of is zero, that of is , and that of is .
- With the forward penalty ,
the maximizer is ,
where the multiplier makes the probabilities sum to
one (exercise 7a). On
8*8with the rewardsloppy, solve for numerically at and compare the probability of the hedge with that under the tilted optimum. How does the gap depend on ? - For responses of tokens, write for the log-ratio of token , and use (15.8.1) to show that
Which terms does the sum of the per-token losses miss? Why does
folding the penalty into the reward, as kl_group_step does, avoid
the omission?
- Asymmetric bands. A token has probability under the sampling
policy. Suppose that every batch raises its probability by exactly the
factor at which the clip stops rewarding
further growth (Section 15.8.3.2), and that the next batch
is sampled from the updated policy.
- How many batches does it take to raise the probability from to with , and how many with ?
- In a two-action problem the other action starts at probability . Compute its ratio after one such batch. Which side of the band, applied to which action, limits how fast a rarely sampled action can gain probability?
- With two actions, the upper clip limits the growth of the more likely action, of probability , only while . For which does raising from to let the likely action grow faster as well, and what does that do to the entropy? Why does the same change keep the entropy of a language model, with tens of thousands of mostly rare tokens, higher?
- Length-normalized ratio. ● GSPO (Zheng et al., 2025)
replaces the per-token ratios, both as weights and inside the clip, by the
geometric mean of (15.8.2). Model the
per-token log-ratios under the sampling policy as
independent and identically distributed, with mean and variance ,
where is the per-token divergence
.
- Show that has mean and variance , whereas has mean and variance .
- Show that and that as . An importance weight satisfies for every function of the response. Does ?
- GSPO clips to , its GRPO baseline per-token ratios to . Use (a) to explain why a sequence-level band must be much narrower to bind.