Key takeaways
- Treat the language model as a policy in reinforcement learning: the state is the prompt plus the tokens written so far, the action is the next token, and the reward arrives only once the answer is finished.
- The goal is the expected reward J(θ), the probability-weighted average score, and we make it bigger with gradient ascent.
- The log-derivative trick gives us REINFORCE: using answers the model samples itself, push up the log probability of high-scoring answers and push down the low-scoring ones.
- Subtracting a baseline that depends only on the state leaves the expected gradient unchanged but shrinks the variance. Use the value function as the baseline and you get the advantage: how much better than expected.
- Off-policy learning reuses old samples through importance ratios rt, but those ratios can run wild. Taming them is PPO's job, next episode.
Just one score. How does a model learn from that?
Back in episode 0 we saw that a model with only pretraining just continues text. Ask it "How do I make scrambled eggs?" and it may carry on with "How do I make pancakes?". It has learned the language, but not what it means to be a helpful, obedient assistant that matches human preferences. Shaping a pretrained model into a proper assistant is called post-training.
The most direct approach is to have people write example answers and train the model to copy them. That's supervised fine-tuning (SFT). But demonstrations are expensive, and for many tasks writing a perfect answer is hard while judging an answer is easy:
- a math problem: check the final answer;
- code: run the tests and see whether it works;
- human preference: show a person two answers side by side, and they can easily pick the better one.
So here is a second idea: let the model write on its own, grade the result, and nudge it toward higher scores. That's reinforcement learning (RL).
The catch: the score is a single number handed out at the very end, while the model has billions of parameters. How can one number tell every parameter which way to move? That's exactly the question this episode's star, the policy gradient, answers.
Intuition: The post-training episodes (18 to 20) follow one clear storyline, where each step patches the one before it. Start from the plainest policy gradient, REINFORCE → add a baseline to cut the noise → make it off-policy so samples can be reused → add clipping to get PPO → add human preferences to get RLHF → replace the critic with group normalization to get GRPO → finally, DPO skips reinforcement learning and optimizes preferences directly. This episode covers the first three steps, the foundation for everything after.
The language model as a "policy"
Let's borrow some vocabulary from reinforcement learning. An agent sees the current state, takes an action, and the environment hands back a new state and, eventually, a reward.
It's like training a puppy. It does something (writes an answer), and you either give it a treat or you don't. You can't explain how to lift its paw. All you can do is reward what it gets right, and let it gradually figure things out. The policy gradient is that simple idea written down as math.
Here is how the roles map onto a language model:
- Policy πθ: the language model itself; θ stands for all of its parameters.
- State st: all the text so far, the prompt plus whatever tokens have been written, st=(s0,a0,…,at−1).
- Action at∈V: the next token at step t. The model draws it from the whole vocabulary V according to the policy's probabilities, at∼πθ(⋅∣st). That's the autoregressive generation from episode 0.
- Starting state s0∼p0: just the prompt, drawn at random from a big pool of prompts whose distribution we call p0.
- Trajectory τ: everything from the prompt to the finished answer. You'll also hear it called a rollout or an episode.
- Reward R(τ): the single score a grader gives the whole trajectory once it's done.
Each chosen token is appended to the end and becomes part of the new state. Then the next one is drawn, and so on, step by step, until the answer is finished.
Watch out: None of the steps in between get a score. There is only one R(τ), at the very end.
How likely is a whole trajectory? It's the probability of drawing this prompt, times the probability of picking each token along the way:
P(τ∣θ)=p0(s0)t∏πθ(at∣st)
We can simply multiply because once a token is appended, the next state is fixed; there's no other randomness. Hold on to this product, because the derivation needs it.
The goal: expected reward
A tiny example makes this concrete. Suppose that for "How do I make scrambled eggs?" the model can only ever write three answers:
| Answer |
Text |
Reward |
Prob. |
| A |
Whisk the eggs, then stir gently over low heat. |
8 |
20% |
| B |
Scrambled eggs are a classic breakfast. |
5 |
30% |
| C |
How do I make pancakes? |
2 |
50% |
A freshly pretrained model loves to continue text, so C is the most likely. On average, how many points does it score? Weight each score by its probability:
J=0.2×8+0.3×5+0.5×2=4.1
This probability-weighted average is the expected reward, written J. It's the objective we want to maximize: for every possible trajectory, take its probability times its reward, and add them all up.
J(θ)=Eτ∼πθ[R(τ)]=τ∑P(τ∣θ)R(τ)
The rewards are fixed; the grader doesn't change. The only thing we can change is the probabilities, that is, which answers the model prefers to write. To make J bigger, the obvious move is to shift probability away from C and onto A.
The way to do it is gradient ascent: follow the gradient and push the parameters uphill, one small step at a time.
θk+1=θk+α∇θJ(θk)
In episode 4, gradient descent walked downhill to shrink the loss. Here we climb uphill to grow the reward, which is why there's a plus sign.
The obstacle: where does the gradient come from?
With three answers the sum has three terms and the gradient is easy. In real life there are three problems:
- Far too many answers to list. With a vocabulary of about 100,000 tokens and an answer 100 tokens long, there are (105)100=10500 possibilities. All we can do is sample: have the model actually write a few answers and see what each one scores.
- The reward is a black box. It might be a program that checks the answer, a set of tests, or even a person. It won't tell you how the score would change if you edited a word, so no gradient flows back from it.
- Sampling is a discrete jump. A token is either picked or it isn't, and the gradient can't flow through that choice.
So we need a formula of this shape: the gradient equals the average of some quantity over samples, and that quantity uses only the gradient of the model's own log probabilities.
REINFORCE: the log-derivative trick
The derivation needs one small trick. The derivative of logx is x1. Swap x for a probability P that depends on the parameters; by the chain rule, ∇θlogP=P1∇θP. Multiply both sides by P and you get the log-derivative trick:
∇θP=P∇θlogP
The magic is in the extra P on the right. Multiply by a probability and add up over every case, and that's exactly how you take an average.
Now the derivation:
∇θJ(θ)=∇θτ∑P(τ∣θ)R(τ)=τ∑∇θP(τ∣θ)R(τ)=τ∑P(τ∣θ)∇θlogP(τ∣θ)R(τ)=Eτ∼πθ[∇θlogP(τ∣θ)R(τ)]
Line by line:
- Line 2: the reward doesn't depend on the parameters, so the gradient slides inside the sum and acts only on the probability.
- Line 3: apply the log-derivative trick.
- Line 4: a sum over all trajectories weighted by P is just an expectation! And an expectation can be estimated by sampling.
All that's left is the trajectory's log probability. The probability is a long product; take the log and the product becomes a sum:
∇θlogP(τ∣θ)==0∇θlogp0(s0)+t∑∇θlogπθ(at∣st)
The prompt's probability doesn't depend on the model's parameters, so its gradient is zero. What remains is the sum, over every token, of the gradient of its log probability. That's the policy gradient. Its most basic form is called REINFORCE, or the vanilla policy gradient:
∇θJ(θ)=Eτ∼πθ[t∑∇θlogπθ(at∣st)R(τ)]
Every piece is computable. The expectation comes from sampling (we let the model write), the gradient of the log probability comes from backprop exactly as in pretraining, and the reward comes from the grader.
In practice we draw prompts from p0, let the policy πθ write a batch of N trajectories τ(i), and use their average in place of the expectation. That gives the gradient estimate g^:
g^=N1i=1∑Nt=1∑T∇θlogπθ(at(i)∣st(i))R(τ(i))
Intuition: push up the high-scoring answers
What is this formula really saying? Put it next to supervised fine-tuning. SFT takes answers written by people and pushes up the log probability of every token in them. The policy gradient does almost the same thing, with two differences:
- the answers (the data τ) are sampled by the model itself;
- each answer's gradient is multiplied by its reward R(τ).
So:
- If R(τ) is positive, we move in the direction that increases logπθ(at∣st) for every token in that answer. If it's negative, we move the other way.
- The bigger the reward's magnitude, the bigger the step.
Running the numbers on the toy example
To actually compute something, pretend the model's parameters are just three scores, one each for A, B and C, which softmax turns into probabilities:
θ=(zA,zB,zC)softmaxπ=(0.2,0.3,0.5)
In episode 2 we found that the gradient of softmax plus cross-entropy is p−y, so the gradient of the log probability with respect to the scores is the reverse, y−p. If we draw A:
∇zlogπA=y−π=(1,0,0)−(0.2,0.3,0.5)=(0.8,−0.3,−0.5)
A scores 8, so this estimate is 8×(0.8,−0.3,−0.5)=(6.4,−2.4,−4): A's score goes up, B's and C's go down. Likewise, drawing B gives 5×(−0.2,0.7,−0.5)=(−1,3.5,−2.5) and drawing C gives 2×(−0.2,−0.3,0.5)=(−0.4,−0.6,1).
Average these, weighted by how likely each answer is to be drawn (0.2, 0.3, 0.5), and you get the exact gradient: (0.78, 0.27, −1.05). Take one step that way and A rises from 20% to 43%, C falls from 50% to 17% (B ends at 39%), and the expected reward climbs from 4.1 to 5.78. A few more steps and the model writes almost nothing but A.
In code: pg_loss
In code we usually build a number called pg_loss, chosen so that the gradient backprop computes from it is exactly our estimate g^:
logp = policy.log_prob(tokens) # log π of every token, shape (N, T)
pg_loss = -(logp.sum(dim=1) * rewards).mean()
pg_loss.backward() # minus sign: descending this = ascending along ĝ
It corresponds to L(θ)=N1∑i=1N∑t=1Tlogπθ(at(i)∣st(i))R(τ(i)), whose gradient is g^. The code adds a minus sign because optimizers are built to go downhill: descending −L is the same as climbing along g^.
Watch out: pg_loss isn't a loss in the usual sense. Its value tells you nothing about how good the policy is; it's only a device for making .backward() produce the right gradient. And because the data is sampled from the current policy, the target shifts at every step. There is no fixed objective.
The problem: too much noise
The formula is correct, but in practice it has a big flaw: high variance. Notice that in our example all three rewards are positive, as on an easy prompt where every answer earns something.
Suppose a step samples just one answer, and it's C, the most likely one. Its reward of 2 is positive, so the gradient pushes C's probability up! C only gets pushed down when we happen to draw A or B, and hardest when we draw A. In other words, even the bad answers in a batch get reinforced.
Look only at the component that pushes C (the third one). The three cases give −4, −2.5 and +1. Weighted by probability the average is −1.05. The direction is right, but individual estimates are all over the place.
That's high variance: right on average, but each single estimate is noisy and often points the wrong way. Training wobbles as a result. Run three independent trainings that each sample one answer per step: some climb smoothly, while others get dragged down by C and stay stuck for a long time.
Subtract a baseline
The fix is simple. Instead of weighting by the raw reward, first subtract a baseline b(st) and weight by R(τ)−b(st). This is the baselined policy gradient:
∇θJ(θ)=Eτ∼πθ[t=0∑T∇θlogπθ(at∣st)(R(τ)−b(st))]
Intuition: Think of test scores. The same 80 points is a great result in a class that averages 50, but a disappointing one in a class that averages 90. Subtracting a baseline means rewarding only the part that beats expectations.
In our example, use the average reward 4.1 as the baseline. A becomes +3.9, B +0.9, and C −2.1. Now even when we draw C, the reward minus the baseline is negative, so the gradient pushes C down.
Back to the component that pushes C. Without a baseline the three cases were spread far apart (−4, −2.5, +1), and drawing C pointed the wrong way. With the baseline they become −1.95, −0.45 and −1.05. The average is still −1.05, not changed one bit, but now they're bunched together and all point the right way. Rerun the same three trainings with a baseline and the curves are much smoother; all three climb steadily.
Three things to remember about baselines:
- As long as b(st) depends only on the state st and not on the action at, it introduces no bias into the gradient estimate.
- We want b(st) to be correlated with R(τ): the closer the baseline is to the actual reward, the smaller R(τ)−b(st), and the less noise in the gradient.
- It doesn't change the objective we're optimizing, only how we estimate its gradient.
Why doesn't the baseline bias anything?
Why should subtracting something leave the average unchanged? Let's prove the extra term, call it B, has an expected value of exactly zero.
B=Eτ∼πθ[t=0∑T∇θlogπθ(at∣st)b(st)]
First, check it on the example. Drop the b, and what's left is the gradient of the log probability weighted by probability: 0.2×(0.8,−0.3,−0.5)+0.3×(−0.2,0.7,−0.5)+0.5×(−0.2,−0.3,0.5). One component at a time: 0.16−0.06−0.1=0, and the other two components are zero as well.
Now the general case. Let Xt=∇θlogπθ(at∣st)b(st). First swap the expectation and the sum over time steps: instead of "sum over t within each trajectory, then average over trajectories", we "average over trajectories at each t, then add up those averages". Since Xt only involves (st,at), we can average over the action given the state first, and then over the state:
B=t=0∑TEst[Eat∣stXt]
The key is the inner expectation:
Eat∣stXt=b(st)Eat∣st∇θlogπθ(at∣st)=b(st)at∑πθ(at∣st)∇θlogπθ(at∣st)=b(st)at∑∇θπθ(at∣st)=b(st)∇θat∑πθ(at∣st)=b(st)∇θ1=0
Step by step:
- The baseline depends only on the state, not the action, so it can be pulled outside the expectation over actions. This is the crucial step.
- Write the expectation as a probability-weighted sum.
- Use the log-derivative trick again: probability times the gradient of log probability is the gradient of the probability.
- Pull the gradient outside the sum.
- The probabilities of all actions always add up to 1, and the gradient of a constant is zero.
Plug back in: B=∑tEst[0]=0. Subtracting a baseline leaves the expected gradient unchanged; it only lowers the variance.
Watch out: The condition matters. The baseline must not depend on the action itself. If b peeks at the action, say by setting b equal to the reward, step 1 breaks and the gradient becomes biased.
Value function and advantage
The most natural baseline is the expected reward from where we stand right now. That brings in a few core RL ideas:
- Value function Vπ(s): start from state s, follow the current policy, and how many points do we score on average?
- Q function Qπ(s,a): in state s, first commit to action a, then follow the policy. How many points on average?
- V is just Q averaged over actions, weighted by their probabilities: Vπ(s)=∑aπ(a∣s)Qπ(s,a).
- Advantage function: the difference Aπ(s,a)=Qπ(s,a)−Vπ(s), how much better action a is than what we'd expect from state s.
In our example, V for the prompt state is 4.1. Picking A has a Q of 8, so its advantage is +3.9; picking C has an advantage of −2.1. These are exactly the reward-minus-baseline numbers from before.
In real training we don't know the exact Q and V:
- the reward R(τ) is a single sample of Qπ(st,at);
- V is estimated by a separately trained value network, written Vψ(st);
- so R(τ)−Vψ(st) is an estimate of the advantage Aπ(st,at). Because it uses the reward of just one sample, it's called a Monte Carlo estimate.
This is the baseline PPO uses:
∇θJ(θ)=Eτ∼πθ[t=0∑T∇θlogπθ(at∣st)(R(τ)−Vψ(st))]
Since Vψ depends only on the state, it's unbiased too. Now each token gets its own signal: compared with how things looked when it was written, did the final score turn out higher or lower? Tokens written while the outcome was still up in the air get a lot of credit, and a token that turns a bad-looking answer (small Vψ(st)) into a good one (high R(τ)) gets the most. Once the answer is already in the bag, the tokens that follow get very little.
Ways to get a baseline
All of these try to estimate the expected return from the current state, Vπ(st):
- Learn a value network, as above. That's what PPO does.
- RLOO (REINFORCE leave-one-out): sample G answers to the same prompt; each answer's baseline is the average reward of the other answers.
- Batch estimate (REINFORCE++): just use the average reward of the whole batch.
An RLOO example: four answers score 8, 2, 5 and 5. The first answer's baseline is the average of the other three, (2+5+5)/3=4, so its advantage is +4. The second one's baseline is (8+5+5)/3=6, so its advantage is −4.
Why leave yourself out? Because the baseline can't depend on your own action, which is exactly the condition from the proof. GRPO, coming up in episode 20, is very similar to RLOO; the differences are that GRPO includes the answer itself in the average and also divides by the standard deviation.
Off-policy: reusing old samples
One last problem: efficiency. With the formula as it stands, every gradient step needs a fresh batch of answers generated by the latest model. This is called on-policy learning. Generation is slow, popping out one token at a time (episode 12). Worse, after one small step the model has barely changed, so throwing the old answers away is a real waste.
Could we train the current model πθ on answers written by an older version πθold? That's off-policy learning, and the tool it needs is importance sampling.
Importance sampling
Say we want the average of f under a distribution p, but we only have samples from a different distribution q. Multiply and divide by q inside the sum (that changes nothing), and a sum weighted by q is an expectation under q:
Ex∼pf(x)=x∑q(x)q(x)p(x)f(x)=Ex∼q[q(x)p(x)f(x)]
So give each sample a weight qp, and samples from q yield the average under p.
Intuition: If a sample is more common under p than under q, it should count for more. If it's less common, it counts for less.
Back to the example. The old model's probabilities are 0.2, 0.3 and 0.5; after one step the new model's are 0.43, 0.39 and 0.17. The new-to-old ratios are 2.17, 1.3 and 0.35. Take the old model's samples, multiply by these ratios, and average: 0.2×2.17×8+0.3×1.3×5+0.5×0.35×2≈5.78, exactly the new model's expected reward.
Products of ratios explode
Over a whole trajectory, the true off-policy estimate is
J(θ)=Eτ∼πθold[P(τ∣θold)P(τ∣θ)R(τ)]=Eτ∼πθold[t=1∏Tπθold(at∣st)πθ(at∣st)R(τ)]
The weight is a product of hundreds of per-step ratios. At 1.1 per step, a hundred steps gives 1.1100≈13781; at 0.9 per step, you're left with 0.9100≈0.00003. The weights either explode or vanish, and the estimate has terrible variance.
The surrogate objective
So in practice we use a surrogate objective: swap the product for a sum over tokens. Each token's own ratio is written rt:
Jsurrogate(θ)=Eτ∼πθold[t=1∑Trtπθold(at∣st)πθ(at∣st)R(τ)]
Note that this is not the same objective as J(θ). But at the point where the new and old models are identical, every rt equals 1 and its gradient matches REINFORCE exactly. So as long as the new model stays close to the old one, it's a good approximation.
To take the gradient: only the numerator of the ratio depends on θ. Apply the log-derivative trick, and the numerator's gradient becomes probability times the gradient of log probability, so rt pops right back out:
∇θrt=πθold(at∣st)∇θπθ(at∣st)=rt∇θlogπθ(at∣st)
That gives the off-policy policy gradient, estimated from a batch of N old trajectories:
g^off-policy=N1i=1∑Nt=1∑Tπθold(at(i)∣st(i))πθ(at(i)∣st(i))∇θlogπθ(at(i)∣st(i))R(τ(i))
Compared with REINFORCE, every term carries one extra factor, the ratio rt. Now one batch of old samples can be reused for several steps.
Watch out: If the new model drifts too far, rt gets huge and the updates spin out of control. How do we rein it in, reusing old samples without letting the updates run wild? That's PPO's clipping, next episode.
Recap
The policy gradient is the foundation of post-training. Treat the language model as a policy and aim to maximize the expected reward J(θ). The log-derivative trick turns "take the gradient of a black-box reward" into "sample your own answers and push up their log probabilities, weighted by reward": that's REINFORCE. It points the right way on average but is very noisy, so we subtract a baseline that depends only on the state, which keeps the expectation and cuts the variance; with the value function as baseline, the weight becomes an estimate of the advantage A=Q−V. Finally, off-policy learning reuses old samples through importance ratios rt to save on generation, at the risk of those ratios running wild. Remember the chain: REINFORCE (high variance) → subtract a baseline (lower variance, equivalent to using the advantage) → off-policy (reuse old samples). PPO and GRPO keep patching on top of it.