Chapter 13
Policy Gradient Methods
Every control method so far, up to the Sarsa() of Chapter 12, has been built on action values: learn , then act greedily or -greedily with respect to it, so that the policy exists only as a by-product of the value estimates. This chapter turns the construction around. The policy itself becomes the object of learning, a differentiable function of a parameter , and it is improved by stochastic gradient ascent on a scalar performance measure :
(13.1)A value function may still be learned, with weights as in , but it is used to train the policy, not to select actions. Methods that learn both are actor–critic methods: the policy is the actor, the value function the critic. The single-state version of everything below already appeared as the gradient bandit algorithm of Chapter 2; the new difficulty is that in an MDP the parameter changes not only which actions are taken but also which states are visited, and the policy gradient theorem is precisely the statement that this second effect need not be differentiated.
13.1Parameterized Policies and Why We Want Them#
For a finite action set the standard choice is the soft-max in action preferences: a numerical preference for each pair, turned into probabilities by
(13.2)where the linear preference on the right, with features built as in Chapter 9, is one option among many (a deep network computing is another). Four reasons favor this kind of parameterization over -greedy selection on .
- It can become deterministic. An -greedy policy keeps probability on every action forever. A soft-max over action values does not help either: the values converge to finite numbers , which fix non-degenerate probabilities, unless a temperature is annealed on a schedule nobody knows how to choose. Preferences are not estimates of anything; if the optimal policy is deterministic, gradient ascent drives the preference of the best action without bound.
- It can represent stochastic optimal policies. With function approximation, states that look alike must be treated alike, and the best policy among those the features allow may be genuinely stochastic, as in the example below (and as in bluffing in poker).
- The policy may be the simpler object. In some problems (Tetris is the book’s example) a good policy is easier to represent than an accurate value function.
- Prior knowledge about the form of a good policy enters naturally through the parameterization, which is often the decisive practical reason.
There is also a theoretical reason. Under -greedy selection an arbitrarily small change in the estimates can flip the greedy action and change the policy discontinuously, which is at the root of the convergence difficulties of control with approximation (Chapter 10, Chapter 11). Here is smooth, so is a smooth function of and the whole toolbox of stochastic gradient methods applies.
Example 13.1 (Short Corridor with Switched Actions). Three non-terminal states in a row, then the goal; reward per step. In the first and third states the actions right and left do what they say (left in the first state bumps into the wall and stays); in the second state they are swapped. The features are and for every , so the agent cannot tell the states apart and every policy it can represent chooses right with the same probability everywhere.
Because does not depend on , an -greedy agent has only two policies: right with probability in every state, or left with that probability. The soft-max policy can choose any . The value of the start state as a function of follows from the Bellman equations of the three states,
where the swapped middle state sends right back to state 1, and . This is Exercise 13.1 of the book.Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction. Adaptive Computation and Machine Learning. MIT Press, Cambridge, MA, second edition, 2018. ISBN 978-0-262-03924-6. URL http://incompleteideas.net/book/the-book-2nd.html
Solve the three Bellman equations for a symbolic right-probability and keep .const corridorJ = await show`With[{sol = Solve[{v1 == -1 + p v2 + (1 - p) v1, v2 == -1 + p v1 + (1 - p) v3, v3 == -1 + (1 - p) v2}, {v1, v2, v3}]}, Simplify[v1 /. First[sol]]]`const corridorOpt = await show`With[{ps = p /. First[Solve[D[${corridorJ}, p] == 0 && 0 < p < 1, p]]}, {ps, FullSimplify[${corridorJ} /. p -> ps], N[{ps, ${corridorJ} /. p -> ps}]}]`So , which tends to at both ends: with the agent never leaves the first state, with it bounces forever between the first two. The optimum gives , against and for the two -greedy policies with (Figure 13.1). No method that acts (nearly) greedily on these features can get anywhere near it.
13.2The Policy Gradient Theorem#
In the episodic case performance is the value of the start state,Assuming one fixed start state loses no generality: a random start is a fixed dummy state with a single action whose transition draws the real start state.
(13.3)The difficulty is visible in the definition. Changing changes the action probabilities in each state, whose effect on reward we can compute from the parameterization, and it changes the distribution of states visited, whose effect depends on the unknown dynamics. The theorem says that the gradient can be written without differentiating the state distribution. We prove it for a discount rate , which costs nothing and produces the factors of the algorithms directly (the book proves the case and leaves the general one as its Exercise 13.2). Define the discounted expected number of visits to in an episode from ,
(13.4)where the event includes “not yet terminated”. For this is the expected number of visits, and normalizing it gives the on-policy distribution of Chapter 9.
Theorem 13.2 (Policy Gradient Theorem, Episodic Case). Let the MDP be finite and episodic, let be differentiable in , and suppose every episode terminates with probability one from every state, for every . Then
(13.5)where and, for , the constant of proportionality is the expected length of an episode.
Proof. Write for the transition matrix among non-terminal states, , which is substochastic because rows lose the probability of terminating. Under the termination assumption exists even for (see Section A.3), and is a rational function of the action probabilities, hence differentiable in . Gradients are with respect to throughout; they are column vectors, and in matrix equations each state contributes a row .
Step 1 (product rule). From ,
Step 2 (only depends on inside ). Since and neither the rewards nor the dynamics depend on , . Writing ,
a Bellman equation for the gradient, with in the role of the reward.
Step 3 (solve it). Stacking rows, , so
The Neumann series is the book’s “repeated unrolling”. Its row has entries , which gives the equality in (13.5). Dividing and multiplying by gives the proportionality. For , . □
The derivative of the state distribution has disappeared: it is absorbed by the recursion of Step 2, because the effect of on later states is again an effect of on later actions, which the recursion counts where it happens. Two remarks on the constant. First, any positive constant can be absorbed into , so “proportional” is all that stochastic gradient ascent needs. Second, for the weights are discounted visit counts, so late states count less; we return to this in Exercise 13.15.
13.2.1In Wolfram Language#
The theorem can be checked exactly on a small MDP where nothing is hidden. Take two non-terminal states , each with two actions and a logistic policy . In , moves to with reward and terminates with ; in , terminates with and returns to with , so may be visited many times. We compute by solving the Bellman equations, differentiate it symbolically, and compare with the right-hand side of (13.5) ().
Expected visits . Visits to exceed one because of the loop through .const pgPol = await wl`{1/(1 + Exp[-Subscript[\[Theta], 0]]), 1/(1 + Exp[-Subscript[\[Theta], 1]])}`
const pgP = await wl`{{0, ${pgPol}[[1]]}, {1 - ${pgPol}[[2]], 0}}`
const pgR = await wl`{${pgPol}[[1]] Subscript[r, 1] + (1 - ${pgPol}[[1]]) Subscript[r, 2], ${pgPol}[[2]] Subscript[r, 3] + (1 - ${pgPol}[[2]]) Subscript[r, 4]}`
const pgV = await wl`Simplify[Inverse[IdentityMatrix[2] - ${pgP}] . ${pgR}]`
const pgEta = await show`Simplify[{1, 0} . Inverse[IdentityMatrix[2] - ${pgP}]]`const pgQ = await wl`{{Subscript[r, 1] + ${pgV}[[2]], Subscript[r, 2]}, {Subscript[r, 3], Subscript[r, 4] + ${pgV}[[1]]}}`
const pgTab = await wl`{{${pgPol}[[1]], 1 - ${pgPol}[[1]]}, {${pgPol}[[2]], 1 - ${pgPol}[[2]]}}`
const pgTh = await wl`{Subscript[\[Theta], 0], Subscript[\[Theta], 1]}`
const pgGrad = await wl`D[${pgV}[[1]], {${pgTh}}]`
const pgRhs = await wl`Sum[${pgEta}[[s]] Sum[${pgQ}[[s, a]] D[${pgTab}[[s, a]], {${pgTh}}], {a, 2}], {s, 2}]`
await show`Simplify[${pgGrad} - ${pgRhs}]`13.3REINFORCE: Monte Carlo Policy Gradient#
The right-hand side of (13.5) is an expectation over the states visited by , which is what makes it estimable by following . One could stop at the all-actions form, , which needs a learned . REINFORCERonald J. Williams. Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. Machine Learning, 8(3–4):229–256, Springer, 1992. doi: 10.1007/BF00992696 instead samples the action too, and the device that makes the sum over actions an expectation is the log-derivative trick (Section A.6): .
Corollary 13.3 (The Gradient as an Expectation over Episodes). Under the assumptions of Theorem 13.2,
(13.6)Proof. By (13.4), a sum equals . Apply this to , a conditional expectation over , so that . Finally, by the Markov property , and is known given that history, so the law of total expectation lets us replace by . □
The vector is the eligibility vector (statisticians call it the score). It is the only place where the parameterization enters. The update moves in the direction that most increases the probability of repeating in , in proportion to the return, and inversely proportional to the probability of the action: without the division, frequently chosen actions would win simply because they are updated more often.
Algorithm 13.4 (REINFORCE: Monte Carlo Policy Gradient (episodic)). Input: a differentiable policy parameterization . Parameter: step size . Initialize (e.g., to ).
Loop for each episode:
- Generate following .
- For :
Summed over an episode, and with held fixed during it, the increments have expectation exactly by Corollary 13.3. REINFORCE is therefore a genuine stochastic gradient method: for small the expected performance improves, and with step sizes satisfying the conditions of Theorem A.7 (and bounded variance) it converges to a stationary point of . Two details of the estimator deserve attention. It uses , the return after , rather than the whole : rewards earned before cannot depend on it, and indeed for by the argument of Proposition 13.5, so dropping them removes noise without bias. And as a Monte Carlo method it waits until the end of the episode, and its variance can be large, which is the theme of the rest of the chapter.
For the soft-max with linear preferences (13.2) the eligibility vector has a simple form (the book’s Exercise 13.3):
(13.7)the feature vector of the chosen action minus its average under the policy. It follows from by differentiating the log-sum-exp.
Three actions with symbolic feature vectors : the gradient of minus the right-hand side of the eligibility formula.const softFeats = await wl`Table[{Subscript[x, b, 1], Subscript[x, b, 2]}, {b, 3}]`
const softTh = await wl`{Subscript[\[Theta], 1], Subscript[\[Theta], 2]}`
const softPi = await wl`Function[a, Exp[${softTh} . ${softFeats}[[a]]]/Sum[Exp[${softTh} . ${softFeats}[[b]]], {b, 3}]]`
await show`Simplify[D[Log[${softPi}[1]], {${softTh}}] - (${softFeats}[[1]] - Sum[${softPi}[b] ${softFeats}[[b]], {b, 3}])]`13.4Baselines#
Any function of the state can be subtracted from the action values without changing the gradient:
(13.8)Proposition 13.5 (Baselines Do Not Bias the Gradient). Let be any function of the state, or a random variable that is conditionally independent of given . Then , for discrete and for continuous actions.
Proof. For discrete actions, . For a density, the same computation with , where differentiation under the integral is justified for the smooth families used in practice (dominated convergence). For a random , condition on it first. □
The score has mean zero; that is the entire content of the proposition, and it is checked below for a three-action soft-max and for a Gaussian. The baseline leaves the mean of the update unchanged and can change its variance a great deal. The resulting update,
(13.9)with a learned , gives the following algorithm. The value step size is easy to set (for linear the rules of thumb of Chapter 9 apply); the policy step size depends on the scale of the rewards and of the parameterization and is harder.
Algorithm 13.6 (REINFORCE with Baseline (episodic)). Input: differentiable and . Parameters: step sizes , . Initialize , .
Loop for each episode:
- Generate following .
- For :
Which baseline is best? Consider a single step with score and return . Because the mean of does not depend on , minimizing the total variance (the trace of the covariance) is the same as minimizing , a parabola in with minimum at
(13.10)This is a score-weighted mean of the return, not the plain mean . The two coincide when is uncorrelated with , and is the convenient, nearly optimal choice made in practice.Evan Greensmith, Peter L. Bartlett, and Jonathan Baxter. Variance Reduction Techniques for Gradient Estimates in Reinforcement Learning. Journal of Machine Learning Research, 5:1471–1530, 2004. URL https://www.jmlr.org/papers/v5/greensmith04a.html A two-armed bandit with logistic policy, , and deterministic rewards shows how different can be from the mean.
Score of each arm with respect to the logit , then the minimizer of , rewritten in terms of .const armP = await wl`1/(1 + Exp[-\[Theta]])`
const armG = await wl`{D[Log[${armP}], \[Theta]], D[Log[1 - ${armP}], \[Theta]]}`
const bOpt = await show`Assuming[0 < p < 1, FullSimplify[(b /. First[Solve[D[${armP} (Subscript[r, 1] - b)^2 ${armG}[[1]]^2 + (1 - ${armP}) (Subscript[r, 2] - b)^2 ${armG}[[2]]^2, b] == 0, b]]) /. \[Theta] -> Log[p/(1 - p)]]]`The optimal baseline is : each arm’s reward is weighted by the probability of the other arm, the opposite of the mean . The rare arm has the larger score ( versus when ), so its updates are the dangerous ones, and the baseline is pulled towards its reward to tame them.
The scores of a three-action soft-max sum to zero, and the score of a Gaussian (with respect to and ) has expectation zero.await show`{Simplify[Total[D[Exp[{t1, t2, t3}]/Total[Exp[{t1, t2, t3}]], {{t1, t2, t3}}]]], Expectation[D[Log[PDF[NormalDistribution[\[Mu], \[Sigma]], a]], {{\[Mu], \[Sigma]}}], a \[Distributed] NormalDistribution[\[Mu], \[Sigma]]]}`13.5Actor–Critic Methods#
REINFORCE with baseline learns a value function but is not an actor–critic method: its only centers the return of the state being updated, it never stands in for future returns. The distinction matters, because only bootstrapping introduces bias and an asymptotic dependence on the quality of the function approximator, and only bootstrapping buys the variance reduction and the online, incremental character of TD learning. The one-step actor–critic replaces by the one-step return and keeps as the baseline:
(13.11)with the TD error (6.2). Why should the TD error be the right signal for the actor? Define the advantage , the amount by which taking and then following beats following from the start. By (13.8) with , the policy gradient is . And if the critic were exact, ,
so is an unbiased one-sample estimate of the advantage of the action just taken. With an imperfect critic the update is biased, but only through the bootstrapped term: is a baseline and harmless by Proposition 13.5, whereas replaces and its error leaks into the gradient. This is the bias–variance trade of Chapter 6 again, now for the actor.
Algorithm 13.7 (One-step Actor–Critic (episodic)). Input: differentiable and . Parameters: step sizes , . Initialize , .
Loop for each episode:
- Initialize (first state of the episode); .
- Loop while is not terminal:
- ; take action , observe , .
- (with if is terminal)
- ;
The factor is the discount weight of (13.6). The algorithm is fully online: each transition is used once and discarded. Its convergence analysis treats it as a two-timescale stochastic approximation in which the critic moves faster than the actor, so that the actor sees an almost converged critic.Konda and Tsitsiklis (2000) proved convergence of actor–critic algorithms with linear critics using features compatible with the actor (Section 13.8.1) and step sizes with ; the general framework is the ODE method of Section A.4.Vijay R. Konda and John N. Tsitsiklis. Actor-Critic Algorithms. In Sara A. Solla, Todd K. Leen, and Klaus-Robert Müller, editors, Advances in Neural Information Processing Systems 12 (NIPS 1999), volume 12, pages 1008–1014. MIT Press, 2000
13.5.1Multi-step Critics and Eligibility Traces#
Replacing the one-step return by the -step return or by the λ-return of (12.1) gives forward-view actor–critic methods that interpolate between Algorithm 13.7 () and REINFORCE with baseline (); we will meet this interpolation again, as generalized advantage estimation, in Section 13.8.3. The backward view uses two eligibility traces after the pattern of Chapter 12: an accumulating trace of value gradients for the critic and a trace of eligibility vectors for the actor, each with its own decay rate.
Algorithm 13.8 (Actor–Critic with Eligibility Traces (episodic)). Input: differentiable and . Parameters: ; . Initialize , .
Loop for each episode:
- Initialize ; ( components); ( components); .
- Loop while is not terminal:
- ; take action , observe , .
- ()
- ;
- ;
- ;
13.6Policy Gradient for Continuing Problems#
Without episodes, performance is the average reward of Section 10.3,
(13.12)where now is the stationary distribution of the chain under , assumed to exist and not to depend on (ergodicity, Section A.3), so that . Values are defined with respect to the differential return .
Theorem 13.9 (Policy Gradient Theorem, Average-Reward Case). For a finite ergodic MDP and differentiable , with the differential values,
with equality: the constant of proportionality is .
Proof. As in the episodic case, but now contains , so Step 2 becomes . Substituting in Step 1 and solving for , which does not depend on ,
Average both sides over . By stationarity , so the last two terms cancel, leaving . (Differential values are determined up to an additive constant, which does not matter: it multiplies .) □
The algorithms carry over with the differential TD error (10.9) and no discounting; Exercise 13.13 checks the theorem symbolically on a two-state chain.
Algorithm 13.10 (Actor–Critic with Eligibility Traces (continuing)). Parameters: ; . Initialize , , , ; , .
Loop for each time step:
- ; take action , observe , .
- ;
- ;
- ; ;
13.7Continuous Actions: Gaussian Policies#
Action-value methods need a maximization over actions at every step, which is a problem in its own right when . A parameterized policy only needs to sample. Instead of one probability per action we learn the statistics of a distribution, typically a Gaussian policy:
(13.13)with and the exponential keeping positive. (Here is the mean of the action, not the on-policy distribution.) From , with and , the two parts of the eligibility vector are (the book’s Exercise 13.4)
(13.14)The mean moves towards actions that did better than the baseline; the standard deviation grows when such actions lay far from the mean (more than one away) and shrinks otherwise.
Score of a Gaussian policy with scalar features: , , so .const gaussPi = await wl`PDF[NormalDistribution[Subscript[\[Theta], \[Mu]] Subscript[x, \[Mu]], Exp[Subscript[\[Theta], \[Sigma]] Subscript[x, \[Sigma]]]], a]`
await show`Simplify[D[Log[${gaussPi}], {{Subscript[\[Theta], \[Mu]], Subscript[\[Theta], \[Sigma]]}}]]`The factor in the mean part is a warning: as the policy becomes nearly deterministic, the eligibility vector explodes and so does the variance of REINFORCE (Exercise 13.14). This is one motivation for the deterministic policy gradients of Section 13.8.4.
13.8Beyond the Book: Modern Policy Optimization#
The book closes its chapter at the methods above. Since then, policy gradient methods have become the workhorse of deep reinforcement learning and, through the fine-tuning of language models, of a large part of applied machine learning. The developments below are each a small step from the ideas of this chapter.Beyond Sutton and Barto (2018). This section collects results not treated in the book: natural gradients and compatible features (2000–2001), trust-region and proximal methods (2015–2017), generalized advantage estimation (2016), deterministic and maximum-entropy actor–critics (2014–2018), global convergence theory (2020–2021) and policy optimization for language models (2022–2025).
13.8.1Natural Policy Gradient and Compatible Features#
The gradient is the steepest-ascent direction for the Euclidean length of , which depends on the arbitrary choice of parameterization. Measuring steps instead by how much they change the policy, , with the Fisher information matrix
gives the natural policy gradient of Kakade.Sham M. Kakade. A Natural Policy Gradient. In Thomas G. Dietterich, Suzanna Becker, and Zoubin Ghahramani, editors, Advances in Neural Information Processing Systems 14 (NIPS 2001), volume 14, pages 1531–1538. MIT Press, 2001Beyond Sutton and Barto (2018). The natural policy gradient (Kakade, 2001) and the compatible-features theorem (Sutton, McAllester, Singh and Mansour, 2000) are classic results that the book does not develop. It connects beautifully with a classic question: when can a learned critic replace in the policy gradient theorem without bias? Sutton, McAllester, Singh and Mansour answered:Richard S. Sutton, David McAllester, Satinder Singh, and Yishay Mansour. Policy Gradient Methods for Reinforcement Learning with Function Approximation. In Sara A. Solla, Todd K. Leen, and Klaus-Robert Müller, editors, Advances in Neural Information Processing Systems 12 (NIPS 1999), volume 12, pages 1057–1063. MIT Press, 2000 when the critic is linear in the eligibility vector itself.
Proposition 13.11 (Compatible Function Approximation). Let (compatible features), and let minimize . Then , and if is invertible, .
Proof. Write . The minimizer satisfies the normal equations . Since , this says that and give the same policy gradient sum. Moreover the second term is and the first is, by Theorem 13.2, proportional to . □
So the weights of the best compatible critic are the natural gradient: an actor–critic that steps along does natural gradient ascent without ever forming . Note that has zero mean under , so a compatible critic approximates the advantage, not . For the tabular soft-max () the natural gradient step reduces to , that is, a multiplicative-weights update , a soft version of the policy improvement of Theorem 4.6.Alekh Agarwal, Sham M. Kakade, Jason D. Lee, and Gaurav Mahajan. On the Theory of Policy Gradient Methods: Optimality, Approximation, and Distribution Shift. Journal of Machine Learning Research, 22(98):1–76, 2021. URL http://jmlr.org/papers/v22/19-736.html
13.8.2Trust Regions: TRPO and PPO#
Policy gradient steps are local, and in deep networks a step that is too large can destroy a good policy. Two ideas make larger steps safe. The first is the surrogate objective: for data collected with ,
(13.15)an importance-sampling ratio as in (5.2) that corrects the actions but not the states. Since at , the surrogate has the same gradient as there; away from it, the error made by ignoring the change in state distribution is controlled by how far the policy has moved (Kakade and Langford’s performance difference lemma).Sham Kakade and John Langford. Approximately Optimal Approximate Reinforcement Learning. In Claude Sammut and Achim G. Hoffmann, editors, Proceedings of the Nineteenth International Conference on Machine Learning (ICML 2002), pages 267–274. Morgan Kaufmann, 2002 Trust region policy optimization (TRPO) maximizes subject to , solved approximately by a natural gradient step (conjugate gradients on ) followed by a line search.John Schulman, Sergey Levine, Philipp Moritz, Michael I. Jordan, and Pieter Abbeel. Trust Region Policy Optimization. In Francis Bach and David Blei, editors, Proceedings of the 32nd International Conference on Machine Learning, volume 37 of Proceedings of Machine Learning Research, pages 1889–1897, Lille, France, 2015. PMLR Proximal policy optimization (PPO) replaces the constraint by a clipped objective, optimized for several epochs of minibatch gradient ascent on the same batch:John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, and Oleg Klimov. Proximal Policy Optimization Algorithms. arXiv preprint arXiv:1707.06347, 2017. doi: 10.48550/arXiv.1707.06347
(13.16)typically with . The minimum makes the objective a pessimistic bound on the unclipped one. Its effect is easiest to see in the derivative with respect to the ratio, computed below for each sign of the advantage and each region of .
for (first row) and (second row), in the regions , , .const ppoL = await wl`Function[{r, A}, Min[r A, Clip[r, {1 - \[Epsilon], 1 + \[Epsilon]}] A]]`
await show`Table[Simplify[D[${ppoL}[r, A], r], 0 < \[Epsilon] < 1 && c && s A > 0], {s, {1, -1}}, {c, {0 < r < 1 - \[Epsilon], 1 - \[Epsilon] < r < 1 + \[Epsilon], r > 1 + \[Epsilon]}}]`A good action () stops being pushed once its probability ratio exceeds , and a bad one once its ratio falls below ; but a good action whose probability has dropped below still gets the full gradient, so mistakes are always corrected. The clip removes the incentive to move far, not the ability to undo.Beyond Sutton and Barto (2018). TRPO (Schulman et al., 2015) and PPO (Schulman et al., 2017); PPO with GAE became the default on-policy deep RL algorithm and later the optimizer of RLHF.
13.8.3Generalized Advantage Estimation#
Advantage estimates trade bias against variance exactly as returns do. Generalized advantage estimation (GAE) applies the λ-return idea of Chapter 12 to the TD errors :John Schulman, Philipp Moritz, Sergey Levine, Michael I. Jordan, and Pieter Abbeel. High-Dimensional Continuous Control Using Generalized Advantage Estimation. In 4th International Conference on Learning Representations (ICLR 2016), San Juan, Puerto Rico, 2016
(13.17)where is the λ-return (12.1) built on . For it is the one-step TD error of Algorithm 13.7; for the sum telescopes to , the signal of REINFORCE with baseline. The check below takes a three-step episode with symbolic rewards and values ( of the terminal state is ).
GAE minus (λ-return minus ), then the limits and .const gaeDeltas = await wl`Table[Subscript[R, k + 1] + \[Gamma] If[k + 1 == 3, 0, Subscript[V, k + 1]] - Subscript[V, k], {k, 0, 2}]`
const gaeA = await wl`Sum[(\[Gamma] \[Lambda])^l ${gaeDeltas}[[l + 1]], {l, 0, 2}]`
const gaeLret = await wl`With[{G = Table[Sum[\[Gamma]^(j - 1) Subscript[R, j], {j, 1, n}] + If[n < 3, \[Gamma]^n Subscript[V, n], 0], {n, 1, 3}]}, (1 - \[Lambda]) Sum[\[Lambda]^(n - 1) G[[n]], {n, 1, 2}] + \[Lambda]^2 G[[3]]]`
await show`{Simplify[${gaeA} - (${gaeLret} - Subscript[V, 0])], ${gaeA} /. \[Lambda] -> 0, Expand[${gaeA} /. \[Lambda] -> 1]}`In practice the advantages are computed backwards over a batch of trajectories with and , then used in (13.16).Beyond Sutton and Barto (2018). Generalized advantage estimation (Schulman, Moritz, Levine, Jordan and Abbeel, ICLR 2016) is the book’s λ-return transplanted to advantages; it is the standard advantage estimator of modern actor–critics.
13.8.4Deterministic Policy Gradients: DPG, DDPG and TD3#
For continuous actions one can also learn a deterministic policy and move it along the gradient of the critic. The deterministic policy gradient theorem of Silver et al. statesDavid Silver, Guy Lever, Nicolas Heess, Thomas Degris, Daan Wierstra, and Martin Riedmiller. Deterministic Policy Gradient Algorithms. In Eric P. Xing and Tony Jebara, editors, Proceedings of the 31st International Conference on Machine Learning, volume 32 of Proceedings of Machine Learning Research, pages 387–395, Beijing, China, 2014. PMLR
(13.18)where is the discounted state distribution and is the Jacobian. There is no integral over actions, hence no score function and none of the variance of (13.14); in fact the stochastic policy gradient of a Gaussian policy tends to (13.18) as . Because the gradient needs only at the actor’s action, the critic can be learned off-policy from an exploratory behavior policy, by Q-learning-like updates. DDPG combines this with the machinery of DQN (Section 15.5: replay buffer, slowly updated target networks) and exploration noise added to the actor’s action.Timothy P. Lillicrap, Jonathan J. Hunt, Alexander Pritzel, Nicolas Heess, Tom Erez, Yuval Tassa, David Silver, and Daan Wierstra. Continuous Control with Deep Reinforcement Learning. In 4th International Conference on Learning Representations (ICLR 2016), San Juan, Puerto Rico, 2016 Like Q-learning, it inherits the maximization bias of Chapter 6: the actor climbs the critic’s errors. TD3 adds three fixes: a clipped double-Q target that uses the smaller of two critics’ estimates (double learning, pessimistic), delayed actor updates (one per two critic updates), and target policy smoothing, noise on the target action so the critic cannot exploit narrow peaks.Scott Fujimoto, Herke van Hoof, and David Meger. Addressing Function Approximation Error in Actor-Critic Methods. In Jennifer Dy and Andreas Krause, editors, Proceedings of the 35th International Conference on Machine Learning, volume 80 of Proceedings of Machine Learning Research, pages 1587–1596, Stockholm, Sweden, 2018. PMLRBeyond Sutton and Barto (2018). The deterministic policy gradient (Silver et al., 2014) predates the book but is not covered in it; DDPG (Lillicrap et al., 2016) and TD3 (Fujimoto, van Hoof and Meger, 2018) are its deep, off-policy descendants.
13.8.5Entropy Regularization and Soft Actor–Critic#
A policy that collapses too early stops exploring. Adding the entropy to the objective, with a temperature , counteracts this; A3C used it as a bonus in the policy loss.Volodymyr Mnih, Adrià Puigdomènech Badia, Mehdi Mirza, Alex Graves, Timothy P. Lillicrap, Tim Harley, David Silver, and Koray Kavukcuoglu. Asynchronous Methods for Deep Reinforcement Learning. In Maria Florina Balcan and Kilian Q. Weinberger, editors, Proceedings of the 33rd International Conference on Machine Learning, volume 48 of Proceedings of Machine Learning Research, pages 1928–1937, New York, NY, USA, 2016. PMLR Maximum-entropy RL puts it in the return itself, . In one state the regularized problem is solved by the Boltzmann policy (it is the case uniform of the computation in Section 13.8.7), and the corresponding soft Bellman equations make the “soft-max over action values” that we dismissed in Section 13.1 the exact optimum of a modified problem. Soft actor–critic (SAC) learns soft -functions off-policy from a replay buffer (with two critics, as TD3), and moves the actor towards by minimizing a KL divergence, using the reparameterization to differentiate through the sampled action; a follow-up by the same authors also tunes automatically to a target entropy.Tuomas Haarnoja, Aurick Zhou, Pieter Abbeel, and Sergey Levine. Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor. In Jennifer Dy and Andreas Krause, editors, Proceedings of the 35th International Conference on Machine Learning, volume 80 of Proceedings of Machine Learning Research, pages 1861–1870, Stockholm, Sweden, 2018. PMLRBeyond Sutton and Barto (2018). Soft actor–critic (Haarnoja, Zhou, Abbeel and Levine, ICML 2018) is, with TD3, the standard off-policy actor–critic for continuous control.
13.8.6Global Convergence of Policy Gradient#
is not concave in , and the book promises only local optima. For tabular soft-max policies with exact gradients much more is now known. Agarwal, Kakade, Lee and Mahajan prove a gradient domination property: suboptimality is bounded by a multiple of the gradient norm, with a constant that involves the mismatch between the optimal policy’s state distribution and the start distribution .Alekh Agarwal, Sham M. Kakade, Jason D. Lee, and Gaurav Mahajan. On the Theory of Policy Gradient Methods: Optimality, Approximation, and Distribution Shift. Journal of Machine Learning Research, 22(98):1–76, 2021. URL http://jmlr.org/papers/v22/19-736.html Consequently every stationary point is globally optimal when has full support; soft-max policy gradient converges to the optimum asymptotically, a log-barrier regularized version at a polynomial rate, and the natural policy gradient at a rate that does not depend on the numbers of states and actions. Mei, Xiao, Szepesvári and Schuurmans showed that soft-max policy gradient itself converges at rate , through a non-uniform Łojasiewicz inequality, but with constants that can be very poor, while entropy regularization yields linear convergence to the regularized optimum.Jincheng Mei, Chenjun Xiao, Csaba Szepesvári, and Dale Schuurmans. On the Global Convergence Rates of Softmax Policy Gradient Methods. In Hal Daumé III and Aarti Singh, editors, Proceedings of the 37th International Conference on Machine Learning, volume 119 of Proceedings of Machine Learning Research, pages 6820–6829. PMLR, 2020 The picture that emerges: the parameterization matters (soft-max gradients vanish near deterministic policies, which slows plain PG), and natural or mirror-descent steps fix it.Beyond Sutton and Barto (2018). Global convergence theory for policy gradient methods (Agarwal et al., JMLR 2021; Mei et al., ICML 2020) postdates the book.
13.8.7Policy Gradients for Language Models: RLHF, DPO and GRPO#
A language model is a policy: the state is the prompt plus the tokens generated so far, an action is the next token, transitions are deterministic, and a reward arrives when the response is complete. Reinforcement learning from human feedback (RLHF) fits a reward model to human comparisons with the Bradley–Terry model ,Paul F. Christiano, Jan Leike, Tom B. Brown, Miljan Martic, Shane Legg, and Dario Amodei. Deep Reinforcement Learning from Human Preferences. In Isabelle Guyon, Ulrike von Luxburg, Samy Bengio, Hanna Wallach, Rob Fergus, S. V. N. Vishwanathan, and Roman Garnett, editors, Advances in Neural Information Processing Systems 30 (NIPS 2017), volume 30, pages 4299–4307. Curran Associates, Inc., 2017 then maximizes, with PPO, the KL-regularized objectiveLong Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Carroll L. Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, John Schulman, Jacob Hilton, Fraser Kelton, Luke Miller, Maddie Simens, Amanda Askell, Peter Welinder, Paul F. Christiano, Jan Leike, and Ryan Lowe. Training Language Models to Follow Instructions with Human Feedback. In S. Koyejo, S. Mohamed, A. Agarwal, D. Belgrave, K. Cho, and A. Oh, editors, Advances in Neural Information Processing Systems 35 (NeurIPS 2022), volume 35, pages 27730–27744. Curran Associates, Inc., 2022. doi: 10.52202/068431-2011
(13.19)where is the supervised model the policy must not drift far from.
DPO. The maximizer of (13.19) is known in closed form, . Inverting it, , and in the Bradley–Terry difference the intractable cancels. Fitting the policy directly to the comparisons by maximum likelihood gives direct preference optimization:Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, and Chelsea Finn. Direct Preference Optimization: Your Language Model is Secretly a Reward Model. In A. Oh, T. Naumann, A. Globerson, K. Saenko, M. Hardt, and S. Levine, editors, Advances in Neural Information Processing Systems 36 (NeurIPS 2023), volume 36, pages 53728–53741. Curran Associates, Inc., 2023. doi: 10.52202/075280-2338
(13.20)No reward model, no sampling, no RL loop: a classification loss. The derivation rests on two facts, checked below with two responses: the KL-regularized optimum is tilted by , and the log-ratio difference recovers the reward difference.
Maximize over , then form the odds ratio of to .const dpoObj = await wl`Function[q, q Subscript[r, 1] + (1 - q) Subscript[r, 2] - \[Beta] (q Log[q/Subscript[\[Pi], 1]] + (1 - q) Log[(1 - q)/(1 - Subscript[\[Pi], 1])])]`
const dpoStar = await wl`Simplify[q /. First[Solve[D[${dpoObj}[q], q] == 0, q]]]`
await show`{${dpoStar}, Simplify[(${dpoStar}/Subscript[\[Pi], 1])/((1 - ${dpoStar})/(1 - Subscript[\[Pi], 1]))]}`Taking of the second entry gives , the argument of in (13.20).
GRPO. For reasoning tasks with verifiable rewards (is the final answer correct?), group relative policy optimization drops the critic of PPO.Zhihong Shao, Peiyi Wang, Qihao Zhu, Runxin Xu, Junxiao Song, Xiao Bi, Haowei Zhang, Mingchuan Zhang, Y. K. Li, Y. Wu, and Daya Guo. DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models. arXiv preprint arXiv:2402.03300, 2024. doi: 10.48550/arXiv.2402.03300 For each prompt it samples a group of responses with rewards and gives every token of response the advantage
(13.21)which is then used in the clipped objective (13.16) together with a KL penalty to . Read through this chapter, GRPO is REINFORCE with baseline ((13.9)) in which the baseline is the empirical mean return of the group, the learned being replaced by Monte Carlo samples of the same state, plus PPO’s clipping. Two subtleties follow from Proposition 13.5. The group mean includes itself, which is not independent of ; the expected update is still in the gradient direction but shrunk by the factor , as the check below shows for on a two-armed bandit. The leave-one-out mean of the other rewards is an exactly unbiased baseline (RLOO).Wouter Kool, Herke van Hoof, and Max Welling. Buy 4 REINFORCE Samples, Get a Baseline for Free! In Deep Reinforcement Learning Meets Structured Prediction, ICLR 2019 Workshop, 2019. URL https://openreview.net/forum?id=r1lgTGL5DE; and Arash Ahmadian, Chris Cremer, Matthias Gallé, Marzieh Fadaee, Julia Kreutzer, Olivier Pietquin, Ahmet Üstün, and Sara Hooker. Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs. In Lun-Wei Ku, Andre Martins, and Vivek Srikumar, editors, Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 12248–12267, Bangkok, Thailand, 2024. Association for Computational Linguistics. doi: 10.18653/v1/2024.acl-long.662 The division by the standard deviation, on the other hand, rescales each prompt by a data-dependent factor, so the update is no longer an unbiased estimate of : prompts on which the model is almost always right or almost always wrong get large weights. “Dr. GRPO” removes this normalization, together with a per-response length normalization that biased the length of responses.Zichen Liu, Changyu Chen, Wenjun Li, Penghui Qi, Tianyu Pang, Chao Du, Wee Sun Lee, and Min Lin. Understanding R1-Zero-Like Training: A Critical Perspective. arXiv preprint arXiv:2503.20783, 2025. doi: 10.48550/arXiv.2503.20783
Expected group-mean REINFORCE update with samples from , divided by the true gradient ; scores w.r.t. are and .const grpoArm = await wl`{1 - p, p}`
await show`Simplify[Sum[${grpoArm}[[i]] ${grpoArm}[[j]] ${grpoArm}[[k]] ({Subscript[r, 0], Subscript[r, 1]}[[i]] - ({Subscript[r, 0], Subscript[r, 1]}[[i]] + {Subscript[r, 0], Subscript[r, 1]}[[j]] + {Subscript[r, 0], Subscript[r, 1]}[[k]])/3) {-1/(1 - p), 1/p}[[i]], {i, 2}, {j, 2}, {k, 2}] / D[${grpoArm} . {Subscript[r, 0], Subscript[r, 1]}, p]]`The factor is in general: the terms with vanish by independence and Proposition 13.5, and only the part of the mean survives. DeepSeek-R1-Zero then showed that GRPO with nothing but rule-based rewards for correctness and format, applied directly to a pre-trained model, produces long chains of reasoning, self-verification and markedly better performance on mathematics and coding benchmarks.Daya Guo, Dejian Yang, Haowei Zhang, Junxiao Song, Peiyi Wang, Qihao Zhu, Runxin Xu, Ruoyu Zhang, Shirong Ma, Xiao Bi, et al. DeepSeek-R1 Incentivizes Reasoning in LLMs through Reinforcement Learning. Nature, 645(8081):633–638, Springer Nature, 2025. doi: 10.1038/s41586-025-09422-z. Preprint: DeepSeek-AI, “DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning”, arXiv:2501.12948 (2025)Beyond Sutton and Barto (2018). RLHF with PPO (Christiano et al., 2017; Ouyang et al., 2022), DPO (Rafailov et al., 2023), GRPO (Shao et al., 2024; Guo et al. for DeepSeek-AI, 2025) and the analysis of its biases (Liu et al., 2025). All are REINFORCE-family estimators with the baselines and trust regions of this chapter.
This closes Part II. The policy-gradient and actor–critic methods of this chapter, with the TD errors and traces of the previous ones, are also the reinforcement learning algorithms that have been most directly compared with animal learning and with the dopamine system, the subject of Chapter 14.
13.9Exercises#
Exercise 13.12. (The book’s Exercise 13.5.) A Bernoulli-logistic unit outputs with . Its preferences satisfy . (a) Show that the soft-max (13.2) gives . (b) Compute the eligibility vector and write the REINFORCE update.
Solution
(a) . (b) Writing , and , whose derivatives in are and , that is, in both cases. By the chain rule
which is the eligibility of the soft-max (13.7) for two actions, and also the gradient of the log-likelihood in logistic regression: REINFORCE here is logistic regression on the agent’s own actions, weighted by the return.
The derivative of in , minus , for and .await show`Simplify[{D[Log[1/(1 + Exp[-z])], z], D[Log[1 - 1/(1 + Exp[-z])], z]} - ({1, 0} - 1/(1 + Exp[-z]))]`Exercise 13.13. Verify Theorem 13.9 symbolically on a two-state continuing MDP: in each state the action stay (chosen with probability ) keeps the state and the action switch moves to the other one, with arbitrary rewards . Compute , , the differential values and , and compare with .
Solution
The chain has , whose stationary distribution is (flows across the cut balance: ; see Section A.3). The differential values solve , determined up to a constant, which we fix by ; then .
, , differential values with , and the difference between the two sides of the theorem.const cSg = await wl`{1/(1 + Exp[-Subscript[\[Theta], 1]]), 1/(1 + Exp[-Subscript[\[Theta], 2]])}`
const cRew = await wl`{{Subscript[r, 1, 1], Subscript[r, 1, 2]}, {Subscript[r, 2, 1], Subscript[r, 2, 2]}}`
const cTab = await wl`{{${cSg}[[1]], 1 - ${cSg}[[1]]}, {${cSg}[[2]], 1 - ${cSg}[[2]]}}`
const cP = await wl`{{${cSg}[[1]], 1 - ${cSg}[[1]]}, {1 - ${cSg}[[2]], ${cSg}[[2]]}}`
const cMu = await wl`Simplify[{1 - ${cSg}[[2]], 1 - ${cSg}[[1]]}/(2 - ${cSg}[[1]] - ${cSg}[[2]])]`
const cRbar = await wl`Simplify[${cMu} . Table[${cTab}[[s]] . ${cRew}[[s]], {s, 2}]]`
const cV = await wl`With[{sol = First[Solve[{h1 == ${cTab}[[1]] . ${cRew}[[1]] - ${cRbar} + ${cP}[[1]] . {h1, h2}, h1 == 0}, {h1, h2}]]}, {h1, h2} /. sol]`
const cQ = await wl`{{${cRew}[[1, 1]] - ${cRbar} + ${cV}[[1]], ${cRew}[[1, 2]] - ${cRbar} + ${cV}[[2]]}, {${cRew}[[2, 1]] - ${cRbar} + ${cV}[[2]], ${cRew}[[2, 2]] - ${cRbar} + ${cV}[[1]]}}`
const cTh = await wl`{Subscript[\[Theta], 1], Subscript[\[Theta], 2]}`
await show`Simplify[D[${cRbar}, {${cTh}}] - Sum[${cMu}[[s]] Sum[${cQ}[[s, a]] D[${cTab}[[s, a]], {${cTh}}], {a, 2}], {s, 2}]]`The difference vanishes identically: in the average-reward case the theorem is an equality, with no expected-episode-length constant. Note that only the first equation of the differential Bellman system (that of state 1) was needed beyond the normalization : the second is implied, because was computed with the stationary , so times the residual of the system vanishes identically.
Exercise 13.14. A one-step problem with a scalar action has reward , and the policy is with fixed. Compute the mean and the variance of the REINFORCE estimator of . What happens as ? Compare with the deterministic policy gradient (13.18).
Solution
Here , so . Write for the distance from the optimum.
Exact mean and variance of the score-function estimator for a Gaussian policy and a quadratic reward.await show`Assuming[\[Sigma] > 0, Simplify[{Expectation[-(a - c)^2 (a - \[Mu])/\[Sigma]^2, a \[Distributed] NormalDistribution[\[Mu], \[Sigma]]], Expand[Expectation[((a - c)^2 (a - \[Mu])/\[Sigma]^2)^2, a \[Distributed] NormalDistribution[\[Mu], \[Sigma]]] - 4 (\[Mu] - c)^2]} /. \[Mu] -> c + \[CapitalDelta]]]`The mean is the exact gradient , but the variance contains the term that blows up as : far from the optimum, a nearly deterministic Gaussian policy gets an almost useless REINFORCE signal. A baseline helps (the term comes from the large mean reward), but cannot remove the scaling of the score. The deterministic policy gradient uses directly: the exact gradient with zero variance, at the price of needing , that is, a differentiable critic.
Exercise 13.15. Most implementations of Algorithm 13.4 and Algorithm 13.7 with omit the factor (the variable ). Using (13.4), describe what the expected update then is, and argue why it is not, in general, the gradient of .
Solution
Without the expected update over an episode is , where counts visits undiscounted while is still discounted. The theorem’s proof shows that the gradient of the discounted objective has weights , so the two differ whenever states are visited at different times. The common update is the gradient of no fixed function in general: the discount factor appears twice in Theorem 13.2, in and in , and the implementation keeps one of them. Nota and Thomas showed that the resulting vector field is not the gradient of any function, call such methods semi-gradient, and construct an MDP on which they converge to the worst policy.Chris Nota and Philip S. Thomas. Is the Policy Gradient a Gradient? In Proceedings of the 19th International Conference on Autonomous Agents and Multiagent Systems (AAMAS 2020), pages 939–947, Auckland, New Zealand, 2020. IFAAMAS In practice is usually best viewed as a variance-reduction device for the undiscounted objective, with the “right” weighting and a biased critic.