The policy gradient theorem gives the gradient of a policy's expected return with respect to its parameters as an expectation you can sample: . It needs no derivative of the environment's dynamics, only the log-probability of the actions the agent actually took and an estimate of how good they turned out to be. Every policy gradient method, from REINFORCE to actor-critic and PPO, is a way of estimating this one expectation.
This page derives the theorem from scratch, starting with the log-derivative trick, then checks every step numerically on a two-state problem small enough to solve exactly. You will see the exact gradient, the sampled estimate, how noisy that estimate is, and two mistakes that quietly turn it into something that is not a gradient at all. All numbers come from seeded numpy runs we did for this article.
A two-state example to keep in mind#
Take the smallest problem where a policy gradient is interesting. There are two states, A and B, and two actions in each. In A, the action stay pays +1 and keeps you in A; the action go pays nothing and moves you to B. In B, stay pays +2 and keeps you in B; go pays nothing and sends you back to A. The agent starts in A, and future rewards are discounted by . (If the vocabulary of states, actions and discounting is new, start with the Markov decision process page.)
The policy has two parameters, one logit per state: and , where is the logistic function. At the agent flips a fair coin everywhere, and its expected return from A is . The best policy goes to B and stays there forever, for a return of . A second, worse policy stays in A forever for a return of 10, and it matters later: it is a local optimum.
Which way should move? Leaving A gives up a sure +1 now for a chance at +2 per step later, and whether that is worth it depends on how the agent behaves in B. The two parameters interact. The policy gradient answers the question precisely: at , it is . Increase the logit of staying in B a lot, and for now slightly decrease the probability of leaving A, because leaving A only pays once the agent reliably stays in B. We will derive where those numbers come from.
What is the policy gradient theorem?#
Write a trajectory as and the discounted return as . The objective is the expected return of the policy from the start-state distribution:
Here is the start-state distribution, the policy, and the environment's transition probabilities, which we do not know and cannot differentiate. The theorem, in its state-action form, says
where is the discounted visitation of state , and is the expected discounted return after taking in and following afterwards (see the Bellman equation page for how is defined and computed). In words: push up the probability of each action in proportion to how good it is, weighted by how often the policy visits the state where it is taken. The striking part is what is missing. Changing changes which states the agent visits, yet no derivative of appears.
Deriving it step by step#
Step 1: the log-derivative trick#
Differentiate and move the gradient inside the sum over trajectories:
This is not yet useful: is not an expectation under anything we can sample. The trick is the identity , which is just the chain rule for the logarithm read backwards:
Now the gradient is an expectation under the policy's own trajectory distribution, so averaging over sampled trajectories estimates it without bias. Statisticians call the score function, and this construction is the score-function or likelihood-ratio gradient estimator; Glynn studied it for general stochastic systems [4], and Williams introduced it to reinforcement learning as REINFORCE [3]. Mohamed and colleagues survey it alongside the alternatives [6].
Step 2: the dynamics drop out#
Take the log of the trajectory probability. The product becomes a sum:
Only the policy terms depend on , so the start distribution and every transition term vanish under the gradient:
This is the whole reason policy gradients work in model-free reinforcement learning. The environment can be a simulator, a physical robot or a human rater; as long as you can run the policy and compute for the actions it took, you can estimate the gradient. The same property is what lets reinforcement learning for language models treat a reward model or a unit test as a black box.
Step 3: rewards cannot be caused by later actions#
The estimator above multiplies every action's score by the whole return, including rewards that arrived before the action was taken. Those terms average to zero. For , the reward is fixed once we condition on the history up to time , and the expected score of a distribution is zero:
This one-line fact does a lot of work in the rest of this cluster: it is also why subtracting a baseline leaves the gradient unbiased. Dropping the past rewards leaves the reward-to-go form
where is the discounted return from time onward and the factor is what remains of after factoring out the rewards from on. Note that stays. We come back to it below because dropping it is the most common error in implementations.
Step 4: from trajectories to states#
Conditioning on , the expected reward-to-go is exactly , so can be replaced by inside the expectation. Grouping the sum over time by which state is visited turns into , and that gives the state-action form stated above. Sutton and colleagues reached the same result by a different route [2]: differentiate the Bellman equation with the product rule, giving , then unroll the recursion. Each unrolling step moves one transition further along the trajectory and multiplies by , and summing the series yields . The two proofs agree because they compute the same quantity; Sutton and Barto's textbook walks through the episodic case in this style [1].
Two remarks. First, is not a probability distribution; it sums to . In our example the visitation from A at is and , which sum to 10. Many texts normalize it and absorb the constant into the step size. Second, the theorem holds for any differentiable stochastic policy, tabular, linear or neural. Silver and colleagues later proved an analogous theorem for deterministic policies in continuous action spaces, which underlies DDPG-style methods [7].
Checking the theorem numerically#
A derivation is easier to trust when you can watch it hold. For the two-state problem everything is computable exactly. solves a 2-by-2 linear system, , and solves another. With a logistic policy, , so the theorem reduces to one product per state.
Setup (simulation). At we computed (a) the gradient from the policy gradient theorem, (b) a central finite difference of the exact , and (c) sampled score-function estimates from 200,000 simulated episodes, each truncated at 150 steps (, so truncation is negligible).
| Method | ||
|---|---|---|
| Policy gradient theorem (exact) | −0.7563 | 2.7563 |
| Finite difference of exact | −0.7563 | 2.7563 |
| Sampled, total return times all scores | −0.752 ± 0.073 | 2.736 ± 0.073 |
| Sampled, reward-to-go with | −0.761 ± 0.015 | 2.744 ± 0.015 |
| Sampled, reward-to-go without | −10.44 ± 0.07 | 45.55 ± 0.08 |
The exact theorem and the finite difference agree to every printed digit, and both unbiased estimators land within their standard errors (shown after ±) of the truth. The reward-to-go estimator, which simply deletes terms whose mean is zero, has a per-episode standard deviation of 6.8 against 32.5 for the full-return version: about 23 times less variance from a free change.
How many episodes does an estimate need? We repeated the reward-to-go estimate 2,000 times at each batch size and measured the error relative to the true gradient's length. With a single episode the median relative error is 2.56, so a typical one-episode estimate is mostly noise, and only 63% of single-episode estimates even point uphill (positive inner product with the true gradient). With 10 episodes the median error is 0.89 and 94% point uphill; with 100 it is 0.28, and with 1,000 it is 0.083. The error falls as , exactly as an average of independent samples should.
Explore the gradient field#
The figure below draws the exact return over both logits as a heat map, with the direction of the policy gradient at a grid of points. Click or tap anywhere (or use the sliders) to move the policy. The thick arrow is the exact gradient from the theorem; the thin red arrows are 20 independent sampled estimates, each averaging episodes, drawn at the same scale. The dashed path follows the exact gradient uphill. The estimator menu lets you switch between the three estimators in the table.
Three things are worth trying. Set and redraw a few times: single-episode estimates scatter in every direction, which is the variance problem the REINFORCE algorithm lives with. Switch to the dropped- estimator: the arrows grow roughly fifteenfold, because each visit is now weighted as if it happened at time zero. And click in the lower left quadrant: the exact gradient leads to the "stay in A" policy, whose return is 10, not 20. The policy gradient theorem gives you a true gradient, and gradient ascent on a non-concave objective finds local optima. In this problem, starting from or ends at return 10, while reaches 18.0 and climbing.
Policy gradient vs Q-learning#
Value-based methods such as Q-learning learn and act greedily on it; the policy is implicit. Policy gradient methods parameterize the policy directly and climb . The theorem explains when the second approach is the better tool:
- Continuous or huge action spaces. A greedy policy needs , which is an optimization problem of its own when actions are continuous torques or entire token sequences. A policy gradient only needs to sample and evaluate .
- Stochastic optimal policies. In partially observed problems and games, the best policy can be random. Greedy value-based policies are deterministic; a softmax or Gaussian policy can represent the right mixture.
- Smooth improvement. A small change in changes action probabilities a little. A small change in can flip an argmax and change behaviour abruptly, which is one reason value-based methods with function approximation can diverge.
- The cost: variance and sample efficiency. The estimator above is on-policy and noisy. Value-based methods reuse old data freely; vanilla policy gradients throw each batch away after one step. Most of the methods built on the theorem exist to reduce that cost: baselines and advantages, learned critics in actor-critic methods and GAE, and the trust regions of TRPO and PPO that let one batch support several update steps.
The two families are less separate than they look. A learned critic that estimates or is exactly a value function, and Schulman, Chen and Abbeel showed that entropy-regularized (soft) Q-learning and policy gradients are closely related, in some settings equivalent [8]. For the broader map of where these methods sit, see what is reinforcement learning.
Common mistakes when implementing the policy gradient#
Dropping the factor#
Most implementations multiply by the discounted reward-to-go but omit the outer . That update weights a state visited at step 50 as if it were visited at the start. Nota and Thomas showed that the resulting direction is, in general, not the gradient of any function [5]. In our example it happens to point almost the right way (cosine similarity 0.999 with the true gradient), but its components are 14 and 17 times too large, so even the relative weighting of the two states is off. In larger problems with states that are only reached late, the direction can be badly wrong. The usual justification is that is a variance-reduction device and the real objective is undiscounted; that is a reasonable engineering choice, but it should be a choice, not an accident.
Using data from a different policy#
The expectation is over the current policy's trajectories. Reusing old samples without correction estimates the gradient of a different objective. Importance weights fix the action mismatch, and the trust-region view in the TRPO and PPO article explains when the state-distribution mismatch can be ignored. Off-policy data from logs is the territory of offline reinforcement learning.
Getting the sign or the stop-gradient wrong#
In autodiff frameworks the theorem is implemented as a surrogate loss , where must be treated as a constant. If the return or advantage estimate depends on (through a shared critic, for example) and gradients flow through it, you are no longer computing the policy gradient. The surrogate's value is also meaningless as a progress metric: it is not , and it can go up while goes down.
Reading a single noisy estimate as signal#
With one episode per update, our estimate pointed downhill 37% of the time. Learning still works, because steps in the wrong direction cancel over many updates if the step size is small, but it is slow, and it makes run-to-run comparisons noisy. If you compare policy gradient variants, use several seeds and report intervals; the evaluating RL agents page covers how.
A minimal estimator in numpy#
The function below computes the reward-to-go policy gradient for a tabular softmax policy from a batch of episodes. It is the estimator used for Figure 2, written for any number of states and actions.
import numpy as np
def policy_gradient(theta, episodes, gamma):
"""theta: (S, A) logits of a tabular softmax policy.
episodes: list of (states, actions, rewards) integer/float arrays.
Returns the reward-to-go estimate of grad J, shape (S, A)."""
pi = np.exp(theta - theta.max(1, keepdims=True))
pi /= pi.sum(1, keepdims=True)
grad = np.zeros_like(theta)
for s, a, r in episodes:
T = len(r)
G = np.zeros(T) # discounted reward-to-go
running = 0.0
for t in range(T - 1, -1, -1):
running = r[t] + gamma * running
G[t] = running
w = gamma ** np.arange(T) * G # keep the gamma^t factor
score = -pi[s] # d log pi(a|s) / d theta[s, :]
score[np.arange(T), a] += 1.0
np.add.at(grad, s, w[:, None] * score)
return grad / len(episodes)
For the score of a softmax policy, , which is what the two lines building score compute. Replace the softmax with a neural network and the score with an autodiff call, and this is the core of every policy gradient implementation.
What to take into practice#
- Use reward-to-go, not total return. It is unbiased and, in our example, cut variance 23-fold for free.
- Decide deliberately about . Keep it if you want the gradient of the discounted objective. Drop it only if you mean to optimize something closer to the undiscounted return and accept that the update is not an exact gradient.
- Budget samples by . Halving gradient noise costs four times as many episodes, which is why variance reduction pays better than brute force.
- Expect local optima. The theorem guarantees a gradient, not a global answer. Initialization, entropy bonuses and exploration decide which basin you end in.
- Treat the surrogate loss as plumbing. Monitor the return, not the loss, and keep advantages out of the computation graph.
Frequently asked questions#
What is the policy gradient theorem in simple terms?
It says the gradient of a policy's expected return equals the expected value of the gradient of the log-probability of each action taken, multiplied by how good that action turned out to be, weighted by how often its state is visited. Because the expectation is over the policy's own behaviour, you can estimate it by running the policy, without knowing or differentiating the environment's dynamics.
What is the log-derivative trick?
It is the identity that the gradient of a probability equals the probability times the gradient of its logarithm. Applied to the trajectory distribution, it rewrites the gradient of an expectation as an expectation of the return times the score, which can be estimated by sampling. Because the log of a product is a sum, the environment's transition terms drop out of the gradient.
Why do the environment dynamics not appear in the policy gradient?
The log-probability of a trajectory is a sum of the start-state term, the policy terms and the transition terms. Only the policy terms depend on the parameters, so the others vanish when you differentiate. The dynamics still matter, but only through which trajectories get sampled, never through a derivative you need to compute.
What is the difference between policy gradient and Q-learning?
Q-learning learns an action-value function and acts greedily on it, so the policy is implicit and deterministic. Policy gradient methods parameterize the policy directly and climb the expected return by gradient ascent. Policy gradients handle continuous and very large action spaces and stochastic optimal policies naturally, but their on-policy estimates are noisier and less sample efficient.
Why use reward-to-go instead of the total return?
An action cannot influence rewards that arrived before it, and those terms average to zero because the expected score of any distribution is zero. Removing them keeps the estimator unbiased and lowers its variance. In our two-state example, the per-episode standard deviation fell from 32.5 to 6.8, roughly a 23-fold reduction in variance.
Is dropping the gamma to the t factor in the policy gradient a bug?
It changes what you estimate. Without the factor, a state visited late is weighted as if visited at the start, and the update is in general not the gradient of any objective. Many implementations drop it deliberately, treating discounting as variance reduction for an undiscounted goal. In our example the biased update pointed almost the right way but was 14 to 17 times too large.
Does the policy gradient theorem guarantee finding the optimal policy?
No. It guarantees an unbiased gradient, and the expected return is usually not concave in the policy parameters. In our two-state problem, exact gradient ascent from some starting points converges to a policy worth 10 while the optimum is worth 20. Initialization, exploration and entropy regularization decide which optimum you reach.
Sources#
- R. S. Sutton, A. G. Barto. Reinforcement Learning: An Introduction (2nd ed.), 2018. incompleteideas.net
- R. S. Sutton, D. McAllester, S. Singh, Y. Mansour. Policy Gradient Methods for Reinforcement Learning with Function Approximation, 1999. proceedings.neurips.cc
- R. J. Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning, 1992. doi.org
- P. W. Glynn. Likelihood ratio gradient estimation for stochastic systems, 1990. doi.org
- C. Nota, P. S. Thomas. Is the Policy Gradient a Gradient?, 2019. arxiv.org
- S. Mohamed, M. Rosca, M. Figurnov, A. Mnih. Monte Carlo Gradient Estimation in Machine Learning, 2019. arxiv.org
- D. Silver, G. Lever, N. Heess, T. Degris, D. Wierstra, M. Riedmiller. Deterministic Policy Gradient Algorithms, 2014. proceedings.mlr.press
- J. Schulman, X. Chen, P. Abbeel. Equivalence Between Policy Gradients and Soft Q-Learning, 2017. arxiv.org