Policy gradients and REINFORCE
A pretrained language model already has a policy, and a good one. It writes fluent text, follows most instructions, and gets some fraction of math problems right. What we want from RL is to make the responses that earn high reward a little more likely and the ones that earn low reward a little less likely, without throwing away everything the model already knows. Q-learning, from §15.2, would start over, learning a value for every (prefix, token) pair from scratch and acting greedily on it. That is the wrong tool.
The right tool treats the policy's parameters as the thing to optimize and climbs the expected reward by gradient ascent, exactly as supervised learning descends a loss. Two obstacles seem to stand in the way. The reward is often not differentiable at all (a unit test passes or fails), and the expectation is taken over samples that the policy itself generates, so changing changes the distribution we are averaging over. One identity, the log-derivative trick from §0.4, removes both obstacles. This section derives the policy gradient from it, proves the policy gradient theorem, builds REINFORCE, runs it on a bandit and on a small environment where only a stochastic policy is optimal, and then confronts its great weakness, variance.
The objective
Let be a policy with parameters (for us, a softmax over logits produced by a network). Running it in the environment for at most steps produces a random trajectory , where as in §15.1 is the reward for taking in . Its probability factors into the start distribution , the policy's choices, and the environment's transitions ,
Write for the discounted return of the whole trajectory. The objective is the expected return,
where the sum runs over all possible trajectories (an integral, if states are continuous). In plain words, is the average total reward the policy earns, and we want to make it larger.
We cannot differentiate with respect to , and we do not need to, because does not depend on at all. A given trajectory has a given return. What depends on is how likely each trajectory is.
The log-derivative trick
Differentiate and move the gradient inside the sum (fine for finite sums, and for integrals under mild regularity conditions),
This is not yet an expectation, so we cannot estimate it by sampling. The trick is the chain rule for the logarithm, , rearranged as . Substituting,
In plain words, the gradient of the expected return is the average, over trajectories the policy actually produces, of "how good was this trajectory" times "which way in parameter space makes this trajectory more likely". Every sampled trajectory pulls the parameters toward making itself more likely, with a strength set by its return, so high-return trajectories win the tug of war (and a negative return pushes away instead).
Why not differentiate through the sampling instead, as the reparameterization trick of §0.4 does for Gaussians? Because that trick needs the sample to be a differentiable function of and the reward to be differentiable in the sample. A discrete action (a token) is neither, and a unit test is not differentiable at all. The score-function estimator needs neither, which is why it is the workhorse of RL on language models, at the price of the variance we will fight for the rest of the chapter.
The environment drops out
Now take the log of the trajectory probability. The product becomes a sum,
and only the middle sum depends on . The start distribution and the dynamics vanish when we take the gradient,
This is the first form of the policy gradient. Read it slowly, because it is remarkable. To estimate the gradient we need only samples of trajectories, their returns, and the gradient of the log-probability of the actions the policy took. We never need , we never need its derivative, and the reward can come from anywhere, a human, a unit test, a reward model, or a game engine. This is why policy gradient methods are called model-free. The vector is called the score of the action.
The score of a softmax policy
For a softmax policy with logits over actions, . The gradient of the log-sum-exp is the softmax itself (§0.2), so
where is the one-hot vector of action and . In plain words, to make action more likely, raise its logit and lower every logit in proportion to its current probability. This is the same as the gradient of cross-entropy in that section, with the sign flipped, which is no coincidence. is the negative cross-entropy loss with target . For a network, the chain rule takes it from the logits to every weight, and autograd does that for us.
The score of a softmax policy
Implement softmax_score(logits, actions) where logits has shape (N, K) and actions is an int array of shape (N,). Return the array of shape (N, K) whose row is . It must be numerically stable for large logits.
A worked example on a bandit
Take a two-armed bandit (a one-step MDP) with deterministic rewards and a softmax policy with logits , so . The objective is . Its exact gradient follows from the softmax Jacobian of §4.3, , giving .
The policy gradient estimator sees one pull at a time. If it pulls arm 1 (probability 0.5), it reports . If it pulls arm 2, it reports . The average of the two reports, weighted by their probabilities, is , exactly the true gradient. Every single report is wrong, though, either twice too large or zero. The estimator is unbiased and noisy, and that combination is the story of the rest of this chapter.
In general, for a -armed bandit the expectation of the estimator is , which matches the exact gradient term by term. The next exercise asks for this exact gradient, which is useful as a test oracle for any sampled implementation.
The exact policy gradient of a softmax bandit
For a bandit with expected rewards r of shape (K,) and a softmax policy with logits z of shape (K,), implement bandit_policy_gradient(z, r) returning where . Also implement sampled_policy_gradient(z, r, n, seed), which draws n actions with np.random.default_rng(seed).choice(K, size=n, p=pi) and returns the average of the single-sample estimates .
The policy gradient theorem
The trajectory form multiplies every action's score by the return of the entire trajectory, including rewards that arrived before the action was taken. That cannot be the most efficient use of the data. An action at step 10 cannot have caused the reward at step 3. The policy gradient theorem (Sutton, McAllester, Singh, and Mansour 2000) gives a sharper form, in which each action is weighted by its own action value.
Theorem. For a discounted MDP with start distribution and objective ,
where and is the discounted state visitation, how often (with discounting) the policy finds itself in .
What is surprising is what is missing. Changing changes which states the agent visits, so you might expect a term involving the derivative of , which would be hopeless to estimate. There is no such term. The gradient only needs the policy's own score, weighted by how good each action is.
∂ Proof of the policy gradient theorem
Fix a state . The value is , and both factors depend on . By the product rule,
The reward and the transitions do not depend on , so differentiating gives . Write for the first part (a vector with the shape of ), and for the probability of being in state after exactly steps of from . Then
The same identity holds for , so substitute it in, and again for the states after that,
(The remainder after unrollings is times a bounded quantity, so it vanishes as when , or when every trajectory ends in finite time.) Average over the start state . The inner sum becomes , and we get the first form of the theorem.
For the second form, use inside , so that , which is written out.
You should not take a theorem like this on faith, and in a gridworld we do not have to. For a tabular softmax policy (one logit per state and action, ), the gradient with respect to the logits of state is , by the same softmax algebra as the bandit. Everything on the right can be computed exactly with linear solves, including , and the left side can be checked by finite differences of the exact .
The theorem's gradient agrees with brute-force finite differences to about ten decimal places, with no derivative of the state distribution anywhere. (The visitation sums to , because the absorbing terminal states keep collecting visitation after the episode ends. They contribute nothing to the gradient, since all their actions have the same value.)
The policy gradient theorem, exactly, for a tabular policy
For a finite MDP with P of shape (S, A, S), R of shape (S, A), start distribution p0 of shape (S,), discount , and a tabular softmax policy with logits theta of shape (S, A), implement exact_policy_gradient(P, R, p0, gamma, theta) that returns , shape (S, A), using the policy gradient theorem (no finite differences). Then implement discounted_visitation(P, p0, gamma, pi) returning , shape (S,).
REINFORCE
We rarely know , but we can sample it. Given , the reward-to-go , the discounted return from step onward, has conditional expectation exactly , by the definition of . Substituting it into the theorem gives an unbiased estimator that needs nothing but sampled episodes. Williams (1992) called the resulting algorithm REINFORCE.
- Run the current policy to collect episodes.
- For every step of every episode, compute the reward-to-go with one backward pass (Exercise 15.1a).
- Estimate the gradient and take a step of gradient ascent,
- Throw the episodes away and repeat. They were sampled from the old policy, and the estimator is only unbiased for the policy that generated the data. This is what on-policy means, and it is the waste that PPO (§15.6) will try to reduce.
In plain words, after each batch of episodes, raise the log-probability of every action in proportion to how much reward followed it.
(That may replace the full of the trajectory form, discarding the rewards before step , also has a direct one-line proof, which we give in §15.4 along with the baseline, because the same lemma proves both.)
The surrogate loss
In code, nobody writes down by hand. We build a scalar whose gradient is the estimator and let autograd differentiate it. Treating the returns as constants (detached from the graph), define
Its gradient is , so minimizing it with any optimizer performs REINFORCE. Look at its shape. It is a cross-entropy loss on the policy's own samples, with each sample's log-likelihood weighted by its return. REINFORCE is weighted maximum likelihood on your own behavior. With a reward that is 1 for success and 0 for failure and no discounting, the loss is exactly the supervised fine-tuning loss on the successful samples, divided by , and the failures contribute nothing. That is a useful bridge to rejection-sampling fine-tuning (§18.2), which does exactly that.
Two warnings about the surrogate. Its value means nothing. It is not the expected return, it can go up while the policy improves, and plotting it as a training curve misleads everyone who reads the plot. Track the average return instead. And the normalization matters more than it looks. Dividing by the number of episodes gives the estimator above. Dividing by the total number of steps in the batch only rescales it by a batch-dependent number, which ties the step size to how long the episodes happened to be. Dividing each episode's sum by its own length before averaging, as the original GRPO loss does, is different in kind. It weights every step of a long episode less than every step of a short one, which changes the objective, a subtle bias that GRPO's variants argue about at length (§18.4).
The REINFORCE loss and its gradient
Implement reinforce_loss(logits, actions, weights) for a batch of decisions, where logits has shape (N, K), actions is an int array of shape (N,), and weights of shape (N,) holds each decision's weight (for example ), treated as constants. Return (loss, dlogits) with
and dlogits , of shape (N, K). Compute the log-softmax stably.
REINFORCE on a bandit
Start with the simplest possible case, a three-armed Bernoulli bandit with success probabilities , , and , a softmax policy over three logits, and small batches of 4 pulls per update, over 30 independent runs. For a bandit every episode is one step, so the reward-to-go is just the reward.
With the small learning rate every one of the 30 runs ends with most of its probability on the best arm. With a learning rate of 4, two runs end certain of the wrong arm, and with 16, a third of them do. A few lucky pulls of a mediocre arm drove its probability so high that the best arm was almost never tried again. A softmax policy that has collapsed onto one action stops exploring, and since the gradient of a nearly deterministic softmax is nearly zero ( vanishes when is one-hot), it cannot climb back out. Keeping the policy from collapsing too early is the job of the entropy bonus in §15.6 and the KL penalty in §15.7.
REINFORCE where only a random policy is optimal
Here is a small environment that shows something value-based methods cannot do, from Sutton and Barto's Example 13.1, the short corridor with switched actions. There are three non-terminal cells in a row and a goal at the right end. Each step costs . Actions are "left" and "right", and they do what they say in the first and third cells, but in the middle cell they are reversed. The catch is that the agent cannot tell the cells apart. Every state looks the same, so the policy is a single probability of choosing "right", used everywhere.
A deterministic policy is a disaster here. Always going right gets stuck bouncing between the first two cells, and always going left never leaves the first cell. Let us compute the value of a general exactly. Write for the values of the three cells (all with ). In cell 1, "right" (probability ) moves to cell 2 and "left" stays put. In cell 2, the reversed actions mean "right" moves back to cell 1 and "left" moves on to cell 3. In cell 3, "right" reaches the goal. So
The first equation gives . Substitute it and the third equation into the second, , which simplifies to . Then
Setting the derivative to zero gives , so the best policy goes right with probability and earns . For comparison, an -greedy agent with , which goes right with probability or , earns or . An agent that learns values and acts (nearly) greedily on them cannot represent the optimum. A policy gradient method can, because it searches over directly.
Starting from the -greedy-like policy , REINFORCE walks down toward the optimum , and the expected return climbs from toward . It needed hundreds of episodes for a problem with one parameter, though, and the step size had to be tiny (). Every return is negative, often large (from near the goal to or worse after a long bounce), so every update pushes down on the probability of every action taken, and the useful signal is only the small difference between how hard good and bad actions get pushed. That observation is the subject of the next part of this section.
Why REINFORCE has high variance
An unbiased gradient is only useful if its noise is small enough that a reasonable number of samples averages it out. REINFORCE's noise is large, for four reasons that are worth separating.
- It scales with the size of the returns, not their differences. Add a constant to every reward of a bandit. The expected gradient does not change, since . But each single-sample estimate gains a term , whose variance grows like . The corridor's returns are all large and negative, so most of each update is this useless term.
- It sums over the horizon. The trajectory estimator multiplies a sum of random scores by a sum of random rewards, so its variance tends to grow with the episode length. A 1,000-token response is a 1,000-step episode.
- One number takes the credit for everything. With a single reward at the end, every action in the episode gets the same weight, whether it helped, hurt, or did nothing.
- Rare, large returns dominate. A trajectory that is unlikely under the policy but has a huge return contributes a huge estimate on the rare occasions it is sampled.
The first effect is the easiest to see and to fix. The widget below uses a two-armed bandit with rewards and a single parameter , the logit of arm 1, so and the true gradient is . Shift both rewards by the same offset and watch the spread of the single-sample estimates, and the learning curves, change while the true gradient stays put.
Subtracting a number from the rewards before multiplying by the score is called using a baseline, and the widget's toggle is the simplest one, the average reward. §15.4 proves that a baseline that does not depend on the action never introduces bias, finds the baseline that minimizes the variance, and arrives at the advantage function, actor-critic methods, and the form of the policy gradient used in every modern algorithm.
Do not conclude from the corridor that REINFORCE is only a teaching device. With a baseline it is a serious method for language models, whose pretrained policy starts so close to good behavior that small, noisy steps are enough. Ahmadian et al. (2024) fine-tuned models of about 7 billion parameters (Pythia-6.9B and Llama-7B) from human preferences on the TL;DR summarization and Anthropic helpful-and-harmless datasets, and found that REINFORCE-style updates matched or beat PPO there, as well as DPO and rejection-sampling fine-tuning. Their best variant used a leave-one-out baseline over several responses to the same prompt, which §15.4 derives and §18.4 turns into RLOO and GRPO.
In PyTorch
The production version of REINFORCE is three lines inside the training loop. Compute the log-probabilities of the taken actions, multiply by the detached returns, and call backward on the negative mean. Here we check that autograd's gradient of that surrogate loss on the gridworld equals the REINFORCE estimator computed by hand with the score formula.
Read more
- Williams (1992). Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. The REINFORCE paper, including the observation that a baseline leaves the gradient unbiased.
- Sutton, McAllester, Singh & Mansour (2000). Policy Gradient Methods for Reinforcement Learning with Function Approximation. The policy gradient theorem.
- OpenAI Spinning Up. Part 3: Intro to Policy Optimization. A clean derivation of the simplest policy gradient, with the reward-to-go argument and a minimal implementation.
- Sutton & Barto (2018). Reinforcement Learning: An Introduction, 2nd edition. Chapter 13 covers policy gradient methods, including the short-corridor example and the proof we followed.
- Ahmadian et al. (2024). Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs. REINFORCE and its leave-one-out variant against PPO and DPO on 7-billion-parameter models.
- Nota & Thomas (2020). Is the Policy Gradient a Gradient? What dropping the factor really does.
- Levine. CS 285, Lecture 5, Policy Gradients. The lecture slides derive the same estimator with the same trajectory notation.