Policy gradient makes each sampled response more likely in proportion to its reward. On the lecture's two-prompt example, raw rewards scatter 24 training runs by 16 points and leave 2 of them on the worse answer. Subtract a baseline of 10 and 1, and the spread falls to half a point.
Choose the weight on each reward, and watch the 24 runs train. Then we build, piece by piece, the gradient, the baseline, the clipped ratio and the KL penalty, and train a sorter with them.
You need a probability, a derivative and the softmax. We build the rest from zero.
Lecture 17 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto), the course's last regular lecture. Previous: Lecture 16, RL from Verifiable Rewards. Start again: Lecture 1, Tokenization.
Illustrative toy, computed live and seeded. The lecture's rewards: in prompt 1 the answers pay 11 and 9, in prompt 2 they pay 0 and 2. Each update samples 4 answers per prompt and moves one logit per prompt by 0.1 times the gradient estimate. 24 runs, 80 updates.
Chapter 0
Map the prompt, the token and the score onto states, actions and rewards
You give a model a prompt: "Sort the list [1, 0, 2]." It writes a response, one token at a time. Then a program checks the response and returns a score. You want more responses that score well. Supervised fine-tuning cannot do this alone, because there is no target response to copy. There is only a score.
Reinforcement learning (RL) is learning from a score. The lecture maps the parts like this. The state s is the prompt plus the response so far. The action is the next token. The policy πθ is the language model: it gives a chance to every next token. The reward R scores the whole response, once, at the end.
Pick a response, then step through it. Each step appends one token to the state. The reward stays 0 until the last token.
Illustrative, with the lecture's sorting task. The reward gives one point per prompt number in the response and one point per neighbouring pair in order.
Two facts make language a friendly RL problem. The next state is fixed: append the token. No dice, no physics. And the model can compute the exact chance of any response it wrote, which the gradient needs.
Two facts make it hard. The reward arrives once, after hundreds of tokens. And it is often verifiable: a program checks the final answer and returns 0 or 1. Most responses then score 0. The goal is one number: the expected reward, the average score over prompts and over the responses the model would sample. This lesson asks one question: which way should each weight move to raise that average?
Worked number, from the device: the sort reward gives partial credit. For [1, 0, 2], the response [0, 1, 2] scores 3 + 2 = 5, the maximum. [2, 2, 2] scores 1 + 2 = 3: only the 2 appears, but both pairs are in order, because 2 ≤ 2.
Symptom: RL on a hard task never moves the model.
Measure: the share of sampled responses with a nonzero reward. At a 5% success rate, a group of 8 samples holds no success 66.3% of the time (0.958).
Fix: start from a model that already succeeds sometimes, fine-tuned as in Lecture 15. Or give partial credit, like the sort reward.
Chapter 1
Turn the gradient of an average into an average you can sample
Take one prompt with only three possible responses: [0, 1, 2], [1, 0, 2] and [2, 1, 0]. The policy gives them chances 0.2, 0.5 and 0.3; the sort reward gives 5, 4 and 3.
Call the prompt s and a whole response a, treated as one action. Call the model's chance of a πθ(a | s), with weights θ, and the reward R(s, a). The expected reward J(θ) is:
J of theta equals the sum over a of pi-theta of a given s, times R of s and a.
For each response a, multiply its chance πθ(a | s) by its reward R(s, a). Add the products. The total is J(θ). With many prompts, average J over them too.
With the toy's numbers: J = 0.2 × 5 + 0.5 × 4 + 0.3 × 3 = 1.0 + 2.0 + 0.9 = 3.9.
A real model has more possible responses than we could ever list, so we can only sample. And a sampled token is a discrete pick: no derivative flows through it.
One line of calculus fixes this. The derivative of log x is 1/x, so ∇π = π ∇ log π. Put that inside the sum, and π comes back as a weight. A sum weighted by π is an average over samples from π:
∇J = Σa ∇πθ(a | s) R(s, a) = Σa πθ(a | s) ∇ log πθ(a | s) R(s, a)
The gradient of J equals the expected value, over responses a sampled from pi-theta, of R of s and a times the gradient of log pi-theta of a given s.
Sample a response a. Find its score, the direction that makes a more likely. Multiply it by the reward R(s, a). Average over many samples.
If the weights are the three logits of a softmax, the score of response k is 1 at k, 0 elsewhere, minus π. Sample [0, 1, 2], reward 5: the push is 5 × (0.8, −0.5, −0.3) = (4, −2.5, −1.5). Averaged over all three outcomes, the push is (0.22, 0.05, −0.27), the exact gradient.
Each sample pushes its own logit up and the others down, scaled by its reward. Sample until the pink dots reach the yellow ticks, the exact gradient.
Illustrative toy with seeded sampling: one prompt, three responses, chances 0.2, 0.5 and 0.3, sort rewards 5, 4 and 3.
Symptom: you call backward() through the sampled tokens or the checker, and get an error or a zero gradient.
Measure: check which tensors require a gradient. The sample and the reward never do.
Fix: treat R as a constant. Put the gradient on log π of the sampled response: loss = −R × log π.
Chapter 2
Split the response into tokens, and find fine-tuning weighted by the reward
A real response is many tokens. Call token t at, the tokens before it a<t, and the length T. The chance of the response is the product of its tokens' chances, so its log is a sum:
Log pi-theta of a given s equals the sum, over t from 1 to T, of log pi-theta of a-t given s and a before t.
Run the model on the prompt s plus the response. At each position t, read the log-chance of the written token at. Add them over t.
With made-up chances 0.6, 0.5 and 0.7 for the tokens 0, 1 and 2: log-chances −0.511, −0.693 and −0.357. The sum is −1.561, so the response has chance e−1.561 = 0.210.
Each per-token gradient is the gradient of the cross-entropy loss that fine-tuning uses. So one sample's update is fine-tuning on the model's own response, scaled by its reward. The lecture calls the weight δ; for now δ = R.
python # log_probs: [batch, trial, pos], log-chance of each written token # deltas: [batch, trial], one weight per response (here the reward) loss = -(log_probs * deltas[..., None]).mean() # the lecture's "naive" loss loss.backward() # reward-weighted fine-tuning
Each group of bars is one position's chances over the tokens 0 to 4; the outlined bar is the written token. Pick a response, then apply one update.
Illustrative toy: a table of logits per position, as in the lecture's non-autoregressive model, and one gradient step of size 1 on the reward-weighted log-chance.
With a reward of 0 or 1, this gradient learns only from correct responses. A wrong one has weight 0. Worked number: at a success chance of 0.2, a group of 8 holds no correct response 0.88 = 16.8% of the time, and gives a zero gradient.
Symptom: easy prompts improve while hard prompts never do.
Measure: for each prompt, the share of groups with no correct response.
Fix: sample more per prompt, give partial credit, or drop prompts that are always wrong from the batch.
Chapter 3
Estimate the gradient from N samples, and measure how far one batch lands from the truth
The trick gives an average. In practice we take N samples and average their pushes. Call sample i's prompt si and response ai. This estimate is REINFORCE (Williams, 1992):
G-hat equals one over N times the sum, over i from 1 to N, of R of s-i and a-i times the gradient of log pi-theta of a-i given s-i.
Sample N prompt and response pairs. Scale each sample's score by its reward R(si, ai). Add the N pushes and divide by N. The result g-hat is the estimate.
The Chapter 1 toy, on the logit of [0, 1, 2]: one sample pushes +4.0 (chance 0.2), −0.8 (chance 0.5) or −0.6 (chance 0.3). The average is 0.8 − 0.4 − 0.18 = 0.22, the true gradient. The spread of one sample is 1.89. At N = 16 it is 1.89 / 4 = 0.47, still twice the signal.
The estimate is unbiased: averaged over many batches, it equals the true gradient. But one batch can point the wrong way. The spread shrinks only as 1 over the square root of N, so four times the samples halve the noise. For two spreads to fit inside the signal of 0.22, this toy needs 296 samples per step.
Each bar counts batch estimates of the push on [0, 1, 2]'s logit. Red bars point the wrong way. Grow the batch, then add 10 to every reward.
Illustrative toy, seeded: 400 batches drawn from the Chapter 1 policy. The yellow line is the exact gradient, 0.22.
The lecture's two-prompt example shows where the noise comes from. In prompt s1, answer a1 pays 11 and a2 pays 9. In s2, a1 pays 0 and a2 pays 2. Raw rewards push the worse answer in s1 with weight 9, far harder than the better answer in s2, with weight 2.
The size of a reward, not its rank inside its prompt, sets the push. With every pair equally likely, the weights 11, 9, 0 and 2 have a standard deviation of 5.32.
Symptom: the reward curve jumps, and the same run with another seed ends somewhere else.
Measure: the spread of the gradient estimate across batches, or three seeds side by side.
Fix: more samples per step help as 1 over √N. A baseline, the next chapter, often helps more and costs nothing.
Chapter 4
Subtract a number that ignores the response, prove the average stays, and watch the spread shrink
Pick a number for each prompt, the baseline b(s). It may depend on the prompt. It must not depend on the response. Use R − b(s) as the weight instead of R. The extra term averages to zero:
Ea[ b(s) ∇ log π(a | s) ] = b(s) Σa π(a | s) ∇π(a | s) / π(a | s) = b(s) ∇ Σa π(a | s) = b(s) ∇ 1 = 0
In words: the chances of all responses add to 1 for every value of the weights. A constant has no slope. So the baseline's term is zero on average, whatever number b is. The b must sit outside the sum over a, which is why it cannot depend on a.
The gradient of J equals the expected value, over a from pi-theta, of R of s and a minus b of s, times the gradient of log pi-theta of a given s.
Before you push, subtract the prompt's baseline b(s) from each reward R(s, a). A response above the baseline goes up; one below it goes down. The average push stays the same.
The lecture's two prompts, with b(s1) = 10 and b(s2) = 1: the weights 11, 9, 0 and 2 become 1, −1, −1 and 1. Their standard deviation falls from 5.32 to 1.15. Now a2 in s1 gets −1, so it goes down.
The histogram holds 400 batch estimates (N = 4); the curve is the one-sample spread for every baseline. Drag b: the centre stays at 0.22 while the spread changes.
Illustrative toy, the Chapter 1 policy. The spread curve is exact; the histogram is seeded sampling.
Worked number, from the device: the toy's mean reward is 3.9. With b = 3.9, the one-sample spread falls from 1.89 to 0.34, 5.5 times less, and the average push stays 0.22.
Symptom: after you add a baseline, the model learns a different answer, not only a smoother curve.
Measure: check whether the baseline reads the response it is scoring.
Fix: compute b from the prompt alone, or from other samples of the same prompt, never from the sample itself.
Chapter 5
Derive the baseline with the least noise, then use a group of samples as a cheap stand-in
Which b gives the least noise? Take one weight. One sample's estimate is (R − b) times its score. Its average does not depend on b, so its variance is lowest where its average square is lowest. Set the derivative of E[(∇ log π)2 (R − b)2] in b to zero and solve:
B-star equals the expected value of the squared score times R, divided by the expected value of the squared score.
Average the rewards R, but weight each one by its response's squared score for this weight. The weighted average is b*.
The Chapter 1 toy, logit of [0, 1, 2]: the weights, chance times squared score, are 0.128, 0.020 and 0.012. So b* = (0.128 × 5 + 0.020 × 4 + 0.012 × 3) / 0.160 = 4.725. The one-sample spread there is 0.087, against 0.34 at the mean reward 3.9.
b* differs for every weight, so people use the prompt's mean reward, the value V(s). Then R − V(s) is the advantage: how much better this response did than usual. PPO learns V(s) with a second network, a critic. GRPO (Shao et al., 2024) samples G responses per prompt and uses their mean. Call response i's reward Ri:
Delta-i equals R-i minus the group mean, divided by the group's standard deviation plus epsilon.
Subtract the group mean from each reward Ri, then divide by the group's spread plus ε. Above the mean, δi is positive; below it, negative.
A group of five with rewards 5, 4, 3, 3 and 1: mean 3.2, spread 1.483. So δ = 1.214, 0.539, −0.135, −0.135 and −1.483. Centred only, without the division: 1.8, 0.8, −0.2, −0.2 and −2.2.
Five responses to [1, 0, 2], their rewards, and their weights. Switch the rule, draw a new group, then try equal rewards.
Illustrative. The four rules are the lecture's compute_deltas modes. New groups are seeded uniform samples of three numbers from 0 to 4.
Two cautions. Dividing by the spread is not a baseline; Lecture 16 covers the bias it adds. And a group mean that includes the sample shrinks the gradient by 1 − 1/G; the mean of the other G − 1 avoids that. Every token of response i gets the same δi. A critic can give token t its own weight, R − V(st): GAE with no discount.
Symptom: many prompts give no update at all.
Measure: the share of groups whose rewards are all equal. Their centred weights are all 0.
Fix: a larger G, or fill the batch with prompts whose groups disagree, as DAPO's dynamic sampling does.
Chapter 6
Take several steps on one batch, correct with a ratio, and clip it so no sample pushes too far
Each rollout is a full generation, so we want several gradient steps per batch. After the first step the model has changed, but the batch came from the old model, πold. Importance sampling corrects for this: weight each sample by the ratio of the two chances.
Rho equals pi-theta of a given s divided by pi-old of a given s.
Divide the current model's chance πθ by the old model's chance πold. In code, take exp of the difference of the two log-chances. The lecture does this per token.
With made-up log-chances −1.20 now and −1.50 at sampling time: ρ = e0.30 = 1.35. The new model likes this token 35% more.
Maximise the average of ρδ over the old batch. At the first step ρ = 1, and its gradient is the policy gradient. If ρ grows large, one sample dominates, so PPO (Schulman et al., 2017) clips it to a band of half-width ε:
L equals the minimum of rho times delta, and clip of rho between one minus epsilon and one plus epsilon, times delta.
Compute ρδ and the clipped ρ times δ. Keep the smaller as L. Past 1 + ε for a good token, or below 1 − ε for a bad one, L goes flat and the token stops pushing.
ε = 0.2, ρ = 1.35, δ = +0.5: ρδ = 0.675, clipped 1.2 × 0.5 = 0.600, so L = 0.600, flat. With ρ = 0.65 and δ = −0.5: −0.325 against 0.8 × −0.5 = −0.400, so L = −0.400, also flat. The lecture's code uses ε = 0.01.
The pink curve is L against ρ. Where it is flat, the sample adds no gradient. Move ρ, flip the sign of δ, and switch ε.
Illustrative, exact arithmetic for one token. The band is yellow; the dashed line is ρδ with no clip.
One trap: πold must be a constant. The lecture's example has one weight w = 2 and p = sigmoid(w). With gradients on in both, p / pold is 1 for every w, so the gradient is 0. Compute pold under torch.no_grad(), and the gradient is 1 − sigmoid(2) = 0.119.
Symptom: after you switch to the ratio loss, the model stops changing.
Measure: the gradient is exactly 0 on every step.
Fix: compute the old log-chances once, under no_grad, before the inner steps, as the lecture's training loop does.
Chapter 7
Charge a cost for drifting from a frozen model, and estimate it per token without negatives
RL can teach a new skill and quietly damage old ones. The lecture's fix is a KL penalty: a cost for moving away from a frozen reference model, πref. Its training loop copies the model into the reference every 10 epochs.
The KL divergence of p from q is the average, under p, of log(p / q). It is 0 when the two agree and positive otherwise. With samples, we estimate it from the tokens we drew. The plain estimate, log(p / q) for each drawn token, is right on average but negative for many single tokens. Call the policy's chance of token x p(x) and the reference's q(x). The lecture uses this form instead:
KL of p from q equals the expected value, over x drawn from p, of q of x over p of x, minus log of q of x over p of x, minus one.
For each sampled token x, compute r = q(x) / p(x). Add r − log r − 1. That term is never negative, because the line r − 1 lies above the curve log r and touches it only at r = 1. It still averages to the KL, because r averages to 1 under p.
With made-up chances p = 0.40 and q = 0.30 for one token: r = 0.75. The plain estimate gives −log 0.75 = 0.288. The new one gives 0.75 + 0.288 − 1 = 0.038. Over the device's five tokens the true KL is 0.0304, and the new per-token estimate spreads 0.011 against 0.247.
Top: the policy's chances (purple) and the reference's (yellow). Bottom: 600 batch estimates of the KL from each formula. Red batches came out negative. Drag the policy away from the reference.
Illustrative toy, seeded. At drift 0 the policy equals the reference; at drift 1 the policy's chances are 0.40, 0.25, 0.15, 0.12 and 0.08.
The loss becomes the clipped objective plus β times this estimate, summed over positions. β trades the new skill against drift. Lecture 16 shows PPO pipelines that add the KL per token to the reward instead; the idea is the same.
Symptom: the reward climbs while the text drifts into odd forms, or other skills drop.
Measure: log the KL to the reference per token at every step.
Fix: raise β, or keep the reference fixed longer so the drift cannot reset.
Chapter 8
Run the sorting task with four weightings, and see which ones learn to sort
The lecture's task has three prompts: [1, 0, 2], [3, 2, 4] and [1, 2, 3]. The policy writes three numbers from 0 to 4. The reward is the sort score from Chapter 0, at most 5. The lecture's model decodes each position on its own, not token by token. Our toy keeps that and swaps the network for a table of logits, one row of 5 per prompt and position.
Each epoch samples G responses per prompt, computes the rewards and δ, and takes one gradient step of size 0.5. The four rules share the seed. The faint curves are the other three rules on the same luck.
Press Play. Each prompt row shows the chances at its three positions and the model's current best answer. Green means sorted. Then switch the rule or the group size and train again.
Illustrative toy, computed live and seeded. It keeps the lecture's prompts and reward, but uses a table of logits, plain gradient steps and one step per batch. Each prompt starts uniform, with expected reward 2.66.
Things to try. With G = 8 on the first seed, raw rewards end near 4.0 of 5. Every reward is positive, so every sampled number goes up, and the run settles on near misses. Centred and normalised rules sort all three prompts. Over 20 seeds, raw rewards sort 17 of 60 prompts, max only 34, centred and normalised 58 each. Drop G to 4: raw falls to 8 of 60.
The lecture saw the same order with its network. In our port of its code (seed 5), raw rewards ended at a mean reward of 2.66. Centred and normalised ones reached 3.33, then stuck in local optima, as the lecture says. Its loop also takes 10 steps per batch with the plain loss and no ratio. So the later steps reuse stale samples without a correction.
Check yourself. Why does "Max only" learn faster early and then stall? Which rule stops updating a prompt once all its samples agree?
Chapter 9
Count the models one RL step keeps in memory, and see why generation sets the pace
The maths fits on a card. The lecture's summary puts the difficulty elsewhere: RL systems are much more complex than pretraining, with inference workloads and several models to manage. One step of policy-gradient training runs in this order:
Each model costs memory. Lecture 2 counted 16 bytes per parameter to train with AdamW in float32: weights, gradients and two optimizer states. A frozen model in bf16 costs 2 bytes per parameter. πold costs nothing extra, because the lecture computes its log-chances once, before the inner steps.
Each blue block is one model's memory. The yellow line is one node of 8 GPUs with 80 GB each. Choose the algorithm and the model size.
Illustrative accounting: 16 bytes per trained parameter, 2 per frozen one, a critic and reward model as large as the policy. Activations, the KV cache and sharding overheads are not counted.
Worked number, from the device: a 7-billion-parameter policy needs 7 × 16 = 112 GB to train. PPO adds a critic of the same size, another 112 GB, plus a frozen reference and reward model at 14 GB each: 252 GB. GRPO with a verifier keeps only the policy and the reference: 126 GB. Dropping the critic halves the bill.
Lecture 16 lists why RL is hard to make efficient. Learning on-policy means rollouts, and rollouts mean slow inference. Generation and training often run in different frameworks. Long chains of thought make batches uneven.
Symptom: the training GPUs sit idle for most of each step.
Measure: time each phase: generate, score, train, sync.
Fix: generate with a fast inference engine that batches requests (Lecture 10), and cap or group response lengths so batches stay even.
Chapter 10
Keep the table, the code, and the whole course traced through one RL step
Policy gradient raises the chance of each sampled response in proportion to its weight. The log-derivative trick makes the gradient an average of samples. A baseline keeps that average and cuts the noise. A group of samples gives a cheap baseline. A clipped ratio lets one batch serve several steps, and a KL penalty keeps the model near a reference.
| Tool | Formula, with a number | Main caveat |
|---|---|---|
| Policy gradient | E[R ∇ log π]; toy gradient (0.22, 0.05, −0.27) | unbiased, noisy |
| Sequence log-chance | Σt log π(at | s, a<t); 0.6, 0.5, 0.7 gives 0.210 | one weight for every token |
| REINFORCE noise | spread 1.89 per sample; 0.47 at N = 16 | falls only as 1/√N |
| Baseline | R − b(s); spread 5.32 to 1.15 on the lecture's example | b must ignore the response |
| Best baseline | b* = E[(∇ log π)2 R] / E[(∇ log π)2]; 4.725 | one per weight; the mean is the stand-in |
| Group weight | (Ri − mean) / (std + ε); 5, 4, 3, 3, 1 gives 1.214 to −1.483 | dividing by std is not a baseline |
| Clipped ratio | min(ρδ, clip(ρ, 1 ± ε)δ); 1.35 and 0.5 gives 0.600 | freeze πold; limits each token only |
| KL estimate | r − log r − 1; r = 0.75 gives 0.038 | β trades skill against drift |
The core, as Python we ran (a port of the lecture's functions):
python import torch def compute_deltas(rewards, mode): # rewards: [batch, trial] mean = rewards.mean(dim=-1, keepdim=True) if mode == "rewards": return rewards if mode == "centered": return rewards - mean if mode == "normalized": return (rewards - mean) / (rewards.std(dim=-1, keepdim=True) + 1e-5) def clipped_loss(log_probs, old_log_probs, deltas, eps=0.01): ratio = torch.exp(log_probs - old_log_probs) # old_log_probs computed under no_grad d = deltas[..., None] # same weight on every token return -torch.minimum(ratio * d, ratio.clamp(1 - eps, 1 + eps) * d).mean() def kl_penalty(log_probs, ref_log_probs): # E_p[r - log r - 1], r = q/p log_r = ref_log_probs - log_probs return (torch.exp(log_r) - log_r - 1).sum(dim=-1).mean() compute_deltas(torch.tensor([[5., 4, 3, 3, 1]]), "normalized") # [1.214, 0.539, -0.135, -0.135, -1.483] torch.std(torch.tensor([11., 9, 0, 2])) # 5.323, then 1.155 with baselines 10 and 1
This was the course's last regular lecture. One step of RL on a language model uses every part the course built:
| Part of the step | Lecture |
|---|---|
| Turn the prompt into token ids | 1, Tokenization |
| Count the memory and FLOPs of each model | 2, Resource accounting |
| Run the forward pass | 3, Architectures and 4, Mixture of experts |
| Make it fast on the GPU | 5, GPUs and 6, Kernels |
| Train across many GPUs | 7 and 8, Parallelism |
| Choose the model size | 9 and 11, Scaling laws |
| Generate the rollouts | 10, Inference |
| Measure whether it helped | 12, Evaluation |
| Pretrain the model RL starts from | 13 and 14, Data |
| Fine-tune it, and learn from preferences | 15, SFT and RLHF |
| Score with a verifier; GRPO in practice | 16, RL from verifiable rewards |
| Turn the scores into a gradient | 17, this lesson |
The lecture closes with its summary: "Reinforcement learning is the key to surpassing human abilities", and "if you can measure it, you can optimize it."
The open problems sit in that "if". Most useful skills have no exact checker. One reward at the end of a long response says little about which step earned it. Process rewards score each step; Lightman et al. trained one on 800,000 step labels. Agents act over many turns, so credit must cross turns.
Two guest lectures follow in the course: Junyang Lin on Qwen 3 and Mike Lewis on Llama 3.
Now teach it: press Present or Teach. Explain why subtracting 10 from a reward of 9 turns a push up into a push down without changing the average gradient. Then go back to the 24 runs and predict which rule scatters them most before you press. "What I cannot create, I do not understand." Seventeen lectures later, you can create each piece.