The Policy Gradient Theorem & REINFORCE
The score-function trick and the simplest policy gradient algorithm.
Move a policy's parameters and everything downstream moves too: the actions, the states the agent visits, the rewards it sees. Differentiating the expected return looks as if it needs a model of all of that. It does not. This lesson derives the policy gradient theorem, turns it into REINFORCE, solves Sutton and Barto's switched corridor exactly, and proves that a baseline costs nothing.
What you’ll learn
- Write softmax and Gaussian policies and compute their score functions .
- Derive the likelihood-ratio gradient of the expected return over trajectories, and use causality to reduce it to the reward-to-go estimator.
- Prove the policy gradient theorem for episodic tasks by unrolling the gradient of the value function.
- Compute the switched corridor's expected return and its optimum .
- Implement REINFORCE in PyTorch, and prove that subtracting an action-independent baseline leaves the gradient unbiased.
Policies with parameters
A parameterized policy must be differentiable in and, to keep exploring, should give every action positive probability. Two families cover most of practice.
For discrete actions, a softmax policy turns action preferences into probabilities. The preferences can be linear, for state–action features (Sutton and Barto's choice), or the logits of a neural network with one output per action.
For continuous actions, a Gaussian policy samples , with the mean and the log standard deviation produced by a network (or the log standard deviation kept as a free parameter). We write for the mean because is the start distribution. Since :
The objective is the expected return from the start distribution, , and the plan is gradient ascent, . From here on means and . One identity does most of the work in this lesson: the score has mean zero under the policy.
Write the expectation as a sum over actions and use :
So for any quantity that does not depend on the action, . This one line is behind causality, baselines and the policy gradient theorem itself. (For a Gaussian the sum becomes an integral; the mean score visibly averages to zero.)
A tabular softmax policy in a single state has one preference per action, , currently all equal. What is the score ?
- , because all preferences are equal
Show the answer
B.
Tabular preferences are linear with one-hot features, so the score is . Raising raises ; raising the others lowers it. The components sum to zero because adding the same constant to every preference changes nothing.
Differentiating through the dice
A trajectory of an episodic task has probability , and . The parameters change which trajectories are likely, not the return of any given trajectory. The likelihood-ratio (log-derivative) trick moves the gradient onto the probabilities.
Differentiate under the sum (finite trajectories, or bounded returns and dominated convergence) and use :
In the start and transition terms do not involve , so they vanish from the gradient. The unknown dynamics are sampled, never differentiated:
Causality. Split . A reward received before step is part of the history , and given the score at step has mean zero. So past rewards contribute nothing on average:
What remains is the reward-to-go form: each action is credited only with the rewards that came after it, and step is discounted by from the start of the episode:
Sample one episode, evaluate the bracket, and you have an unbiased estimate of . Stepping along it is REINFORCE (Williams, 1992), whose name spells out its update: REward Increment = Nonnegative Factor × Offset Reinforcement × Characteristic Eligibility. The nonnegative factor is the step size, the offset reinforcement is the return minus a baseline (zero so far), and the characteristic eligibility is the score.
The policy gradient theorem
The trajectory form already gives an algorithm. The policy gradient theorem (Sutton, McAllester, Singh & Mansour, 2000) states the same gradient in terms of states and actions, which is what critics need. Take the episodic case of Sutton & Barto (§13.2): undiscounted, a fixed start state , and every policy reaches a terminal state with probability 1, so that .
Differentiate with the product rule. Rewards and dynamics do not depend on , so :
The second term is the expected gradient one step later. Substitute the same identity for , then again for the state after that:
After unrollings the remainder is . In a finite MDP whose episodes end with probability 1, the probability of still running decays geometrically and is bounded (and zero at the terminal state), so the remainder vanishes:
Finally turns the sum over actions into an expectation under the policy, and normalizing gives the second form.
Read the theorem as a recipe: sample states the way the policy visits them, sample an action from the policy, and weight its score by how good that action is, . REINFORCE uses the return as an unbiased sample of ; actor–critic methods use a learned critic instead (Actor–Critic Methods).
Think first The visit counts depend on : changing the policy changes where the agent goes. Why does no derivative of appear in the theorem?
It has been absorbed into . Unrolling the recursion follows every downstream effect of a parameter change, and the value of acting differently now already includes the value of reaching different states later. A second view uses the performance difference lemma: there, the effect of shifting the state distribution is multiplied by , the policy's average advantage over itself, which is zero. The Policy Gradient Theorem in Depth proves the discounted and average-reward versions that way.
Solving the switched corridor
Back to the corridor of the Exploration lesson (Sutton & Barto, Example 13.1): cells 1, 2, 3 and a goal, reward per step, . Left in cell 1 bumps into the wall, and in cell 2 the actions are switched. The cells look identical, so one parameter, , acts everywhere. The expected return can be found by solving three Bellman equations; here is a shorter route that also explains the shape of the answer.
Leaving cell 1. Each step there moves right with probability , so the number of steps until the agent enters cell 2 is geometric with mean . Writing for the expected number of steps to the goal from cell :
Excursions from cell 2. Each visit to cell 2 starts an excursion that ends either at the goal or back in cell 2. With probability the agent goes right into cell 1 and needs more steps on average to come back, a cost of . With probability it goes left into cell 3 and then either finishes (right) or returns (left), two steps either way:
Excursions are i.i.d. (the chain restarts at each return to cell 2), and the number of excursions up to the first that finishes is geometric with mean . It is a stopping time for the sequence of excursions, so Wald's identity multiplies the means:
So , the curve the widget draws. The derivative of has numerator , which vanishes at
The formula explains the optimum. The only way out is left then right from cell 2, probability per excursion, which alone would favor ; but each trip back into cell 1 costs steps against the wall, which favors a larger . The balance lands at . The top of the landscape is also flat: , only a third of a step worse than the optimum, while ε-greedy's gives .
At , how many excursions from the middle cell does an episode need on average?
Show the answer
4
Each excursion finishes with probability , so . Each costs steps on average, so , and adding the steps needed to leave cell 1 first gives , the twelve steps of the fair coin in the Exploration lesson.
REINFORCE in code, and a free baseline
In an automatic-differentiation framework you never write the score by hand. Build a scalar whose gradient is minus the REINFORCE estimate, and let the optimizer descend it.
import torch
from torch.distributions import Categorical
def reinforce_loss(logits, actions, rewards, gamma=0.99, baseline=None):
"""One episode. logits: (T, A); actions: (T,) ints; rewards: (T,), rewards[t] = R_{t+1}."""
T = rewards.shape[0]
returns = torch.empty(T)
g = torch.tensor(0.0)
for t in reversed(range(T)): # reward-to-go: G_t = R_{t+1} + gamma * G_{t+1}
g = rewards[t] + gamma * g
returns[t] = g
if baseline is not None: # e.g. a value network's V(S_t), shape (T,)
returns = returns - baseline.detach()
log_probs = Categorical(logits=logits).log_prob(actions)
discounts = gamma ** torch.arange(T, dtype=torch.float32) # the gamma^t most code omits
return -(discounts * returns * log_probs).sum()The returns and the baseline are constants: gradients flow only through the log-probabilities. Deleting discounts gives the update most libraries implement; with , as in the corridor, the two coincide.
import gymnasium as gym
import torch.nn as nn
env = gym.make("CartPole-v1")
policy = nn.Sequential(nn.Linear(4, 64), nn.Tanh(), nn.Linear(64, 2))
opt = torch.optim.Adam(policy.parameters(), lr=1e-2)
for episode in range(500):
obs, info = env.reset(seed=episode)
logits, actions, rewards, done = [], [], [], False
while not done:
out = policy(torch.as_tensor(obs, dtype=torch.float32))
a = Categorical(logits=out).sample()
obs, r, terminated, truncated, info = env.step(a.item())
logits.append(out); actions.append(a); rewards.append(float(r))
done = terminated or truncated
loss = reinforce_loss(torch.stack(logits), torch.stack(actions), torch.tensor(rewards))
opt.zero_grad(); loss.backward(); opt.step()One gradient step per episode, on-policy: every episode is generated by the current parameters and used once. Treating a time-limit truncation like a true ending slightly misjudges the returns near the limit; Generalized Advantage Estimation shows the fix.
Let be any function of the state , and possibly of the history before it, but not of or anything after. Condition on the history and use the zero-mean score:
So for every such . The mean is untouched, and can be chosen purely to reduce variance. The usual choice is a learned , which turns into an estimate of the advantage .
The condition matters. A baseline that depends on the action, , generally adds a bias unless a correction term is added, the subject of Baselines & Variance Reduction.
Which of these, subtracted from with no correction term, would bias the REINFORCE gradient?
- A constant, such as the average return of the previous 100 episodes
- A learned state value
- A critic's estimate of the action's value
- The sum of the rewards received before step
Show the answer
C. A critic's estimate of the action's value
depends on the action, so is not zero. With a perfect critic it equals the whole policy-gradient term at that state, so subtracting it would cancel the signal entirely. Anything fixed before is drawn, whether a constant, a state value or past rewards, is free.
Key takeaways
- A linear softmax policy's score is the chosen action's features minus their policy average; a Gaussian's mean score is . Every score has mean zero under the policy.
- The likelihood-ratio trick gives : the dynamics drop out of the gradient, and causality removes past rewards.
- The policy gradient theorem, , needs no derivative of the state distribution; REINFORCE samples it with in place of .
- In the switched corridor, peaks at with , while every deterministic policy runs forever.
- Any baseline that does not depend on the action leaves the gradient unbiased; a state value close to turns returns into advantage estimates.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A Gaussian policy has mean and standard deviation , and it samples . With a positive return and no baseline, what does the REINFORCE update do to and to ?
- It raises and lowers
- It raises and raises
- It lowers and raises
- It changes only, because has no score
Show the answer
B. It raises and raises
The scores are for the mean and for , both positive. The action was two standard deviations above the mean and it paid off, so the update moves the mean toward it and widens the distribution, making such actions more likely. An action within one standard deviation would have narrowed it.
Why may REINFORCE weight the score at step by the reward-to-go instead of the whole-episode return ?
- Because rewards before step are always zero
- Because is a lower-variance but biased replacement for
- Because past rewards are fixed given the history up to , and the score at step has mean zero given that history, so their contribution averages to zero
- Because discounting makes earlier rewards negligible
Show the answer
C. Because past rewards are fixed given the history up to , and the score at step has mean zero given that history, so their contribution averages to zero
Dropping the past rewards removes terms whose mean is exactly zero, so the estimator stays unbiased, and its variance usually falls, since those rewards were pure noise as far as is concerned.
In the switched corridor, why is the optimal probability of right above ?
- Leaving needs left then right from the middle cell, which alone would favor , but every return to the first cell costs steps at the wall, which favors a larger
- The goal is to the right, so right is always the better action
- Episodes terminate only when
- REINFORCE is biased toward right
Show the answer
A. Leaving needs left then right from the middle cell, which alone would favor , but every return to the first cell costs steps at the wall, which favors a larger
An excursion from the middle cell finishes with probability , maximized at , but trips back to the first cell cost steps. Minimizing balances the two at .
In the episodic policy gradient theorem, . What is ?
- The probability of starting in
- The stationary distribution of the policy's Markov chain
- The fraction of the episode's reward collected in
- The expected number of visits to during an episode
Show the answer
D. The expected number of visits to during an episode
. Normalized, it is the on-policy distribution from which REINFORCE's sampled states arrive; the normalizing constant, the expected episode length, is absorbed into the step size in practice.
Go deeper
- The Policy Gradient Theorem in Depth · Episodic, discounted and average-reward forms, and the discounting mistake most code makes.
- Baselines & Variance Reduction · Optimal baselines, control variates and the mirage of action-dependent baselines.
- Global Convergence of Policy Gradients · Gradient domination, softmax convergence rates and the role of entropy.
Further reading
- R. J. Williams, "Simple statistical gradient-following algorithms for connectionist reinforcement learning," Machine Learning 8, 229–256 (1992).
- R. S. Sutton, D. McAllester, S. Singh & Y. Mansour, "Policy gradient methods for reinforcement learning with function approximation," NIPS 12 (2000).
- R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 13 (MIT Press, 2nd ed., 2018).