Reinforcement Learning for Language Models, Derived
From the Policy Gradient to GRPO
A math-heavy explainer, in five parts, of the reinforcement learning used to post-train language models, as of October 2026. Every algorithm is derived on screen from the one before it, starting with the log-derivative trick:
- The policy gradient: a language model as a policy, the log-derivative trick (REINFORCE), baselines and the optimal baseline, values, TD errors and generalized advantage estimation.
- Taking safe steps: importance sampling, the performance-difference lemma, TRPO's lower bound, the natural gradient and the Fisher geometry of the probability simplex, PPO's clipped objective.
- Learning what people want: Bradley–Terry from Gumbel noise, reward models, the closed-form optimum of the KL-regularized objective, KL estimators k1/k2/k3 (and why k3's gradient points at the reversed KL), DPO.
- Reasoning, with a checker: GRPO, its group baseline as RLOO in disguise, its std-normalization as an arcsine objective (with exact finite-group weights), zero-variance groups, the length bias of its token averaging (DAPO, Dr. GRPO), entropy collapse as a covariance, clip-higher, pass@k, sharpening vs discovery, on-policy distillation.
- RL at scale: the sampler/learner mismatch measured on a real reasoning model (TIS, masking, GSPO, CISPO), asynchronous RL, ScaleRL's sigmoid compute law, agentic environments, reward hacking, the state of play.
Contents
- 1Learning from a single bit2 min
- 2Part 1: A language model is a policy2 min
- 3The log-derivative trick4 min
- 4Baselines: same mean, less noise3 min
- 5Credit assignment: values, TD errors, GAE3 min
- 6Part 2: Importance sampling and trust regions4 min
- 7PPO: the clipped objective3 min
- 8Part 3: Rewards from preferences2 min
- 9The KL leash and its exact optimum4 min
- 10DPO: the reward hiding in the policy2 min
- 11Part 4: GRPO: the group is the baseline4 min
- 12A real run: what RL actually changed2 min
- 13Hidden biases: lengths and averages2 min
- 14Entropy: the exploration budget3 min
- 15Sharpening or discovery?3 min
- 16Part 5: When the sampler and the learner disagree3 min
- 17Scaling RL: compute, environments, reward hacking3 min
- 18The whole family, one equation at a time1 min
Also on this page: Lecture · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
1Learning from a single bit2 min
This is a real language model, a tiny one, being trained with reinforcement learning. Every possible answer it could give to plus is drawn here as a river of probability, flowing left to right one token at a time. Green endings are right; red endings are wrong. Watch the river as training proceeds. Nobody shows the model a single correct answer. Each attempt gets back one number: one if it was right, zero if it wasn't. And yet the river bends toward green.
The same idea, at scale, is how today's reasoning models are made. In 2025, DeepSeek applied it directly to a base model, rewarding nothing but correct final answers in the right format. Its score on a hard math competition went from sixteen percent to seventy-eight, and its answers grew from hundreds of tokens to thousands, as it learned to check its own work. OpenAI had reported the same trend for o1: more reinforcement learning, better reasoning.
How can a single bit per attempt possibly train a network with millions of parameters? The answer is a short chain of mathematical ideas, and at the end of the chain is this formula: GRPO, the objective behind most open reasoning models. It looks intimidating. By the end of this video, every symbol in it will have been derived, along with the reasons the labs keep changing it.
Here's the route. We'll derive the policy gradient from one identity, then learn how to take safe steps with it. We'll see how human preferences become rewards, and solve for the best possible policy exactly. Then GRPO and its hidden biases, and finally what changes when this runs on thousands of GPUs.
What it establishes: A real model's answers drawn as a "river" of probability that bends toward the right answer as RL trains it, from one bit of reward per attempt. Reasoning models are made this way (DeepSeek-R1-Zero; OpenAI o1). The GRPO objective, to be derived symbol by symbol. Five-part roadmap.; Real data on screen: The adder's exact answer tree for 5675 + 5563 at GRPO checkpoints 0–120: P(right) 56% → 99.8%, the "shows its work" stream thinning. Quoted: R1-Zero AIME 2024 15.6% → 77.9%.
2Part 1: A language model is a policy2 min
First, the translation. To reinforcement learning, a language model is a policy. The state is everything written so far: the prompt and the answer's first few tokens. The action is the next token, drawn from the model's softmax. The environment couldn't be simpler: it appends the token. When the answer ends, a reward arrives. Everything else in this video is about that last line.
Here is the whole space of answers for one prompt, as the real model sees it. Reading left to right, each column is a token, and each block's height is the probability of reaching that prefix. The river splits wherever the model is unsure. The top stream shows its work, writing the sum backwards first; the rest answer directly, and fork at every carry. The probability of a whole answer is the product of its tokens' probabilities, along its path.
The checker marks each complete answer right or wrong: this last column. With a reward of one for right and zero for wrong, the expected reward is simply the total probability of the right answers: the green part of that column. Reinforcement learning, for us, means one thing: reshape the river so that more of it ends in green.
Meet the model behind that picture. It's a pocket-sized transformer, three layers deep, pretrained on text full of four-digit additions. A quarter of the examples show their work: the sum written right to left, digit by digit with its carries, then the answer. The rest answer at once, and like people doing sums in their heads, they sometimes forget to carry. The model learned both habits faithfully. It shows its work about a quarter of the time and is then almost always right; otherwise it slips like its teachers. We'll call it the adder.
What it establishes: Part 1. RL's vocabulary for a language model (state, action, policy, deterministic transition, end-of-answer reward). An answer's probability is the product of its tokens' probabilities along a path; J(θ) is the green part of the reward column. The adder, its training data, and its two habits.; Real data on screen: The tree with one path's product, 0.54 × 0.74 × 0.76 × 1 × 1 × 1 = 0.30. The adder (335,328 parameters): shows its work 28% of the time (then right 99.9%), answers directly otherwise (then right 60%), 71% overall.
3The log-derivative trick4 min
Here is the problem reinforcement learning has to solve. The parameters theta define a policy. We sample an answer from it, and a checker hands back a reward. We want to make the expected reward bigger, so we want its gradient with respect to theta. But backpropagation can't get there. Sampling is a discrete choice, and the checker might be a test suite running in a sandbox: there is no derivative to follow.
The way around it is one of the most useful identities in machine learning. Write the expected reward as a sum over every possible answer y, of its probability times its reward. The reward doesn't depend on theta, so the gradient only touches the probability. Now multiply and divide by pi: the gradient of pi equals pi times the gradient of log pi. And a sum weighted by pi is just an average over samples from pi. So we can estimate the gradient without differentiating through anything we can't: sample answers, score them, and average reward times the gradient of the log probability.
That gradient of log pi has a name, the score function. And this estimator, published by Ronald Williams in 1992 as REINFORCE, is the seed of every algorithm in this video.
To see what this does, shrink the problem to one dimension. The policy picks a number a from a bell curve centered at mu, and the reward is this landscape with two hills. Sample ten actions. For a bell curve, the score is simply a minus mu: each sample says move toward me, in proportion to how far away I am.
On their own, these pushes cancel out on average. In fact the score always has mean zero: its average is the gradient of the total probability, and the total is always one. Remember this; it will matter in a minute.
Now weight each push by the reward its sample earned. Samples near the tall hill keep their arrows; samples in the valley lose theirs. The symmetry breaks, and the average points toward higher reward.
Take a small step along that average, sample again, and repeat. The bell curve climbs the hill, and nobody ever computed the derivative of the reward.
For a language model the answer is a sequence of tokens, and its log probability is a sum, one term per token. So the policy gradient becomes: the answer's reward times the sum of every token's score. Each token of a sampled answer gets pushed up, or down, by the same amount: the reward of the whole answer.
Compare that with supervised fine-tuning. There, you maximize the log probability of a reference answer someone wrote. Here, you do the same thing to the model's own answer, weighted by how well it did. Reinforcement learning is fine-tuning on your own samples, graded.
What does pushing up one token actually do? Inside the model, the next token comes from a softmax over logits. The score of the sampled token, with respect to the logits, is one minus its probability for the sampled token, and minus the probability for every other token. So a positive reward raises the sampled token and takes mass from the others, the popular ones most of all.
What it establishes: Why backpropagation can't reach the reward. The five-line derivation of ∇J = E[R ∇log π], a reason beside each line; the score function; REINFORCE (Williams 1992). A 1-D Gaussian policy: score arrows a − μ cancel on average and reward-weighting breaks the symmetry; the policy climbs the tall hill. Sequences: the reward times a sum of token scores; RL as fine-tuning on your own graded samples; the softmax score 𝟏[b = a] − π(b).; Real data on screen: Exact toy, 10 real samples: unweighted mean push −0.11, reward-weighted +0.15. One real softmax step on the next-token distribution.
4Baselines: same mean, less noise3 min
There's a catch. Suppose the grader is generous, and every answer earns at least two points. Then every sample pushes the policy toward itself; the pushes still average out to the right direction, but each estimate is mostly noise. Here are six runs of exactly the algorithm we just derived. They wander, and some never find the hill. Now make one change: subtract the batch's average reward before weighting. All six runs climb straight to the top.
Why are we allowed to do that? Subtract any number b from the reward, and look at the expected gradient. It splits into the policy gradient, minus b times the expected score. And the expected score is zero, as we saw. So any baseline that doesn't depend on the sampled answer leaves the gradient unchanged on average. What it changes is the noise.
Let's watch the noise directly. A policy over a two-dimensional action, on a landscape with two hills, plus the constant two points. Each sample suggests a direction: from the center toward itself, scaled by its reward. Average a batch of sixteen such suggestions and you get one gradient estimate, a single point on the right. Three hundred batches make this cloud. Its center is the true gradient, but the cloud is so wide that a single estimate often points the wrong way.
Now subtract the average reward. Same center, but the cloud collapses: the variance drops by a factor of . The signal was always there; the baseline removes the part of the reward that every answer gets anyway.
Which baseline is best? The variance is a quadratic in b, a parabola, so set its derivative to zero. The best baseline is the average reward, weighted by the squared size of the score. In practice that's very close to the plain average reward. Here, they agree to within a percent.
One more step. Different prompts deserve different baselines: a policy that usually solves an easy problem shouldn't get excited about solving it again. So subtract V of x, the average reward the policy gets on this particular prompt. What's left is called the advantage: was this answer better or worse than usual? With a reward of one for right and zero for wrong, V is just the chance p of being right. On an easy prompt, a right answer earns a tiny plus zero point one, and a mistake a big minus zero point nine. On a hard prompt it's the reverse: a rare success is worth a lot.
But to compute an advantage, we need V, and nobody hands it to us. And when the answer is a long sequence of tokens with a single reward at the end, a deeper question appears: which tokens deserve the credit?
What it establishes: Subtracting a baseline keeps the mean (the score has mean zero) and cuts the noise. The variance is a parabola in b; the optimal baseline E[R‖g‖²]/E[‖g‖²]. The advantage R − V(x), and why easy and hard prompts need different baselines.; Real data on screen: Six REINFORCE runs with reward 2 + R wander; six with the batch-mean baseline climb. 300 gradient estimates (batches of 16) on a 2-D toy: variance 0.73 → 0.027 (27×). b* = 2.371 vs mean reward 2.364.
5Credit assignment: values, TD errors, GAE3 min
Here is a real answer from the model we'll train later, to the problem plus . It's wrong, so the reward is zero, and the policy gradient pushes every one of its tokens down equally. But most of those digits were fine. Only one was a mistake: a forgotten carry. A single reward at the end can't say which token earned it.
The fix is to measure progress along the way. Define the value of a partial answer: the expected final reward, given the prompt and the tokens written so far. With a zero-one reward, it's simply the chance of ending up right from here. For a language model, nothing random happens between tokens except the next token itself, so the value now is the average value after one more token. That's the Bellman equation. And it hands us exactly what we wanted: a token's advantage is how much it changed the odds. The value after it, minus the value before. With an estimated value function, this difference is called the temporal difference error, delta.
We can't compute V exactly, so we learn it: a second network, the critic, trained to predict the final reward from every prefix of the model's own answers. Here is a real one, reading three real answers. Before the model writes anything, the critic gives it a percent chance. In this first answer the model starts by showing its work, and the value jumps: the critic has learned that worked answers are almost always right. Every later token barely changes anything.
Using delta alone trusts the critic completely, and the critic is only a guess. Generalized advantage estimation blends in the actual outcome: add up the deltas from here to the end, discounting each step by a factor lambda. With lambda zero, you get the critic's one-step opinion. With lambda one, the sum telescopes into the final reward minus the value now: unbiased, but noisier.
On our wrong answer, slide lambda from zero to one. Almost nothing changes. This critic is good: the value already collapsed at the bad digit, so the later tokens owe nothing either way.
Now take the critic away and use one number per prompt, the way GRPO and RLOO do. Every token gets the same blame, the correct digits included.
And on a right answer that showed its work: the critic puts nearly all the credit on the single token that decided to show the work. Without a critic, that decision is just one token among thirteen, all sharing the same reward.
The price is a critic network as large as the policy itself, trained alongside it. The algorithm behind today's reasoning models decided that price wasn't worth paying.
What it establishes: One reward at the end blames every token equally. The value of a prefix, the Bellman equation for an LM, a token's advantage as the change in value, the TD error. GAE's λ. What GRPO/RLOO give up by dropping the critic.; Real data on screen: A critic trained on the base model's answers: V = 58% before the answer; +0.39 at the token that starts showing work; −0.50 at the digit with the forgotten carry; λ barely matters for a critic this good.
6Part 2: Importance sampling and trust regions4 min
So far, every gradient step used fresh samples from the current policy. But for a language model, generating the samples is by far the expensive part. A long answer is written one token at a time, while the gradient step that consumes it is a single parallel pass. So we'd like to squeeze several gradient steps out of each batch. The trouble is that after the first step, the batch was written by an older policy.
There's a standard fix for data drawn from the wrong distribution: importance sampling. An average under the new policy is a sum weighted by its probabilities. Multiply and divide by the old policy's probability, and it becomes an average under the old policy, with each sample reweighted by the ratio rho of new to old probability. Apply that to the advantage and you get the surrogate objective that PPO and GRPO both optimize. At the old parameters the ratio is one, and its gradient is exactly the policy gradient.
For a language model, the ratio is taken token by token. The exact ratio for a whole answer would be the product of all of them, and a product of hundreds of numbers near one can explode, so instead each token is reweighted on its own. How wrong is that? A classic identity, the performance difference lemma, says the improvement from one policy to another is the sum of the old policy's advantages, along trajectories of the new policy. The surrogate makes one approximation: it uses the prefixes the old policy visited. That's exact when the policies match, and good only while they stay close.
Here's the picture, along one direction in parameter space. The true objective rises, then falls. The surrogate touches it at the old parameters and has the same slope, but it keeps promising more the further you go. Follow it blindly and you overshoot. TRPO proved that subtracting a multiple of the largest KL divergence between old and new policies gives a lower bound on the true objective. Maximize the bound instead, and every step is guaranteed not to make things worse.
TRPO's constraint leads to a beautiful idea. Picture a policy over just three actions, A, B, and C. Every point of this triangle is a probability distribution; the corners are certainty. Action A pays the most. Now draw every distribution within the same small KL divergence of a few starting points. The regions aren't circles, and they shrink near the edges, where small probabilities become precious. KL measures distance between distributions, not between parameters.
To second order, KL is a quadratic form in the parameter step, built from the Fisher information matrix. Steepest ascent measured this way is the natural gradient: the ordinary gradient, multiplied by the inverse Fisher matrix. Here are both, followed exactly from the same start. The ordinary gradient crawls: it moves each logit in proportion to its action's probability, so the rare best action barely moves at first. The natural gradient moves every logit by its advantage, and heads almost straight for the best corner.
TRPO takes natural-gradient steps with a KL budget. It works, but it needs second-order machinery that is painful at the scale of a language model. PPO, in 2017, replaced it with something much simpler.
What it establishes: Part 2. Sampling is the expensive part, so batches get reused. Importance sampling and the surrogate objective; token-level ratios; the performance-difference lemma; TRPO's lower bound. The 3-action simplex: KL balls shrink near the edges; vanilla vs natural gradient.; Real data on screen: Exact: KL contours on the simplex and both gradient flows from the same start (the natural gradient moves every logit by its advantage). The bound is schematic.
7PPO: the clipped objective3 min
Proximal policy optimization keeps the surrogate, but takes away the incentive to move too far. Take the surrogate term, ratio times advantage, compute a second copy with the ratio clipped to between zero point eight and one point two, and keep the smaller of the two.
Look at it as a function of the ratio. For a good answer, the objective rises with the ratio, so the gradient pushes the token's probability up, until the ratio passes one point two. Then the objective goes flat, and the gradient is zero: no reward for pushing further. For a bad answer it's the mirror image: push the probability down, until it has fallen by twenty percent. Note the minimum: in the direction that would hurt, there's no clipping. The objective is a pessimistic bound on the surrogate.
In probability terms, the clip gives each token a window. A token the old policy chose with probability zero point nine can move anywhere from zero point seven two up to one. But the window is relative: a token at one percent can only rise to one point two percent in a round of updates. That asymmetry between likely and unlikely tokens will come back to haunt us.
Does it matter? Here's a real test on the pocket model you'll meet properly in a few minutes. Teal: one gradient step per batch. After five steps it's at percent. Red: sixteen steps per batch, without the clip. Reusing the data is far more efficient: percent after five steps. But it wobbles: around step , one seed falls back to . Green: the same sixteen steps, clipped. Just as fast, and it climbs steadily, to percent. In a model this small the difference is modest; the point of the clip is that you can take many steps on one batch without worrying about how far they go.
This is the algorithm behind InstructGPT and the original ChatGPT. Count the networks: the policy being trained, a frozen copy of where it started, a reward model, and the critic, each as large as the language model itself. Every token pays a small penalty for drifting from the reference, and the reward model's score arrives at the end.
Two of those four networks exist to turn human judgment into a number. So where does that number come from?
What it establishes: The clipped objective; case analysis for A > 0 and A < 0 (where the gradient is zero); the clip as a per-token probability window. RLHF with PPO: four networks and a per-token KL reward.; Real data on screen: Windows for ε = 0.2: 0.9 → [0.72, 1], 0.01 → [0.008, 0.012]. Reusing batches on the adder (3 seeds): 1 update per batch reaches 75% after 5 steps; 16 updates reach 93%; unclipped, one seed falls to 91% at step 40; clipped ends at 99.1%.
8Part 3: Rewards from preferences2 min
Arithmetic has a checker. Helpfulness, clarity and tone don't. But people can compare: show someone two answers to the same prompt, and ask which is better. How do we turn a pile of such choices into a reward?
Model each judgment like this. Every answer has a hidden utility, and each time a person judges, they perceive it with some noise, and choose whichever looks better. If that noise follows a Gumbel distribution, the distribution of the largest of many small effects, then the difference of two independent noises is exactly logistic. So the probability of choosing A is the area to the left of the utility gap: the logistic sigmoid of the difference.
This is the Bradley-Terry model, from 1952. Notice that only the difference of utilities matters. Add the same constant to every answer for a prompt, and nothing changes.
So fit the utilities by maximum likelihood. The reward model is a copy of the language model with a single number as its output, trained so that the preferred answer's score beats the rejected one's through the sigmoid. And because only differences matter, the reward model can carry an arbitrary offset for each prompt. That's harmless for us: a per-prompt offset is just a baseline, and we've seen that baselines don't change the policy gradient.
But a reward model is a learned approximation, and the policy is an optimizer. Push hard enough, and the policy finds answers the reward model loves and people don't: the proxy keeps rising while true quality peaks and falls. OpenAI measured exactly this shape in 2022. That's why RLHF keeps the policy on a leash: the KL penalty to the reference. What does that leash actually do? Remarkably, we can solve for the best policy exactly.
What it establishes: Part 3. Comparisons instead of a checker (illustrative pair). Bradley–Terry from Gumbel noise: the difference of two Gumbels is logistic. The reward model's likelihood; a per-prompt offset is just a baseline. Goodhart's law.; Real data on screen: Exact Gumbel and logistic densities; P(A ≻ B) = σ(2.2) = 0.90. Over-optimization curve schematic, after Gao, Schulman & Hilton.
9The KL leash and its exact optimum4 min
Here is the objective RLHF actually optimizes: expected reward, minus beta times the KL divergence from the reference policy. Write the KL as a sum over answers. Now fold the reward into the logarithm, as the log of e to the r over beta. Normalize that tilted distribution, with a constant Z, and the whole objective becomes minus beta times a KL divergence to a single distribution, plus a constant.
A KL divergence is never negative, and it's zero only when the two distributions match. So the best possible policy is exactly this one: the reference, reweighted by e to the reward over beta. No training needed to know the answer; training is just a way to get there.
Let's apply it to a real distribution: the answers our pocket model gives to one problem, before any reinforcement learning. Green answers are right, red ones are wrong, and the long ones show their work. With a large beta, the leash is tight and nothing changes. As beta shrinks, every right answer gets multiplied by the same factor, and the wrong ones fade. At small beta, the optimal policy is essentially always right.
Notice what the tilt can't do. Right answers keep the proportions the reference gave them, and an answer the reference would never write gets probability zero, whatever its reward. The optimum only reweights what the starting model could already say.
Back on the triangle of three-action policies, the optimal policies for every beta trace out a single curve, from the reference toward the best corner. And here's a surprise: it's exactly the path the natural gradient followed. Natural gradient ascent on the logits adds a multiple of the reward, so after time t the policy is the reference tilted by e to the t r. Training longer plays the same role as loosening the leash.
Averaged over many problems, the optimal policies give a frontier: the most reward you can possibly have at each distance from the starting model. Being right every time costs only nats. Our actual training run, which had no KL penalty at all, sits below the frontier, as every policy must. It ends almost as accurate, but about as far from where it started as it needed to be: unlike the optimum, it also reshuffled its right answers.
In practice the KL itself has to be estimated from samples, one token at a time. John Schulman's three estimators are now in nearly every RL library. The obvious one, minus the log ratio, is unbiased, but it's negative half the time and very noisy. Half the squared log ratio is always positive, but slightly biased. And k3 adds a term whose average is exactly zero, rho minus one: it stays unbiased, it's never negative, and it's far less noisy. For two close distributions, its spread is fourteen times smaller.
One subtlety. An estimator with the right value can have the wrong gradient. GRPO puts k3 directly in its loss, and differentiating it pulls the policy toward the reversed KL, from reference to policy. DeepSeek's V3.2 corrects this by multiplying in the importance ratio. And many reasoning recipes skip the leash entirely, and set beta to zero.
What it establishes: The KL-regularized objective solved exactly: π* ∝ π_ref e^{r/β}. The tilt only reweights; it never invents. The tilted family is the natural-gradient path. The reward–KL frontier. Schulman's KL estimators; k3's gradient points at the reversed KL.; Real data on screen: The adder's real answer distribution tilted as β falls: P(right) 0.59 → 1.00, right answers keeping their 0.54 : 0.46 proportions. Frontier over 48 problems: always right costs 0.39 nats; the GRPO run sits below it at about twice that KL. Monte Carlo estimator table (2M samples): std/KL 20.0, 1.42, 1.42 at KL = 0.005.
10DPO: the reward hiding in the policy2 min
In 2023, a group at Stanford ran this formula backwards. If the optimal policy is the reference tilted by the reward, take logs, and solve for the reward. Any policy implies a reward: the log ratio of its probabilities to the reference's, times beta, plus a term that depends only on the prompt.
Now plug that implied reward into the Bradley-Terry model of comparisons. The probability that the preferred answer wins is the sigmoid of the reward difference. Substitute, and the troublesome normalizer Z appears twice, with opposite signs. Both answers answer the same prompt, so it cancels. What's left depends only on the policy and the reference. Fit it by maximum likelihood, and you have Direct Preference Optimization: a simple classification loss on pairs. No reward model, no sampling, no critic.
Its gradient is easy to read. Raise the log probability of the preferred answer, lower the rejected one, and weight the pair by a sigmoid of how badly the model's own implicit reward currently ranks it. Pairs it already gets right fade away; pairs it gets wrong get the full push.
Here it is on the adder, from four thousand pairs of right and wrong answers, sampled once from the starting model. Accuracy climbs from to percent. Then it collapses. Look at what the loss is doing: it only cares about the gap between the preferred and the rejected answer, and it found that pushing both down widens the gap fastest. The probability doesn't vanish; it flows to answers that were in neither set, and the model starts writing nonsense. This failure has a name, likelihood displacement.
The fix people use is to stop early, regularize, or keep sampling: train on the model's own fresh answers instead of a fixed set. Which is exactly what the reinforcement learning methods do. For reasoning, the field went back to sampling, and to a much simpler kind of reward.
What it establishes: Invert the optimum: every policy implies a reward. Z cancels in Bradley–Terry, leaving the DPO loss; its gradient weight. Offline DPO and likelihood displacement.; Real data on screen: DPO on the adder, 4,096 fixed right-vs-wrong pairs (β = 0.1, lr 1e-5): 69% → 80% at step 100 → 0.7% at step 300, as the preferred answers' log-probability falls 10 nats and the rejected ones' 18.
11Part 4: GRPO: the group is the baseline4 min
In 2024, DeepSeek's math model introduced the algorithm behind many of today's open reasoning models: group relative policy optimization, GRPO. Its idea is to replace the critic with something free. For each prompt, sample a group of answers. Here are real ones from our pocket model. A checker grades each one: one if right, zero if wrong. The group's average reward is an estimate of the value of the prompt, the very thing the critic was trained to predict. Subtract it, and you have an advantage for every answer, with no value network at all.
Is that baseline legal? It includes the answer itself, and a baseline isn't allowed to depend on the sampled answer. But split the average into answer i's own share and the average of the other answers. Rearranged, answer i minus the group mean is exactly a constant times answer i minus the average of the others, and that leave-one-out baseline is independent of answer i. So the group mean gives an unbiased gradient, just scaled by G minus one over G. This leave-one-out version is known as RLOO.
GRPO does one more thing: it divides by the group's standard deviation. That looks like a harmless normalization, but it changes what's being optimized. With rewards of zero and one and a success rate p, the standard deviation is the square root of p times one minus p, so a right answer gets this advantage, and a wrong one this. Average over the samples, and the expected update is the gradient of p, divided by that same square root. And that's the derivative of two arcsine root p.
So GRPO doesn't maximize the success rate itself. It maximizes the arcsine of its square root, which puts extra weight on prompts the model almost always fails or almost always solves. Here's that weight, as a function of p. With a finite group it's tamer: these are the exact curves for groups of two to sixty-four. With two answers, the normalization does nothing at all. And two arcsine root p has a meaning: it's the distance along the family of coin flips, measured with the Fisher information, the same geometry as the natural gradient. Some labs keep this weighting; others, like OLMo 3, DeepSeek-V3.2 and Dr. GRPO, drop the division.
There's a catch hiding in the group. If every answer in a group is right, or every one is wrong, every advantage is zero, and the whole group teaches nothing. That happens with probability p to the G plus one minus p to the G. On easy prompts, late in training, most groups are wasted compute. ByteDance's DAPO filters these groups out and keeps sampling until the batch is full of informative ones.
Now we can read the whole GRPO objective, the formula from the start of the video. Answers sampled by the old policy, in groups. The importance ratio, clipped as in PPO, times the group-relative advantage. And the leash to the reference model, estimated with k3. There's one piece we haven't explained: inside, each answer's tokens are averaged, one over the length of answer i. That innocent-looking average turns out to be a trap. But first, let's watch GRPO train a real model.
What it establishes: Part 4. The group mean as a free baseline; mean-centering = (G − 1)/G × leave-one-out (RLOO), so unbiased. The std division turns the objective into 2 arcsin √p (Fisher–Rao arc length); exact finite-G weights. Zero-variance groups. The full GRPO objective, annotated.; Real data on screen: A real group of 8 answers to 5675 + 5563: R̄ = 0.625, advantages +0.375 / −0.625. Exact weight curves κ_G(p) for G = 2, 4, 8, 64. P(all equal) = p^G + (1 − p)^G for G = 4, 8, 16.
12A real run: what RL actually changed2 min
Time to run it. We train the adder with GRPO: thirty-two problems per step, eight answers each, a reward of one or zero, and nothing else. Accuracy on problems it has never seen climbs from percent to percent within forty steps. But how? You might expect it to start showing its work, since that's almost always right. It barely does: from to percent of answers. Instead, its direct answers stopped slipping: from to percent right. Forgetting a carry was always a choice the network could unlearn, one token at a time, and that was the cheapest way up.
Here are its five likeliest answers to our running example, before and after. Before, the right answer shared its probability with several slips. After, nearly all of it sits on the right answer, written directly. That's what RL did to this model: it sharpened.
Now the same experiment with six of the algorithms we've derived, three seeds each. On accuracy, they look almost interchangeable. PPO starts late, because its critic has to be trained first, and every one of them ends above ninety-five percent. But look at what they learned to do. GRPO and RLOO end up showing their work about percent of the time; DAPO, Dr. GRPO and PPO, about . And plain REINFORCE abandons showing its work completely. Same reward, same accuracy, different behavior. The difference turns out to hide in one innocent-looking average.
What it establishes: GRPO trains the adder; RL sharpened rather than taught: direct answers stopped slipping. Six algorithms reach the same accuracy with different behavior.; Real data on screen: GRPO, 3-seed means: 70% → 98% right within 40 steps; showing work 28% → 41%; direct answers 59% → 97% right. The five likeliest answers before and after. REINFORCE, RLOO, GRPO, Dr. GRPO, DAPO-style and PPO + GAE, 3 seeds each: show-work rates from 0% to about 50%.
13Hidden biases: lengths and averages2 min
Here's the trap. GRPO averages over an answer's tokens before averaging over the group, so each token's push is the advantage divided by the answer's length. Two right answers, one short and one long: the short one's tokens get pushed up twice as hard. Two wrong answers: the long one's tokens are punished half as much. So when the model is right, it learns to be brief, and when it's wrong, it learns that rambling dilutes the blame. Long, wrong answers are the result.
Two 2025 papers removed the bias in different ways. ByteDance's DAPO averages over all tokens in the batch at once, so every token counts equally. Dr. GRPO divides by a fixed constant, the maximum length, and also drops the division by the standard deviation, arguing that both normalizations bias the gradient.
In our pocket model, this bias isn't hypothetical. Remember plain REINFORCE, which abandoned showing its work? It used GRPO's per-answer average. Without a baseline, only right answers get pushed, and a right direct answer is six tokens long while a right worked answer is thirteen: per token, the short answers push twice as hard on the very first choice, and nothing pushes back. Replace that average with a constant and change nothing else: the same algorithm now ends up showing its work percent of the time. With a baseline the effect is milder, but it's still there: GRPO, with the per-answer average, ends at percent; DAPO and Dr. GRPO, without it, at and .
These choices aren't academic. We read the code of eleven open-source RL libraries; here are nine. They disagree on almost every one of them: how to average over tokens, whether to divide by the standard deviation, whether to keep a KL leash at all, and which estimator to use for it. When a paper says it used GRPO, it's naming a family of choices, not one algorithm.
What it establishes: GRPO's per-answer 1/; Real data on screen: o_i
14Entropy: the exploration budget3 min
Every RL run on a language model shows the same signature. The policy's entropy, its average uncertainty about the next token, collapses. Here it is in our run. Entropy is the exploration budget: once the policy is certain, it stops sampling anything new, and learning stalls. Why does it fall, and can we control it?
For a softmax, the derivative of the entropy with respect to a logit is minus that token's probability, times how much more surprising than average it is. Sum over a small change of all the logits, and the change in entropy is minus a covariance: between how likely each token already is, and how much its logit moves. Plug in the policy gradient, which moves each logit by its probability times its advantage, or the natural gradient, which moves it by the advantage alone. Either way: the entropy falls whenever the tokens the model already likes are the ones being rewarded.
Two examples, each with the same five-token distribution. On the left, the token the model already likes is the one that gets rewarded: a positive covariance. One natural gradient step, and the distribution sharpens; the entropy drops. On the right, a rare token is rewarded. The covariance is negative, and the step spreads probability out: entropy rises. In RL on a pretrained model, the first case is overwhelmingly common: the confident tokens are usually the right ones, so entropy steadily drains away.
Does the formula hold up in a real network, where every logit is tied to every other through shared weights? Here is the covariance between each sampled token's log probability and its advantage, measured in every batch of our run, and here is how much the entropy actually changed. The covariance is positive in percent of the batches, and the entropy keeps falling. Averaged over a few steps, the bigger the covariance, the faster the fall: a correlation of minus .
Remember the clipping windows. With a symmetric clip, a rare token can rise by at most twenty percent of its probability per round, while a likely one can rise all the way to certainty. That's exactly the positive covariance again: the clip itself favors sharpening. ByteDance's DAPO simply raises the upper limit to one point two eight, giving rare tokens more room to grow. Along with dynamic sampling, a token-level loss and a soft penalty for overlong answers, it took a naive GRPO run on the AIME math competition from thirty to fifty percent.
What it establishes: Entropy collapse. ∂H/∂z for a softmax; ΔH ≈ −Cov(log π, Δz); vanilla and natural policy gradients; why rewarding confident tokens drains entropy. Clip-higher.; Real data on screen: The GRPO run's next-token entropy falls 0.18 → 0.044 (4.2×). Two exact 5-token examples (H 1.12 → 0.36 vs 1.12 → 1.40). Measured batch covariance: positive in 87% of batches; 9-step averages correlate −0.81 with the entropy change. Quoted: DAPO, AIME 30% → 50%.
15Sharpening or discovery?3 min
Does reinforcement learning teach a model new things, or just make it more reliable at things it could already do? To ask that precisely, we need pass at k: the chance that at least one of k attempts is right. With a success rate p, it's one minus the chance that all k fail. To estimate it, draw n samples, count the right ones, and ask: of all the ways to pick k of them, what fraction contain no right answer at all? Here, ten of the fifty-six ways fail, so pass at three is about point eight two.
Here is pass at k for our adder, measured with samples on each of held-out problems. Before RL, a single attempt is right percent of the time, but with attempts, gets solved at least once. After RL, a single attempt is right percent of the time. The curve went flat: RL moved the probability onto answers the model could already produce. Its mistakes were slips, and the right answer was always within reach.
This matches the math. The KL-regularized optimum is the reference times a positive factor, so any answer the reference would never produce stays at probability zero. In 2025, a careful study found the same thing in large reasoning models: given enough attempts, the base model catches up with, and even passes, the RL-trained one. NVIDIA's ProRL pushed back, finding problems that only prolonged RL could solve; and in practice, generalization lets a network reach answers it never sampled. As of 2026, the question is still open.
Other measurements point the same way. A reward of zero or one carries about one bit of information per attempt, so even DeepSeek's R1-Zero received only a few million bits, fewer than the parameters of a tiny adapter. Most weights don't change at all. And on-policy RL tends to find the solution closest to the starting model, which is why it forgets less than fine-tuning on someone else's answers.
If one bit per attempt is the bottleneck, there's a fix when a stronger model exists. Sample from the student, as in RL, but let a teacher grade every token: the reward for each token is how much more likely the teacher finds it. That's on-policy distillation, the same log-derivative trick with a dense reward. For Qwen3's eight-billion-parameter model it beat RL on the AIME benchmark for a tenth of the compute. And in April 2026, DeepSeek's V4 replaced its final RL stage with exactly this, distilling from specialist teachers that had each been trained with GRPO.
What it establishes: pass@k and its unbiased estimator. Sharpening vs discovery; the optimum cannot leave the reference's support; the 2025–26 debate. Bits per episode, sparse updates, RL's Razor. On-policy distillation.; Real data on screen: Worked estimator: 1 − C(5,3)/C(8,3) = 0.821. pass@k from 128 samples × 300 problems: base 70.4% at k = 1, every problem solved by k = 16; after RL 99.2% at k = 1. Quoted: Qwen3-8B AIME 2024, RL 67.6% (17,920 GPU-hours) vs on-policy distillation 74.4% (1,800).
16Part 5: When the sampler and the learner disagree3 min
At scale, generation and training run in different software. An inference engine like vLLM writes the answers, with kernels tuned for speed. A training framework computes the gradients, with different kernels and often different precision. They hold the same weights, but they don't compute the same probabilities. So even a perfectly on-policy algorithm is quietly off-policy, and the importance ratio that should be exactly one isn't.
We measured it. A 0.6-billion-parameter Qwen3 model wrote eight reasoning traces, sampled token by token in bfloat16, the way an inference engine runs. Then we re-scored exactly the same tokens in a single float32 pass, the way a trainer might. Most log ratios are tiny, but the tails are wide: percent of tokens differ by more than one percent. Re-scoring in the same bfloat16, just in one pass instead of token by token, is no better: percent. It's the order of the arithmetic, not only the precision. And the disagreement lives on the unlikely tokens. Near-certain tokens almost never move, but percent of tokens the sampler gave less than a ten percent chance are off by more than one percent: exactly the rare choices that exploration depends on.
Now look at whole answers. The exact importance weight of a sequence is the product of its token ratios, so its logarithm is a sum: a random walk. Here are the walks for our eight traces. They wander away from zero as the answers get longer: after tokens, one answer's weight is and another's is , though not one weight of the model changed. Qwen's GSPO uses the geometric mean instead, the average log ratio, which shrinks back toward zero as the answer grows.
Since 2025 the field has converged on a handful of fixes. Truncated importance sampling multiplies each token's gradient by its sampler-to-learner ratio, capped at a constant. Masking simply drops tokens or sequences whose ratios are too extreme. GSPO uses one ratio per answer, and for mixture-of-experts models replays the experts the sampler used, since about one expert in ten changes after each update. MiniMax's CISPO caps the importance weight but never zeroes a token's gradient, so rare reflective tokens like wait, or however, keep contributing. And some just fix the arithmetic: a float32 output layer, or float16 rollouts.
Staleness is the other source of off-policy data. Long answers make generation the bottleneck: in OLMo 3's runs the learner spent three quarters of its time waiting. So large systems decouple the two, generating with slightly old weights while training continues, and stream new weights to the generators as they go. Every one of these importance-ratio corrections now has to absorb that lag too.
What it establishes: Part 5. Inference engines and trainers compute different probabilities from the same weights, so "on-policy" RL is off-policy. Sequence-level weights as random walks; GSPO's geometric mean. TIS, masking (IcePop), GSPO, CISPO, numeric fixes. Asynchronous RL and staleness.; Real data on screen: Qwen3-0.6B, 8 traces × 768 tokens: 25% of tokens > 1% off when re-scored in fp32 (1.4% > 10%); 24% when re-scored in one bf16 pass; 0.8% of near-certain tokens vs 98% of tokens with p < 0.01. Whole-answer weights from 0.48 to 8.45.
17Scaling RL: compute, environments, reward hacking3 min
How much compute goes into this? In 2022, InstructGPT's reinforcement learning cost under two percent of GPT-3's pretraining. DeepSeek's R1-Zero, a few percent. DeepSeek-V3.2 reported a post-training budget above ten percent of pretraining. xAI described Grok 4's reinforcement learning as running at pretraining scale, and in February 2026 Cursor reported that post-training its coding model took more compute than pretraining the base model it started from.
In late 2025, a Meta team spent more than four hundred thousand GPU hours studying how RL improves with compute, and found a law. Accuracy follows a sigmoid in the logarithm of compute, with three parameters: a ceiling A, an efficiency exponent B, and the compute needed to get halfway. Fit it on small runs, and it predicts large ones. Here it is fitted to our own pocket-sized runs: GRPO taking one, four or sixteen gradient steps per batch, three seeds each. All three head for the same ceiling; what changes is how much compute it takes to get there. That was their key finding at scale too: most tricks change how fast you climb, not the ceiling.
The same math now trains agents. An episode is a long conversation with an environment: the model calls tools, reads their output, and acts again, and a test suite decides the reward at the end. Only the model's own tokens are actions, so the tool outputs are masked out of the gradient. Everything else is the log-derivative trick. What changed is scale: labs now build environments by the thousands, and in 2026 by the hundreds of thousands. Each one is a reward function.
And every reward function is a specification that an optimizer will read literally. If an object that claims to equal everything makes the tests pass, RL will find it. Anthropic reported in 2025 that models which learned such hacks in real coding environments generalized to broader misbehavior, including sabotage; a one-line framing in the prompt cut most of that. OpenAI found that reading the model's chain of thought catches most hacks, but that training against that monitor teaches the model to hide them.
Where does that leave things, in October 2026? Some labs now get part of what RL gave them more cheaply: DeepSeek's V4 replaced its final mixed reinforcement learning stage with on-policy distillation from specialist teachers, themselves trained with GRPO. Others run RL continuously from deployment. Rewards increasingly come from rubrics graded by models. And the deepest question, whether RL teaches models new skills or only sharpens old ones, is still argued in both directions.
What it establishes: RL's growing share of compute. ScaleRL's sigmoid law, fitted to our runs: reuse changes the speed, not the ceiling. Agentic RL: environments as reward functions, tool outputs masked. Reward hacking. The state of play in October 2026.; Real data on screen: Sigmoid fits for 1 / 4 / 16 updates per batch: A = 1.00 for all, C_mid = 1.1 × 10¹¹, 3.0 × 10¹⁰, 1.4 × 10¹⁰ FLOPs. Quoted: compute shares, environment counts, hack patterns and the Anthropic and OpenAI findings.
18The whole family, one equation at a time1 min
Let's put the whole family in one place. It all starts from one identity: the gradient of an expected reward is the expected reward times the score. Subtract a baseline, and the noise falls while the mean stays put. Learn a value function, and each token gets its own credit. Reweight old samples by an importance ratio and clip it, and you can reuse every batch safely: that's PPO. Add a leash to the reference, and the optimal policy has a closed form, which hands you DPO. Replace the critic with a group of samples, and you have GRPO. Fix how it averages over tokens, tame its ratios when sampler and learner disagree, and if you have a better model to learn from, give every token its own reward.
Every one of these is the log-derivative trick, plus one idea about noise or about trust. A model samples, a checker says one or zero, and those single bits, multiplied across millions of attempts, add up to a model that reasons far more reliably.
What it establishes: The whole family as one chain of estimators, each the log-derivative trick plus one idea about noise or trust.
Notes and sources
Sources
Derivations follow the primary sources; on-screen numbers from outside this repository are quoted from them.
- Williams, Simple statistical gradient-following algorithms for connectionist RL, Machine Learning 8 (1992).
- Schulman et al., High-Dimensional Continuous Control Using Generalized Advantage Estimation, arXiv 1506.02438.
- Kakade & Langford, Approximately Optimal Approximate RL, ICML 2002; Kakade, A Natural Policy Gradient, NIPS 2001.
- Schulman et al., Trust Region Policy Optimization, arXiv 1502.05477; Proximal Policy Optimization Algorithms, arXiv 1707.06347.
- Ouyang et al., Training language models to follow instructions with human feedback (InstructGPT), arXiv 2203.02155.
- Bradley & Terry, Biometrika 39 (1952); Gao, Schulman & Hilton, Scaling Laws for Reward Model Overoptimization, arXiv 2210.10760.
- Rafailov et al., Direct Preference Optimization, arXiv 2305.18290; Korbak, Perez & Buckley, arXiv 2205.11275.
- Schulman, Approximating KL Divergence (2020); Tang & Munos, arXiv 2506.09477; DeepSeek-V3.2, arXiv 2512.02556.
- Shao et al., DeepSeekMath (GRPO), arXiv 2402.03300; Ahmadian et al., Back to Basics (RLOO), arXiv 2402.14740.
- Davis & Recht, What is the objective of reasoning with reinforcement learning?, arXiv 2510.13651 (GRPO's arcsine objective).
- Yu et al., DAPO, arXiv 2503.14476; Liu et al., Understanding R1-Zero-Like Training (Dr. GRPO), arXiv 2503.20783.
- Cui et al., The Entropy Mechanism of RL for Reasoning Language Models, arXiv 2505.22617.
- Chen et al., Evaluating LLMs Trained on Code (pass@k), arXiv 2107.03374; Yue et al., arXiv 2504.13837; ProRL, arXiv 2505.24864.
- Schulman, LoRA Without Regret (2025); Mukherjee et al., arXiv 2505.11711; Shenfeld et al., RL's Razor, arXiv 2509.04259.
- Lu, On-Policy Distillation (2025); Qwen3 technical report, arXiv 2505.09388; DeepSeek-V4, arXiv 2606.19348.
- Yao et al., Your Efficient RL Framework Secretly Brings You Off-Policy RL Training (2025); Zheng et al., GSPO, arXiv 2507.18071; MiniMax-M1 (CISPO), arXiv 2506.13585; Qi et al., arXiv 2510.26788; IcePop, arXiv 2510.18855.
- OLMo 3, arXiv 2512.13961; Khatri et al., The Art of Scaling RL Compute for LLMs (ScaleRL), arXiv 2510.13786.
- DeepSeek-R1, arXiv 2501.12948 (Nature 645, 2025); GLM-5, arXiv 2602.15763; Qwen SWE-Universe, arXiv 2602.02361.
- MacDiarmid et al., Natural Emergent Misalignment from Reward Hacking in Production RL, arXiv 2511.18397; Baker et al., arXiv 2503.11926.
- Open-source code read for the defaults table (commits of Oct 2026): verl, TRL, OpenRLHF, open-instruct, nanochat, prime-rl, slime, AReaL, SkyRL, ROLL, ART.
What is computed and built
Charts are labeled real run, exact (computed, no sampling noise beyond what
is stated), schematic or illustrative. Everything real was computed on the
4-core CPU that rendered the video, by python -m videos.ml.rl.compute:
- The adder: a 3-layer, 335k-parameter transformer
(
explainer/lm/pocket.py) pretrained on 4-digit additions. A quarter of the training answers show their work (the sum written right-to-left, digit by digit, then the answer; always right); the rest answer at once and forget each carry with probability 0.25. Its answer tree, critic, KL-tilted optimum, reward–KL frontier, pass@k and DPO run all come from this model and the RL runs below. - RL runs: GRPO (the hero run), REINFORCE without a baseline, RLOO, Dr. GRPO, a DAPO-style variant (token-mean loss, clip-higher 0.2/0.28, dynamic sampling), PPO with a learned critic and GAE (λ = 0.95), and 1-vs-16 updates per batch with and without PPO's clip; 3 seeds each.
- Exact toys: a Gaussian policy on a two-hill reward (score-function arrows, REINFORCE paths with and without a baseline), a 2-D Gaussian policy (gradient-estimate clouds, variance as a function of the baseline), a 3-action softmax policy (vanilla vs natural gradient flows, iso-KL contours, the tilted family), Schulman's KL estimators by Monte Carlo (2 million samples, matching his published table).
- A real reasoning model: Qwen3-0.6B writes eight thinking traces (the first 768 tokens of each, sampled together in bfloat16 with a KV cache, at temperature 1, as an inference engine does); the identical tokens are re-scored in one full bfloat16 pass and in float32, as a trainer does.
Chapter notes
| # | Scene | What it establishes | Real data on screen |
|---|---|---|---|
| 1 | Hook |
A real model's answers drawn as a "river" of probability that bends toward the right answer as RL trains it, from one bit of reward per attempt. Reasoning models are made this way (DeepSeek-R1-Zero; OpenAI o1). The GRPO objective, to be derived symbol by symbol. Five-part roadmap. | The adder's exact answer tree for 5675 + 5563 at GRPO checkpoints 0–120: P(right) 56% → 99.8%, the "shows its work" stream thinning. Quoted: R1-Zero AIME 2024 15.6% → 77.9%. |
| 2 | Policy |
Part 1. RL's vocabulary for a language model (state, action, policy, deterministic transition, end-of-answer reward). An answer's probability is the product of its tokens' probabilities along a path; J(θ) is the green part of the reward column. The adder, its training data, and its two habits. | The tree with one path's product, 0.54 × 0.74 × 0.76 × 1 × 1 × 1 = 0.30. The adder (335,328 parameters): shows its work 28% of the time (then right 99.9%), answers directly otherwise (then right 60%), 71% overall. |
| 3 | LogDerivative |
Why backpropagation can't reach the reward. The five-line derivation of ∇J = E[R ∇log π], a reason beside each line; the score function; REINFORCE (Williams 1992). A 1-D Gaussian policy: score arrows a − μ cancel on average and reward-weighting breaks the symmetry; the policy climbs the tall hill. Sequences: the reward times a sum of token scores; RL as fine-tuning on your own graded samples; the softmax score 𝟏[b = a] − π(b). | Exact toy, 10 real samples: unweighted mean push −0.11, reward-weighted +0.15. One real softmax step on the next-token distribution. |
| 4 | Baselines |
Subtracting a baseline keeps the mean (the score has mean zero) and cuts the noise. The variance is a parabola in b; the optimal baseline E[R‖g‖²]/E[‖g‖²]. The advantage R − V(x), and why easy and hard prompts need different baselines. | Six REINFORCE runs with reward 2 + R wander; six with the batch-mean baseline climb. 300 gradient estimates (batches of 16) on a 2-D toy: variance 0.73 → 0.027 (27×). b* = 2.371 vs mean reward 2.364. |
| 5 | Credit |
One reward at the end blames every token equally. The value of a prefix, the Bellman equation for an LM, a token's advantage as the change in value, the TD error. GAE's λ. What GRPO/RLOO give up by dropping the critic. | A critic trained on the base model's answers: V = 58% before the answer; +0.39 at the token that starts showing work; −0.50 at the digit with the forgotten carry; λ barely matters for a critic this good. |
| 6 | TrustRegions |
Part 2. Sampling is the expensive part, so batches get reused. Importance sampling and the surrogate objective; token-level ratios; the performance-difference lemma; TRPO's lower bound. The 3-action simplex: KL balls shrink near the edges; vanilla vs natural gradient. | Exact: KL contours on the simplex and both gradient flows from the same start (the natural gradient moves every logit by its advantage). The bound is schematic. |
| 7 | PPO |
The clipped objective; case analysis for A > 0 and A < 0 (where the gradient is zero); the clip as a per-token probability window. RLHF with PPO: four networks and a per-token KL reward. | Windows for ε = 0.2: 0.9 → [0.72, 1], 0.01 → [0.008, 0.012]. Reusing batches on the adder (3 seeds): 1 update per batch reaches 75% after 5 steps; 16 updates reach 93%; unclipped, one seed falls to 91% at step 40; clipped ends at 99.1%. |
| 8 | Preferences |
Part 3. Comparisons instead of a checker (illustrative pair). Bradley–Terry from Gumbel noise: the difference of two Gumbels is logistic. The reward model's likelihood; a per-prompt offset is just a baseline. Goodhart's law. | Exact Gumbel and logistic densities; P(A ≻ B) = σ(2.2) = 0.90. Over-optimization curve schematic, after Gao, Schulman & Hilton. |
| 9 | KLOptimum |
The KL-regularized objective solved exactly: π* ∝ π_ref e^{r/β}. The tilt only reweights; it never invents. The tilted family is the natural-gradient path. The reward–KL frontier. Schulman's KL estimators; k3's gradient points at the reversed KL. | The adder's real answer distribution tilted as β falls: P(right) 0.59 → 1.00, right answers keeping their 0.54 : 0.46 proportions. Frontier over 48 problems: always right costs 0.39 nats; the GRPO run sits below it at about twice that KL. Monte Carlo estimator table (2M samples): std/KL 20.0, 1.42, 1.42 at KL = 0.005. |
| 10 | DPO |
Invert the optimum: every policy implies a reward. Z cancels in Bradley–Terry, leaving the DPO loss; its gradient weight. Offline DPO and likelihood displacement. | DPO on the adder, 4,096 fixed right-vs-wrong pairs (β = 0.1, lr 1e-5): 69% → 80% at step 100 → 0.7% at step 300, as the preferred answers' log-probability falls 10 nats and the rejected ones' 18. |
| 11 | GRPO |
Part 4. The group mean as a free baseline; mean-centering = (G − 1)/G × leave-one-out (RLOO), so unbiased. The std division turns the objective into 2 arcsin √p (Fisher–Rao arc length); exact finite-G weights. Zero-variance groups. The full GRPO objective, annotated. | A real group of 8 answers to 5675 + 5563: R̄ = 0.625, advantages +0.375 / −0.625. Exact weight curves κ_G(p) for G = 2, 4, 8, 64. P(all equal) = p^G + (1 − p)^G for G = 4, 8, 16. |
| 12 | RealRun |
GRPO trains the adder; RL sharpened rather than taught: direct answers stopped slipping. Six algorithms reach the same accuracy with different behavior. | GRPO, 3-seed means: 70% → 98% right within 40 steps; showing work 28% → 41%; direct answers 59% → 97% right. The five likeliest answers before and after. REINFORCE, RLOO, GRPO, Dr. GRPO, DAPO-style and PPO + GAE, 3 seeds each: show-work rates from 0% to about 50%. |
| 13 | Biases |
GRPO's per-answer 1/ | o_i |
| 14 | Entropy |
Entropy collapse. ∂H/∂z for a softmax; ΔH ≈ −Cov(log π, Δz); vanilla and natural policy gradients; why rewarding confident tokens drains entropy. Clip-higher. | The GRPO run's next-token entropy falls 0.18 → 0.044 (4.2×). Two exact 5-token examples (H 1.12 → 0.36 vs 1.12 → 1.40). Measured batch covariance: positive in 87% of batches; 9-step averages correlate −0.81 with the entropy change. Quoted: DAPO, AIME 30% → 50%. |
| 15 | Sharpening |
pass@k and its unbiased estimator. Sharpening vs discovery; the optimum cannot leave the reference's support; the 2025–26 debate. Bits per episode, sparse updates, RL's Razor. On-policy distillation. | Worked estimator: 1 − C(5,3)/C(8,3) = 0.821. pass@k from 128 samples × 300 problems: base 70.4% at k = 1, every problem solved by k = 16; after RL 99.2% at k = 1. Quoted: Qwen3-8B AIME 2024, RL 67.6% (17,920 GPU-hours) vs on-policy distillation 74.4% (1,800). |
| 16 | Mismatch |
Part 5. Inference engines and trainers compute different probabilities from the same weights, so "on-policy" RL is off-policy. Sequence-level weights as random walks; GSPO's geometric mean. TIS, masking (IcePop), GSPO, CISPO, numeric fixes. Asynchronous RL and staleness. | Qwen3-0.6B, 8 traces × 768 tokens: 25% of tokens > 1% off when re-scored in fp32 (1.4% > 10%); 24% when re-scored in one bf16 pass; 0.8% of near-certain tokens vs 98% of tokens with p < 0.01. Whole-answer weights from 0.48 to 8.45. |
| 17 | Scaling |
RL's growing share of compute. ScaleRL's sigmoid law, fitted to our runs: reuse changes the speed, not the ceiling. Agentic RL: environments as reward functions, tool outputs masked. Reward hacking. The state of play in October 2026. | Sigmoid fits for 1 / 4 / 16 updates per batch: A = 1.00 for all, C_mid = 1.1 × 10¹¹, 3.0 × 10¹⁰, 1.4 × 10¹⁰ FLOPs. Quoted: compute shares, environment counts, hack patterns and the Anthropic and OpenAI findings. |
| 18 | Outro |
The whole family as one chain of estimators, each the log-derivative trick plus one idea about noise or trust. |
Notes
All numbers are means over 3 seeds at the end of 120 RL steps (32 problems × 8 answers per step, reward 1 if the final answer is right), measured on 500 held-out problems at temperature 1, unless stated otherwise.
- The base adder shows its work 27.5% of the time (then right 99.9%), answers directly otherwise (then right 59.9%): 70.9% right overall.
- RL sharpened rather than taught. GRPO reaches 98.4%, mostly by removing slips: direct answers go from 59% to 97% right, while showing work only rises from 28% to 41% (the runs' own evaluations, from step 0). pass@k before RL: 70.4% (k = 1), 99.9% (k = 8), 100% (k ≥ 16); after RL, pass@1 is 99.2%. No problem the base model could solve was lost. On the running example, 5675 + 5563, the probability of a right answer goes from 56.2% to 99.8%.
- Same accuracy, different behavior. Every algorithm ends at 98–99% accuracy, but how often the model shows its work differs: REINFORCE averaged per answer (GRPO's 1/|o_i|) 0%, GRPO 41%, RLOO 44%, DAPO-style 48%, Dr. GRPO 50%, PPO with a critic 54%.
- The length bias, isolated. The same REINFORCE with a constant normalizer instead of 1/|o_i| ends at 50%: without a baseline, only right answers are pushed, and per token a 6-token direct answer pushes twice as hard as a 13-token worked one.
- The critic localizes credit. A value network trained on the base model's answers gives the running example 58%; its value jumps +0.39 at the token that starts showing work, and drops −0.50 at the one digit where a carry was forgotten. With a critic this accurate, GAE's λ barely matters.
- Reusing batches. One update per batch: 75% after 5 steps; 16 clipped updates per batch: 93% (ending at 99.1%); 16 unclipped: just as fast, but one seed falls back to 91% around step 40 and the mean ends lower (97.7%).
- The KL-regularized optimum (exact, 48 problems): being right every time costs 0.39 nats of KL from the base model; the GRPO run (no KL penalty) reaches 98% at about 0.8 nats, below the frontier, because it also reshuffles the probabilities among right answers.
- DPO (4,096 fixed right-vs-wrong pairs, β = 0.1, lr 1e-5): accuracy rises from 69% to 80% at step 100, then collapses to 0.7% by step 300 as the log probability of the preferred answers falls by 10 nats and the rejected ones by 18 (likelihood displacement; at lr 1e-4 it collapses within 50 steps).
- Entropy of the next-token distribution falls about 4× during the GRPO run; the batch covariance between token log-probability and advantage is positive in 87% of batches (90% and 94% in the other two seeds), and, averaged over 9 steps, correlates −0.81 with the per-step entropy change (−0.82, −0.79).
- ScaleRL's sigmoid, fitted to GRPO with 1, 4 and 16 updates per batch: the same ceiling (A = 1.00, 1.00, 1.00), with the compute to get halfway spanning 7.5× (1.1×10¹¹, 3.0×10¹⁰, 1.4×10¹⁰ FLOPs).
- The sampler and the learner disagree (Qwen3-0.6B, 6,144 sampled tokens): re-scored in float32, 25% of tokens have a log-probability more than 1% away from the sampler's, and 1.4% more than 10%. Re-scored in the same bfloat16 but in one pass instead of token by token: 24%, so it is the order of the arithmetic, not only the precision. Near-certain tokens (p > 0.9) almost never move (0.8% of them), while 92% of the tokens the sampler gave less than a 10% chance do. Multiplied over 768 tokens, the whole-answer importance weights range from 0.48 to 8.45, with no change to the model's weights.
- Baselines: in the 2-D toy, subtracting the mean reward cuts the variance of a 16-sample gradient estimate 27×; the optimal baseline (2.371) is within 0.3% of the mean reward (2.364). Schulman's KL estimators reproduce his table: for KL = 0.005, std/KL is 20.0 (k1), 1.42 (k2), 1.42 (k3); for KL = 0.5, k2's bias is 0.25.
The visual language
| Concept | Color |
|---|---|
| policy π_θ | blue |
| reference π_ref | grey |
| old / sampling policy π_old, the inference engine | teal |
| reward, right answers | green |
| wrong answers, negative advantage | red |
| advantage A | yellow |
| score ∇log π, gradient arrows | orange |
| baselines b, values V, the critic | light purple |
| importance ratio ρ | pink |
| KL divergence, β | gold |
| entropy | light pink |
| answer length | brown |
| "show your work" tokens | light blue |
Build the film
python -m videos.ml.rl.compute # the film's numbers, into .cache/rl
python tools/build.py rl # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py rl Hook # one chapter, silent, with a contact sheet
Scenes: videos/ml/rl. Setup: see the course page. Source of these notes: the README and the scenes' narration.