Policy gradients & REINFORCE
How a reward becomes a weight update
So far we have a reward modelreward model (RM)A model trained from human preference data to output a scalar score for how good a response is. Stands in for a human judge so RL can query reward millions of times.See in glossary → that scores a response, and we want the language model to produce responses it scores highly. The obvious idea (just backpropagate the reward into the model, the way we train on next-token loss) doesn’t work. Generating a response means sampling tokens one at a time, and you can’t take a gradient through a random choice of which token got picked. (And the reward might be a black box we can’t differentiate at all.) So we need a way to improve the model from nothing but the single number the reward hands back at the end. That tool is the policy gradient, and this chapter builds it from scratch.
The LLM as a policy
In reinforcement learning, a policypolicyIn RL, the thing that chooses actions — here, the language model itself, viewed as a distribution over next tokens given the context. RL post-training optimizes the policy.See in glossary → is a rule for choosing actions. We write it : given a state , it gives a probability distribution over actions , controlled by parameters . The whole vocabulary of RL maps cleanly onto a language model:
- The state is the prompt-so-far: the input plus whatever tokens have already been generated.
- An action is choosing the next token.
- The policy is the model itself. At each step it emits logitslogitsThe raw, pre-softmax scores the model produces — one per vocabulary token, per position. Bigger logit = the model finds that token more likely; the actual value can be any real number, positive or negative. Applying softmax across the vocabulary turns logits into a probability distribution that sums to 1. Sampling then picks one token from that distribution.See in glossary →, the softmaxsoftmaxFunction that turns any vector into a probability distribution (positive, sums to 1) by exponentiating and normalizing.See in glossary → turns them into a distribution over the vocabulary, and we sample.
Because the model generates one token at a time and feeds each choice back in, the probability of a complete response given prompt factorizes:
This is the same autoregressive factorization you already know from next-token predictionnext-token predictionThe pre-training objective for GPT-style models: given the tokens so far, predict a probability distribution over the next token. Also called causal or autoregressive language modeling.See in glossary →. Nothing about the network has changed. What changes is how we score the output and what gradient we push through it.
A single act of generating a full response is a rolloutrolloutA complete generated sample from the policy — for an LLM, one full response to a prompt. RL collects rollouts, scores them, and updates the policy.See in glossary →. The sequence of states and actions it produces (prompt, token, new state, token, …) is a trajectorytrajectoryThe sequence of states and actions in a rollout. For text generation, the tokens generated one after another, each conditioned on those before it.See in glossary →. At the end, a scalar rewardrewardA single-number feedback signal in reinforcement learning that says how good an outcome was. The agent tries to collect as much reward as possible over time.See in glossary → (here, the reward-model score) judges the whole thing. Summed over the trajectory, that’s the returnreturnThe total (often discounted) reward accumulated over a trajectory. Policy-gradient methods push up the probability of actions that led to high return.See in glossary →; for a single terminal reward at the end of a response, return and reward coincide, and we’ll just write .
To make all four words concrete, fix one prompt and sample the model four times. Say the prompt is = “Explain in one sentence why you see lightning before you hear thunder.” Each sample below is one rollout; sampling is random, so the same prompt yields different responses, some good, some not:
| Rollout | Sampled response | Reward | Why the reward model scores it that way |
|---|---|---|---|
| 1 | ”Light travels much faster than sound, so the flash reaches your eyes almost instantly while the rumble takes several seconds to reach your ears.” | Correct, complete, follows the one-sentence instruction. | |
| 2 | ”Because light is faster than sound.” | Correct but unhelpfully terse; states the fact without explaining the experience. | |
| 3 | ”Because the lightning happens first, and the thunder only happens a few seconds later.” | Fluent and confident, but a misconception: they happen together; only their signals arrive apart. | |
| 4 | ”You see the flash first because the light arrives first, the light arrives first, and the light arrives…” | Starts correctly, then degenerates into repetition. |
Each row’s trajectory is the full state-action alternation behind that response. For rollout 2 it looks like: state = the prompt ; action = sample the token “Because”; new state = + “Because”; action = sample ” light”; and so on until the model emits its end-of-response token, seven actions in total. Rollout 1’s trajectory is the same kind of object, just ~30 actions long. The reward is one number for the whole trajectory, handed out only at the end: nothing scored “Because” on its own, and no token was labeled right or wrong. That’s the whole learning problem in miniature: from these four (response, score) pairs alone, the update we build next should make responses like rollout 1 more likely and responses like rollouts 3 and 4 less likely.
The objective: maximize expected reward
We want a policy whose rollouts tend to score high. Formally, maximize the expected reward over the responses the policy itself generates:
Read it carefully: the expectation is taken over drawn from the current policy. That is the crux of the difficulty. The thing we are differentiating with respect to, (the model parameters), also controls the distribution we are averaging over. Change and you don’t just change : you change which ‘s show up at all. Worse, may be a non-differentiable black box: a reward model, a unit-test pass/fail, a human thumbs-up. We can’t simply backpropagate through .
The log-derivative trick
The way out is a small, beautiful identity. Write the expectation as a sum (over all possible responses) and differentiate:
Two symbols are new here. is the gradient with respect to the parameters: the vector of partial derivatives, one per weight, pointing in the direction in weight-space that most increases whatever follows it. And is a sum over every possible response the model could produce, an astronomically large set, which is exactly what makes this expression intractable until we fix it. (, , and are the objective, policy probability, and reward from above.)
The reward doesn’t depend on , so it slides outside the gradient. We’re left with , which is still awkward: it’s not an expectation we can sample. The trick is to multiply and divide by :
The one new object is : the gradient of the log-probability the policy assigns to response . Read it as a direction in weight-space: the way to nudge every parameter so that this exact response becomes more likely.
That last step uses the identity . Substituting back, the out front turns the sum back into an expectation:
Every symbol here is now one you’ve met, so read the finished formula term by term. averages over responses sampled from the current policy; for each sampled response, is the direction that makes that response more likely, and is a scalar weight on it. Put together, it says: sample responses, and step toward making each one more likely in proportion to the reward it earned. Push up what scored well, push down what scored badly.
This is the policy gradientpolicy gradientA family of RL methods that directly adjust the policy’s parameters in the direction that increases expected reward, using the score-function (REINFORCE) estimator.See in glossary →, also called the score-function estimatorscore-function estimatorThe identity ∇E[R] = E[R · ∇log π] that lets us estimate a reward gradient by sampling, even though the reward itself isn’t differentiable in the model’s parameters.See in glossary → (the quantity is the “score” in statistics). It is the entire foundation of RL for LLMs.
REINFORCE: push up what worked
Turning that estimator into a learning rule gives the REINFORCEREINFORCEThe basic Monte-Carlo policy-gradient estimator (Williams, 1992): scale the gradient of each action’s log-probability by the reward (or advantage) it earned. Everything else builds on it.See in glossary → algorithm (Williams, 1992). One step is:
- Sample a batch of rollouts from the current policy.
- Score each one with the reward function to get .
- Update by ascending the estimated gradient:
The intuition is exactly what you’d hope. is the direction in parameter space that makes response more likely. Multiply it by the reward and sum: rollouts with high reward get pushed up in probability, and (if rewards can be negative) low-reward rollouts get pushed down. The policy reshapes itself to put more mass on the responses that scored well. It is supervised learning where the model writes its own training examples and the reward decides how hard to learn from each one: weighted maximum likelihoodlikelihoodThe probability a model assigns to observed data. Supervised fine-tuning maximizes the likelihood of human-written target responses given their prompts.See in glossary →, with the weights handed down by the reward.
Because the factorization is autoregressive, , a sum of per-token log-prob gradients, every one of which you already compute during an ordinary forward/backward pass.
On-policy vs. off-policy
One subtlety is hiding in the expectation . The data must come from the policy we are currently updating. An algorithm that learns only from its own fresh rollouts is on-policyon-policyRL where the data used to update the policy was generated by the current policy. PPO and GRPO are (approximately) on-policy; they resample as the policy changes.See in glossary →; REINFORCE is the canonical example. The moment you take a gradient step, moves, your old samples are stale, and strictly speaking you must collect new rollouts before the next step.
The alternative is off-policyoff-policyRL that learns from data generated by a different (older or separate) policy. DPO and rejection-sampling methods are off-policy / offline.See in glossary → learning: reusing data generated by a different (older, or entirely separate) policy. That’s more sample-efficient (you don’t throw rollouts away after a single step) but it requires a correction, because you’re now averaging over the wrong distribution. The fix, importance sampling, is exactly the bridge that leads from REINFORCE to PPOPPOProximal Policy Optimization (Schulman, 2017) — nudges the policy toward higher reward in small, clipped steps with a KL leash to a reference model. The RLHF workhorse: stable, simple, widely used.See in glossary → in chapter 17.
Try it
Below is a tiny world: a banditbanditThe simplest reinforcement-learning setting: a single decision with a fixed set of actions, each giving a reward, and no states or follow-on consequences. Named after the "one-armed bandit," old slang for a slot machine.See in glossary → with a handful of actions, each hiding its own average reward. The policy is a single softmax over the actions. Watch pure REINFORCE in action (sample, reward, update) and see the action distribution migrate toward whatever earns reward.
Play with it and one thing jumps out: the updates are noisy. With a small number of samples, a couple of lucky high-reward draws can yank the distribution around (sometimes in the wrong direction) before later samples correct it. That noise is not a quirk of the toy. It is the central weakness of REINFORCE.
The catch: variance
The policy-gradient estimator is unbiased (on average it points the right way), but it has punishing variance. Two reasons. First, we estimate an expectation from only a handful of samples. Second, and more insidiously, the raw reward scales every update. If all your rewards happen to be large and positive (say every response scores between and ) then REINFORCE pushes up the log-prob of every rollout, hard, and only weakly distinguishes the from the . The gradient is dominated by the level of the reward rather than by which responses were better than average. With billions of parameters and long sequences, that variance makes training slow and brittle.
The good news: there is a clean fix that costs nothing in bias. We can subtract a reference value from the reward (a baseline) so that what multiplies the log-prob becomes “how much better than expected was this rollout?” rather than the raw score. That single idea is the subject of the next chapter — and the value functions and advantage estimates built on top of it fill the two after that.