Chapter 08 · Part 3: Learning policies
Policy gradients are score-function estimators
The policy gradient is the likelihood-ratio estimator of the derivative of an expectation; baselines are control variates, reward-to-go drops zero-mean terms, and GAE is a bias-variance dial.
Chapter 7 learned values and then acted greedily on them. That route has a limit: a over estimated values is awkward when actions are continuous, and a greedy policy cannot be stochastic. The alternative is to parametrise the policy directly, , and ascend the objective by gradient steps. The obstacle is that is an expectation over trajectories whose distribution depends on , and we need its derivative from samples. A statistician would say: this is the problem of differentiating an expectation with respect to a parameter of the distribution. There are two standard tools, the pathwise (reparametrisation) derivative and the score-function derivative. RL almost always uses the second, because the environment is a black box we cannot differentiate through.
To keep the algebra light, this chapter takes episodes of fixed length and no discounting, so . With discounting, replace by in the return; nothing else in the derivations changes. Practitioners usually also drop the leading weight on each term of the gradient; that changes the quantity being estimated, and is a separate topic.
Where does the policy gradient come from?
Write for the probability (density) of a trajectory under . Then . Differentiate under the integral (this needs smooth in and, for the interchange, a dominating integrable bound; for a softmax policy on a finite problem it is automatic, and the support of does not depend on ), and use :
This is the likelihood-ratio method of Glynn (1990) and, in RL, the REINFORCE estimator of Williams (1992). is the score of the trajectory, familiar from maximum likelihood: the gradient of the log-likelihood. It has mean zero, and the estimator multiplies it by the observed return.
The dynamics drop out
The trajectory probability factorises:
Take logs and differentiate. Only the policy factors depend on :
The initial-state distribution and the transition and reward model vanish. This is why the method is "model-free": we never need , only the ability to sample from it and to evaluate the gradient of our own policy's log-probability. Write and . The single-trajectory estimator is
It is unbiased for by the derivation above, and an average of independent trajectories has variance times that of one. The only issue is that variance, which is large.
The score has mean zero
For any state ,
(An integral for continuous actions.) This one fact generates every variance-reduction trick in the chapter. The first consequence is the policy gradient theorem in the form of Sutton, McAllester, Singh and Mansour (2000): in a finite-horizon problem
with the action value at time . Their paper states the infinite-horizon version with the discounted state-visitation weighting and shows that a compatible function approximator for preserves unbiasedness.
Why can we replace the full return by reward-to-go?
Expand the estimator into terms for all pairs , . Consider : a reward received before action . Condition on everything up to and including , which determines (it is already realised). Then
Past rewards cannot depend on a future action, and the score of the future action is mean zero given the past. Dropping those terms leaves the reward-to-go estimator
Same expectation, fewer terms. This is "causality" in the policy-gradient literature. In statistical terms we deleted summands that have mean zero but non-zero variance. That typically reduces the variance, because we remove noise; it need not do so in every problem, since the deleted terms can be correlated with the retained ones. (This is why I call it a Rao–Blackwell-flavoured step, not a Rao–Blackwellisation: we are not conditioning on a sufficient statistic.)
Why is a baseline a control variate?
Take any that does not depend on the action at the time it multiplies . Then and
so subtracting from the estimator does not change its mean. In control-variate language: is the estimator, is a variable with known mean , and we use . The textbook coefficient is . Work it out for component of the gradient, using :
Equivalently, minimise the variance directly. The -th component of has mean (free of ) and second moment , so we minimise :
and , so this is the minimum. The optimal constant baseline is the mean return weighted by the squared score: trajectories whose score is large in component count more, because they are the ones that make the estimator swing. It coincides with only if and are uncorrelated. Greensmith, Bartlett and Baxter (2004) treat baselines and critics as additive control variates, derive the optimal baseline, and show that the average reward is in general suboptimal, consistent with this calculation.
A state-dependent baseline and the advantage
The baseline is allowed to depend on the state at time (and on anything else that precedes ), because the argument above only used that it does not depend on . Use in the -th term:
The natural choice is , the state value. Since , the weight is an unbiased noisy version of the advantage . The advantage has a clear interpretation: how much better than average is this action in this state. Making the weight a function of the state and action rather than of the whole future trajectory gives actor–critic methods: replace by an estimate or from a learned critic. That lowers variance more but can introduce bias if the critic is wrong, the same trade-off as chapters 4 and 5.
The state value is not the variance-minimising baseline either (Greensmith et al. show this); it is a good, cheap, learnable one, and it is what the learned baseline in the experiment uses.
Generalised advantage estimation as a dial
Let be a learned value function and the TD error from chapter 5. Using a -step return to form an advantage estimate gives
where is the -step return. At this is : low variance, biased unless . At it is , a Monte Carlo advantage: unbiased for any (the baseline only shifts the variance), high variance. Generalised advantage estimation (GAE; Schulman, Moritz, Levine, Jordan and Abbeel, 2016) averages these with geometric weights :
where is exactly the -return from chapter 5 for the fixed function . The weight moves the estimator from the one-step TD advantage () to the Monte Carlo advantage (). The bias at intermediate comes from the error of , damped by powers of the further it enters; the variance comes from summing more random 's. Nothing new is needed to understand this: it is the bias-variance dial of chapter 5, applied to an advantage instead of a value. (Schulman et al. also use itself as a variance-reduction parameter; the discussion above fixes as part of the problem.)
Where this is used
The policy-optimisation methods you will meet in practice are built from these pieces. PPO (Schulman et al., 2017) takes an advantage estimate, typically GAE, and uses it in a clipped surrogate objective that lets one batch be reused for several gradient steps. GRPO, introduced for language-model post-training in DeepSeekMath (Shao et al., 2024), samples a group of outputs per prompt and uses the group-standardised reward as the advantage, dropping the learned critic: the group mean is the baseline. A statistical remark on that choice, which chapter 10 returns to: if the baseline for sample is the mean of a group of rewards including sample , it is no longer independent of that sample's action, and the expectation of the estimator is scaled by . A leave-one-out mean is exactly unbiased. Dividing by the group's standard deviation rescales the gradient prompt by prompt and is a different estimator again.
A worked example by hand: a two-armed bandit
One state, one step (), two arms, softmax policy with parameters :
Score. , so . The score is , with the indicator vector of the chosen arm. Check mean zero: .
Let , so , and let the rewards be deterministic, . Then .
True gradient. . For component 1:
By symmetry (the two components of the softmax score sum to zero), .
The estimator. Draw ; the estimate of component 1 is .
- (probability ): .
- (probability ): .
Mean: . Unbiased. Variance: .
With a baseline . The estimate is . For , and the value is . For , and the value is . Subtract the mean from each: and . Both have magnitude , so
At the variance is ; at it is ; at it is . With the estimator returns on every draw: every sample reports the exact gradient. Check against the formula: here for both arms, a constant, so . This is the special case where the optimal baseline equals the mean, because does not vary. With it does vary, and the two baselines separate (exercise 1).
Experiment
ch08_policy_gradient.py builds a small episodic problem: 3 states, 2 actions, horizon , stochastic transitions, mean rewards between and plus Gaussian noise of standard deviation , a tabular softmax policy (6 parameters). The mean rewards are deliberately shifted upward so that raw returns are large (about 19) and a baseline has something to remove. The true gradient is computed exactly by backward induction on and forward propagation of state probabilities, and the script checks it against finite differences first.
For a fixed policy we draw 400,000 independent single-trajectory estimates under each of five estimators:
- no baseline: ;
- constant baseline equal to (fitted from a pilot sample of 200,000 trajectories);
- optimal constant baseline , estimated from the same pilot;
- reward-to-go;
- reward-to-go minus a learned time-and-state value , the mean of in each cell of the pilot sample.
Baselines are fitted on a separate sample from the estimates, so they are fixed constants as far as the estimation sample is concerned, and unbiasedness holds. "max z-score" is the largest, over the six components, of divided by its standard error.
check: max |exact grad - finite difference| = 2.97e-10
True J = 19.3015; ||true gradient|| = 1.3546; 6 parameters; 400000 single-trajectory estimates per row.
Baselines fitted on a separate pilot of 200000 trajectories; mean pilot return 19.306.
estimator | ||mean - truth|| | max z-score | total variance | rel. to none
no baseline | 0.0512 | 1.84 | 737.03 | 1.0000
constant mean baseline | 0.0040 | 0.90 | 16.98 | 0.0230
optimal constant baseline | 0.0043 | 1.08 | 14.40 | 0.0195
reward-to-go | 0.0336 | 1.46 | 339.50 | 0.4606
reward-to-go, learned V(t,s) | 0.0040 | 1.31 | 9.75 | 0.0132
component 0..5 of the gradient: truth and empirical means
truth | -0.540 0.540 0.331 -0.331 -0.718 0.718
no baseline | -0.576 0.576 0.325 -0.325 -0.712 0.712
constant mean baseline | -0.539 0.539 0.333 -0.333 -0.719 0.719
optimal constant baseline | -0.541 0.541 0.334 -0.334 -0.720 0.720
reward-to-go | -0.564 0.564 0.327 -0.327 -0.719 0.719
reward-to-go, learned V(t,s) | -0.541 0.541 0.334 -0.334 -0.720 0.720
Learning: 150 SGD steps, batch 32, step 0.05, 40 seeds. J(uniform) = 19.161, J(optimal) = 22.720
variant | final J mean | final J sd
no baseline | 22.127 | 0.206
reward-to-go | 22.124 | 0.182
reward-to-go + learned V | 22.110 | 0.082What the numbers show.
- All five are unbiased. The largest z-score is ; no estimator is distinguishable from the exact gradient at that sample size. The estimators with large variance have visibly larger discrepancies in the mean (norm for no baseline, for reward-to-go against for the baselined ones), which is what a Monte Carlo error proportional to the standard deviation looks like, not bias. The gradient components come in pairs because softmax scores within a state sum to zero.
- A constant baseline removes 98% of the variance. The raw return has mean and a much smaller standard deviation, so multiplying the score by mostly multiplies it by a constant. Subtracting the mean cuts total variance from to , a factor of . The optimal constant baseline improves on it modestly (to ): in this problem and are only weakly related, so the score-weighted mean is close to the plain mean, as the theory predicts.
- Reward-to-go helps without any baseline, halving the variance ( of the no-baseline value), by deleting the mean-zero terms that pair each action with earlier rewards.
- Combining causality and a state baseline is best: , or of the no-baseline variance, a factor of about . The state baseline removes more than a constant baseline because later returns depend strongly on which state the chain is in.
- In learning, the means are similar and the spread is not. After 150 steps with 32 trajectories per step, all three variants reach about of the optimal from for the uniform policy. The learned-baseline variant has less than half the seed-to-seed standard deviation ( against ). The variance of the gradient estimate shows up as run-to-run variability of the learned policy. Here the problem is small and the step is moderate, so baselines do not change where learning ends up; with a larger step size, a smaller batch, or a longer horizon, that variance would also slow or derail learning.
Exercises
- Pen and paper. In the bandit example, set and . Compute and the optimal baseline . Then compute the variance of the estimator of component 1 at each of the two baselines.
- Pen and paper. Show that the weights and are the same thing. (Telescope the sum.)
- Pen and paper. Suppose is the batch mean of returns including the sample it multiplies. Show that .
- Change the code and predict. Lower
REWARD_SDto 0 and rerun the variance experiment. Which row's variance falls most? Then raise to 8 and predict how the no-baseline and reward-to-go variances scale. - Change the code and predict. In
learn, setbatch=4andlr=0.05. Predict whether the ordering of final- standard deviations persists, then run.
Sources
- Sutton, R. S. and Barto, A. G. (2018). Reinforcement Learning: An Introduction, 2nd ed. MIT Press. Chapter 13 (policy gradient methods).
- Glynn, P. W. (1990). Likelihood ratio gradient estimation for stochastic systems. Communications of the ACM 33(10), 75–84.
- Williams, R. J. (1992). Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine Learning 8, 229–256.
- Sutton, R. S., McAllester, D., Singh, S. and Mansour, Y. (2000; NIPS 12, 1999). Policy gradient methods for reinforcement learning with function approximation. Advances in Neural Information Processing Systems 12.
- Greensmith, E., Bartlett, P. L. and Baxter, J. (2004). Variance reduction techniques for gradient estimates in reinforcement learning. Journal of Machine Learning Research 5, 1471–1530.
- Schulman, J., Moritz, P., Levine, S., Jordan, M. and Abbeel, P. (2016). High-dimensional continuous control using generalized advantage estimation. ICLR 2016 (arXiv:1506.02438).
- Schulman, J., Wolski, F., Dhariwal, P., Radford, A. and Klimov, O. (2017). Proximal policy optimization algorithms. arXiv:1707.06347.
- Shao, Z. et al. (2024). DeepSeekMath: pushing the limits of mathematical reasoning in open language models. arXiv:2402.03300.