4  Policy Gradient and Actor-Critic Methods

\[ \newcommand{\E}{\mathbb{E}} \newcommand{\R}{\mathbb{R}} \newcommand{\Prob}{\mathbb{P}} \newcommand{\BR}{\operatorname{BR}} \newcommand{\eps}{\varepsilon} \newcommand{\given}{\,\vert\,} \newcommand{\argmax}{\operatorname*{arg\,max}} \newcommand{\argmin}{\operatorname*{arg\,min}} \newcommand{\sm}{\setminus} \newcommand{\defeq}{\equiv} \]

NoteSource:

Ben Moll’s RL lecture slides, Lecture 4.

4.1 From value-based to policy-based methods

Why the shift

The value-based methods of Chapters 1 to 3 derive a greedy or \(\eps\)-greedy policy from \(q_{\pi}\) (Definition 2.2). Policy gradient methods choose a family indexed by \(\theta\) and improve the policy by gradient ascent on its value. Policy evaluation still estimates an action-value function using the methods of Chapters 2 and 3.

NotePolicy gradients in language models

In language-model post-training, reinforcement learning from human feedback (RLHF) and reinforcement learning with verifiable rewards (RLVR) use sequence-level rewards. The language model is a stochastic policy \(\pi(a\given s,\theta)\): context \(s\) determines a distribution over next tokens \(a\). Proximal policy optimization (PPO) refines the policy-gradient update below.

Policies as tables, policies as functions

Replace the policy table with a parameterized function

\[ \pi(a\given s,\theta),\qquad \theta\in\R^{m}, \tag{4.1}\]

where \(\theta\) might be neural-network weights. As with Equation 3.11, \(m\) can be smaller than the table’s \(|\mathcal{S}|\times|\mathcal{A}|\) entries, and shared parameters allow an update at \(s\) to affect other states.

Tip

In Equation 3.11, \(\hat{v}(s,w)\) approximates the value \(v_{\pi}\) of a given policy. In Equation 4.1, the policy family is the feasible set over which value is maximized. The restrictions therefore enter as value-approximation error or as a restriction on available policies.

Notation varies: \(\pi(a\given s,\theta)\), \(\pi(a,s,\theta)\), and \(\pi_{\theta}(a\given s)\) all appear in the literature and all mean the same object. This chapter uses the first. For the deterministic case of the next section the policy returns an action rather than a distribution, and is written \(a=\pi(s,\theta)\).

4.2 Setting up the optimization

The goal is to choose \(\theta\) to maximize

\[ v_{\pi}(s)=\E_{0}\!\left[\sum_{t=0}^{\infty}\gamma^{t}r(s_{t},a_{t})\ \given\ s_{0}=s\right], \qquad s_{t+1}\sim p(\cdot\given s_{t},a_{t}),\ \ a_{t}\sim\pi(\cdot\given s_{t},\theta), \]

by some version of gradient ascent,

\[ \theta_{j+1}=\theta_{j}+\alpha\,\nabla_{\theta}J(\theta_{j}), \tag{4.2}\]

using a sampled gradient when the exact gradient is unavailable. This requires a scalar objective and a gradient representation that can be estimated without the model.

Problem 1: \(v_{\pi}\) is not a scalar

Average \(v_{\pi}(s)\) across initial states to obtain a scalar objective:

\[ J(\theta)=\sum_{s\in\mathcal{S}}v_{\pi}(s)\,\mu(s), \tag{4.3}\]

where \(\mu\) is an exogenous distribution over starting states, independent of \(\theta\). Thus \(J(\theta)=\E_{s_{0}\sim\mu}[v_{\pi}(s_{0})]\). Its weights determine the relative importance of starting states.

Problem 2: the model reappears

For a deterministic policy \(a=\pi(s,\theta)\), the Bellman equation is

\[ v_{\pi}(s)=r\big(s,\pi(s,\theta)\big)+\gamma\sum_{s'\in\mathcal{S}}v_{\pi}(s')\,p\big(s'\given s,\pi(s,\theta)\big). \]

Differentiating through the action gives

\[ \nabla_{\theta}v_{\pi}(s)=\Big(\underbrace{\nabla_{a}r(s,\pi)}_{\text{unknown}}+\gamma\sum_{s'\in\mathcal{S}}v_{\pi}(s')\underbrace{\nabla_{a}p(s'\given s,\pi)}_{\text{unknown}}\Big)\nabla_{\theta}\pi+\gamma\sum_{s'\in\mathcal{S}}\big(\nabla_{\theta}v_{\pi}(s')\big)\,p(s'\given s,\pi). \tag{4.4}\]

Both marked terms require the model: how the reward responds to a marginal change in the action, and how the transition density does. Neither is available in a model-free setting.

Important

The policy gradient theorem absorbs the model derivatives into \(q_{\pi}\), which can be estimated from samples.

4.3 The deterministic policy gradient theorem

Theorem 4.1 (Deterministic policy gradient theorem) Let \(\mathcal S\) be finite and \(\gamma\in(0,1)\). The deterministic policy \(a=\pi(s,\theta)\) is continuously differentiable in \(\theta\) and takes values in an open action domain. Suppose \(r(s,a)\) and \(p(s'\mid s,a)\) are continuously differentiable in \(a\) on a neighborhood of these actions. With a fixed initial distribution \(\mu\) and \(J\) as in Equation 4.3,

\[ \nabla_{\theta}J(\theta)=\E_{0}\!\left[\sum_{t=0}^{\infty}\gamma^{t}\,\nabla_{a}q_{\pi}(s_{t},a_{t})\,\nabla_{\theta}\pi(s_{t},\theta)\right], \tag{4.5}\]

where the expectation is over trajectories with \(s_{0}\sim\mu\), \(a_{t}=\pi(s_{t},\theta)\), and \(s_{t+1}\sim p(\cdot\given s_{t},a_{t})\).

This form uses on-policy trajectories (Definition 3.3) and requires a continuous action space for \(\nabla_{a}\). The unknowns are \(q_{\pi}\) and its action derivative. The result is due to Silver et al. (2014); their supplement states regularity conditions for general state spaces.

NoteProof of the deterministic policy gradient theorem

Step 1: differentiate the Bellman equation. The finite-state representation \(\mathbf v_\pi=(I-\gamma\mathbf P_\pi)^{-1}\mathbf r_\pi\) is continuously differentiable under the stated assumptions. Differentiating gives Equation 4.4: \[ \nabla_{\theta}v_{\pi}(s)=\Big(\nabla_{a}r(s,\pi)+\gamma\sum_{s'\in\mathcal{S}}v_{\pi}(s')\nabla_{a}p(s'\given s,\pi)\Big)\nabla_{\theta}\pi+\gamma\sum_{s'\in\mathcal{S}}\big(\nabla_{\theta}v_{\pi}(s')\big)p(s'\given s,\pi). \] The first group collects the effect of \(\theta\) on today’s action; the second collects its effect on the continuation value, because \(v_{\pi}\) at every future state also depends on \(\theta\).

Step 2: recognize the bracket as \(\nabla_{a}q_{\pi}\). The action value under \(\pi\) is, by Equation 2.5, \[ q_{\pi}(s,a)=r(s,a)+\gamma\sum_{s'\in\mathcal{S}}v_{\pi}(s')\,p(s'\given s,a). \] Differentiate it with respect to \(a\), holding the continuation values \(v_{\pi}(s')\) fixed, which is legitimate because \(q_{\pi}(s,a)\) is by construction the value of deviating to \(a\) today only and following \(\pi\) from tomorrow on: \[ \nabla_{a}q_{\pi}(s,a)=\nabla_{a}r(s,a)+\gamma\sum_{s'\in\mathcal{S}}v_{\pi}(s')\,\nabla_{a}p(s'\given s,a). \] That is exactly the bracket in Step 1. Substituting, \[ \nabla_{\theta}v_{\pi}(s)=\nabla_{a}q_{\pi}\big(s,\pi(s,\theta)\big)\,\nabla_{\theta}\pi(s,\theta)+\gamma\sum_{s'\in\mathcal{S}}\big(\nabla_{\theta}v_{\pi}(s')\big)\,p\big(s'\given s,\pi(s,\theta)\big). \tag{4.6}\] Step 3: read Equation 4.6 as a Bellman equation. Define the unknown function \(x(s)\defeq\nabla_{\theta}v_{\pi}(s)\) and the “reward” \[ \rho(s)\defeq\nabla_{a}q_{\pi}\big(s,\pi(s,\theta)\big)\,\nabla_{\theta}\pi(s,\theta). \] Both are functions of the state alone, since \(\theta\) is fixed while we differentiate. Then Equation 4.6 reads \[ x(s)=\rho(s)+\gamma\sum_{s'\in\mathcal{S}}x(s')\,p_{\pi}(s'\given s), \] This is Equation 1.2 with reward \(\rho\) and transition kernel \(p_{\pi}\), applied to each of the \(m\) coordinates of \(x\) and \(\rho\).

Step 4: solve it as a present discounted value. In matrix form, \(\mathbf{x}=\boldsymbol{\rho}+\gamma\mathbf{P}_{\pi}\mathbf{x}\). Since \(\mathbf{P}_{\pi}\) is row-stochastic its spectral radius is \(1\), so for \(\gamma\in(0,1)\) the matrix \(I-\gamma\mathbf{P}_{\pi}\) is invertible and the solution is unique: \[ \mathbf{x}=(I-\gamma\mathbf{P}_{\pi})^{-1}\boldsymbol{\rho}=\sum_{t=0}^{\infty}\gamma^{t}\mathbf{P}_{\pi}^{t}\boldsymbol{\rho}, \] the Neumann series converging because \(\|\gamma\mathbf P_\pi\|_\infty=\gamma<1\) in the induced infinity norm. Row \(s\) of \(\mathbf{P}_{\pi}^{t}\boldsymbol{\rho}\) is \(\E[\rho(s_{t})\given s_{0}=s]\), so component-wise this says \[ \nabla_{\theta}v_{\pi}(s_{0})=\E_{0}\!\left[\sum_{t=0}^{\infty}\gamma^{t}\,\nabla_{a}q_{\pi}(s_{t},a_{t})\,\nabla_{\theta}\pi(s_{t},\theta)\right], \qquad a_{t}=\pi(s_{t},\theta),\ \ s_{t+1}\sim p(\cdot\given s_{t},a_{t}). \]

Step 5: average over starting states. By Equation 4.3, \(\nabla_{\theta}J(\theta)=\sum_{s}\mu(s)\nabla_{\theta}v_{\pi}(s)\), since \(\mu\) does not depend on \(\theta\). Drawing \(s_{0}\sim\mu\) instead of fixing it gives Equation 4.5. \(\square\)

Replacing the expectation in Equation 4.5 by one sampled trajectory of length \(T\) gives

\[ \theta_{j+1}=\theta_{j}+\alpha\sum_{t=0}^{T}\gamma^{t}\,\nabla_{a}q_{\pi}(s_{t},a_{t})\,\nabla_{\theta}\pi(s_{t},\theta_{j}). \]

The algorithm still requires estimates of \(q_{\pi}\) and \(\nabla_{a}q_{\pi}\).

4.4 The stochastic policy gradient theorem

Now let the policy be stochastic, \(a_{t}\sim\pi(\cdot\given s_{t},\theta)\).

Theorem 4.2 (Stochastic policy gradient theorem) Let \(\mathcal{S}\) and \(\mathcal{A}\) be finite, let \(\gamma\in(0,1)\), let \(\pi(a\given s,\theta)>0\) be differentiable in \(\theta\) for all \((s,a)\), and let \(J(\theta)=\sum_{s}v_{\pi}(s)\mu(s)\) as in Equation 4.3. Then

\[ \nabla_{\theta}J(\theta)=\E_{0}\!\left[\sum_{t=0}^{\infty}\gamma^{t}\,q_{\pi}(s_{t},a_{t})\,\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta)\right], \tag{4.7}\]

where the expectation is over trajectories with \(s_{0}\sim\mu\), \(a_{t}\sim\pi(\cdot\given s_{t},\theta)\), and \(s_{t+1}\sim p(\cdot\given s_{t},a_{t})\).

Positivity of \(\pi\) makes \(\ln\pi\) well defined. This form requires \(q_{\pi}\) but no action derivative, so finite action spaces are allowed.

NoteProof of the stochastic policy gradient theorem

Step 1: differentiate the Bellman equation. For a fixed stochastic policy \(\pi\), Equation 2.1 without the maximization reads \[ v_{\pi}(s)=\sum_{a\in\mathcal{A}}\pi(a\given s,\theta)\left(r(s,a)+\gamma\sum_{s'\in\mathcal{S}}v_{\pi}(s')\,p(s'\given s,a)\right). \] Apply the product rule. Since \(r(s,a)\) and \(p(s'\given s,a)\) are evaluated at fixed actions, their action derivatives do not enter: \[ \nabla_{\theta}v_{\pi}(s)=\sum_{a\in\mathcal{A}}\nabla_{\theta}\pi(a\given s,\theta)\left(r(s,a)+\gamma\sum_{s'}v_{\pi}(s')p(s'\given s,a)\right)+\sum_{a\in\mathcal{A}}\pi(a\given s,\theta)\,\gamma\sum_{s'}\big(\nabla_{\theta}v_{\pi}(s')\big)p(s'\given s,a). \]

Step 2: name the bracket. By Equation 2.5 the bracket is \(q_{\pi}(s,a)\), so \[ \nabla_{\theta}v_{\pi}(s)=\sum_{a\in\mathcal{A}}\nabla_{\theta}\pi(a\given s,\theta)\,q_{\pi}(s,a)+\gamma\sum_{a\in\mathcal{A}}\pi(a\given s,\theta)\sum_{s'\in\mathcal{S}}\big(\nabla_{\theta}v_{\pi}(s')\big)p(s'\given s,a). \] The second term uses the policy-averaged transition \(p_{\pi}\) (Definition 2.1). To express the first as an expectation under \(\pi\), use the log identity below.

Step 3: the log trick. Multiply and divide by \(\pi\), which is legitimate because \(\pi>0\): \[ \nabla_{\theta}\pi(a\given s,\theta)=\pi(a\given s,\theta)\,\frac{\nabla_{\theta}\pi(a\given s,\theta)}{\pi(a\given s,\theta)}=\pi(a\given s,\theta)\,\nabla_{\theta}\ln\pi(a\given s,\theta), \tag{4.8}\] the second equality being the chain rule for \(\ln\). Substituting, both terms now carry the same weights \(\pi(a\given s,\theta)\) and can be collected: \[ \nabla_{\theta}v_{\pi}(s)=\sum_{a\in\mathcal{A}}\pi(a\given s,\theta)\left(\nabla_{\theta}\ln\pi(a\given s,\theta)\,q_{\pi}(s,a)+\gamma\sum_{s'\in\mathcal{S}}\big(\nabla_{\theta}v_{\pi}(s')\big)p(s'\given s,a)\right). \tag{4.9}\]

Step 4: read it as a Bellman equation and solve. Equation 4.9 has exactly the shape of the stochastic-policy Bellman equation, with unknown \(x(s)=\nabla_{\theta}v_{\pi}(s)\) and state-action reward \[ \rho(s,a)\defeq q_{\pi}(s,a)\,\nabla_{\theta}\ln\pi(a\given s,\theta). \] As in Step 4 of the deterministic proof, \(I-\gamma\mathbf{P}_{\pi}\) is invertible for \(\gamma\in(0,1)\) because \(\mathbf{P}_{\pi}\) is row-stochastic, so the fixed point is unique and equals its present discounted value: \[ \nabla_{\theta}v_{\pi}(s_{0})=\E_{0}\!\left[\sum_{t=0}^{\infty}\gamma^{t}\,q_{\pi}(s_{t},a_{t})\,\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta)\right],\qquad a_{t}\sim\pi(\cdot\given s_{t},\theta). \]

Step 5: average over starting states. Drawing \(s_{0}\sim\mu\) in Equation 4.3 gives Equation 4.7. \(\square\)

Sampling the policy gradient

The weights \(\nabla_{\theta}\pi(a\given s,\theta)\) in Step 2 may be negative and sum to zero: differentiating \(\sum_{a}\pi(a\given s,\theta)=1\) gives \(\sum_{a}\nabla_{\theta}\pi(a\given s,\theta)=0\). The identity Equation 4.8 moves the derivative into the integrand, leaving probabilities \(\pi(a\given s,\theta)\) as weights. The score, \(\nabla_{\theta}\ln\pi(a\given s,\theta)\), is evaluated at sampled \((s,a)\). This is the likelihood-ratio estimator in simulation and the score-function identity used in statistics.

Softmax builds the required positivity, \(\pi>0\), into the policy.

Example 4.1 (Softmax parameterization) Let \(h(s,a,\theta)\) be an arbitrary differentiable preference function, for example the output of a neural network, and set \[ \pi(a\given s,\theta)=\frac{e^{h(s,a,\theta)}}{\sum_{a'\in\mathcal{A}}e^{h(s,a',\theta)}}. \tag{4.10}\] Because the exponential is strictly positive, \(\pi(a\given s,\theta)\in(0,1)\) for every \((s,a)\) and \(\sum_{a}\pi(a\given s,\theta)=1\) automatically. The score has a clean form: \[ \nabla_{\theta}\ln\pi(a\given s,\theta)=\nabla_{\theta}h(s,a,\theta)-\sum_{a'\in\mathcal{A}}\pi(a'\given s,\theta)\,\nabla_{\theta}h(s,a',\theta), \] the gradient of the chosen action’s preference minus its average across actions.

Important

Under Equation 4.10, similar preferences give a diffuse action distribution; separated preferences make the policy nearly deterministic.

Comparing the two theorems

Table 4.1: The deterministic and stochastic policy gradient theorems require different value estimates.
Deterministic, Theorem 4.1 Stochastic, Theorem 4.2
Policy \(a=\pi(s,\theta)\), an action \(a\sim\pi(\cdot\given s,\theta)\), a distribution
Gradient \(\E_{0}\big[\sum_{t}\gamma^{t}\nabla_{a}q_{\pi}(s_{t},a_{t})\nabla_{\theta}\pi(s_{t},\theta)\big]\) \(\E_{0}\big[\sum_{t}\gamma^{t}q_{\pi}(s_{t},a_{t})\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta)\big]\)
Needs estimated \(q_{\pi}\) and its action-derivative \(\nabla_{a}q_{\pi}\) \(q_{\pi}\) only, at visited pairs
Action space continuous, or \(\nabla_{a}\) is meaningless finite or continuous
Action sampling one chosen action per state randomizes when \(\pi>0\); repeated visitation needs further conditions
Where the \(\theta\)-derivative sits on the action, hence on \(r\) and \(p\) on \(\pi\) alone, hence never on the model

Estimate \(q_{\pi}(s,a)\) with Monte-Carlo returns (Equation 2.6), Sarsa (Equation 3.7), or Sarsa with function approximation (Equation 3.14). Estimating \(\nabla_{a}q_{\pi}(s,a)\) also requires information about neighboring actions. Finite differences amplify value-estimation noise, and a deterministic policy supplies only one action per state. Deep Deterministic Policy Gradient therefore adds exploration and a critic differentiable in the action.

The algorithms below use Equation 4.7, which requires only \(q_{\pi}(s_{t},a_{t})\) at visited pairs.

4.5 REINFORCE

Sample a trajectory and truncate Equation 4.7 at horizon \(T\):

\[ \theta_{j+1}=\theta_{j}+\alpha\sum_{t=0}^{T}\gamma^{t}\,q_{\pi}(s_{t},a_{t})\,\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta_{j}). \]

The score \(\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta_{j})\) is computable from the chosen policy function. The unknown \(q_{\pi}(s_{t},a_{t})\) is estimated by Monte Carlo or TD, as in Table 3.1.

For Monte Carlo, use the return

\[ G_{t}\defeq\sum_{k=t}^{T}\gamma^{k-t}r_{k+1}. \]

If \(T\) is the last decision in a complete terminating episode and later rewards are zero, \(\E[G_t\mid s_t,a_t]=q_\pi(s_t,a_t)\). At an artificial cutoff, the missing term is the continuation value: \[ q_\pi(s_t,a_t)=\E_\pi\!\left[G_t+\gamma^{T-t+1}v_\pi(s_{T+1})\mid s_t,a_t\right]. \] The full-episode algorithm below uses the first case. The numerical comparison caps episodes at 80 steps, so its truncated returns can carry bias.

In Figure 4.2, one action advances along six corridor states and the other goes back, stopping at the wall at \(s_{0}\). Exiting the far end pays 10 and ends the episode; other rewards have mean zero, and all carry \(N(0,3^{2})\) noise. step(s, a) returns the next state, reward, and termination flag. prob_back(theta, s) evaluates Equation 4.10 at \(s\).

NoteAlgorithm: REINFORCE (Monte-Carlo policy gradient)

Initialize \(\theta_{0}\), a step size \(\alpha>0\), and a discount \(\gamma\in(0,1)\). For each episode \(j=0,1,2,\dots\)

  1. Generate a full episode \(s_{0},a_{0},r_{1},\dots,s_{T},a_{T},r_{T+1}\) by following \(\pi(\cdot\given\cdot,\theta_{j})\), indexing rewards as in Chapter 3 so that \(r_{t+1}\) is the reward for acting at \(t\).
  2. Compute the returns \(G_{t}=\sum_{k=t}^{T}\gamma^{k-t}r_{k+1}\) for \(t=0,\dots,T\).
  3. Update the policy parameter once: \[ \theta_{j+1}=\theta_{j}+\alpha\sum_{t=0}^{T}\gamma^{t}\,G_{t}\,\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta_{j}). \tag{4.11}\]

REINFORCE is episodic (Definition 3.1): each \(G_t\) uses rewards through the episode’s end, so the update waits for the final reward.

TipWhat the update does, one term at a time

Write a single term of Equation 4.11 using Equation 4.8 in reverse: \[ \alpha\gamma^{t}G_{t}\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta_{j})=\alpha\gamma^{t}\underbrace{\frac{G_{t}}{\pi(a_{t}\given s_{t},\theta_{j})}}_{\text{weight}}\nabla_{\theta}\pi(a_{t}\given s_{t},\theta_{j}), \] For this term alone, a positive \(G_t\) moves along the gradient of the sampled action’s probability; a negative \(G_t\) reverses the direction. The size also depends on that gradient. With tabular softmax preferences, the score is \(e_{a_t}-\pi(\cdot\mid s_t)\), whose entries stay between \(-1\) and \(1\) even for a rare action.

Softmax randomizes at each finite parameter value. Repeated exploration depends on the sequence of probabilities: an action sampled with probability \(2^{-t}\) has a finite expected total number of visits, although its probability is always positive.

Parameters in the post-episode loop

Equation 4.11 evaluates every score at the parameter \(\theta_j\) that generated the episode, as in Moll’s episode-level formula and Murphy’s equation (3.19).

NoteDerivation: accumulating the episode gradient

Write \(\theta_{j}^{t}\) for the running value of the accumulator inside episode \(j\), initialized at \(\theta_{j}^{0}=\theta_{j}\). The inner loop performs \[ \theta_{j}^{t+1}=\theta_{j}^{t}+\alpha\gamma^{t}G_{t}\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta_{j}),\qquad t=0,\dots,T. \] Holding the score’s argument at \(\theta_j\) makes each increment a fixed vector. Unrolling the recursion gives \[ \theta_{j}^{T+1}=\theta_{j}^{0}+\alpha\sum_{t=0}^{T}\gamma^{t}G_{t}\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta_{j})=\theta_{j+1}, \] which is Equation 4.11.

NoteSuccessive post-episode updates

Sutton and Barto (§13.3), Zhao (Algorithm 9.1), and Murphy (Algorithm 3) print parameter assignments inside the post-episode loop without a separate frozen copy. With these assignments, the score’s parameter changes between terms. The update uses a completed episode and differs from Equation 4.11 at a finite step size. Returns sampled under \(\theta_j\) generally give a biased policy-gradient estimate at the changed parameter. To implement Equation 4.11, evaluate all scores at \(\theta_j\) before updating, or retain a frozen copy.

4.6 The discounted state visitation distribution

Absorb the \(\gamma^{t}\) weights in Equation 4.7 into a distribution over states.

Definition 4.1 (Discounted state visitation distribution) For a policy \(\pi\) and an initial distribution \(\mu\), define \[ d_{\pi,\mu}(s)\defeq(1-\gamma)\sum_{t=0}^{\infty}\gamma^{t}\,\Prob\big(s_{t}=s\ \given\ s_{0}\sim\mu,\ \pi\big). \tag{4.12}\]

A visit to \(s\) at time \(t\) has weight \(\gamma^{t}\). The factor \((1-\gamma)\) normalizes total discounted occupancy to one.

NoteProof that \(d_{\pi,\mu}\) is a probability distribution

Every term in Equation 4.12 is nonnegative. To show the entries sum to one, use matrix notation.

Let \(\mathbf{P}_{\pi}\) be the \(n\times n\) policy-averaged transition matrix built from Definition 2.1, with \((\mathbf{P}_{\pi})_{ij}=p_{\pi}(s_{j}\given s_{i})\), and let \(\boldsymbol{\mu}\) be the column vector of initial probabilities. If \(\boldsymbol{\mu}_{t}\) denotes the distribution of \(s_{t}\) as a column vector, then \[ \boldsymbol{\mu}_{t+1}(j)=\sum_{i}\boldsymbol{\mu}_{t}(i)\,(\mathbf{P}_{\pi})_{ij} \qquad\Longleftrightarrow\qquad \boldsymbol{\mu}_{t+1}=\mathbf{P}_{\pi}^{\!\top}\boldsymbol{\mu}_{t}, \] so \(\boldsymbol{\mu}_{t}=(\mathbf{P}_{\pi}^{\!\top})^{t}\boldsymbol{\mu}\) and Equation 4.12 is \[ \mathbf{d}_{\pi,\mu}=(1-\gamma)\sum_{t=0}^{\infty}\gamma^{t}\big(\mathbf{P}_{\pi}^{\!\top}\big)^{t}\boldsymbol{\mu}. \] Now sum the entries by taking the inner product with the vector of ones \(\mathbf{1}\): \[ \mathbf{d}_{\pi,\mu}^{\!\top}\mathbf{1}=(1-\gamma)\sum_{t=0}^{\infty}\gamma^{t}\,\boldsymbol{\mu}^{\!\top}\mathbf{P}_{\pi}^{t}\,\mathbf{1}. \] Two facts finish it. First, \(\mathbf{P}_{\pi}\) is row-stochastic, meaning each row is a probability distribution over next states, so \(\mathbf{P}_{\pi}\mathbf{1}=\mathbf{1}\); by induction \(\mathbf{P}_{\pi}^{t}\mathbf{1}=\mathbf{1}\) for every \(t\). Second, \(\boldsymbol{\mu}\) is a distribution, so \(\boldsymbol{\mu}^{\!\top}\mathbf{1}=1\). Hence every term of the sum collapses to \(\gamma^{t}\), and \[ \mathbf{d}_{\pi,\mu}^{\!\top}\mathbf{1}=(1-\gamma)\sum_{t=0}^{\infty}\gamma^{t}=(1-\gamma)\cdot\frac{1}{1-\gamma}=1. \qquad\square \]

Figure 4.1 solves Equation 4.12 on the six-state corridor and compares \(d_{\pi,\mu}\) with the initial distribution \(\mu\) and its long-run limit as \(\gamma\to1\).

Solving the visitation distribution exactly at two discount factors
import matplotlib.pyplot as plt

# --- the same six-state corridor, made continuing ------------------------------
# States s0 -> ... -> s5 as behind @fig-4-reinforce-qac: advancing moves one state right,
# going back moves one left and bumps a wall at s0, and advancing from s5 steps off the
# end. There it ended the episode; here it RESTARTS at s0, which is the continuing
# version of the same corridor and is what gives the chain a long-run distribution for
# d to be compared against. d itself needs no such fix, only the comparison does.
# Nothing below is random: every number is a linear solve, so the figure is exact.
N_S = 6
P_BACK = 0.25  # the softmax @eq-softmax at a preference gap of ln 3 in favour of advancing
GAMMAS = (0.5, 0.95)  # 0.95 is the corridor's own discount factor


def transition_matrix(p_back):
    """P_pi of @def-policy-averaged: row s is the distribution of the next state."""
    P = np.zeros((N_S, N_S))
    for s in range(N_S):
        if s < N_S - 1:
            P[s, s + 1] += 1.0 - p_back
        else:
            P[s, 0] += 1.0 - p_back  # off the far end and back to the start
        P[s, max(s - 1, 0)] += p_back  # the wall at s0
    return P


def visitation(P, mu, gamma):
    """d_{pi,mu} of @eq-dvisit in closed form, not by simulation.

    The vector form d = (1-gamma) sum_t gamma^t (P^T)^t mu is a Neumann series, so the
    whole infinite sum collapses to one linear solve. No sampling, no truncation of the
    tail, no Monte-Carlo error anywhere in the figure.
    """
    return (1.0 - gamma) * np.linalg.solve(np.eye(N_S) - gamma * P.T, mu)


def stationary(P):
    """The undiscounted long-run distribution: the one that solves d = P_pi^T d.

    Stacking those fixed-point equations with the normalization 1^T d = 1 gives an
    overdetermined system with exactly one solution, which least squares returns.
    """
    A = np.vstack([P.T - np.eye(N_S), np.ones(N_S)])
    return np.linalg.lstsq(A, np.r_[np.zeros(N_S), 1.0], rcond=None)[0]


P = transition_matrix(P_BACK)
mu = np.zeros(N_S)
mu[0] = 1.0  # every episode starts at s0
d_inf = stationary(P)
ds = [visitation(P, mu, g) for g in GAMMAS]

# Position along the corridor, so that E[position] summarizes a whole distribution in one
# number and the interpolation from mu to the long run can be drawn as a single curve.
pos = np.arange(N_S)
grid = np.linspace(0.0, 0.995, 400)
sweep = np.array([visitation(P, mu, g) @ pos for g in grid])

series = [(mu, INK), (ds[0], COL["sky"]), (ds[1], COL["blue"]), (d_inf, GREY)]

fig, (axL, axR) = plt.subplots(1, 2, figsize=(9.6, 4.0))
trim(axL), trim(axR)

# --- left: the four distributions over the same six states -------------------
w = 0.2
for k, (v, colour) in enumerate(series):
    axL.bar(pos + (k - 1.5) * w, v, width=w * 0.92, color=colour, zorder=3)
axL.set_xticks(pos)
axL.set_xticklabels([rf"$s_{{{s}}}$" for s in pos])
axL.set_xlim(-0.62, 5.62)
axL.set_ylim(0, 1.15)
axL.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
axL.set_xlabel("state")
axL.set_ylabel("probability")
axL.set_title("Discounting tilts the weight toward the states reached first",
              fontsize=11)

# Each label sits above its own bars, in space no bar reaches: the whole upper half of
# the panel is empty except for mu's single spike at s0.
label_at(axL, -0.28, 1.06, r"$\mu$: all mass on $s_{0}$", color=INK, fontsize=9.5)
label_at(axL, 0.02, 0.70, r"$d_{\pi,\mu}$ at $\gamma=0.5$",
         color=COL["sky"], fontsize=9.5)
label_at(axL, 2.15, 0.32, r"$d_{\pi,\mu}$ at $\gamma=0.95$",
         color=COL["blue"], fontsize=9.5)
label_at(axL, 5.45, 0.26, "undiscounted\nlong run", color=GREY, fontsize=9.5,
         ha="right", va="bottom", linespacing=1.35)
label_at(axL, 1.95, 0.94,
         r"$\mathbf{d}_{\pi,\mu}=(1-\gamma)(\mathbf{I}-\gamma"
         r"\mathbf{P}_{\pi}^{\top})^{-1}\boldsymbol{\mu}$, solved exactly;"
         "\nall four series sum to 1",
         color=INK, fontsize=9, va="top", linespacing=1.5)

# --- right: where d lands, as gamma runs the whole way from 0 to 1 -----------
# Only the long-run rule is drawn. The other endpoint is mu, whose mean position is zero,
# so its rule would lie under the axis spine and add ink without adding information.
axR.plot([0, 1], [d_inf @ pos] * 2, color=GREY, lw=0.9, ls="--", zorder=2)
axR.plot(grid, sweep, color=INK, lw=2.0, zorder=4)
for g, (_, colour) in zip(GAMMAS, series[1:3]):
    y = visitation(P, mu, g) @ pos
    axR.plot([g, g], [0, y], color=colour, lw=0.9, ls=":", zorder=3)
    axR.plot([g], [y], "o", color=colour, ms=6, zorder=5)
axR.set_xlim(0, 1.0)
axR.set_ylim(0, 2.75)
axR.set_xticks([0, 0.25, 0.5, 0.75, 1.0])
axR.set_xlabel(r"discount factor $\gamma$")
axR.set_ylabel("mean position along the corridor")
axR.set_title(r"$\gamma$ dials $d_{\pi,\mu}$ from $\mu$ to the long run", fontsize=11)

# Every label sits in the wedge the curve leaves empty: the two endpoint tags at the left
# margin, one above the dashed rule and one above the curve's flat start, and each marked
# gamma beside its own drop line, low enough that the curve is nowhere near.
label_at(axR, 0.02, d_inf @ pos + 0.15, r"$\gamma\to1$: the undiscounted long run",
         color=GREY, fontsize=9)
label_at(axR, 0.03, 0.52, r"$\gamma=0$: $d_{\pi,\mu}=\mu$", color=GREY, fontsize=9)
label_at(axR, 0.53, 0.22, r"$\gamma=0.5$", color=COL["sky"], fontsize=9.5)
label_at(axR, 0.92, 0.80, r"$\gamma=0.95$", color=COL["blue"], fontsize=9.5, ha="right")

fig.tight_layout()

# ponytail: one runnable check of the figure's claims, on the exact numbers plotted. Each
# row is a probability distribution, which is what @def-visitation asserts; the four are
# ordered by first-order stochastic dominance, mu earliest and the long run latest, which
# is the sense in which d sits between them; and d minus the long run changes sign exactly
# once, which is the "more weight early, less weight late" the left title claims.
rows = np.array([mu] + ds + [d_inf])
assert np.allclose(rows.sum(axis=1), 1.0)
assert np.all(np.diff(np.cumsum(rows, axis=1), axis=0) <= 1e-12)
assert all(np.count_nonzero(np.diff(np.sign(d - d_inf))) == 1 for d in ds)
plt.show()
Figure 4.1: The six-state corridor of Figure 4.2, with a fixed policy that advances with probability 0.75 at every state, the softmax Equation 4.10 at a preference gap of \(\ln3\). Stepping off the far end restarts at \(s_{0}\), making the chain continuing. The Neumann series in Equation 4.12 gives \(\mathbf{d}_{\pi,\mu}=(1-\gamma)(\mathbf{I}-\gamma\mathbf{P}_{\pi}^{\top})^{-1}\boldsymbol{\mu}\), used to compute every bar. Left: \(\mu\) puts all mass on \(s_{0}\); the long-run distribution is nearly flat because the policy spends comparable time in all six states. The discounted distribution is a geometric average of the time-\(t\) state distributions with weights \((1-\gamma)\gamma^{t}\). Early states receive more weight than in the long run and later states less; the crossover moves from between \(s_{1}\) and \(s_{2}\) at \(\gamma=0.5\) to between \(s_{2}\) and \(s_{3}\) at \(\gamma=0.95\). Right: mean position under \(d_{\pi,\mu}\) as \(\gamma\) varies. At \(\gamma=0\), \(d_{\pi,\mu}=\mu\); the long-run value is reached as \(\gamma\to1\). At \(\gamma=0.95\) the mean is 2.10, compared with 2.32 in the long run. The expectation in Equation 4.13 uses \(d_{\pi,\mu}\), which differs from the distribution of states sampled along an ongoing trajectory.

The simple expectation form

NoteDerivation: from the discounted sum to a single expectation

Start from the present-discounted-value form Equation 4.7 and exchange the sum and the expectation, which is legitimate by dominated convergence when rewards are bounded and \(\gamma<1\): \[ \nabla_{\theta}J(\theta)=\sum_{t=0}^{\infty}\gamma^{t}\,\E\big[q_{\pi}(s_{t},a_{t})\,\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta)\big]. \]

Now write out the time-\(t\) expectation by conditioning first on the state and then on the action. Given \(s_{t}=s\), the action is drawn from \(\pi(\cdot\given s,\theta)\) regardless of \(t\), so \[ \E\big[q_{\pi}(s_{t},a_{t})\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta)\big] =\sum_{s\in\mathcal{S}}\Prob(s_{t}=s)\underbrace{\sum_{a\in\mathcal{A}}\pi(a\given s,\theta)\,q_{\pi}(s,a)\,\nabla_{\theta}\ln\pi(a\given s,\theta)}_{\defeq\ g(s)}, \] where \(\Prob(s_{t}=s)\) abbreviates \(\Prob(s_{t}=s\given s_{0}\sim\mu,\pi)\). Since \(g(s)\) is independent of \(t\), collect the time weights at each state: \[ \nabla_{\theta}J(\theta)=\sum_{s\in\mathcal{S}}\underbrace{\left[\sum_{t=0}^{\infty}\gamma^{t}\Prob(s_{t}=s)\right]}_{=\ d_{\pi,\mu}(s)/(1-\gamma)}g(s) =\frac{1}{1-\gamma}\sum_{s\in\mathcal{S}}d_{\pi,\mu}(s)\,g(s), \] the identification of the bracket being Equation 4.12 divided by \((1-\gamma)\). Finally, \(\sum_{s}d_{\pi,\mu}(s)(\cdot)\) is an expectation because Definition 4.1 is a distribution, and \(g(s)\) is itself an expectation over \(a\sim\pi(\cdot\given s,\theta)\). Composing the two gives Equation 4.13. \(\square\)

\[ \nabla_{\theta}J(\theta)=\frac{1}{1-\gamma}\,\E_{s\sim d_{\pi,\mu},\ a\sim\pi(\cdot\given s,\theta)}\big[\,q_{\pi}(s,a)\,\nabla_{\theta}\ln\pi(a\given s,\theta)\,\big]. \tag{4.13}\]

Important

In Equation 4.13, \(d_{\pi,\mu}\) incorporates the trajectory weights \(\gamma^{t}\). Given an estimate of the action value, one sampled pair \((s,a)\) supports a gradient update.

WarningTwo conveniences hidden in the implementation

Absorb \(1/(1-\gamma)\) into the step size \(\alpha\). To sample \(s\) from \(d_{\pi,\mu}\), start from \(\mu\) and stop with probability \(1-\gamma\) at each step. Using states from an ongoing trajectory changes the sampling distribution; absorbing the constant does not.

4.7 Actor-critic methods

What actor and critic mean

Definition 4.2 (Actor and critic) The actor updates policy parameters \(\theta\). The critic estimates \(q_{\pi}\) for the actor.

Actor-critic methods update the policy and value estimate in the same loop.

Which critic

To sample the gradient in Equation 4.13, draw \(s_t\sim d_{\pi,\mu}\) and \(a_t\sim\pi(\cdot\mid s_t)\), absorb \(1/(1-\gamma)\) into \(\alpha\), and update

\[ \theta_{t+1}=\theta_{t}+\alpha\,q_{\pi}(s_{t},a_{t})\,\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta_{t}). \tag{4.14}\]

Estimate \(q_{\pi}(s_{t},a_{t})\) using either:

  • Monte Carlo, substituting the realized return \(G_{t}\). That is REINFORCE, Equation 4.11, and it is episodic.
  • Temporal difference, substituting a bootstrapped estimate maintained by its own recursion. That is actor-critic, and it is incremental.

The QAC algorithm

The simplest instance keeps a parametric action-value function \(\hat{q}(s,a,w)\) and trains it by Sarsa with function approximation. It is usually called Q actor-critic.

NoteAlgorithm: Q actor-critic (QAC)

Initialize policy parameters \(\theta_{0}\), critic parameters \(w_{0}\), and step sizes \(\alpha_{\theta},\alpha_{w}>0\). At each time step \(t\) of each episode:

  1. Interact. Take \(a_{t}\sim\pi(\cdot\given s_{t},\theta_{t})\), observe \(r_{t+1}\) and \(s_{t+1}\), and draw \(a_{t+1}\sim\pi(\cdot\given s_{t+1},\theta_{t})\).

  2. Critic (value update). \[ w_{t+1}=w_{t}+\alpha_{w}\big[\,r_{t+1}+\gamma\hat{q}(s_{t+1},a_{t+1},w_{t})-\hat{q}(s_{t},a_{t},w_{t})\,\big]\nabla_{w}\hat{q}(s_{t},a_{t},w_{t}). \tag{4.15}\]

  3. Actor (policy update). \[ \theta_{t+1}=\theta_{t}+\alpha_{\theta}\,\hat{q}(s_{t},a_{t},w_{t})\,\nabla_{\theta}\ln\pi(a_{t}\given s_{t},\theta_{t}). \tag{4.16}\]

The critic update Equation 4.15 is Sarsa with function approximation (Equation 3.14). The actor replaces \(q_{\pi}(s_{t},a_{t})\) in Equation 4.14 with \(\hat{q}(s_{t},a_{t},w_{t})\).

Both update incrementally. In the code below, states come from ordinary episodes rather than draws from \(d_{\pi,\mu}\). The actor step is therefore an approximation to the gradient of \(J\); the discount factor in the critic does not supply the missing state weights.

Both algorithms on one corridor, scored by the exact objective
def run_reinforce(grid):
    """REINFORCE @eq-reinforce: one full episode in, ONE parameter update out."""
    theta = np.zeros((N_S, 2))
    curve = np.full(len(grid), objective(theta))
    k, steps, n_updates = 1, 0, 0
    while steps < BUDGET:
        s, traj = 0, []
        for _ in range(T_MAX):  # 1. generate a full episode
            p1 = prob_back(theta, s)
            a = 1 if RNG.random() < p1 else 0
            s2, r, done = step(s, a)
            traj.append((s, a, r, p1))
            s = s2
            if done:
                break
        steps += len(traj)
        # The whole episode is scored first, then theta moves once: every score below is
        # evaluated at the theta that generated the episode, per @eq-reinforce. The three
        # lines touching g are the softmax score of @exm-softmax written out by hand for
        # two actions, and g accumulates the entire sum before theta moves at all.
        g, G = np.zeros((N_S, 2)), 0.0  # 2. returns, accumulated backwards
        for t in range(len(traj) - 1, -1, -1):
            s_, a_, r_, p1_ = traj[t]
            G = r_ + GAMMA * G  # G_t, the Monte-Carlo estimate of q_pi(s_t, a_t)
            d = GAMMA**t * G
            g[s_, a_] += d
            g[s_, 0] -= d * (1.0 - p1_)
            g[s_, 1] -= d * p1_
        theta += ALPHA_THETA * g  # 3. ONE update, after the episode
        n_updates += 1
        k = record(curve, k, grid, steps, theta)
    return curve, n_updates


def run_qac(grid):
    """QAC @eq-qac-critic and @eq-qac-actor: one transition in, one update out.

    The actor reads q_sa before the critic update. It uses ordinary episode states
    without gamma**t weights, so it approximates the gradient of J rather than
    sampling d_{pi,mu} exactly. The critic is the table q(s,a) = w[s,a].
    """
    theta, w = np.zeros((N_S, 2)), np.zeros((N_S, 2))  # actor table, critic table
    curve = np.full(len(grid), objective(theta))
    k, steps = 1, 0
    while steps < BUDGET:
        s = 0
        p1 = prob_back(theta, s)
        a = 1 if RNG.random() < p1 else 0
        for _ in range(T_MAX):
            s2, r, done = step(s, a)  # 1. interact
            if done:
                target = r
            else:
                p1n = prob_back(theta, s2)
                a2 = 1 if RNG.random() < p1n else 0
                target = r + GAMMA * w[s2, a2]  # bootstrap, not a realized return
            q_sa = w[s, a]
            w[s, a] += ALPHA_W * (target - q_sa)  # 2. critic, @eq-qac-critic
            # The score must be read at the CURRENT theta. Reusing the p1 cached when
            # this state was entered is stale whenever the actor already moved row s,
            # which happens on every wall bump where s2 == s.
            pp = prob_back(theta, s)
            theta[s, a] += ALPHA_THETA * q_sa  # 3. actor, one per transition
            theta[s, 0] -= ALPHA_THETA * q_sa * (1.0 - pp)
            theta[s, 1] -= ALPHA_THETA * q_sa * pp
            steps += 1
            k = record(curve, k, grid, steps, theta)
            if done or steps >= BUDGET:
                break
            s, a, p1 = s2, a2, p1n
    return curve  # its update count is the step count, so there is nothing to report


grid = np.linspace(0, BUDGET, 201)
runs = [run_reinforce(grid) for _ in range(N_RUNS)]
rein, n_up = np.array([c for c, _ in runs]), np.mean([n for _, n in runs])
qac = np.array([run_qac(grid) for _ in range(N_RUNS)])

# Check the plotted comparison for this seed and configuration.
# The algorithms differ in targets, update timing and time weights.
m_rein, m_qac = np.median(rein, axis=0), np.median(qac, axis=0)
iqr = {k: np.percentile(a, 75, axis=0) - np.percentile(a, 25, axis=0)
       for k, a in (("rein", rein), ("qac", qac))}
half = len(m_qac) // 2
assert np.all(m_qac[half:] > m_rein[half:]), "QAC median does not lead throughout"
assert np.all(iqr["rein"][[half, -1]] > iqr["qac"][[half, -1]]), "REINFORCE not the wider"

fig, ax = new_ax(6.8, 4.6)
j_opt = GAMMA ** (N_S - 1) * R_GOAL
ax.plot([0, BUDGET], [j_opt, j_opt], color=GREY, lw=0.9, ls="--", zorder=2)

for arr, colour in ((rein, COL["sky"]), (qac, COL["vermilion"])):
    lo, med, hi = np.percentile(arr, [25, 50, 75], axis=0)
    ax.fill_between(grid, lo, hi, color=colour, alpha=0.22, lw=0, zorder=3)
    ax.plot(grid, med, color=colour, lw=2.0, zorder=5)

ax.set_xlim(0, BUDGET * 1.02)
ax.set_ylim(2.2, 8.2)  # headroom above the dashed rule carries its tag, not data
ax.set_xticks([0, 5000, 10000, 15000, 20000])
ax.set_xticklabels(["0", "5k", "10k", "15k", "20k"])
ax.set_xlabel("environment steps (transitions consumed)")
ax.set_ylabel(r"$J(\theta)=v_{\pi}(s_{0})$")

# Every label sits in space no curve or band enters: the reference tag above the dashed
# rule, "QAC" in the empty wedge above its own steep rise, "REINFORCE" under its own curve,
# and the two notes in the whole empty lower-right quadrant.
label_at(ax, 300, 7.94, r"$J$ at the optimal policy", color=GREY, fontsize=8.5)
label_at(ax, 3000, 6.95, "QAC", color=COL["vermilion"], fontsize=10.5)
label_at(ax, 6300, 5.25, "REINFORCE", color=COL["sky"], fontsize=10.5)
label_at(ax, 11200, 4.55, f"shaded: interquartile range across {N_RUNS} runs",
         color=GREY, fontsize=8.5, va="top")
label_at(ax, 11200, 3.85,
         "the same 20k transitions buy QAC 20,000\n"
         f"updates and REINFORCE {n_up:,.0f}, one per episode",
         color=INK, fontsize=8.5, va="top")
ax.set_title("REINFORCE and QAC on the six-state corridor", fontsize=11)
plt.show()
Figure 4.2: REINFORCE Equation 4.11 and QAC Equation 4.16 on the same six-state corridor, charged against environment steps rather than updates. Every episode starts at \(s_{0}\), one action advances along the corridor and one goes back, stepping off the far end pays \(10\) and ends the episode, every other reward is zero in expectation, and every reward carries independent \(N(0,3^{2})\) noise; \(\gamma=0.95\) and episodes are capped at 80 steps. The policy is the softmax Equation 4.10 on a table of preferences, the critic is a table trained by Equation 3.14 with \(\alpha_{w}=0.05\); and both algorithms use the same actor step size \(\alpha_{\theta}=0.003\). Lines are medians and bands interquartile ranges over 60 runs, with \(J(\theta)=v_{\pi}(s_{0})\) solved for exactly at every point, so the width of a band is dispersion in the learned \(\theta\) rather than measurement noise. QAC’s median improves little during its first thousand steps, and REINFORCE briefly leads. QAC then leads in the plotted medians. Timing: 20,000 transitions buy QAC 20,000 parameter updates and REINFORCE about 2,000, one per episode, and by 5,000 steps the median \(J\) is \(6.9\) against \(5.5\). At 10,000 steps, REINFORCE’s interquartile range is roughly three times QAC’s.

Figure 4.3 reports action probabilities at each state from independent QAC runs on the same corridor as Figure 4.2.

Watching the softmax policy sharpen at all six states as QAC ascends
import matplotlib.pyplot as plt

RNG = np.random.default_rng(20260725)

# --- the corridor of @fig-4-reinforce-qac, unchanged --------------------------
# Six states s0 -> ... -> s5. Action 0 ADVANCES, and from s5 it steps off the end,
# collects R_GOAL and ends the episode; action 1 GOES BACK, and at s0 it bumps into
# the wall. Advancing is therefore the good action at every state, which is what makes
# a single probability per state the whole policy worth watching.
N_S, GAMMA, R_GOAL, SD, T_MAX = 6, 0.95, 10.0, 3.0, 80
ALPHA_THETA, ALPHA_W = 0.003, 0.05
BUDGET, N_RUNS, LEVEL = 20_000, 60, 0.75
GRID = np.linspace(0, BUDGET, 201)


def step(s, a):
    """One transition: returns (next state, realized reward, episode over?)."""
    r = RNG.normal(R_GOAL if (a == 0 and s == N_S - 1) else 0.0, SD)
    if a == 0:
        return s + 1, r, s == N_S - 1
    return max(s - 1, 0), r, False


def p_advance(theta):
    """pi(advance | s, theta) at every state: the softmax @eq-softmax, two actions.

    With |A| = 2 the softmax collapses to a logistic in the preference gap, so the
    entire policy is these six numbers and the figure can just plot them.
    """
    return 1.0 / (1.0 + np.exp(theta[:, 1] - theta[:, 0]))


def run_qac():
    """One QAC run; returns pi(advance | s, theta) at every grid point, per state.

    Identical to the QAC of @fig-4-reinforce-qac. What is recorded differs: there the
    run was scored by J(theta), here by the policy itself, sampled on a common grid of
    environment steps and held flat between the crossings of that grid.
    """
    theta, w = np.zeros((N_S, 2)), np.zeros((N_S, 2))
    curve = np.full((len(GRID), N_S), 0.5)  # theta_0 = 0 is a coin flip everywhere
    k, steps = 1, 0
    while steps < BUDGET:
        s = 0
        a = 0 if RNG.random() < p_advance(theta)[s] else 1
        for _ in range(T_MAX):
            s2, r, done = step(s, a)
            if done:
                target = r
            else:
                a2 = 0 if RNG.random() < p_advance(theta)[s2] else 1
                target = r + GAMMA * w[s2, a2]  # bootstrap, not a realized return
            q_sa = w[s, a]  # the critic BEFORE its own update, per @eq-qac-actor
            w[s, a] += ALPHA_W * (target - q_sa)  # critic, @eq-qac-critic
            pa = p_advance(theta)[s]  # the score, read at the CURRENT theta
            theta[s, a] += ALPHA_THETA * q_sa  # actor, @eq-qac-actor
            theta[s, 0] -= ALPHA_THETA * q_sa * pa
            theta[s, 1] -= ALPHA_THETA * q_sa * (1.0 - pa)
            steps += 1
            if k < len(GRID) and GRID[k] <= steps:
                row = p_advance(theta)
                while k < len(GRID) and GRID[k] <= steps:
                    curve[k] = row
                    k += 1
            if done or steps >= BUDGET:
                break
            s, a = s2, a2
    return curve


curves = np.array([run_qac() for _ in range(N_RUNS)])  # runs x grid x state
med = np.median(curves, axis=0)

# When each RUN first puts probability LEVEL on advancing at each state. A run that
# never gets there inside the budget is censored at the budget rather than dropped,
# which understates the lag at s0 instead of hiding it.
hit = curves >= LEVEL
first = np.where(hit.any(axis=1), GRID[hit.argmax(axis=1)], BUDGET)
lo, mid, hi = np.percentile(first, [25, 50, 75], axis=0)

# ponytail: one runnable check of the figure's claim, on the simulated runs themselves.
# The good action must end near certain everywhere without ever reaching one, the fan
# must open in corridor order while it is opening, and the experience each state needs
# to reach LEVEL must fall monotonically as the state gets nearer the goal.
i3k = int(np.argmin(np.abs(GRID - 3000)))
assert 0.85 < med[-1].min() and med[-1].max() < 1.0, np.round(med[-1], 3)
assert np.all(np.diff(med[i3k]) > 0), np.round(med[i3k], 3)
assert np.all(np.diff(mid) < 0), mid

fig, (axL, axR) = plt.subplots(1, 2, figsize=(9.4, 3.9),
                               gridspec_kw={"width_ratios": [1.5, 1]})
trim(axL), trim(axR)

# --- left: the six probabilities, from a coin flip toward one ----------------
# s5 touches the reward and s0 is where J is measured, so those two carry colour and
# the four in between stay grey: the fan's ordering is the right panel's job.
axL.plot([0, BUDGET], [LEVEL, LEVEL], color=GREY, lw=0.9, ls="--", zorder=2)
for j in range(N_S):
    colour = COL["vermilion"] if j == N_S - 1 else COL["blue"] if j == 0 else GREY
    axL.plot(GRID, med[:, j], color=colour, lw=2.0 if colour != GREY else 1.2,
             zorder=5 if colour != GREY else 3)

axL.set_xlim(0, BUDGET * 1.02)
axL.set_ylim(0.44, 1.005)
axL.set_xticks([0, 5000, 10000, 15000, 20000])
axL.set_xticklabels(["0", "5k", "10k", "15k", "20k"])
axL.set_yticks([0.5, 0.6, 0.7, 0.8, 0.9, 1.0])
axL.set_xlabel("environment steps (transitions consumed)")
axL.set_ylabel(r"$\pi(\mathrm{advance}\mid s,\theta)$, median over runs")

# Every label sits where no curve goes: the threshold tag on the dashed rule at the
# right margin, the s5 tag in the empty strip above every curve, and the s0 tag plus
# the grey note in the whole empty lower-right quadrant beneath the slowest curve.
label_at(axL, 17400, 0.716, r"$\pi=0.75$", color=GREY, fontsize=8.5)
label_at(axL, 300, 0.468, r"$\theta_{0}=0$: a coin flip at every state",
         color=GREY, fontsize=8.5)
label_at(axL, 4500, 0.985, r"$s_{5}$, one step from the goal",
         color=COL["vermilion"], fontsize=9.5)
label_at(axL, 6300, 0.632, r"$s_{0}$, the start", color=COL["blue"], fontsize=9.5)
label_at(axL, 6300, 0.560, r"$s_{1}$ to $s_{4}$ in grey", color=GREY, fontsize=8.5)
axL.set_title("Every state's good action climbs toward certainty", fontsize=11)

# --- right: when each state gets there --------------------------------------
# States run up the y-axis so that this panel's vertical order is the left panel's
# fan order, and both panels are read in the same units on x.
axR.plot(mid, range(N_S), color=GREY, lw=1.0, zorder=3)
for j in range(N_S):
    colour = COL["vermilion"] if j == N_S - 1 else COL["blue"] if j == 0 else INK
    axR.plot([lo[j], hi[j]], [j, j], color=GREY, lw=1.4, zorder=4)
    axR.plot([mid[j]], [j], "o", color=colour, ms=6, zorder=5)

axR.set_xlim(0, 8600)
axR.set_ylim(-0.6, 5.6)
axR.set_xticks([0, 2000, 4000, 6000, 8000])
axR.set_xticklabels(["0", "2k", "4k", "6k", "8k"])
axR.set_yticks(range(N_S))
axR.set_yticklabels([rf"$s_{{{j}}}$" for j in range(N_S)])
axR.set_xlabel(r"environment steps to first reach $\pi=0.75$")
label_at(axR, 4500, 5.15, "dot: median across\n"
         f"{N_RUNS} runs, bar: their\ninterquartile range",
         color=GREY, fontsize=8.5, va="top")
axR.set_title("The far end sharpens first, the tilt travels back", fontsize=11)

fig.tight_layout()
plt.show()
Figure 4.3: QAC on the six-state corridor of Figure 4.2, rerun to record the policy. Preferences start at \(\theta_{0}=0\), so Equation 4.10 assigns probability \(1/2\) to each action. The only nonzero expected reward is the \(10\) paid on leaving the far end, making advancing optimal at every state. Left: median probability of advancing at each state across 60 runs. The medians stay near \(1/2\) for roughly the first thousand transitions, then rise. The actor step in Equation 4.16 multiplies the score of Example 4.1 by \(\hat{q}(s_{t},a_{t},w_{t})\); the critic starts at zero, though reward noise can move its estimates before the terminal reward is reached. Right: transitions until the probability of advancing first reaches \(0.75\), with interquartile ranges across runs. States nearer the goal reach this threshold sooner: Equation 4.15 propagates the expected terminal reward backward by bootstrapping, with a factor of \(\gamma\) per state. \(s_{0}\) needs about 5,700 transitions, compared with 2,500 for \(s_{5}\). By 20,000 steps the three states nearest the goal are nearly tied and \(s_{0}\) still lags.
Table 4.2: REINFORCE and Q actor-critic. REINFORCE uses explicit \(\gamma^t\) weights. The unweighted QAC actor matches Equation 4.13 only with states sampled from \(d_{\pi,\mu}\).
REINFORCE, Equation 4.11 QAC, Equation 4.16 and Equation 4.15
Estimate of \(q_{\pi}\) realized return \(G_{t}\), as in Equation 2.6 bootstrapped \(\hat{q}(s,a,w)\), as in Equation 3.14
Timing episodic, in the sense of Definition 3.1 incremental: one update per transition
Value target unbiased return for a complete terminating episode bootstrapped estimate, generally biased before evaluation converges
Sampling noise the actor uses a return containing future reward and transition noise the actor uses the critic; each critic target adds one sampled reward and continuation
What is stored policy parameters \(\theta\) \(\theta\) and critic parameters \(w\)
Task type needs terminal states handles continuing tasks too
Important

The estimator in Equation 4.13 is on-policy: it uses the current policy’s discounted state distribution and action probabilities. Off-policy policy-gradient methods must account for the change in sampling law.

PPO collects a batch under \(\pi_{\mathrm{old}}\) and takes several optimization steps on it. Its clipped surrogate uses the action ratio \(\pi_\theta(a\mid s)/\pi_{\mathrm{old}}(a\mid s)\) times an estimated advantage, and removes the incentive for some large ratio changes. It remains a surrogate evaluated on the old batch; the ratio alone does not turn that batch into exact samples of the new policy’s state distribution.