Chapter 13

Policy Gradient Methods

Every control method so far, up to the Sarsa(λ\lambda) of Chapter 12, has been built on action values: learn QQ, then act greedily or ε\varepsilon-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 π(a∣s,𝜽)≐Pr⁡{At=a∣St=s,𝜽t=𝜽}\pi(a \mid s, \boldsymbol{\theta}) \doteq \Pr\{A_t = a \mid S_t = s, \boldsymbol{\theta}_t = \boldsymbol{\theta}\} of a parameter 𝜽∈ℝd′\boldsymbol{\theta} \in \mathbb{R}^{d'}, and it is improved by stochastic gradient ascent on a scalar performance measure J(𝜽)J(\boldsymbol{\theta}):

𝜽t+1=𝜽t+α ∇J(𝜽t)̂,𝔼[∇J(𝜽t)̂]∝∇J(𝜽t). \boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t + \alpha\,\widehat{\nabla J(\boldsymbol{\theta}_t)}, \qquad \mathbb{E}\bigl[\widehat{\nabla J(\boldsymbol{\theta}_t)}\bigr] \propto \nabla J(\boldsymbol{\theta}_t). (13.1)

A value function may still be learned, with weights 𝐰∈ℝd\mathbf{w} \in \mathbb{R}^d as in v^(s,𝐰)\hat v(s, \mathbf{w}), 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 h(s,a,𝜽)∈ℝh(s, a, \boldsymbol{\theta}) \in \mathbb{R} for each pair, turned into probabilities by

π(a∣s,𝜽)≐eh(s,a,𝜽)∑beh(s,b,𝜽),h(s,a,𝜽)=𝜽⊤𝐱(s,a), \pi(a \mid s, \boldsymbol{\theta}) \doteq \frac{e^{h(s, a, \boldsymbol{\theta})}}{\sum_b e^{h(s, b, \boldsymbol{\theta})}}, \qquad h(s, a, \boldsymbol{\theta}) = \boldsymbol{\theta}^\top \mathbf{x}(s, a), (13.2)

where the linear preference on the right, with features 𝐱(s,a)∈ℝd′\mathbf{x}(s, a) \in \mathbb{R}^{d'} built as in Chapter 9, is one option among many (a deep network computing hh is another). Four reasons favor this kind of parameterization over ε\varepsilon-greedy selection on q^\hat q.

  1. It can become deterministic. An ε\varepsilon-greedy policy keeps probability ε/∣𝒜∣\varepsilon/\lvert\mathcal{A}\rvert on every action forever. A soft-max over action values does not help either: the values converge to finite numbers qπ(s,a)q_\pi(s,a), 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.
  2. 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).
  3. 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.
  4. 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 ε\varepsilon-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 𝜽↦π(⋅∣s,𝜽)\boldsymbol{\theta} \mapsto \pi(\cdot \mid s, \boldsymbol{\theta}) is smooth, so JJ is a smooth function of 𝜽\boldsymbol{\theta} 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 −1-1 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 𝐱(s,right)=(1,0)⊤\mathbf{x}(s, \text{right}) = (1, 0)^\top and 𝐱(s,left)=(0,1)⊤\mathbf{x}(s, \text{left}) = (0, 1)^\top for every ss, so the agent cannot tell the states apart and every policy it can represent chooses right with the same probability pp everywhere.

Because q^(s,a,𝐰)=𝐰⊤𝐱(s,a)\hat q(s, a, \mathbf{w}) = \mathbf{w}^\top\mathbf{x}(s, a) does not depend on ss, an ε\varepsilon-greedy agent has only two policies: right with probability 1−ε/21 - \varepsilon/2 in every state, or left with that probability. The soft-max policy can choose any p∈(0,1)p \in (0, 1). The value of the start state as a function of pp follows from the Bellman equations of the three states,

v1=−1+p v2+(1−p) v1,v2=−1+p v1+(1−p) v3,v3=−1+(1−p) v2, \begin{aligned} v_1 &= -1 + p\,v_2 + (1 - p)\,v_1, \\ v_2 &= -1 + p\,v_1 + (1 - p)\,v_3, \\ v_3 &= -1 + (1 - p)\,v_2, \end{aligned}

where the swapped middle state sends right back to state 1, and J(p)=v1J(p) = v_1. 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 pp and keep v1=J(p)v_1 = J(p).
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]]]`
J(p)=−2(−2+p)(−1+p)p J(p) = -\frac{2 (-2+p)}{(-1+p) p} Set J′(p)=0J'(p) = 0 on (0,1)(0,1) and evaluate JJ at the root: the optimal probability is irrational.
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}]}]`
(p∗, J(p∗), numerically)={2−2,−6−42,{0.585786,−11.6569}} \bigl(p^*,\ J(p^*),\ \text{numerically}\bigr) = \left\{2-\sqrt{2},-6-4 \sqrt{2},\{0.585786,-11.6569\}\right\}

So J(p)=−2(2−p)/(p(1−p))J(p) = -2(2 - p)/\bigl(p(1 - p)\bigr), which tends to −∞-\infty at both ends: with p→0p \to 0 the agent never leaves the first state, with p→1p \to 1 it bounces forever between the first two. The optimum p∗=2−2≈0.586p^* = 2 - \sqrt{2} \approx 0.586 gives J(p∗)=−6−42≈−11.66J(p^*) = -6 - 4\sqrt{2} \approx -11.66, against −44.2-44.2 and −82.1-82.1 for the two ε\varepsilon-greedy policies with ε=0.1\varepsilon = 0.1 (Figure 13.1). No method that acts (nearly) greedily on these features can get anywhere near it.

Figure 13.1: The exact performance J(p)=−2(2−p)/(p(1−p))J(p) = -2(2-p)/\bigl(p(1-p)\bigr) of the short corridor with switched actions. The best stochastic policy, at p∗=2−2p^* = 2 - \sqrt{2}, is about four times better than the better of the two policies available to an ε\varepsilon-greedy action-value method (ε=0.1\varepsilon = 0.1).The value of the start state of the short corridor as a function of the probability p of choosing right: a concave curve tending to minus infinity at p = 0 and p = 1, with its maximum about -11.66 at p = 2 - sqrt 2, and the two epsilon-greedy policies marked at p = 0.05 (about -82) and p = 0.95 (about -44)

13.2The Policy Gradient Theorem

In the episodic case performance is the value of the start state,Assuming one fixed start state s0s_0 loses no generality: a random start is a fixed dummy state with a single action whose transition draws the real start state.

J(𝜽)≐vπ𝜽(s0). J(\boldsymbol{\theta}) \doteq v_{\pi_{\boldsymbol{\theta}}}(s_0). (13.3)

The difficulty is visible in the definition. Changing 𝜽\boldsymbol{\theta} 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 γ∈[0,1]\gamma \in [0, 1], which costs nothing and produces the γt\gamma^t factors of the algorithms directly (the book proves the case γ=1\gamma = 1 and leaves the general one as its Exercise 13.2). Define the discounted expected number of visits to ss in an episode from s0s_0,

η(s)≐∑k=0∞γkPr⁡{Sk=s∣S0=s0}=𝔼π[∑t=0T−1γt 𝟙{St=s}], \eta(s) \doteq \sum_{k=0}^\infty \gamma^k \Pr\{S_k = s \mid S_0 = s_0\} = \mathbb{E}_\pi\Bigl[\sum_{t=0}^{T-1}\gamma^t\,\mathbb{1}\{S_t = s\}\Bigr], (13.4)

where the event Sk=sS_k = s includes “not yet terminated”. For γ=1\gamma = 1 this is the expected number of visits, and normalizing it gives the on-policy distribution μ(s)=η(s)/∑s′η(s′)\mu(s) = \eta(s)/\sum_{s'}\eta(s') of Chapter 9.

Theorem 13.2 (Policy Gradient Theorem, Episodic Case). Let the MDP be finite and episodic, let π(a∣s,𝜽)\pi(a \mid s, \boldsymbol{\theta}) be differentiable in 𝜽\boldsymbol{\theta}, and suppose every episode terminates with probability one from every state, for every 𝜽\boldsymbol{\theta}. Then

∇J(𝜽)=∑sη(s)∑aqπ(s,a) ∇π(a∣s,𝜽)∝∑sμ(s)∑aqπ(s,a) ∇π(a∣s,𝜽), \begin{aligned} \nabla J(\boldsymbol{\theta}) &= \sum_s \eta(s) \sum_a q_\pi(s, a)\,\nabla\pi(a \mid s, \boldsymbol{\theta}) \\ &\propto \sum_s \mu(s) \sum_a q_\pi(s, a)\,\nabla\pi(a \mid s, \boldsymbol{\theta}), \end{aligned} (13.5)

where π=π𝜽\pi = \pi_{\boldsymbol{\theta}} and, for γ=1\gamma = 1, the constant of proportionality ∑sη(s)\sum_s \eta(s) is the expected length of an episode.

Proof. Write 𝐏π\mathbf{P}_\pi for the transition matrix among non-terminal states, 𝐏π(s,s′)=∑aπ(a∣s) p(s′∣s,a)\mathbf{P}_\pi(s, s') = \sum_a \pi(a \mid s)\,p(s' \mid s, a), which is substochastic because rows lose the probability of terminating. Under the termination assumption (𝐈−γ𝐏π)−1=∑k≥0(γ𝐏π)k(\mathbf{I} - \gamma\mathbf{P}_\pi)^{-1} = \sum_{k \ge 0}(\gamma\mathbf{P}_\pi)^k exists even for γ=1\gamma = 1 (see Section A.3), and 𝐯π=(𝐈−γ𝐏π)−1𝐫π\mathbf{v}_\pi = (\mathbf{I} - \gamma\mathbf{P}_\pi)^{-1}\mathbf{r}_\pi is a rational function of the action probabilities, hence differentiable in 𝜽\boldsymbol{\theta}. Gradients are with respect to 𝜽\boldsymbol{\theta} throughout; they are column vectors, and in matrix equations each state contributes a row ∇vπ(s)⊤\nabla v_\pi(s)^\top.

Step 1 (product rule). From vπ(s)=∑aπ(a∣s) qπ(s,a)v_\pi(s) = \sum_a \pi(a \mid s)\,q_\pi(s, a),

∇vπ(s)=∑a∇π(a∣s) qπ(s,a)+∑aπ(a∣s) ∇qπ(s,a). \nabla v_\pi(s) = \sum_a \nabla\pi(a \mid s)\,q_\pi(s, a) + \sum_a \pi(a \mid s)\,\nabla q_\pi(s, a).

Step 2 (only vπv_\pi depends on 𝜽\boldsymbol{\theta} inside qπq_\pi). Since qπ(s,a)=∑s′,rp(s′,r∣s,a)[r+γvπ(s′)]q_\pi(s, a) = \sum_{s', r} p(s', r \mid s, a)\bigl[r + \gamma v_\pi(s')\bigr] and neither the rewards nor the dynamics depend on 𝜽\boldsymbol{\theta}, ∇qπ(s,a)=γ∑s′p(s′∣s,a) ∇vπ(s′)\nabla q_\pi(s, a) = \gamma\sum_{s'} p(s' \mid s, a)\,\nabla v_\pi(s'). Writing 𝐠(s)≐∑aqπ(s,a)∇π(a∣s)\mathbf{g}(s) \doteq \sum_a q_\pi(s, a)\nabla\pi(a \mid s),

∇vπ(s)=𝐠(s)+γ∑s′𝐏π(s,s′) ∇vπ(s′), \nabla v_\pi(s) = \mathbf{g}(s) + \gamma\sum_{s'}\mathbf{P}_\pi(s, s')\,\nabla v_\pi(s'),

a Bellman equation for the gradient, with 𝐠\mathbf{g} in the role of the reward.

Step 3 (solve it). Stacking rows, ∇𝐯π=𝐠+γ𝐏π∇𝐯π\nabla\mathbf{v}_\pi = \mathbf{g} + \gamma\mathbf{P}_\pi\nabla\mathbf{v}_\pi, so

∇𝐯π=(𝐈−γ𝐏π)−1𝐠=∑k=0∞γk𝐏πk 𝐠. \nabla\mathbf{v}_\pi = (\mathbf{I} - \gamma\mathbf{P}_\pi)^{-1}\mathbf{g} = \sum_{k=0}^\infty \gamma^k\mathbf{P}_\pi^k\,\mathbf{g}.

The Neumann series is the book’s “repeated unrolling”. Its row s0s_0 has entries ∑kγk𝐏πk(s0,s)=∑kγkPr⁡{Sk=s∣S0=s0}=η(s)\sum_k \gamma^k\mathbf{P}_\pi^k(s_0, s) = \sum_k \gamma^k\Pr\{S_k = s \mid S_0 = s_0\} = \eta(s), which gives the equality in (13.5). Dividing and multiplying by ∑sη(s)\sum_s \eta(s) gives the proportionality. For γ=1\gamma = 1, ∑sη(s)=∑kPr⁡{T>k}=𝔼[T]\sum_s \eta(s) = \sum_k \Pr\{T > k\} = \mathbb{E}[T]. □

The derivative of the state distribution has disappeared: it is absorbed by the recursion of Step 2, because the effect of 𝜽\boldsymbol{\theta} on later states is again an effect of 𝜽\boldsymbol{\theta} on later actions, which the recursion counts where it happens. Two remarks on the constant. First, any positive constant can be absorbed into α\alpha, so “proportional” is all that stochastic gradient ascent needs. Second, for γ<1\gamma < 1 the weights η(s)\eta(s) 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 s0,s1s_0, s_1, each with two actions and a logistic policy π(a1∣si)=1/(1+e−θi)\pi(a_1 \mid s_i) = 1/(1 + e^{-\theta_i}). In s0s_0, a1a_1 moves to s1s_1 with reward r1r_1 and a2a_2 terminates with r2r_2; in s1s_1, a1a_1 terminates with r3r_3 and a2a_2 returns to s0s_0 with r4r_4, so s0s_0 may be visited many times. We compute J(𝜽)=vπ(s0)J(\boldsymbol{\theta}) = v_\pi(s_0) by solving the Bellman equations, differentiate it symbolically, and compare with the right-hand side of (13.5) (γ=1\gamma = 1).

Expected visits η⊤=𝐞s0⊤(𝐈−𝐏π)−1\eta^\top = \mathbf{e}_{s_0}^\top(\mathbf{I} - \mathbf{P}_\pi)^{-1}. Visits to s0s_0 exceed one because of the loop through s1s_1.
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}]]`
(η(s0),η(s1))={(1+eθ0)(1+eθ1)1+eθ1+eθ0+θ1,eθ0(1+eθ1)1+eθ1+eθ0+θ1} \bigl(\eta(s_0), \eta(s_1)\bigr) = \left\{\frac{\left(1+e^{\theta _0}\right) \left(1+e^{\theta _1}\right)}{1+e^{\theta _1}+e^{\theta _0+\theta _1}},\frac{e^{\theta _0} \left(1+e^{\theta _1}\right)}{1+e^{\theta _1}+e^{\theta _0+\theta _1}}\right\} Differentiate J=vπ(s0)J = v_\pi(s_0) directly and subtract ∑sη(s)∑aqπ(s,a)∇π(a∣s)\sum_s \eta(s)\sum_a q_\pi(s,a)\nabla\pi(a \mid s): the difference vanishes identically in θ0,θ1,r1,…,r4\theta_0, \theta_1, r_1, \dots, r_4.
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}]`
∇J(𝜽)−∑sη(s)∑aqπ(s,a)∇π(a∣s,𝜽)={0,0} \nabla J(\boldsymbol{\theta}) - \sum_s \eta(s)\sum_a q_\pi(s,a)\nabla\pi(a \mid s, \boldsymbol{\theta}) = \{0,0\}

13.3REINFORCE: Monte Carlo Policy Gradient

The right-hand side of (13.5) is an expectation over the states visited by π\pi, which is what makes it estimable by following π\pi. One could stop at the all-actions form, 𝜽←𝜽+α∑aq^(St,a,𝐰)∇π(a∣St,𝜽)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} + \alpha\sum_a \hat q(S_t, a, \mathbf{w})\nabla\pi(a \mid S_t, \boldsymbol{\theta}), which needs a learned q^\hat q. 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): ∇π=π ∇ln⁡π\nabla\pi = \pi\,\nabla\ln\pi.

Corollary 13.3 (The Gradient as an Expectation over Episodes). Under the assumptions of Theorem 13.2,

∇J(𝜽)=𝔼π[∑t=0T−1γt Gt ∇ln⁡π(At∣St,𝜽)]. \nabla J(\boldsymbol{\theta}) = \mathbb{E}_\pi\Bigl[\sum_{t=0}^{T-1}\gamma^t\,G_t\,\nabla\ln\pi(A_t \mid S_t, \boldsymbol{\theta})\Bigr]. (13.6)

Proof. By (13.4), a sum ∑sη(s)f(s)\sum_s \eta(s) f(s) equals 𝔼π[∑tγtf(St)]\mathbb{E}_\pi\bigl[\sum_t \gamma^t f(S_t)\bigr]. Apply this to f(s)=∑aqπ(s,a)∇π(a∣s)=∑aπ(a∣s) qπ(s,a)∇ln⁡π(a∣s)f(s) = \sum_a q_\pi(s, a)\nabla\pi(a \mid s) = \sum_a \pi(a \mid s)\,q_\pi(s, a)\nabla\ln\pi(a \mid s), a conditional expectation over At∼π(⋅∣St)A_t \sim \pi(\cdot \mid S_t), so that ∇J=𝔼π[∑tγtqπ(St,At)∇ln⁡π(At∣St)]\nabla J = \mathbb{E}_\pi\bigl[\sum_t \gamma^t q_\pi(S_t, A_t)\nabla\ln\pi(A_t \mid S_t)\bigr]. Finally, by the Markov property 𝔼π[Gt∣S0,A0,…,St,At]=qπ(St,At)\mathbb{E}_\pi[G_t \mid S_0, A_0, \dots, S_t, A_t] = q_\pi(S_t, A_t), and ∇ln⁡π(At∣St)\nabla\ln\pi(A_t \mid S_t) is known given that history, so the law of total expectation lets us replace qπ(St,At)q_\pi(S_t, A_t) by GtG_t. □

The vector ∇ln⁡π(At∣St,𝜽)=∇π(At∣St,𝜽)/π(At∣St,𝜽)\nabla\ln\pi(A_t \mid S_t, \boldsymbol{\theta}) = \nabla\pi(A_t \mid S_t, \boldsymbol{\theta})/\pi(A_t \mid S_t, \boldsymbol{\theta}) is the eligibility vector (statisticians call it the score). It is the only place where the parameterization enters. The update moves 𝜽\boldsymbol{\theta} in the direction that most increases the probability of repeating AtA_t in StS_t, 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 π(a∣s,𝜽)\pi(a \mid s, \boldsymbol{\theta}). Parameter: step size α>0\alpha > 0. Initialize 𝜽∈ℝd′\boldsymbol{\theta} \in \mathbb{R}^{d'} (e.g., to 𝟎\mathbf{0}).

Loop for each episode:

  1. Generate S0,A0,R1,…,ST−1,AT−1,RTS_0, A_0, R_1, \dots, S_{T-1}, A_{T-1}, R_T following π(⋅∣⋅,𝜽)\pi(\cdot \mid \cdot, \boldsymbol{\theta}).
  2. For t=0,1,…,T−1t = 0, 1, \dots, T-1:
    1. G←∑k=t+1Tγk−t−1RkG \leftarrow \sum_{k=t+1}^{T}\gamma^{k-t-1}R_k (=Gt)\quad(= G_t)
    2. 𝜽←𝜽+α γt G ∇ln⁡π(At∣St,𝜽)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} + \alpha\,\gamma^t\,G\,\nabla\ln\pi(A_t \mid S_t, \boldsymbol{\theta})

Summed over an episode, and with 𝜽\boldsymbol{\theta} held fixed during it, the increments have expectation exactly α∇J(𝜽)\alpha\nabla J(\boldsymbol{\theta}) by Corollary 13.3. REINFORCE is therefore a genuine stochastic gradient method: for small α\alpha 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 JJ. Two details of the estimator deserve attention. It uses GtG_t, the return after tt, rather than the whole G0G_0: rewards earned before AtA_t cannot depend on it, and indeed 𝔼[Rk∇ln⁡π(At∣St)]=0\mathbb{E}[R_k\nabla\ln\pi(A_t \mid S_t)] = 0 for k≤tk \le t 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):

∇ln⁡π(a∣s,𝜽)=𝐱(s,a)−∑bπ(b∣s,𝜽) 𝐱(s,b), \nabla\ln\pi(a \mid s, \boldsymbol{\theta}) = \mathbf{x}(s, a) - \sum_b \pi(b \mid s, \boldsymbol{\theta})\,\mathbf{x}(s, b), (13.7)

the feature vector of the chosen action minus its average under the policy. It follows from ln⁡π(a∣s)=𝜽⊤𝐱(s,a)−ln⁡∑be𝜽⊤𝐱(s,b)\ln\pi(a \mid s) = \boldsymbol{\theta}^\top\mathbf{x}(s, a) - \ln\sum_b e^{\boldsymbol{\theta}^\top\mathbf{x}(s, b)} by differentiating the log-sum-exp.

Three actions with symbolic feature vectors 𝐱b∈ℝ2\mathbf{x}_b \in \mathbb{R}^2: the gradient of ln⁡π(a1)\ln\pi(a_1) 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}])]`
∇ln⁡π(a1∣s,𝜽)−(𝐱1−∑bπ(b∣s,𝜽) 𝐱b)={0,0} \nabla\ln\pi(a_1 \mid s, \boldsymbol{\theta}) - \Bigl(\mathbf{x}_1 - \sum_b \pi(b \mid s, \boldsymbol{\theta})\,\mathbf{x}_b\Bigr) = \{0,0\}

13.4Baselines

Any function of the state can be subtracted from the action values without changing the gradient:

∇J(𝜽)∝∑sμ(s)∑a(qπ(s,a)−b(s))∇π(a∣s,𝜽). \nabla J(\boldsymbol{\theta}) \propto \sum_s \mu(s)\sum_a \bigl(q_\pi(s, a) - b(s)\bigr)\nabla\pi(a \mid s, \boldsymbol{\theta}). (13.8)

Proposition 13.5 (Baselines Do Not Bias the Gradient). Let b(s)b(s) be any function of the state, or a random variable that is conditionally independent of AtA_t given StS_t. Then 𝔼π[b(St) ∇ln⁡π(At∣St,𝜽)∣St=s]=𝟎\mathbb{E}_\pi\bigl[b(S_t)\,\nabla\ln\pi(A_t \mid S_t, \boldsymbol{\theta}) \mid S_t = s\bigr] = \mathbf{0}, for discrete and for continuous actions.

Proof. For discrete actions, ∑aπ(a∣s) b(s) ∇ln⁡π(a∣s)=b(s) ∇∑aπ(a∣s)=b(s) ∇1=𝟎\sum_a \pi(a \mid s)\,b(s)\,\nabla\ln\pi(a \mid s) = b(s)\,\nabla\sum_a \pi(a \mid s) = b(s)\,\nabla 1 = \mathbf{0}. For a density, the same computation with ∫∇π(a∣s) da=∇∫π(a∣s) da=𝟎\int \nabla\pi(a \mid s)\,da = \nabla\int\pi(a \mid s)\,da = \mathbf{0}, where differentiation under the integral is justified for the smooth families used in practice (dominated convergence). For a random bb, 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,

𝜽t+1≐𝜽t+α γt(Gt−b(St))∇ln⁡π(At∣St,𝜽t), \boldsymbol{\theta}_{t+1} \doteq \boldsymbol{\theta}_t + \alpha\,\gamma^t\bigl(G_t - b(S_t)\bigr)\nabla\ln\pi(A_t \mid S_t, \boldsymbol{\theta}_t), (13.9)

with a learned b(St)=v^(St,𝐰)b(S_t) = \hat v(S_t, \mathbf{w}), gives the following algorithm. The value step size is easy to set (for linear v^\hat v 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 π(a∣s,𝜽)\pi(a \mid s, \boldsymbol{\theta}) and v^(s,𝐰)\hat v(s, \mathbf{w}). Parameters: step sizes α𝜽>0\alpha^{\boldsymbol{\theta}} > 0, α𝐰>0\alpha^{\mathbf{w}} > 0. Initialize 𝜽∈ℝd′\boldsymbol{\theta} \in \mathbb{R}^{d'}, 𝐰∈ℝd\mathbf{w} \in \mathbb{R}^d.

Loop for each episode:

  1. Generate S0,A0,R1,…,ST−1,AT−1,RTS_0, A_0, R_1, \dots, S_{T-1}, A_{T-1}, R_T following π(⋅∣⋅,𝜽)\pi(\cdot \mid \cdot, \boldsymbol{\theta}).
  2. For t=0,1,…,T−1t = 0, 1, \dots, T-1:
    1. G←∑k=t+1Tγk−t−1RkG \leftarrow \sum_{k=t+1}^{T}\gamma^{k-t-1}R_k
    2. δ←G−v^(St,𝐰)\delta \leftarrow G - \hat v(S_t, \mathbf{w})
    3. 𝐰←𝐰+α𝐰 δ ∇v^(St,𝐰)\mathbf{w} \leftarrow \mathbf{w} + \alpha^{\mathbf{w}}\,\delta\,\nabla\hat v(S_t, \mathbf{w})
    4. 𝜽←𝜽+α𝜽 γt δ ∇ln⁡π(At∣St,𝜽)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} + \alpha^{\boldsymbol{\theta}}\,\gamma^t\,\delta\,\nabla\ln\pi(A_t \mid S_t, \boldsymbol{\theta})

Which baseline is best? Consider a single step with score 𝐠=∇ln⁡π(A∣s)\mathbf{g} = \nabla\ln\pi(A \mid s) and return GG. Because the mean of (G−b)𝐠(G - b)\mathbf{g} does not depend on bb, minimizing the total variance (the trace of the covariance) is the same as minimizing 𝔼∥(G−b)𝐠∥2=𝔼[G2∥𝐠∥2]−2b 𝔼[G∥𝐠∥2]+b2 𝔼∥𝐠∥2\mathbb{E}\lVert(G - b)\mathbf{g}\rVert^2 = \mathbb{E}[G^2\lVert\mathbf{g}\rVert^2] - 2b\,\mathbb{E}[G\lVert\mathbf{g}\rVert^2] + b^2\,\mathbb{E}\lVert\mathbf{g}\rVert^2, a parabola in bb with minimum at

b∗(s)=𝔼[G ∥∇ln⁡π(A∣s)∥2∣S=s]𝔼[∥∇ln⁡π(A∣s)∥2∣S=s]. b^*(s) = \frac{\mathbb{E}\bigl[G\,\lVert\nabla\ln\pi(A \mid s)\rVert^2 \mid S = s\bigr]}{\mathbb{E}\bigl[\lVert\nabla\ln\pi(A \mid s)\rVert^2 \mid S = s\bigr]}. (13.10)

This is a score-weighted mean of the return, not the plain mean vπ(s)v_\pi(s). The two coincide when ∥𝐠∥2\lVert\mathbf{g}\rVert^2 is uncorrelated with GG, and vπv_\pi 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, π(1)=p=1/(1+e−θ)\pi(1) = p = 1/(1 + e^{-\theta}), and deterministic rewards r1,r2r_1, r_2 shows how different b∗b^* can be from the mean.

Score of each arm with respect to the logit θ\theta, then the minimizer of 𝔼[(rA−b)2gA2]\mathbb{E}[(r_A - b)^2 g_A^2], rewritten in terms of p=π(1)p = \pi(1).
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)]]]`
b∗=−((−1+p)r1)+pr2 b^* = -\left((-1+p) r_1\right)+p r_2

The optimal baseline is b∗=(1−p) r1+p r2b^* = (1 - p)\,r_1 + p\,r_2: each arm’s reward is weighted by the probability of the other arm, the opposite of the mean p r1+(1−p) r2p\,r_1 + (1-p)\,r_2. The rare arm has the larger score (∣g2∣=p\lvert g_2\rvert = p versus ∣g1∣=1−p\lvert g_1\rvert = 1 - p when p>1/2p > 1/2), 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 μ\mu and σ\sigma) 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]]]}`
(∑a∇π(a), 𝔼[∇(μ,σ)ln⁡𝒩(A;μ,σ2)])={{0,0,0},{0,0}} \Bigl(\textstyle\sum_a \nabla\pi(a),\ \mathbb{E}\bigl[\nabla_{(\mu,\sigma)}\ln\mathcal{N}(A; \mu, \sigma^2)\bigr]\Bigr) = \{\{0,0,0\},\{0,0\}\}

13.5Actor–Critic Methods

REINFORCE with baseline learns a value function but is not an actor–critic method: its v^\hat v 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 GtG_t by the one-step return Gt:t+1=Rt+1+γv^(St+1,𝐰)G_{t:t+1} = R_{t+1} + \gamma\hat v(S_{t+1}, \mathbf{w}) and keeps v^(St,𝐰)\hat v(S_t, \mathbf{w}) as the baseline:

𝜽t+1≐𝜽t+α(Rt+1+γv^(St+1,𝐰)−v^(St,𝐰))∇ln⁡π(At∣St,𝜽t)=𝜽t+α δt ∇ln⁡π(At∣St,𝜽t), \begin{aligned} \boldsymbol{\theta}_{t+1} &\doteq \boldsymbol{\theta}_t + \alpha\bigl(R_{t+1} + \gamma\hat v(S_{t+1}, \mathbf{w}) - \hat v(S_t, \mathbf{w})\bigr)\nabla\ln\pi(A_t \mid S_t, \boldsymbol{\theta}_t) \\ &= \boldsymbol{\theta}_t + \alpha\,\delta_t\,\nabla\ln\pi(A_t \mid S_t, \boldsymbol{\theta}_t), \end{aligned} (13.11)

with δt\delta_t the TD error (6.2). Why should the TD error be the right signal for the actor? Define the advantage adv⁡π(s,a)≐qπ(s,a)−vπ(s)\operatorname{adv}_\pi(s, a) \doteq q_\pi(s, a) - v_\pi(s), the amount by which taking aa and then following π\pi beats following π\pi from the start. By (13.8) with b=vπb = v_\pi, the policy gradient is ∑sη(s)∑aπ(a∣s)adv⁡π(s,a)∇ln⁡π(a∣s)\sum_s\eta(s)\sum_a \pi(a \mid s)\operatorname{adv}_\pi(s, a)\nabla\ln\pi(a \mid s). And if the critic were exact, v^=vπ\hat v = v_\pi,

𝔼π[δt∣St=s,At=a]=∑s′,rp(s′,r∣s,a)[r+γvπ(s′)]−vπ(s)=qπ(s,a)−vπ(s)=adv⁡π(s,a), \begin{aligned} \mathbb{E}_\pi[\delta_t \mid S_t = s, A_t = a] &= \sum_{s', r}p(s', r \mid s, a)\bigl[r + \gamma v_\pi(s')\bigr] - v_\pi(s) \\ &= q_\pi(s, a) - v_\pi(s) = \operatorname{adv}_\pi(s, a), \end{aligned}

so δt\delta_t 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: −v^(St)-\hat v(S_t) is a baseline and harmless by Proposition 13.5, whereas γv^(St+1)\gamma\hat v(S_{t+1}) replaces γvπ(St+1)\gamma v_\pi(S_{t+1}) 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 π(a∣s,𝜽)\pi(a \mid s, \boldsymbol{\theta}) and v^(s,𝐰)\hat v(s, \mathbf{w}). Parameters: step sizes α𝜽>0\alpha^{\boldsymbol{\theta}} > 0, α𝐰>0\alpha^{\mathbf{w}} > 0. Initialize 𝜽∈ℝd′\boldsymbol{\theta} \in \mathbb{R}^{d'}, 𝐰∈ℝd\mathbf{w} \in \mathbb{R}^d.

Loop for each episode:

  1. Initialize SS (first state of the episode); I←1I \leftarrow 1.
  2. Loop while SS is not terminal:
    1. A∼π(⋅∣S,𝜽)A \sim \pi(\cdot \mid S, \boldsymbol{\theta}); take action AA, observe S′S', RR.
    2. δ←R+γv^(S′,𝐰)−v^(S,𝐰)\delta \leftarrow R + \gamma\hat v(S', \mathbf{w}) - \hat v(S, \mathbf{w}) \quad (with v^(S′,𝐰)≐0\hat v(S', \mathbf{w}) \doteq 0 if S′S' is terminal)
    3. 𝐰←𝐰+α𝐰 δ ∇v^(S,𝐰)\mathbf{w} \leftarrow \mathbf{w} + \alpha^{\mathbf{w}}\,\delta\,\nabla\hat v(S, \mathbf{w})
    4. 𝜽←𝜽+α𝜽 I δ ∇ln⁡π(A∣S,𝜽)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} + \alpha^{\boldsymbol{\theta}}\,I\,\delta\,\nabla\ln\pi(A \mid S, \boldsymbol{\theta})
    5. I←γII \leftarrow \gamma I;  S←S′\ S \leftarrow S'

The factor I=γtI = \gamma^t 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 αt𝜽/αt𝐰→0\alpha^{\boldsymbol{\theta}}_t/\alpha^{\mathbf{w}}_t \to 0; 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 nn-step return Gt:t+nG_{t:t+n} or by the λ-return GtλG_t^\lambda of (12.1) gives forward-view actor–critic methods that interpolate between Algorithm 13.7 (λ=0\lambda = 0) and REINFORCE with baseline (λ=1\lambda = 1); 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 𝐳𝐰\mathbf{z}^{\mathbf{w}} of value gradients for the critic and a trace 𝐳𝜽\mathbf{z}^{\boldsymbol{\theta}} of eligibility vectors for the actor, each with its own decay rate.

Algorithm 13.8 (Actor–Critic with Eligibility Traces (episodic)). Input: differentiable π(a∣s,𝜽)\pi(a \mid s, \boldsymbol{\theta}) and v^(s,𝐰)\hat v(s, \mathbf{w}). Parameters: λ𝜽,λ𝐰∈[0,1]\lambda^{\boldsymbol{\theta}}, \lambda^{\mathbf{w}} \in [0, 1]; α𝜽,α𝐰>0\alpha^{\boldsymbol{\theta}}, \alpha^{\mathbf{w}} > 0. Initialize 𝜽\boldsymbol{\theta}, 𝐰\mathbf{w}.

Loop for each episode:

  1. Initialize SS; 𝐳𝜽←𝟎\mathbf{z}^{\boldsymbol{\theta}} \leftarrow \mathbf{0} (d′d' components); 𝐳𝐰←𝟎\mathbf{z}^{\mathbf{w}} \leftarrow \mathbf{0} (dd components); I←1I \leftarrow 1.
  2. Loop while SS is not terminal:
    1. A∼π(⋅∣S,𝜽)A \sim \pi(\cdot \mid S, \boldsymbol{\theta}); take action AA, observe S′S', RR.
    2. δ←R+γv^(S′,𝐰)−v^(S,𝐰)\delta \leftarrow R + \gamma\hat v(S', \mathbf{w}) - \hat v(S, \mathbf{w}) \quad (v^(terminal)≐0\hat v(\text{terminal}) \doteq 0)
    3. 𝐳𝐰←γλ𝐰𝐳𝐰+∇v^(S,𝐰)\mathbf{z}^{\mathbf{w}} \leftarrow \gamma\lambda^{\mathbf{w}}\mathbf{z}^{\mathbf{w}} + \nabla\hat v(S, \mathbf{w}); 𝐳𝜽←γλ𝜽𝐳𝜽+I ∇ln⁡π(A∣S,𝜽)\quad \mathbf{z}^{\boldsymbol{\theta}} \leftarrow \gamma\lambda^{\boldsymbol{\theta}}\mathbf{z}^{\boldsymbol{\theta}} + I\,\nabla\ln\pi(A \mid S, \boldsymbol{\theta})
    4. 𝐰←𝐰+α𝐰 δ 𝐳𝐰\mathbf{w} \leftarrow \mathbf{w} + \alpha^{\mathbf{w}}\,\delta\,\mathbf{z}^{\mathbf{w}}; 𝜽←𝜽+α𝜽 δ 𝐳𝜽\quad \boldsymbol{\theta} \leftarrow \boldsymbol{\theta} + \alpha^{\boldsymbol{\theta}}\,\delta\,\mathbf{z}^{\boldsymbol{\theta}}
    5. I←γII \leftarrow \gamma I;  S←S′\ S \leftarrow S'

13.6Policy Gradient for Continuing Problems

Without episodes, performance is the average reward of Section 10.3,

J(𝜽)≐r(π)≐lim⁡h→∞1h∑t=1h𝔼[Rt∣S0,A0:t−1∼π]=∑sμ(s)∑aπ(a∣s)∑s′,rp(s′,r∣s,a) r, \begin{aligned} J(\boldsymbol{\theta}) \doteq r(\pi) &\doteq \lim_{h \to \infty}\frac{1}{h}\sum_{t=1}^h \mathbb{E}[R_t \mid S_0, A_{0:t-1} \sim \pi] \\ &= \sum_s \mu(s)\sum_a \pi(a \mid s)\sum_{s', r}p(s', r \mid s, a)\,r, \end{aligned} (13.12)

where now μ\mu is the stationary distribution of the chain under π\pi, assumed to exist and not to depend on S0S_0 (ergodicity, Section A.3), so that ∑sμ(s)∑aπ(a∣s) p(s′∣s,a)=μ(s′)\sum_s \mu(s)\sum_a \pi(a \mid s)\,p(s' \mid s, a) = \mu(s'). Values are defined with respect to the differential return Gt=∑k≥1(Rt+k−r(π))G_t = \sum_{k \ge 1}(R_{t+k} - r(\pi)).

Theorem 13.9 (Policy Gradient Theorem, Average-Reward Case). For a finite ergodic MDP and differentiable π\pi, with vπ,qπv_\pi, q_\pi the differential values,

∇r(π)=∑sμ(s)∑aqπ(s,a) ∇π(a∣s,𝜽), \nabla r(\pi) = \sum_s \mu(s)\sum_a q_\pi(s, a)\,\nabla\pi(a \mid s, \boldsymbol{\theta}),

with equality: the constant of proportionality is 11.

Proof. As in the episodic case, but now qπ(s,a)=∑s′,rp(s′,r∣s,a)[r−r(π)+vπ(s′)]q_\pi(s, a) = \sum_{s', r}p(s', r \mid s, a)\bigl[r - r(\pi) + v_\pi(s')\bigr] contains r(π)r(\pi), so Step 2 becomes ∇qπ(s,a)=−∇r(π)+∑s′p(s′∣s,a)∇vπ(s′)\nabla q_\pi(s, a) = -\nabla r(\pi) + \sum_{s'}p(s' \mid s, a)\nabla v_\pi(s'). Substituting in Step 1 and solving for ∇r(π)\nabla r(\pi), which does not depend on ss,

∇r(π)=𝐠(s)+∑s′𝐏π(s,s′) ∇vπ(s′)−∇vπ(s)for every s. \nabla r(\pi) = \mathbf{g}(s) + \sum_{s'}\mathbf{P}_\pi(s, s')\,\nabla v_\pi(s') - \nabla v_\pi(s) \qquad \text{for every } s.

Average both sides over s∼μs \sim \mu. By stationarity ∑sμ(s)𝐏π(s,s′)=μ(s′)\sum_s \mu(s)\mathbf{P}_\pi(s, s') = \mu(s'), so the last two terms cancel, leaving ∇r(π)=∑sμ(s) 𝐠(s)\nabla r(\pi) = \sum_s \mu(s)\,\mathbf{g}(s). (Differential values are determined up to an additive constant, which does not matter: it multiplies ∑a∇π(a∣s)=𝟎\sum_a \nabla\pi(a \mid s) = \mathbf{0}.) □

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: λ𝜽,λ𝐰∈[0,1]\lambda^{\boldsymbol{\theta}}, \lambda^{\mathbf{w}} \in [0, 1]; α𝜽,α𝐰,αR¯>0\alpha^{\boldsymbol{\theta}}, \alpha^{\mathbf{w}}, \alpha^{\bar R} > 0. Initialize R¯∈ℝ\bar R \in \mathbb{R}, 𝐰\mathbf{w}, 𝜽\boldsymbol{\theta}, SS; 𝐳𝐰←𝟎\mathbf{z}^{\mathbf{w}} \leftarrow \mathbf{0}, 𝐳𝜽←𝟎\mathbf{z}^{\boldsymbol{\theta}} \leftarrow \mathbf{0}.

Loop for each time step:

  1. A∼π(⋅∣S,𝜽)A \sim \pi(\cdot \mid S, \boldsymbol{\theta}); take action AA, observe S′S', RR.
  2. δ←R−R¯+v^(S′,𝐰)−v^(S,𝐰)\delta \leftarrow R - \bar R + \hat v(S', \mathbf{w}) - \hat v(S, \mathbf{w}); R¯←R¯+αR¯δ\quad \bar R \leftarrow \bar R + \alpha^{\bar R}\delta
  3. 𝐳𝐰←λ𝐰𝐳𝐰+∇v^(S,𝐰)\mathbf{z}^{\mathbf{w}} \leftarrow \lambda^{\mathbf{w}}\mathbf{z}^{\mathbf{w}} + \nabla\hat v(S, \mathbf{w}); 𝐳𝜽←λ𝜽𝐳𝜽+∇ln⁡π(A∣S,𝜽)\quad \mathbf{z}^{\boldsymbol{\theta}} \leftarrow \lambda^{\boldsymbol{\theta}}\mathbf{z}^{\boldsymbol{\theta}} + \nabla\ln\pi(A \mid S, \boldsymbol{\theta})
  4. 𝐰←𝐰+α𝐰δ 𝐳𝐰\mathbf{w} \leftarrow \mathbf{w} + \alpha^{\mathbf{w}}\delta\,\mathbf{z}^{\mathbf{w}}; 𝜽←𝜽+α𝜽δ 𝐳𝜽\quad \boldsymbol{\theta} \leftarrow \boldsymbol{\theta} + \alpha^{\boldsymbol{\theta}}\delta\,\mathbf{z}^{\boldsymbol{\theta}}; S←S′\quad S \leftarrow S'

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 𝒜=ℝ\mathcal{A} = \mathbb{R}. A parameterized policy only needs to sample. Instead of one probability per action we learn the statistics of a distribution, typically a Gaussian policy:

π(a∣s,𝜽)≐1σ(s,𝜽)2πexp⁡(−(a−μ(s,𝜽))22σ(s,𝜽)2),μ(s,𝜽)=𝜽μ⊤𝐱μ(s),σ(s,𝜽)=exp⁡(𝜽σ⊤𝐱σ(s)), \begin{aligned} \pi(a \mid s, \boldsymbol{\theta}) &\doteq \frac{1}{\sigma(s, \boldsymbol{\theta})\sqrt{2\pi}}\exp\Bigl(-\frac{(a - \mu(s, \boldsymbol{\theta}))^2}{2\sigma(s, \boldsymbol{\theta})^2}\Bigr), \\ \mu(s, \boldsymbol{\theta}) &= \boldsymbol{\theta}_\mu^\top\mathbf{x}_\mu(s), \qquad \sigma(s, \boldsymbol{\theta}) = \exp\bigl(\boldsymbol{\theta}_\sigma^\top\mathbf{x}_\sigma(s)\bigr), \end{aligned} (13.13)

with 𝜽=(𝜽μ,𝜽σ)\boldsymbol{\theta} = (\boldsymbol{\theta}_\mu, \boldsymbol{\theta}_\sigma) and the exponential keeping σ\sigma positive. (Here μ\mu is the mean of the action, not the on-policy distribution.) From ln⁡π=−ln⁡σ−12ln⁡2π−(a−μ)2/(2σ2)\ln\pi = -\ln\sigma - \tfrac{1}{2}\ln 2\pi - (a - \mu)^2/(2\sigma^2), with ∇𝜽μμ=𝐱μ\nabla_{\boldsymbol{\theta}_\mu}\mu = \mathbf{x}_\mu and ∇𝜽σσ=σ 𝐱σ\nabla_{\boldsymbol{\theta}_\sigma}\sigma = \sigma\,\mathbf{x}_\sigma, the two parts of the eligibility vector are (the book’s Exercise 13.4)

∇𝜽μln⁡π(a∣s,𝜽)=a−μ(s,𝜽)σ(s,𝜽)2 𝐱μ(s),∇𝜽σln⁡π(a∣s,𝜽)=((a−μ(s,𝜽))2σ(s,𝜽)2−1)𝐱σ(s). \begin{aligned} \nabla_{\boldsymbol{\theta}_\mu}\ln\pi(a \mid s, \boldsymbol{\theta}) &= \frac{a - \mu(s, \boldsymbol{\theta})}{\sigma(s, \boldsymbol{\theta})^2}\,\mathbf{x}_\mu(s), \\ \nabla_{\boldsymbol{\theta}_\sigma}\ln\pi(a \mid s, \boldsymbol{\theta}) &= \Bigl(\frac{(a - \mu(s, \boldsymbol{\theta}))^2}{\sigma(s, \boldsymbol{\theta})^2} - 1\Bigr)\mathbf{x}_\sigma(s). \end{aligned} (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 σ\sigma away) and shrinks otherwise.

Score of a Gaussian policy with scalar features: μ=θμxμ\mu = \theta_\mu x_\mu, σ=eθσxσ\sigma = e^{\theta_\sigma x_\sigma}, so e−2xσθσ=1/σ2e^{-2x_\sigma\theta_\sigma} = 1/\sigma^2.
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]]}}]]`
(∂θμ,∂θσ)ln⁡π(a∣s,𝜽)={e−2xσθσxμ(a−xμθμ),xσ(−1+e−2xσθσ(a−xμθμ)2)} \begin{aligned} &\bigl(\partial_{\theta_\mu}, \partial_{\theta_\sigma}\bigr)\ln\pi(a \mid s, \boldsymbol{\theta}) \\ &\quad = \left\{e^{-2 x_{\sigma } \theta _{\sigma }} x_{\mu } \left(a-x_{\mu } \theta _{\mu }\right),x_{\sigma } \left(-1+e^{-2 x_{\sigma } \theta _{\sigma }} \left(a-x_{\mu } \theta _{\mu }\right){}^2\right)\right\} \end{aligned}

The factor 1/σ21/\sigma^2 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 Δ𝜽\Delta\boldsymbol{\theta}, which depends on the arbitrary choice of parameterization. Measuring steps instead by how much they change the policy, 𝔼S∼μ[KL(π𝜽(⋅∣S) ∥ π𝜽+Δ(⋅∣S))]≈12Δ⊤𝐅(𝜽)Δ\mathbb{E}_{S \sim \mu}\bigl[\mathrm{KL}\bigl(\pi_{\boldsymbol{\theta}}(\cdot \mid S)\,\Vert\,\pi_{\boldsymbol{\theta} + \Delta}(\cdot \mid S)\bigr)\bigr] \approx \tfrac{1}{2}\Delta^\top\mathbf{F}(\boldsymbol{\theta})\Delta, with the Fisher information matrix

𝐅(𝜽)≐𝔼S∼μ, A∼π[∇ln⁡π(A∣S,𝜽) ∇ln⁡π(A∣S,𝜽)⊤], \mathbf{F}(\boldsymbol{\theta}) \doteq \mathbb{E}_{S \sim \mu,\, A \sim \pi}\bigl[\nabla\ln\pi(A \mid S, \boldsymbol{\theta})\,\nabla\ln\pi(A \mid S, \boldsymbol{\theta})^\top\bigr],

gives the natural policy gradient 𝐅(𝜽)−1∇J(𝜽)\mathbf{F}(\boldsymbol{\theta})^{-1}\nabla J(\boldsymbol{\theta}) 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 q^𝐰\hat q_{\mathbf{w}} replace qπq_\pi 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 q^𝐰(s,a)=𝐰⊤∇ln⁡π(a∣s,𝜽)\hat q_{\mathbf{w}}(s, a) = \mathbf{w}^\top\nabla\ln\pi(a \mid s, \boldsymbol{\theta}) (compatible features), and let 𝐰∗\mathbf{w}^* minimize ∑sμ(s)∑aπ(a∣s)(qπ(s,a)−q^𝐰(s,a))2\sum_s \mu(s)\sum_a \pi(a \mid s)\bigl(q_\pi(s, a) - \hat q_{\mathbf{w}}(s, a)\bigr)^2. Then ∑sμ(s)∑aq^𝐰∗(s,a)∇π(a∣s)=∑sμ(s)∑aqπ(s,a)∇π(a∣s)\sum_s \mu(s)\sum_a \hat q_{\mathbf{w}^*}(s, a)\nabla\pi(a \mid s) = \sum_s \mu(s)\sum_a q_\pi(s, a)\nabla\pi(a \mid s), and if 𝐅\mathbf{F} is invertible, 𝐰∗∝𝐅−1∇J(𝜽)\mathbf{w}^* \propto \mathbf{F}^{-1}\nabla J(\boldsymbol{\theta}).

Proof. Write 𝝍(s,a)=∇ln⁡π(a∣s)\boldsymbol{\psi}(s, a) = \nabla\ln\pi(a \mid s). The minimizer satisfies the normal equations ∑sμ(s)∑aπ(a∣s)(qπ(s,a)−𝐰∗⊤𝝍(s,a))𝝍(s,a)=𝟎\sum_s \mu(s)\sum_a \pi(a \mid s)\bigl(q_\pi(s, a) - \mathbf{w}^{*\top}\boldsymbol{\psi}(s, a)\bigr)\boldsymbol{\psi}(s, a) = \mathbf{0}. Since π𝝍=∇π\pi\boldsymbol{\psi} = \nabla\pi, this says that qπq_\pi and q^𝐰∗\hat q_{\mathbf{w}^*} give the same policy gradient sum. Moreover the second term is 𝐅𝐰∗\mathbf{F}\mathbf{w}^* and the first is, by Theorem 13.2, proportional to ∇J\nabla J. □

So the weights of the best compatible critic are the natural gradient: an actor–critic that steps along 𝐰\mathbf{w} does natural gradient ascent without ever forming 𝐅\mathbf{F}. Note that 𝐰⊤𝝍\mathbf{w}^\top\boldsymbol{\psi} has zero mean under π(⋅∣s)\pi(\cdot \mid s), so a compatible critic approximates the advantage, not qπq_\pi. For the tabular soft-max (h(s,a)=θs,ah(s, a) = \theta_{s,a}) the natural gradient step reduces to θs,a←θs,a+α1−γadv⁡π(s,a)\theta_{s,a} \leftarrow \theta_{s,a} + \frac{\alpha}{1-\gamma}\operatorname{adv}_\pi(s, a), that is, a multiplicative-weights update πk+1(a∣s)∝πk(a∣s) eαadv⁡πk(s,a)/(1−γ)\pi_{k+1}(a \mid s) \propto \pi_k(a \mid s)\,e^{\alpha\operatorname{adv}_{\pi_k}(s, a)/(1-\gamma)}, 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 πold\pi_{\text{old}},

Lold(𝜽)≐𝔼πold[ρt(𝜽) adv⁡̂t],ρt(𝜽)≐π(At∣St,𝜽)πold(At∣St), L_{\text{old}}(\boldsymbol{\theta}) \doteq \mathbb{E}_{\pi_{\text{old}}}\Bigl[\rho_t(\boldsymbol{\theta})\,\widehat{\operatorname{adv}}_t\Bigr], \qquad \rho_t(\boldsymbol{\theta}) \doteq \frac{\pi(A_t \mid S_t, \boldsymbol{\theta})}{\pi_{\text{old}}(A_t \mid S_t)}, (13.15)

an importance-sampling ratio as in (5.2) that corrects the actions but not the states. Since ∇ρt=∇ln⁡π\nabla\rho_t = \nabla\ln\pi at 𝜽=𝜽old\boldsymbol{\theta} = \boldsymbol{\theta}_{\text{old}}, the surrogate has the same gradient as JJ 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 LoldL_{\text{old}} subject to 𝔼S[KL(πold(⋅∣S) ∥ π𝜽(⋅∣S))]≤δ\mathbb{E}_S\bigl[\mathrm{KL}(\pi_{\text{old}}(\cdot \mid S)\,\Vert\,\pi_{\boldsymbol{\theta}}(\cdot \mid S))\bigr] \le \delta, solved approximately by a natural gradient step (conjugate gradients on 𝐅\mathbf{F}) 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

LCLIP(𝜽)=𝔼t[min⁡(ρt(𝜽) adv⁡̂t,clip⁡(ρt(𝜽),1−ε,1+ε) adv⁡̂t)], \begin{aligned} L^{\text{CLIP}}(\boldsymbol{\theta}) = \mathbb{E}_t\Bigl[\min\bigl(&\rho_t(\boldsymbol{\theta})\,\widehat{\operatorname{adv}}_t, \\ &\operatorname{clip}(\rho_t(\boldsymbol{\theta}), 1 - \varepsilon, 1 + \varepsilon)\,\widehat{\operatorname{adv}}_t\bigr)\Bigr], \end{aligned} (13.16)

typically with ε≈0.2\varepsilon \approx 0.2. 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 ρ\rho.

∂LCLIP/∂ρ\partial L^{\text{CLIP}}/\partial\rho for adv⁡̂>0\widehat{\operatorname{adv}} > 0 (first row) and <0< 0 (second row), in the regions ρ<1−ε\rho < 1-\varepsilon, 1−ε<ρ<1+ε1-\varepsilon < \rho < 1+\varepsilon, ρ>1+ε\rho > 1+\varepsilon.
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]}}]`
∂LCLIP∂ρ=(AA00AA) \frac{\partial L^{\text{CLIP}}}{\partial\rho} = \left( \begin{array}{ccc} A & A & 0 \\ 0 & A & A \\ \end{array} \right)

A good action (adv⁡̂>0\widehat{\operatorname{adv}} > 0) stops being pushed once its probability ratio exceeds 1+ε1 + \varepsilon, and a bad one once its ratio falls below 1−ε1 - \varepsilon; but a good action whose probability has dropped below 1−ε1 - \varepsilon 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 δt=Rt+1+γv^(St+1)−v^(St)\delta_t = R_{t+1} + \gamma\hat v(S_{t+1}) - \hat v(S_t):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

adv⁡̂tGAE(γ,λ)≐∑l=0∞(γλ)l δt+l=Gtλ−v^(St), \widehat{\operatorname{adv}}{}_t^{\text{GAE}(\gamma, \lambda)} \doteq \sum_{l=0}^{\infty}(\gamma\lambda)^l\,\delta_{t+l} = G_t^\lambda - \hat v(S_t), (13.17)

where GtλG_t^\lambda is the λ-return (12.1) built on v^\hat v. For λ=0\lambda = 0 it is the one-step TD error of Algorithm 13.7; for λ=1\lambda = 1 the sum telescopes to Gt−v^(St)G_t - \hat v(S_t), the signal of REINFORCE with baseline. The check below takes a three-step episode with symbolic rewards and values (v^\hat v of the terminal state is 00).

GAE minus (λ-return minus V0V_0), then the limits λ=0\lambda = 0 and λ=1\lambda = 1.
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]}`
(adv⁡̂0GAE−(G0λ−V0), λ=0, λ=1)={0,R1−V0+γV1,R1+γR2+γ2R3−V0} \begin{aligned} &\Bigl(\widehat{\operatorname{adv}}{}_0^{\text{GAE}} - (G_0^\lambda - V_0),\ \lambda = 0,\ \lambda = 1\Bigr) \\ &\quad = \left\{0,R_1-V_0+\gamma V_1,R_1+\gamma R_2+\gamma ^2 R_3-V_0\right\} \end{aligned}

In practice the advantages are computed backwards over a batch of trajectories with γ≈0.99\gamma \approx 0.99 and λ≈0.95\lambda \approx 0.95, 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 a=μ𝜽(s)a = \mu_{\boldsymbol{\theta}}(s) 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

∇J(𝜽)=𝔼S∼ρμ[∇𝜽μ𝜽(S) ∇aqμ(S,a)∣a=μ𝜽(S)], \nabla J(\boldsymbol{\theta}) = \mathbb{E}_{S \sim \rho^\mu}\Bigl[\nabla_{\boldsymbol{\theta}}\mu_{\boldsymbol{\theta}}(S)\,\nabla_a q_\mu(S, a)\big|_{a = \mu_{\boldsymbol{\theta}}(S)}\Bigr], (13.18)

where ρμ\rho^\mu is the discounted state distribution and ∇𝜽μ𝜽\nabla_{\boldsymbol{\theta}}\mu_{\boldsymbol{\theta}} is the Jacobian. There is no integral over actions, hence no score function and none of the 1/σ21/\sigma^2 variance of (13.14); in fact the stochastic policy gradient of a Gaussian policy tends to (13.18) as σ→0\sigma \to 0. Because the gradient needs qμq_\mu 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 ℋ(π(⋅∣s))=−∑aπ(a∣s)ln⁡π(a∣s)\mathcal{H}(\pi(\cdot \mid s)) = -\sum_a \pi(a \mid s)\ln\pi(a \mid s) to the objective, with a temperature α>0\alpha > 0, 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, J(π)=∑t𝔼[Rt+1+α ℋ(π(⋅∣St))]J(\pi) = \sum_t \mathbb{E}\bigl[R_{t+1} + \alpha\,\mathcal{H}(\pi(\cdot \mid S_t))\bigr]. In one state the regularized problem max⁡π∑aπ(a)q(a)+αℋ(π)\max_\pi \sum_a \pi(a)q(a) + \alpha\mathcal{H}(\pi) is solved by the Boltzmann policy π(a)∝eq(a)/α\pi(a) \propto e^{q(a)/\alpha} (it is the case πref\pi_{\text{ref}} 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 qq-functions off-policy from a replay buffer (with two critics, as TD3), and moves the actor towards exp⁡(q^/α)\exp(\hat q/\alpha) by minimizing a KL divergence, using the reparameterization a=μ𝜽(s)+σ𝜽(s) ξa = \mu_{\boldsymbol{\theta}}(s) + \sigma_{\boldsymbol{\theta}}(s)\,\xi to differentiate through the sampled action; a follow-up by the same authors also tunes α\alpha 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

JJ is not concave in 𝜽\boldsymbol{\theta}, 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 ∥dπ∗/ν∥∞\lVert d^{\pi^*}/\nu\rVert_\infty between the optimal policy’s state distribution and the start distribution ν\nu.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 ν\nu 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 O(1/T)O(1/T) 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 O(1/t)O(1/t), 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 xx plus the tokens generated so far, an action is the next token, transitions are deterministic, and a reward arrives when the response yy is complete. Reinforcement learning from human feedback (RLHF) fits a reward model r(x,y)r(x, y) to human comparisons with the Bradley–Terry model Pr⁡{yw≻yl∣x}=σ(r(x,yw)−r(x,yl))\Pr\{y_w \succ y_l \mid x\} = \sigma\bigl(r(x, y_w) - r(x, y_l)\bigr),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

max⁡π 𝔼x, y∼π(⋅∣x)[r(x,y)]−β KL(π(⋅∣x) ∥ πref(⋅∣x)), \max_\pi\ \mathbb{E}_{x,\, y \sim \pi(\cdot \mid x)}\bigl[r(x, y)\bigr] - \beta\,\mathrm{KL}\bigl(\pi(\cdot \mid x)\,\Vert\,\pi_{\text{ref}}(\cdot \mid x)\bigr), (13.19)

where πref\pi_{\text{ref}} is the supervised model the policy must not drift far from.

DPO. The maximizer of (13.19) is known in closed form, π∗(y∣x)=πref(y∣x) er(x,y)/β/Z(x)\pi^*(y \mid x) = \pi_{\text{ref}}(y \mid x)\,e^{r(x, y)/\beta}/Z(x). Inverting it, r(x,y)=βln⁡π∗(y∣x)πref(y∣x)+βln⁡Z(x)r(x, y) = \beta\ln\frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta\ln Z(x), and in the Bradley–Terry difference the intractable Z(x)Z(x) 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

ℒDPO(𝜽)=−𝔼(x,yw,yl)[ln⁡σ(βln⁡π𝜽(yw∣x)πref(yw∣x)−βln⁡π𝜽(yl∣x)πref(yl∣x))]. \mathcal{L}_{\text{DPO}}(\boldsymbol{\theta}) = -\mathbb{E}_{(x, y_w, y_l)}\Bigl[\ln\sigma\Bigl(\beta\ln\frac{\pi_{\boldsymbol{\theta}}(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta\ln\frac{\pi_{\boldsymbol{\theta}}(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)}\Bigr)\Bigr]. (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 πref\pi_{\text{ref}} tilted by er/βe^{r/\beta}, and the log-ratio difference recovers the reward difference.

Maximize qr1+(1−q)r2−β KL((q,1−q) ∥ (π1,1−π1))q r_1 + (1-q) r_2 - \beta\,\mathrm{KL}\bigl((q, 1-q)\,\Vert\,(\pi_1, 1-\pi_1)\bigr) over qq, then form the odds ratio of π∗\pi^* to πref\pi_{\text{ref}}.
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]))]}`
(π∗(y1), π∗(y1)/πref(y1)π∗(y2)/πref(y2))={er1βπ1−er2β(−1+π1)+er1βπ1,er1−r2β} \Bigl(\pi^*(y_1),\ \frac{\pi^*(y_1)/\pi_{\text{ref}}(y_1)}{\pi^*(y_2)/\pi_{\text{ref}}(y_2)}\Bigr) = \left\{\frac{e^{\frac{r_1}{\beta }} \pi _1}{-e^{\frac{r_2}{\beta }} \left(-1+\pi _1\right)+e^{\frac{r_1}{\beta }} \pi _1},e^{\frac{r_1-r_2}{\beta }}\right\}

Taking βln⁡\beta\ln of the second entry gives βln⁡π∗(y1)πref(y1)−βln⁡π∗(y2)πref(y2)=r1−r2\beta\ln\frac{\pi^*(y_1)}{\pi_{\text{ref}}(y_1)} - \beta\ln\frac{\pi^*(y_2)}{\pi_{\text{ref}}(y_2)} = r_1 - r_2, the argument of σ\sigma 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 GG responses with rewards r1,…,rGr_1, \dots, r_G and gives every token of response ii the advantage

adv⁡̂i=ri−mean⁡(r1,…,rG)std⁡(r1,…,rG), \widehat{\operatorname{adv}}_i = \frac{r_i - \operatorname{mean}(r_1, \dots, r_G)}{\operatorname{std}(r_1, \dots, r_G)}, (13.21)

which is then used in the clipped objective (13.16) together with a KL penalty to πref\pi_{\text{ref}}. 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 v^\hat v 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 rir_i itself, which is not independent of AiA_i; the expected update is still in the gradient direction but shrunk by the factor (G−1)/G(G-1)/G, as the check below shows for G=3G = 3 on a two-armed bandit. The leave-one-out mean of the other G−1G - 1 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 ∇J\nabla J: 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 G=3G = 3 samples from π=(1−p,p)\pi = (1-p, p), divided by the true gradient ∂pJ\partial_p J; scores w.r.t. pp are −1/(1−p)-1/(1-p) and 1/p1/p.
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]]`
𝔼[(rA1−r¯) ∂pln⁡π(A1)]∂pJ=23 \frac{\mathbb{E}\bigl[(r_{A_1} - \bar r)\,\partial_p\ln\pi(A_1)\bigr]}{\partial_p J} = \frac{2}{3}

The factor is 1−1/G1 - 1/G in general: the terms 𝔼[rj ∇ln⁡π(Ai)]\mathbb{E}[r_j\,\nabla\ln\pi(A_i)] with j≠ij \ne i vanish by independence and Proposition 13.5, and only the −ri/G-r_i/G 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 At∈{0,1}A_t \in \{0, 1\} with Pr⁡{At=1}=Pt\Pr\{A_t = 1\} = P_t. Its preferences satisfy h(s,1,𝜽)−h(s,0,𝜽)=𝜽⊤𝐱(s)h(s, 1, \boldsymbol{\theta}) - h(s, 0, \boldsymbol{\theta}) = \boldsymbol{\theta}^\top\mathbf{x}(s). (a) Show that the soft-max (13.2) gives Pt=1/(1+e−𝜽t⊤𝐱(St))P_t = 1/(1 + e^{-\boldsymbol{\theta}_t^\top\mathbf{x}(S_t)}). (b) Compute the eligibility vector ∇ln⁡π(a∣s,𝜽)\nabla\ln\pi(a \mid s, \boldsymbol{\theta}) and write the REINFORCE update.

Solution

(a) π(1∣s)=eh1/(eh0+eh1)=1/(1+e−(h1−h0))\pi(1 \mid s) = e^{h_1}/(e^{h_0} + e^{h_1}) = 1/(1 + e^{-(h_1 - h_0)}). (b) Writing z=𝜽⊤𝐱(s)z = \boldsymbol{\theta}^\top\mathbf{x}(s), ln⁡π(1∣s)=ln⁡σ(z)\ln\pi(1 \mid s) = \ln\sigma(z) and ln⁡π(0∣s)=ln⁡(1−σ(z))\ln\pi(0 \mid s) = \ln(1 - \sigma(z)), whose derivatives in zz are 1−σ(z)1 - \sigma(z) and −σ(z)-\sigma(z), that is, a−σ(z)a - \sigma(z) in both cases. By the chain rule

∇ln⁡π(a∣s,𝜽)=(a−P) 𝐱(s),𝜽t+1=𝜽t+α γt Gt (At−Pt) 𝐱(St), \nabla\ln\pi(a \mid s, \boldsymbol{\theta}) = (a - P)\,\mathbf{x}(s), \qquad \boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t + \alpha\,\gamma^t\,G_t\,(A_t - P_t)\,\mathbf{x}(S_t),

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 ln⁡π(a)\ln\pi(a) in zz, minus a−σ(z)a - \sigma(z), for a=1a = 1 and a=0a = 0.
await show`Simplify[{D[Log[1/(1 + Exp[-z])], z], D[Log[1 - 1/(1 + Exp[-z])], z]} - ({1, 0} - 1/(1 + Exp[-z]))]`
(∂zln⁡π(a)−(a−σ(z)))a=1,0={0,0} \Bigl(\partial_z\ln\pi(a) - (a - \sigma(z))\Bigr)_{a = 1, 0} = \{0,0\}

Exercise 13.13. Verify Theorem 13.9 symbolically on a two-state continuing MDP: in each state s∈{1,2}s \in \{1, 2\} the action stay (chosen with probability πs=1/(1+e−θs)\pi_s = 1/(1 + e^{-\theta_s})) keeps the state and the action switch moves to the other one, with arbitrary rewards rs,ar_{s,a}. Compute μ\mu, r(π)r(\pi), the differential values and qπq_\pi, and compare ∇r(π)\nabla r(\pi) with ∑sμ(s)∑aqπ(s,a)∇π(a∣s)\sum_s \mu(s)\sum_a q_\pi(s, a)\nabla\pi(a \mid s).

Solution

The chain has 𝐏π=(π11−π11−π2π2)\mathbf{P}_\pi = \begin{pmatrix}\pi_1 & 1 - \pi_1\\ 1 - \pi_2 & \pi_2\end{pmatrix}, whose stationary distribution is μ∝(1−π2,1−π1)\mu \propto (1 - \pi_2, 1 - \pi_1) (flows across the cut balance: μ(1)(1−π1)=μ(2)(1−π2)\mu(1)(1 - \pi_1) = \mu(2)(1 - \pi_2); see Section A.3). The differential values solve v=𝐫π−r(π)𝟏+𝐏πvv = \mathbf{r}_\pi - r(\pi)\mathbf{1} + \mathbf{P}_\pi v, determined up to a constant, which we fix by v(1)=0v(1) = 0; then qπ(s,a)=rs,a−r(π)+v(next state)q_\pi(s, a) = r_{s,a} - r(\pi) + v(\text{next state}).

μ\mu, r(π)=∑sμ(s)∑aπ(a∣s)rs,ar(\pi) = \sum_s\mu(s)\sum_a\pi(a \mid s)r_{s,a}, differential values with v(1)=0v(1) = 0, 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}]]`
∇r(π)−∑sμ(s)∑aqπ(s,a)∇π(a∣s)={0,0} \nabla r(\pi) - \sum_s \mu(s)\sum_a q_\pi(s,a)\nabla\pi(a \mid s) = \{0,0\}

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 v(1)=0v(1) = 0: the second is implied, because r(π)r(\pi) was computed with the stationary μ\mu, so μ⊤\mu^\top times the residual of the system vanishes identically.

Exercise 13.14. A one-step problem with a scalar action has reward R(a)=−(a−c)2R(a) = -(a - c)^2, and the policy is 𝒩(μ,σ2)\mathcal{N}(\mu, \sigma^2) with σ\sigma fixed. Compute the mean and the variance of the REINFORCE estimator g^=R(A) (A−μ)/σ2\hat g = R(A)\,(A - \mu)/\sigma^2 of ∂J/∂μ\partial J/\partial\mu. What happens as σ→0\sigma \to 0? Compare with the deterministic policy gradient (13.18).

Solution

Here J(μ)=𝔼[R(A)]=−(μ−c)2−σ2J(\mu) = \mathbb{E}[R(A)] = -(\mu - c)^2 - \sigma^2, so ∂J/∂μ=−2(μ−c)\partial J/\partial\mu = -2(\mu - c). Write Δ=μ−c\Delta = \mu - c 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]]]`
(𝔼[g^], Var⁡[g^])Δ=μ−c={−2Δ,14Δ2+Δ4σ2+15σ2} \bigl(\mathbb{E}[\hat g],\ \operatorname{Var}[\hat g]\bigr)_{\Delta = \mu - c} = \left\{-2 \Delta ,14 \Delta ^2+\frac{\Delta ^4}{\sigma ^2}+15 \sigma ^2\right\}

The mean is the exact gradient −2Δ-2\Delta, but the variance contains the term Δ4/σ2\Delta^4/\sigma^2 that blows up as σ→0\sigma \to 0: 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 1/σ21/\sigma^2 scaling of the score. The deterministic policy gradient uses ∇aR(a)∣a=μ=−2(μ−c)\nabla_a R(a)\vert_{a = \mu} = -2(\mu - c) directly: the exact gradient with zero variance, at the price of needing ∇aq\nabla_a q, that is, a differentiable critic.

Exercise 13.15. Most implementations of Algorithm 13.4 and Algorithm 13.7 with γ<1\gamma < 1 omit the factor γt\gamma^t (the variable II). Using (13.4), describe what the expected update then is, and argue why it is not, in general, the gradient of J(𝜽)=vπ𝜽(s0)J(\boldsymbol{\theta}) = v_{\pi_{\boldsymbol{\theta}}}(s_0).

Solution

Without γt\gamma^t the expected update over an episode is 𝔼π[∑tqπ(St,At)∇ln⁡π(At∣St)]=∑sη1(s)∑aqπ(s,a)∇π(a∣s)\mathbb{E}_\pi\bigl[\sum_t q_\pi(S_t, A_t)\nabla\ln\pi(A_t \mid S_t)\bigr] = \sum_s \eta_1(s)\sum_a q_\pi(s, a)\nabla\pi(a \mid s), where η1\eta_1 counts visits undiscounted while qπq_\pi is still discounted. The theorem’s proof shows that the gradient of the discounted objective has weights ηγ\eta_\gamma, 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 qπq_\pi and in η\eta, 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 γ\gamma is usually best viewed as a variance-reduction device for the undiscounted objective, with η1\eta_1 the “right” weighting and qπq_\pi a biased critic.