Chapter 6

Temporal-Difference Learning

Monte Carlo waits for the end of the episode, because only then is the return known; dynamic programming does not wait for anything, but it needs a model. Temporal-difference (TD) learning takes the sampling of the first and the bootstrapping of the second: after a single transition it moves the estimate of the state it has left toward the reward just received plus the estimated value of the state it has reached.Richard S. Sutton. Learning to Predict by the Methods of Temporal Differences. Machine Learning, 3(1):9–44, 1988. doi: 10.1007/BF00115009; and 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 Sutton and Barto call it the idea that is “central and novel to reinforcement learning”, and this chapter shows why. TD learning converges to the right answer, it is faster than Monte Carlo on Markov problems for a reason that can be stated precisely (it computes the maximum-likelihood model’s values without building the model), and its control versions, Sarsa and Q-learning, are the two most widely used algorithms of the field. They also bring a new pathology, maximization bias, with a remedy whose descendants run in today’s deep reinforcement learning.

6.1TD Prediction

Both Monte Carlo and TD methods update an estimate VV of vπv_\pi from experience under π\pi. A simple every-visit Monte Carlo rule with a constant step size, constant-α\alpha MC, is

V(St)←V(St)+α[Gt−V(St)], V(S_t) \leftarrow V(S_t) + \alpha\bigl[G_t - V(S_t)\bigr],

usable only at the end of the episode. The simplest TD method, **TD(0)**, replaces the return by a one-step estimate of it and updates as soon as Rt+1R_{t+1} and St+1S_{t+1} are observed:

V(St)←V(St)+α[Rt+1+γV(St+1)−V(St)]. V(S_t) \leftarrow V(S_t) + \alpha\bigl[R_{t+1} + \gamma V(S_{t+1}) - V(S_t)\bigr]. (6.1)

Algorithm 6.1 (Tabular TD(0)). Input: the policy π\pi. Parameter: step size α∈(0,1]\alpha \in (0, 1]. Initialize: V(s)V(s) arbitrary for s∈𝒮+s \in \mathcal{S}^+, except V(terminal)=0V(\text{terminal}) = 0.

Loop for each episode:

  1. Initialize SS.
  2. Loop for each step of the episode, until SS is terminal:
    • A←A \leftarrow action given by π\pi for SS; take AA, observe R,S′R, S';
    • V(S)←V(S)+α[R+γV(S′)−V(S)]V(S) \leftarrow V(S) + \alpha\bigl[R + \gamma V(S') - V(S)\bigr];
    • S←S′S \leftarrow S'.

The two targets estimate two different expressions of the same value. By definition and by the Bellman equation ((3.9)),

vπ(s)=𝔼π[Gt∣St=s]=𝔼π[Rt+1+γvπ(St+1)∣St=s]. v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s] = \mathbb{E}_\pi\bigl[R_{t+1} + \gamma v_\pi(S_{t+1}) \bigm| S_t = s\bigr].

Monte Carlo estimates the first expression: its target GtG_t is a sample, so the expectation is replaced by one draw, but nothing else is approximated. Dynamic programming uses the second expression with the expectation computed exactly from the model, but with vπv_\pi replaced by the current estimate. The TD target Rt+1+γV(St+1)R_{t+1} + \gamma V(S_{t+1}) does both: it samples the expectation and bootstraps on VV. The TD backup diagram is correspondingly a single sampled transition, a sample update as opposed to the expected updates of dynamic programming.

The bracket in (6.1) is the TD error,

δt≐Rt+1+γV(St+1)−V(St), \delta_t \doteq R_{t+1} + \gamma V(S_{t+1}) - V(S_t), (6.2)

the error in the estimate V(St)V(S_t), available only at time t+1t + 1. If VV is held fixed during an episode, as it is in Monte Carlo methods, the Monte Carlo error is the discounted sum of TD errors:

Gt−V(St)=∑k=tT−1γk−t δk. G_t - V(S_t) = \sum_{k=t}^{T-1}\gamma^{k-t}\,\delta_k. (6.3)

Indeed, Gt−V(St)=Rt+1+γGt+1−V(St)=δt+γ(Gt+1−V(St+1))G_t - V(S_t) = R_{t+1} + \gamma G_{t+1} - V(S_t) = \delta_t + \gamma\bigl(G_{t+1} - V(S_{t+1})\bigr), and unrolling to GT−V(ST)=0−0G_T - V(S_T) = 0 - 0 telescopes. This identity, and its versions for changing VV (Exercise 6.10), nn-step returns and λ\lambda-returns, will tie Monte Carlo and TD together in Chapter 7 and Chapter 12.

6.1.1In Wolfram Language

The identity (6.3) for a three-step episode S0,R1,S1,R2,S2,R3,S3S_0, R_1, S_1, R_2, S_2, R_3, S_3, with Vk≐V(Sk)V_k \doteq V(S_k) and V3=0V_3 = 0 for the terminal state.

Sum the discounted TD errors δk=Rk+1+γVk+1−Vk\delta_k = R_{k+1} + \gamma V_{k+1} - V_k: the intermediate values cancel and what remains is G0−V0G_0 - V_0.
const tdSum = await show`Module[{v = {Subscript[V, 0], Subscript[V, 1], Subscript[V, 2], 0}, r = {Subscript[R, 1], Subscript[R, 2], Subscript[R, 3]}}, Expand[Sum[\[Gamma]^k (r[[k + 1]] + \[Gamma] v[[k + 2]] - v[[k + 1]]), {k, 0, 2}]]]`
∑k=02γkδk=R1+γR2+γ2R3−V0 \sum_{k=0}^{2}\gamma^k\delta_k = R_1+\gamma R_2+\gamma ^2 R_3-V_0

6.2Why TD Learning Works

TD(0) needs no model, unlike dynamic programming, and it learns online, from incomplete episodes and in continuing tasks, unlike Monte Carlo. But it learns a guess from a guess; does it converge to the right answer?

Take the conditional expectation of the TD error given the current state, for a fixed VV:

𝔼π[δt∣St=s]=∑aπ(a∣s)∑s′,rp(s′,r∣s,a)[r+γV(s′)]−V(s)=(TπV)(s)−V(s), \begin{aligned} \mathbb{E}_\pi[\delta_t \mid S_t = s] &= \sum_a \pi(a \mid s)\sum_{s', r}p(s', r \mid s, a)\bigl[r + \gamma V(s')\bigr] - V(s) \\ &= (T_\pi V)(s) - V(s), \end{aligned} (6.4)

where TπT_\pi is the Bellman expectation operator of Chapter 4. In expectation, then, TD(0) performs a damped step of iterative policy evaluation, V←V+α(TπV−V)V \leftarrow V + \alpha(T_\pi V - V), at the visited state; the noise is the difference between the sampled and the expected target. That is exactly the setting of stochastic approximation: a noisy, asynchronous iteration toward the fixed point of an operator that is a γ\gamma-contraction in the max norm (Theorem A.3), or, in undiscounted episodic tasks, a contraction in a weighted max norm when all policies terminate.

Theorem 6.2 (Convergence of tabular TD(0)). Let the policy π\pi be fixed, the rewards have bounded variance, and every state be visited infinitely often. If the step sizes αt(s)\alpha_t(s) used at the visits to each state satisfy ∑tαt(s)=∞\sum_t \alpha_t(s) = \infty and ∑tαt(s)2<∞\sum_t \alpha_t(s)^2 < \infty, then V→vπV \to v_\pi with probability one. With a constant, sufficiently small α\alpha, the estimates converge in the mean but keep fluctuating around vπv_\pi.

Proof. (Sketch.) Write the update at a visit to ss as V(s)←(1−α)V(s)+α[(TπV)(s)+w]V(s) \leftarrow (1 - \alpha)V(s) + \alpha\bigl[(T_\pi V)(s) + w\bigr], where w=Rt+1+γV(St+1)−(TπV)(St)w = R_{t+1} + \gamma V(S_{t+1}) - (T_\pi V)(S_t) has conditional mean zero by (6.4) and conditional variance bounded by C(1+max⁡sV(s)2)C(1 + \max_s V(s)^2). The general theorem on asynchronous stochastic approximation of a max-norm contraction (Jaakkola, Jordan and Singh; Tsitsiklis; see Section 6.9.1 and Theorem A.7) then gives convergence to the unique fixed point vπv_\pi. For a constant step the noise never averages out. Heuristically, averaging over the visited state, the mean of VV follows the deterministic iteration V¯←V¯+α 𝐃(TπV¯−V¯)\bar V \leftarrow \bar V + \alpha\,\mathbf{D}(T_\pi\bar V - \bar V), with 𝐃\mathbf{D} the diagonal matrix of visit probabilities, which converges for small α\alpha because its iteration matrix has spectral radius below one; Sutton’s 1988 proof of convergence in the mean makes this precise. □

Sutton proved convergence in the mean in 1988 and Dayan with probability one in 1992; the theorem above is the form obtained a few years later from stochastic approximation.Richard S. Sutton. Learning to Predict by the Methods of Temporal Differences. Machine Learning, 3(1):9–44, 1988. doi: 10.1007/BF00115009; Peter Dayan. The Convergence of TD(λ\lambda) for General λ\lambda. Machine Learning, 8(3–4):341–362, 1992. doi: 10.1007/BF00992701; Tommi Jaakkola, Michael I. Jordan, and Satinder P. Singh. On the Convergence of Stochastic Iterative Dynamic Programming Algorithms. Neural Computation, 6(6):1185–1201, 1994. doi: 10.1162/neco.1994.6.6.1185; and John N. Tsitsiklis. Asynchronous Stochastic Approximation and Q-Learning. Machine Learning, 16(3):185–202, 1994. doi: 10.1007/BF00993306 It says nothing about speed, and no general theorem says that TD beats Monte Carlo; but the examples and the batch analysis below explain why it usually does.

Example 6.3 (Random walk). A Markov reward process (an MDP without actions) with states A,B,C,D,EA, B, C, D, E in a row: every episode starts in CC and moves left or right with equal probability, terminating beyond either end; the reward is +1+1 on termination at the right and 00 otherwise, and γ=1\gamma = 1. Then v(s)v(s) is the probability of leaving on the right: 16,26,…,56\frac{1}{6}, \frac{2}{6}, \dots, \frac{5}{6}. Starting from V=0.5V = 0.5 and comparing root-mean-squared errors over the first 100 episodes, Sutton and Barto find TD(0) consistently better than constant-α\alpha MC for all the step sizes they try.

For nn states the Bellman equation is the discrete Laplace equation vk=12(vk−1+vk+1)v_k = \frac{1}{2}(v_{k-1} + v_{k+1}) with v0=0v_0 = 0 and vn+1=1v_{n+1} = 1 for the terminal “states” on the two sides, so vv is linear.

Solve the boundary-value recurrence of the random walk with nn states: the value of the kk-th state is the probability k/(n+1)k/(n+1) of exiting on the right.
const rwValues = await show`RSolve[{v[k + 1] - 2 v[k] + v[k - 1] == 0, v[0] == 0, v[n + 1] == 1}, v[k], k]`
vk=kn+1:{{v(k)→k1+n}} v_k = \frac{k}{n+1}:\quad \left\{\left\{v(k)\to \frac{k}{1+n}\right\}\right\} The expected synchronous TD(0) update on the 5-state walk is V←V+α(𝐫+𝐏V−V)V \leftarrow V + \alpha(\mathbf{r} + \mathbf{P}V - V), with iteration matrix 𝐈−α(𝐈−𝐏)\mathbf{I} - \alpha(\mathbf{I} - \mathbf{P}), whose eigenvalues are 1−αλ1 - \alpha\lambda for the eigenvalues λ\lambda of 𝐈−𝐏\mathbf{I} - \mathbf{P}. These are 1−cos⁡jπ61 - \cos\frac{j\pi}{6}, j=1,…,5j = 1, \dots, 5.
const rwEig = await show`Module[{P = {{0, 1/2, 0, 0, 0}, {1/2, 0, 1/2, 0, 0}, {0, 1/2, 0, 1/2, 0}, {0, 0, 1/2, 0, 1/2}, {0, 0, 0, 1/2, 0}}}, Simplify[Eigenvalues[IdentityMatrix[5] - P]]]`
spec⁡(𝐈−𝐏)={12(2+3),32,1,12,1−32} \operatorname{spec}(\mathbf{I} - \mathbf{P}) = \left\{\frac{1}{2} \left(2+\sqrt{3}\right),\frac{3}{2},1,\frac{1}{2},1-\frac{\sqrt{3}}{2}\right\} The fixed point of the expected update solves (𝐈−𝐏)V=𝐫(\mathbf{I} - \mathbf{P})V = \mathbf{r}, with 𝐫=(0,0,0,0,12)\mathbf{r} = (0, 0, 0, 0, \frac{1}{2}) the expected reward from each state: the values k6\frac{k}{6} again.
const rwFixed = await show`Module[{P = {{0, 1/2, 0, 0, 0}, {1/2, 0, 1/2, 0, 0}, {0, 1/2, 0, 1/2, 0}, {0, 0, 1/2, 0, 1/2}, {0, 0, 0, 1/2, 0}}}, LinearSolve[IdentityMatrix[5] - P, {0, 0, 0, 0, 1/2}]]`
v=(𝐈−𝐏)−1𝐫={16,13,12,23,56} v = (\mathbf{I} - \mathbf{P})^{-1}\mathbf{r} = \left\{\frac{1}{6},\frac{1}{3},\frac{1}{2},\frac{2}{3},\frac{5}{6}\right\}

Every λ\lambda lies in (0,2)(0, 2), so the eigenvalues 1−αλ1 - \alpha\lambda of the iteration matrix lie in (−1,1)(-1, 1) for 0<α≤10 < \alpha \le 1, and the expected iteration converges; the slowest mode, 1−α(1−32)≈1−0.13α1 - \alpha(1 - \frac{\sqrt{3}}{2}) \approx 1 - 0.13\alpha, is the smooth one, in which information about the right-hand reward must diffuse across the whole chain one bootstrapping step at a time.

6.3Batch Updating and Certainty Equivalence

Suppose the experience is finite, say ten episodes, and it is presented over and over. In batch updating the increments (6.1) (or the Monte Carlo ones) are computed for every time step of the batch with VV fixed, and VV is changed once by their sum; this is repeated until VV stops changing. On the random walk, batch TD(0) is consistently better than batch Monte Carlo. Both have a precise meaning.

Let the batch contain n(s)n(s) visits to each nonterminal state ss, let n(s,s′)n(s, s') count the transitions from ss to s′s' (terminal included), and define the maximum-likelihood model

p^(s′∣s)≐n(s,s′)n(s),r^(s)≐1n(s)∑t: St=sRt+1. \hat p(s' \mid s) \doteq \frac{n(s, s')}{n(s)}, \qquad \hat r(s) \doteq \frac{1}{n(s)}\sum_{t:\,S_t = s}R_{t+1}.

The value of this model, VCE=r^+γ𝐏^VCEV_{\mathrm{CE}} = \hat r + \gamma\hat{\mathbf{P}}V_{\mathrm{CE}}, is the certainty-equivalence estimate: the right answer if the estimated model were exactly right.

Theorem 6.4 (What batch MC and batch TD(0) compute). With a sufficiently small constant step size, and episodic data:

  1. batch constant-α\alpha MC converges to the sample averages of the observed returns, the minimizer of ∑t(Gt−V(St))2\sum_{t}(G_t - V(S_t))^2 over the batch;
  2. batch TD(0) converges to the certainty-equivalence estimate VCEV_{\mathrm{CE}}.

Proof. (1) The summed increment at ss is α∑t:St=s(Gt−V(s))\alpha\sum_{t:S_t = s}(G_t - V(s)), which vanishes exactly at the sample mean of those returns, the minimizer of the squared error; each sweep moves V(s)V(s) a fraction αn(s)\alpha n(s) of the way there, so it converges when αn(s)<2\alpha n(s) < 2.

(2) The summed TD increment at ss is

α∑t: St=s[Rt+1+γV(St+1)−V(s)]=α n(s)[r^(s)+γ∑s′p^(s′∣s) V(s′)−V(s)], \begin{aligned} &\alpha\sum_{t:\,S_t = s}\bigl[R_{t+1} + \gamma V(S_{t+1}) - V(s)\bigr] \\ &\quad= \alpha\,n(s)\Bigl[\hat r(s) + \gamma\sum_{s'}\hat p(s' \mid s)\,V(s') - V(s)\Bigr], \end{aligned}

so a fixed point satisfies V=r^+γ𝐏^VV = \hat r + \gamma\hat{\mathbf{P}}V, and in vector form the sweep is V←V−α𝐍[(𝐈−γ𝐏^)V−r^]V \leftarrow V - \alpha\mathbf{N}\bigl[(\mathbf{I} - \gamma\hat{\mathbf{P}})V - \hat r\bigr] with 𝐍=diag⁡(n(s))\mathbf{N} = \operatorname{diag}(n(s)). Every state of the data leads to termination in the empirical model, so 𝐏^\hat{\mathbf{P}} (restricted to nonterminal states) has spectral radius below one even for γ=1\gamma = 1, and 𝐈−γ𝐏^\mathbf{I} - \gamma\hat{\mathbf{P}} is a nonsingular M-matrix. Multiplying it on the left by the positive diagonal 𝐍\mathbf{N} keeps it a nonsingular M-matrix, whose eigenvalues have positive real parts. For α\alpha small enough all eigenvalues of 𝐈−α𝐍(𝐈−γ𝐏^)\mathbf{I} - \alpha\mathbf{N}(\mathbf{I} - \gamma\hat{\mathbf{P}}) lie inside the unit circle, and the sweep converges to the unique solution VCEV_{\mathrm{CE}}. □

Example 6.5 (You are the predictor). Eight episodes of an unknown Markov reward process: one is A,0,B,0A, 0, B, 0 (from AA to BB with reward 00, then termination with reward 00); six are B,1B, 1; one is B,0B, 0. Everyone agrees that V(B)=34V(B) = \frac{3}{4}. But V(A)V(A)? Batch Monte Carlo answers 00, the only return ever observed from AA, with zero error on the training data. Batch TD answers 34\frac{3}{4}: in the data AA always leads to BB, so AA is worth what BB is worth.

The two batch answers: TD’s fixed point equations ∑t:St=sδt=0\sum_{t:S_t = s}\delta_t = 0 for s=A,Bs = A, B, and Monte Carlo’s least-squares fit to the returns 00 from AA and 0,0,1,…,10, 0, 1, \dots, 1 from BB.
const predictor = await show`Module[{va = Subscript[V, A], vb = Subscript[V, B]}, {Solve[{0 + vb - va == 0, 6 (1 - vb) + 2 (0 - vb) == 0}, {va, vb}], Solve[D[(0 - va)^2 + 2 (0 - vb)^2 + 6 (1 - vb)^2, {{va, vb}}] == {0, 0}, {va, vb}]}]`
(batch TD, batch MC):{{{VA→34,VB→34}},{{VA→0,VB→34}}} \bigl(\text{batch TD},\ \text{batch MC}\bigr):\quad \left\{\left\{\left\{V_A\to \frac{3}{4},V_B\to \frac{3}{4}\right\}\right\},\left\{\left\{V_A\to 0,V_B\to \frac{3}{4}\right\}\right\}\right\}

If the process really is Markov, the TD answer will have lower error on future data; Monte Carlo minimizes error on the past. That is the sense in which TD is “optimal”, and it explains the batch results: certainty equivalence uses every transition to inform every state upstream of it. Online TD(0) does not reach VCEV_{\mathrm{CE}}, but it moves toward it, which is the best available explanation of its speed on Markov tasks. It is also remarkable computationally: building 𝐏^\hat{\mathbf{P}} needs O(∣𝒮∣2)O(|\mathcal{S}|^2) memory and solving for VCEV_{\mathrm{CE}} O(∣𝒮∣3)O(|\mathcal{S}|^3) time, whereas TD approaches the same answer with O(∣𝒮∣)O(|\mathcal{S}|) memory.The converse matters too. When the state signal is not Markov, the certainty-equivalence model is wrong, and Monte Carlo’s minimization of error on the observed returns can be the better choice; this is one reason why Monte Carlo methods are said to be less harmed by violations of the Markov property.

6.4Sarsa: On-Policy TD Control

For control we follow generalized policy iteration (Section 4.7) with TD prediction of action values. The sequence St,At,Rt+1,St+1,At+1,…S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}, \dots is a Markov chain on state–action pairs with rewards, so TD(0) applies to it verbatim:

Q(St,At)←Q(St,At)+α[Rt+1+γQ(St+1,At+1)−Q(St,At)], Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha\bigl[R_{t+1} + \gamma Q(S_{t+1}, A_{t+1}) - Q(S_t, A_t)\bigr], (6.5)

with Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0. The quintuple (St,At,Rt+1,St+1,At+1)(S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}) names the algorithm, Sarsa.Gavin A. Rummery and Mahesan Niranjan. On-Line Q-Learning Using Connectionist Systems. Technical Report CUED/F-INFENG/TR 166, Cambridge University Engineering Department, 1994

Algorithm 6.6 (Sarsa (on-policy TD control)). Parameters: α∈(0,1]\alpha \in (0, 1], ε>0\varepsilon > 0. Initialize: Q(s,a)Q(s, a) arbitrary for s∈𝒮+s \in \mathcal{S}^+, a∈𝒜(s)a \in \mathcal{A}(s), except Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0.

Loop for each episode:

  1. Initialize SS; choose AA from SS with the policy derived from QQ (e.g. ε\varepsilon-greedy).
  2. Loop for each step, until SS is terminal:
    • take AA, observe R,S′R, S';
    • choose A′A' from S′S' with the policy derived from QQ;
    • Q(S,A)←Q(S,A)+α[R+γQ(S′,A′)−Q(S,A)]Q(S, A) \leftarrow Q(S, A) + \alpha\bigl[R + \gamma Q(S', A') - Q(S, A)\bigr];
    • S←S′S \leftarrow S', A←A′A \leftarrow A'.

Sarsa evaluates the policy it follows, which keeps changing toward greediness. It converges with probability one to q∗q_* and an optimal policy if every pair is visited infinitely often, the step sizes satisfy the usual conditions, and the policy is greedy in the limit with infinite exploration (GLIE), for example ε\varepsilon-greedy with εt=1/t\varepsilon_t = 1/t.Satinder Singh, Tommi Jaakkola, Michael L. Littman, and Csaba Szepesvári. Convergence Results for Single-Step On-Policy Reinforcement-Learning Algorithms. Machine Learning, 38(3):287–308, 2000. doi: 10.1023/A:1007678930559 With a fixed ε\varepsilon the best it can aim for is the best ε\varepsilon-soft policy, the target of on-policy Monte Carlo control in Theorem 5.5. Being online is a real advantage over Monte Carlo control: in the windy gridworld, where a crosswind pushes the agent upward, a policy can trap the agent forever, so an episode-by-episode method may never get to learn; Sarsa learns during the episode that the trap is bad and leaves it.

6.5Q-learning: Off-Policy TD Control

Q-learning bootstraps on the best next action instead of the one actually taken:Christopher John Cornish Hellaby Watkins. Learning from Delayed Rewards. PhD thesis, King’s College, University of Cambridge, Cambridge, UK, May 1989. doi: 10.17863/CAM.132164. URL https://www.repository.cam.ac.uk/handle/1810/406035; and Christopher J. C. H. Watkins and Peter Dayan. Technical Note: Q-Learning. Machine Learning, 8(3–4):279–292, 1992. doi: 10.1007/BF00992698

Q(St,At)←Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)−Q(St,At)]. Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha\bigl[R_{t+1} + \gamma\max_a Q(S_{t+1}, a) - Q(S_t, A_t)\bigr]. (6.6)

Algorithm 6.7 (Q-learning (off-policy TD control)). Parameters: α∈(0,1]\alpha \in (0, 1], ε>0\varepsilon > 0. Initialize: Q(s,a)Q(s, a) arbitrary for s∈𝒮+s \in \mathcal{S}^+, a∈𝒜(s)a \in \mathcal{A}(s), except Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0.

Loop for each episode:

  1. Initialize SS.
  2. Loop for each step, until SS is terminal:
    • choose AA from SS with a policy derived from QQ (e.g. ε\varepsilon-greedy);
    • take AA, observe R,S′R, S';
    • Q(S,A)←Q(S,A)+α[R+γmax⁡aQ(S′,a)−Q(S,A)]Q(S, A) \leftarrow Q(S, A) + \alpha\bigl[R + \gamma\max_a Q(S', a) - Q(S, A)\bigr];
    • S←S′S \leftarrow S'.

Q-learning is off-policy, yet it uses no importance sampling. The reason is visible in the expected update. Conditioned on (St,At)=(s,a)(S_t, A_t) = (s, a), the target’s mean is

∑s′,rp(s′,r∣s,a)[r+γmax⁡a′Q(s′,a′)]=(T∗Q)(s,a), \sum_{s', r}p(s', r \mid s, a)\bigl[r + \gamma\max_{a'}Q(s', a')\bigr] = (T_* Q)(s, a),

the Bellman optimality operator of (3.18): the next action of the behavior policy does not enter at all. The behavior policy only decides which pairs get updated and how often, so all that convergence needs is that every pair keeps being updated. Under that condition and the usual step-size conditions, Q-learning converges to q∗q_* with probability one; Watkins and Dayan gave the first proof, and the stochastic-approximation proofs of 1994 cover it as the case of a contraction in the max norm (Section 6.9.1). If the behavior policy is greedy too, Q-learning and Sarsa nearly coincide, but not exactly (Exercise 6.12).

6.5.1On-Policy versus Off-Policy: Cliff Walking

In a 4×124 \times 12 gridworld the agent goes from the bottom-left corner to the bottom-right one, with reward −1-1 per step; the cells between them are a cliff, and stepping in costs −100-100 and sends the agent back to the start. Both methods behave ε\varepsilon-greedily with ε=0.1\varepsilon = 0.1. Q-learning learns q∗q_*, whose greedy policy walks along the edge of the cliff in 1313 steps, and while doing so it occasionally falls off because of the random actions. Sarsa learns the values of the ε\varepsilon-greedy policy it actually follows, prefers the 1717-step route along the top, and earns more reward online. The difference is not that one method is wrong: they answer different questions. Q-learning asks “what is the best I could do if I stopped exploring?”; Sarsa asks “what will I get, given that I keep exploring?”

A caricature makes the trade-off computable. On the edge route, k=11k = 11 of the 1313 decisions are next to the cliff, and at each of them the exploratory action that falls (one of four) is taken with probability f=ε/4f = \varepsilon/4; ignore all other exploratory moves. The value uu of the edge route under ε\varepsilon-greedy behavior satisfies a renewal equation, since a fall restarts the same route.

Solve u=∑j<k(1−f)j[f(−100+u)−(1−f)]+(1−f)k(−2)u = \sum_{j<k}(1-f)^j\bigl[f(-100 + u) - (1-f)\bigr] + (1-f)^k(-2) for uu: the value of the edge route when each of kk risky steps falls with probability ff.
const cliffU = await show`Assuming[0 < f < 1 && k > 0, FullSimplify[u /. First[Solve[u == Sum[(1 - f)^j (f (-100 + u) - (1 - f)), {j, 0, k - 1}] + (1 - f)^k (-2), u]]]]`
u(f,k)=1+97f−(1−f)−k(1+99f)f u(f, k) = \frac{1+97 f-(1-f)^{-k} (1+99 f)}{f} The exploration rate at which the edge route, valued on-policy, becomes worse than the safe route’s −17-17, for k=11k = 11 and f=ε/4f = \varepsilon/4.
const cliffEps = await show`\[Epsilon] /. FindRoot[(${cliffU} /. {k -> 11, f -> \[Epsilon]/4}) == -17, {\[Epsilon], 0.02}]`
εswitch=0.0135767 \varepsilon_{\text{switch}} = 0.0135767

To first order in ff, u≈−13−1155f=−13−289 εu \approx -13 - 1155f = -13 - 289\,\varepsilon for k=11k = 11: each unit of exploration costs far more than the four steps saved. So for any ε\varepsilon above about 0.0140.014, Sarsa’s values make the safe route look better, while Q-learning’s values never depend on ε\varepsilon (Figure 6.1). If ε\varepsilon is decreased to zero, both converge to the edge route.

Value of the edge route as a function of epsilon from 0 to 0.2: the on-policy value falls from -13 to below -100, crossing the safe route value -17 near epsilon 0.014; the Q-learning value stays at -13Figure 6.1: Value of the edge route in the cliff-walking caricature: on-policy, under ε\varepsilon-greedy behavior (black), and as learned by Q-learning (blue, −13-13 for every ε\varepsilon). The dashed line is the safe route’s −17-17.

6.6Expected Sarsa

Replace the sampled next action of Sarsa by its expectation under the target policy:

Q(St,At)←Q(St,At)+α[Rt+1+γ∑aπ(a∣St+1) Q(St+1,a)−Q(St,At)]. \begin{aligned} Q(S_t, A_t) \leftarrow{}& Q(S_t, A_t) \\ &+ \alpha\Bigl[R_{t+1} + \gamma\sum_a \pi(a \mid S_{t+1})\,Q(S_{t+1}, a) - Q(S_t, A_t)\Bigr]. \end{aligned} (6.7)

Given St+1S_{t+1}, Expected Sarsa moves deterministically in the direction in which Sarsa moves on average, so it removes the variance due to the random choice of At+1A_{t+1} at the cost of a sum over actions.Harm van Seijen, Hado van Hasselt, Shimon Whiteson, and Marco Wiering. A Theoretical and Empirical Analysis of Expected Sarsa. In 2009 IEEE Symposium on Adaptive Dynamic Programming and Reinforcement Learning (ADPRL), pages 177–184, 2009. doi: 10.1109/ADPRL.2009.4927542 In cliff walking, where all randomness comes from the policy, it can use α=1\alpha = 1 without losing asymptotic performance, whereas Sarsa needs a small α\alpha. Its target policy π\pi need not be the behavior policy: with π\pi greedy, (6.7) is Q-learning, so Expected Sarsa contains both of the previous algorithms.

Conditional variances of the two targets given St+1S_{t+1}, with two actions of values q1,q2q_1, q_2 taken with probabilities x,1−xx, 1 - x (same reward in both): Sarsa’s target varies with At+1A_{t+1}, Expected Sarsa’s does not.
const esVar = await show`Module[{w = {x, 1 - x}, t = \[Gamma] {Subscript[q, 1], Subscript[q, 2]}}, Factor[{w . t^2 - (w . t)^2, (w . t)^2 - (w . t)^2}]]`
(Var⁡Sarsa, Var⁡Expected Sarsa)={−((−1+x)xγ2(q1−q2)2),0} \bigl(\operatorname{Var}_{\text{Sarsa}},\ \operatorname{Var}_{\text{Expected Sarsa}}\bigr) = \left\{-\left((-1+x) x \gamma ^2 \left(q_1-q_2\right){}^2\right),0\right\}

6.7Maximization Bias and Double Learning

Every control method so far builds its target policy with a maximum over estimated values, and the maximum of estimates is a biased estimate of the maximum. Suppose the true values q(a)q(a) of all actions in a state are zero but the estimates Q(a)Q(a) are noisy: their maximum is positive. This maximization bias can mislead control. In Sutton and Barto’s example, from state AA action right terminates with reward 00, and left leads with reward 00 to a state BB in which many actions all terminate with a reward drawn from 𝒩(−0.1,1)\mathcal{N}(-0.1, 1). Left is a mistake, but the maximum over the noisy estimates in BB makes BB look positive, and ε\varepsilon-greedy Q-learning initially chooses left far more often than the 5%5\% forced by exploration.

Proposition 6.8 (Maximization bias and the double estimator). Let Q(a)Q(a), a∈𝒜a \in \mathcal{A}, be unbiased estimates of q(a)q(a), and let Q′(a)Q'(a) be unbiased estimates independent of them. Then

𝔼[max⁡aQ(a)]≥max⁡aq(a),𝔼[Q′(arg⁡max⁡aQ(a))]≤max⁡aq(a). \mathbb{E}\Bigl[\max_a Q(a)\Bigr] \ge \max_a q(a), \qquad \mathbb{E}\Bigl[Q'\bigl(\arg\max_a Q(a)\bigr)\Bigr] \le \max_a q(a). (6.8)

If all q(a)q(a) are equal, the second estimate is exactly unbiased.

Proof. The maximum is convex, so Jensen’s inequality gives 𝔼[max⁡aQ(a)]≥max⁡a𝔼[Q(a)]\mathbb{E}[\max_a Q(a)] \ge \max_a\mathbb{E}[Q(a)]. For the second, condition on QQ: the selected action A∗=arg⁡max⁡aQ(a)A^* = \arg\max_a Q(a) is then fixed and independent of Q′Q', so 𝔼[Q′(A∗)∣Q]=q(A∗)\mathbb{E}[Q'(A^*) \mid Q] = q(A^*), and 𝔼[Q′(A∗)]=∑aPr⁡{A∗=a} q(a)\mathbb{E}[Q'(A^*)] = \sum_a \Pr\{A^* = a\}\,q(a), a weighted average of the true values, which is at most their maximum and equals it when they are all equal. □

The bias comes from using the same samples to select the maximizing action and to evaluate it. For two independent 𝒩(0,σ2)\mathcal{N}(0, \sigma^2) estimates the excess is σ/π≈0.56σ\sigma/\sqrt{\pi} \approx 0.56\sigma, and it keeps growing with the number of actions (Figure 6.2).

The expected maximum of two independent 𝒩(0,σ2)\mathcal{N}(0, \sigma^2) estimates of two true values 00.
const emax2 = await show`Expectation[Max[Subscript[X, 1], Subscript[X, 2]], {Subscript[X, 1] \[Distributed] NormalDistribution[0, \[Sigma]], Subscript[X, 2] \[Distributed] NormalDistribution[0, \[Sigma]]}, Assumptions -> \[Sigma] > 0]`
𝔼[max⁡(X1,X2)]=σπ \mathbb{E}[\max(X_1, X_2)] = \frac{\sigma }{\sqrt{\pi }} The double estimator with Q,Q′Q, Q' independent, both 𝒩(μa,σ2)\mathcal{N}(\mu_a, \sigma^2): its mean is μ1Pr⁡{Q(1)>Q(2)}+μ2Pr⁡{Q(2)>Q(1)}\mu_1\Pr\{Q(1) > Q(2)\} + \mu_2\Pr\{Q(2) > Q(1)\}, a weighted average of the true values. Writing μ2=μ1−Δ\mu_2 = \mu_1 - \Delta with Δ≥0\Delta \ge 0, its bias with respect to the maximum μ1\mu_1 is negative.
const dbl = await show`Module[{pr = Probability[Subscript[X, 1] > Subscript[X, 2], {Subscript[X, 1] \[Distributed] NormalDistribution[Subscript[\[Mu], 1], \[Sigma]], Subscript[X, 2] \[Distributed] NormalDistribution[Subscript[\[Mu], 1] - \[CapitalDelta], \[Sigma]]}]}, Simplify[Subscript[\[Mu], 1] pr + (Subscript[\[Mu], 1] - \[CapitalDelta]) (1 - pr) - Subscript[\[Mu], 1], \[Sigma] > 0]]`
𝔼[Q′(arg⁡max⁡aQ(a))]−μ1=−12Δerfc(Δ2σ) \mathbb{E}\bigl[Q'(\arg\max_a Q(a))\bigr] - \mu_1 = -\frac{1}{2} \Delta \text{erfc}\left(\frac{\Delta }{2 \sigma }\right) The expected maximum of three standard normal estimates: the bias grows with the number of actions.
const emax3 = await show`Integrate[3 x PDF[NormalDistribution[], x] CDF[NormalDistribution[], x]^2, {x, -Infinity, Infinity}]`
𝔼[max⁡(X1,X2,X3)]=32π \mathbb{E}[\max(X_1, X_2, X_3)] = \frac{3}{2 \sqrt{\pi }}
Figure 6.2: Maximization bias: 𝔼[max⁡a≤nQ(a)]\mathbb{E}[\max_{a \le n} Q(a)] when all true values are 00 and the estimates are independent standard normals (black), against the classical upper bound 2ln⁡n\sqrt{2\ln n} (dashed). Exact values 1/π1/\sqrt{\pi} for n=2n = 2 and 3/(2π)3/(2\sqrt{\pi}) for n=3n = 3; in the example above, if BB had ten actions estimated from one reward each, BB would look worth about 1.441.44 on average instead of −0.1-0.1.Expected maximum of n independent standard normal variables for n from 1 to 100, rising from 0 through 0.56 at n equals 2 to about 2.5 at n equals 100, below the dashed curve square root of 2 log n

Double learning splits the experience in two, learns two independent estimates Q1,Q2Q_1, Q_2, and uses one to choose and the other to evaluate. For Q-learning this gives Double Q-learning:Hado van Hasselt. Double Q-learning. In Advances in Neural Information Processing Systems 23 (NIPS 2010), pages 2613–2621, 2010 on each step a coin decides which estimate to update, and the update of Q1Q_1 is

Q1(St,At)←Q1(St,At)+α[Yt−Q1(St,At)],Yt≐Rt+1+γ Q2(St+1,arg⁡max⁡aQ1(St+1,a)), \begin{aligned} Q_1(S_t, A_t) &\leftarrow Q_1(S_t, A_t) + \alpha\bigl[Y_t - Q_1(S_t, A_t)\bigr], \\ Y_t &\doteq R_{t+1} + \gamma\,Q_2\bigl(S_{t+1}, \arg\max_a Q_1(S_{t+1}, a)\bigr), \end{aligned} (6.9)

with the roles exchanged for Q2Q_2. Memory doubles; computation per step does not.

Algorithm 6.9 (Double Q-learning). Parameters: α∈(0,1]\alpha \in (0, 1], ε>0\varepsilon > 0. Initialize: Q1(s,a)Q_1(s, a), Q2(s,a)Q_2(s, a) arbitrary, with Qi(terminal,⋅)=0Q_i(\text{terminal}, \cdot) = 0.

Loop for each episode: initialize SS, and for each step until SS is terminal,

  1. choose AA ε\varepsilon-greedily with respect to Q1+Q2Q_1 + Q_2; take AA, observe R,S′R, S';
  2. with probability 12\frac{1}{2} apply (6.9) to Q1Q_1; otherwise apply it with Q1Q_1 and Q2Q_2 exchanged;
  3. S←S′S \leftarrow S'.

On the example of this section Double Q-learning is essentially unaffected by maximization bias. By Proposition 6.8 its estimates can err on the low side when the true values differ, a much milder fault in control, because an underestimated action is simply tried less rather than chased. Double versions of Sarsa and Expected Sarsa are built the same way (Exercise 6.13).

6.8Afterstates

Sometimes the immediate effect of an action is known and only what follows is uncertain. In tic-tac-toe (Chapter 1) or chess the board after our move is determined by the move; the opponent’s reply is not. Values of these afterstates (post-decision states) are more economical than action values: different position–move pairs that produce the same board share one value, so learning about one transfers immediately to the others. Queueing problems, where actions assign or reject customers, have the same structure. Nothing else changes: afterstate methods are still generalized policy iteration, and they still face the on-policy/off-policy choice.

6.9Beyond the Book: Convergence Theory and Double Estimators Today

6.9.1Asymptotic Convergence of Q-learning and TD

Sutton and Barto state the convergence of TD(0), Sarsa and Q-learning but prove none of them. The proofs of the early 1990s share one template.Beyond Sutton and Barto (2018). The book cites these results without proof. Watkins and Dayan (1992) proved Q-learning’s convergence by an “action replay” construction; Jaakkola, Jordan and Singh (1994) and Tsitsiklis (1994) independently proved a general theorem on asynchronous stochastic approximation of max-norm contractions, which covers Q-learning and TD(λ\lambda) at once.Christopher J. C. H. Watkins and Peter Dayan. Technical Note: Q-Learning. Machine Learning, 8(3–4):279–292, 1992. doi: 10.1007/BF00992698; Tommi Jaakkola, Michael I. Jordan, and Satinder P. Singh. On the Convergence of Stochastic Iterative Dynamic Programming Algorithms. Neural Computation, 6(6):1185–1201, 1994. doi: 10.1162/neco.1994.6.6.1185; and John N. Tsitsiklis. Asynchronous Stochastic Approximation and Q-Learning. Machine Learning, 16(3):185–202, 1994. doi: 10.1007/BF00993306 Write any of the updates, at the pair (or state) ii visited at time tt, as

xt+1(i)=(1−αt(i))xt(i)+αt(i)[(Hxt)(i)+wt(i)], x_{t+1}(i) = \bigl(1 - \alpha_t(i)\bigr)x_t(i) + \alpha_t(i)\bigl[(Hx_t)(i) + w_t(i)\bigr], (6.10)

with αt(i)=0\alpha_t(i) = 0 for the components not updated. If (a) HH is a contraction in a weighted max norm with fixed point x∗x^*, (b) the noise has 𝔼[wt(i)∣ℱt]=0\mathbb{E}[w_t(i) \mid \mathcal{F}_t] = 0 and 𝔼[wt(i)2∣ℱt]≤C(1+∥xt∥2)\mathbb{E}[w_t(i)^2 \mid \mathcal{F}_t] \le C(1 + \lVert x_t\rVert^2), and (c) ∑tαt(i)=∞\sum_t\alpha_t(i) = \infty and ∑tαt(i)2<∞\sum_t\alpha_t(i)^2 < \infty for every ii with probability one, then xt→x∗x_t \to x^* with probability one. For Q-learning, x=Qx = Q, H=T∗H = T_* is a γ\gamma-contraction in the max norm, and wt=Rt+1+γmax⁡aQ(St+1,a)−(T∗Q)(St,At)w_t = R_{t+1} + \gamma\max_a Q(S_{t+1}, a) - (T_*Q)(S_t, A_t); condition (c) contains the requirement that every pair be visited infinitely often. The key step is to compare xtx_t with a deterministic sequence of shrinking boxes around x∗x^*: the contraction pulls the iterates into the next box, and the weighted average of the noise, a martingale with summable variance, eventually stays smaller than the gap.

6.9.2Finite-Time Analysis of TD Learning

Asymptotic convergence says nothing about how many samples are needed. Since 2018 finite-time bounds have been proved by treating TD with linear features 𝐱(s)\mathbf{x}(s) (the tabular case is the one-hot special case) as a linear stochastic approximation 𝐰t+1=𝐰t+αt(𝐀t𝐰t+𝐛t)\mathbf{w}_{t+1} = \mathbf{w}_t + \alpha_t(\mathbf{A}_t\mathbf{w}_t + \mathbf{b}_t) whose mean matrix 𝐀\mathbf{A} is negative definite in the sense of Chapter 9, so that the associated ODE 𝐰˙=𝐀𝐰+𝐛\dot{\mathbf{w}} = \mathbf{A}\mathbf{w} + \mathbf{b} has the TD fixed point (9.5) as a globally stable equilibrium.Beyond Sutton and Barto (2018). Bhandari, Russo and Singal (COLT 2018; Operations Research 2021) gave a short finite-time analysis that mirrors stochastic gradient descent; Srikant and Ying (COLT 2019) removed the projection step and the i.i.d. assumption for constant step sizes with a Lyapunov drift argument. The ODE method itself goes back to Borkar and Meyn (2000).Jalaj Bhandari, Daniel Russo, and Raghav Singal. A Finite Time Analysis of Temporal Difference Learning with Linear Function Approximation. Operations Research, 69(3):950–973, 2021. doi: 10.1287/opre.2020.2024. Extended abstract in Proceedings of the 31st Conference on Learning Theory (COLT 2018), PMLR 75; arXiv:1806.02450; R. Srikant and Lei Ying. Finite-Time Error Bounds for Linear Stochastic Approximation and TD Learning. In Proceedings of the Thirty-Second Conference on Learning Theory, volume 99 of Proceedings of Machine Learning Research, pages 2803–2830. PMLR, 2019; and Vivek S. Borkar and Sean P. Meyn. The O.D.E. Method for Convergence of Stochastic Approximation and Reinforcement Learning. SIAM Journal on Control and Optimization, 38(2):447–469, SIAM, 2000. doi: 10.1137/S0363012997331639 Bhandari, Russo and Singal show that with i.i.d. transitions, step size 1/T1/\sqrt{T} and averaged iterate 𝐰¯T\bar{\mathbf{w}}_T,

𝔼[∥v^(⋅,𝐰∗)−v^(⋅,𝐰¯T)∥𝐃2]≤∥𝐰∗−𝐰0∥22+2σ2T (1−γ), \mathbb{E}\Bigl[\bigl\lVert \hat v(\cdot, \mathbf{w}^*) - \hat v(\cdot, \bar{\mathbf{w}}_T)\bigr\rVert_{\mathbf{D}}^2\Bigr] \le \frac{\lVert\mathbf{w}^* - \mathbf{w}_0\rVert_2^2 + 2\sigma^2}{\sqrt{T}\,(1 - \gamma)},

where 𝐃\mathbf{D} weights states by the stationary distribution and σ2\sigma^2 is the variance of the update at the fixed point; for Markovian data a projected variant obtains the same rate with an extra factor of the mixing time, and decaying step sizes improve the rate to roughly O(1/T)O(1/T). Srikant and Ying prove that with a constant step α\alpha and Markovian data, the mean squared error decays geometrically, at rate (1−cα)t(1 - c\alpha)^t, down to a floor of order α τmix\alpha\,\tau_{\mathrm{mix}}. The lesson for the tabular algorithms of this chapter is quantitative: the 1−γ1 - \gamma in the denominator is the price of bootstrapping, the slow mode of the random walk in Section 6.2 made concrete.

6.9.3Heirs of Double Q-learning

Maximization bias became a practical problem with deep Q-networks (Section 15.5), where function-approximation error plays the role of the noise in Proposition 6.8.Beyond Sutton and Barto (2018). Double DQN (van Hasselt, Guez and Silver, AAAI 2016) and the clipped double Q-learning of TD3 (Fujimoto, van Hoof and Meger, ICML 2018) are the two most influential descendants of Double Q-learning; the overestimation analysis goes back to Thrun and Schwartz (1993).Hado van Hasselt, Arthur Guez, and David Silver. Deep Reinforcement Learning with Double Q-Learning. In Proceedings of the Thirtieth AAAI Conference on Artificial Intelligence, volume 30, pages 2094–2100. AAAI Press, 2016. doi: 10.1609/aaai.v30i1.10295; 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. PMLR; and Sebastian Thrun and Anton Schwartz. Issues in Using Function Approximation for Reinforcement Learning. In Michael C. Mozer, Paul Smolensky, David S. Touretzky, Jeffrey L. Elman, and Andreas S. Weigend, editors, Proceedings of the 1993 Connectionist Models Summer School, pages 255–263, Hillsdale, NJ, 1993. Lawrence Erlbaum Van Hasselt, Guez and Silver prove that if the true values of m≥2m \ge 2 actions are all V∗(s)V_*(s) and the estimates are unbiased on average, ∑a(Q(s,a)−V∗(s))=0\sum_a (Q(s, a) - V_*(s)) = 0, but not all correct, 1m∑a(Q(s,a)−V∗(s))2=C>0\frac{1}{m}\sum_a (Q(s, a) - V_*(s))^2 = C > 0, then max⁡aQ(s,a)≥V∗(s)+C/(m−1)\max_a Q(s, a) \ge V_*(s) + \sqrt{C/(m-1)}, whatever the source of the errors, and the bound is tight. Their Double DQN keeps the online network 𝜽t\boldsymbol{\theta}_t for selection and lets the slowly updated target network 𝜽t−\boldsymbol{\theta}^-_t evaluate:

Yt=Rt+1+γ q^(St+1,arg⁡max⁡aq^(St+1,a,𝜽t),𝜽t−). Y_t = R_{t+1} + \gamma\,\hat q\bigl(S_{t+1}, \arg\max_a \hat q(S_{t+1}, a, \boldsymbol{\theta}_t), \boldsymbol{\theta}^-_t\bigr).

In continuous control, where an actor maximizes the critic, the overestimation is worse and the two estimates are not independent enough. TD3 trains two critics and takes the minimum of their target networks at a smoothed target action,

y=r+γmin⁡i=1,2q^(s′,π𝝓′(s′)+ϵ,𝜽i′),ϵ∼clip⁡(𝒩(0,σ2),−c,c), y = r + \gamma\min_{i=1,2}\hat q\bigl(s', \pi_{\boldsymbol{\phi}'}(s') + \epsilon, \boldsymbol{\theta}'_i\bigr), \qquad \epsilon \sim \operatorname{clip}(\mathcal{N}(0, \sigma^2), -c, c),

deliberately trading overestimation for underestimation, which, as noted after Proposition 6.8, is the safer error because it is not propagated by the policy update. Actor–critic methods themselves are the subject of Chapter 13, and TD3 as a whole is described in Section 13.8.4.

Back in the tabular setting, the one-step methods of this chapter and the Monte Carlo methods of Chapter 5 are two ends of a spectrum. Chapter 7 fills the space between them by bootstrapping after nn steps instead of one.

6.10Exercises

Exercise 6.10. (Sutton and Barto, Exercise 6.1.) Let VtV_t be the value array used at time tt in the TD error δt=Rt+1+γVt(St+1)−Vt(St)\delta_t = R_{t+1} + \gamma V_t(S_{t+1}) - V_t(S_t) and in the update (6.1). Find the correction that must be added to ∑kγk−tδk\sum_k\gamma^{k-t}\delta_k to obtain Gt−Vt(St)G_t - V_t(S_t) exactly.

Solution

Add and subtract γVt+1(St+1)\gamma V_{t+1}(S_{t+1}):

Gt−Vt(St)=δt+γ(Gt+1−Vt+1(St+1))+γ(Vt+1(St+1)−Vt(St+1)), G_t - V_t(S_t) = \delta_t + \gamma\bigl(G_{t+1} - V_{t+1}(S_{t+1})\bigr) + \gamma\bigl(V_{t+1}(S_{t+1}) - V_t(S_{t+1})\bigr),

and unroll:

Gt−Vt(St)=∑k=tT−1γk−tδk+∑k=tT−1γk−t+1(Vk+1(Sk+1)−Vk(Sk+1)), G_t - V_t(S_t) = \sum_{k=t}^{T-1}\gamma^{k-t}\delta_k + \sum_{k=t}^{T-1}\gamma^{k-t+1}\bigl(V_{k+1}(S_{k+1}) - V_k(S_{k+1})\bigr),

with VT(ST)=VT−1(ST)=0V_T(S_T) = V_{T-1}(S_T) = 0 at the terminal state. TD(0) changes only Vk(Sk)V_k(S_k) at time kk, so the correction term Vk+1(Sk+1)−Vk(Sk+1)V_{k+1}(S_{k+1}) - V_k(S_{k+1}) equals αδk\alpha\delta_k if Sk+1=SkS_{k+1} = S_k and 00 otherwise: the identity is exact unless the episode revisits a state on consecutive steps, and otherwise off by terms of order α\alpha.

A three-step check, with Vk,jV_{k,j} standing for Vk(Sj)V_k(S_j): the difference between G0−V0,0G_0 - V_{0,0} and the two sums vanishes identically.
const exChanging = await show`Module[{v = Function[{k, j}, If[j == 3, 0, Subscript[V, k, j]]], r = {Subscript[R, 1], Subscript[R, 2], Subscript[R, 3]}}, Simplify[(r[[1]] + \[Gamma] r[[2]] + \[Gamma]^2 r[[3]] - v[0, 0]) - Sum[\[Gamma]^k (r[[k + 1]] + \[Gamma] v[k, k + 1] - v[k, k]), {k, 0, 2}] - Sum[\[Gamma]^(k + 1) (v[k + 1, k + 1] - v[k, k + 1]), {k, 0, 2}]]]`
(G0−V0(S0))−∑k=02γkδk−∑k=02γk+1(Vk+1(Sk+1)−Vk(Sk+1))=0 \bigl(G_0 - V_0(S_0)\bigr) - \sum_{k=0}^{2}\gamma^k\delta_k - \sum_{k=0}^{2}\gamma^{k+1}\bigl(V_{k+1}(S_{k+1}) - V_k(S_{k+1})\bigr) = 0

Exercise 6.11. (Sutton and Barto, Exercise 6.3.) In the random walk of Example 6.3, with V=0.5V = 0.5 initially and α=0.1\alpha = 0.1, only V(A)V(A) changes during the first episode. What happened in that episode, and by how much did V(A)V(A) change?

Solution

Every transition between nonterminal states has reward 00 and, as long as both values are still 0.50.5, TD error 0+0.5−0.5=00 + 0.5 - 0.5 = 0: nothing changes. The only nonzero TD errors occur on termination. Termination on the right would have changed V(E)V(E), so the episode ended on the left, from AA, with δ=0+0−0.5\delta = 0 + 0 - 0.5. Hence V(A)V(A) decreased by α⋅0.5=0.05\alpha\cdot 0.5 = 0.05, to 0.450.45. (If the walk visited AA before, those transitions also had zero error.)

Exercise 6.12. (Sutton and Barto, Exercise 6.12.) Suppose action selection is greedy. Is Q-learning then exactly the same algorithm as Sarsa? Do they make the same action selections and the same updates?

Solution

Almost, but not exactly. With greedy selection Sarsa’s A′A' is arg⁡max⁡aQ(S′,a)\arg\max_a Q(S', a), so its target coincides with Q-learning’s, evaluated with QQ before the update. But Sarsa chooses A′A' before updating Q(S,A)Q(S, A) and then executes that A′A', while Q-learning chooses its next action after the update. When S′=SS' = S the update can change which action is greedy in S′S': Q-learning then acts on the new values, Sarsa on the old choice, and from then on the trajectories, and hence the updates, can differ. (Ties broken at random are a second source of divergence.)

Exercise 6.13. (Sutton and Barto, Exercise 6.13.) Write the update equations of Double Expected Sarsa with an ε\varepsilon-greedy target policy.

Solution

Keep two estimates. With probability 12\frac{1}{2} update Q1Q_1, using Q1Q_1 to define the target policy and Q2Q_2 to evaluate it:

Q1(St,At)←Q1(St,At)+α[Yt−Q1(St,At)],Yt≐Rt+1+γ∑aπ1(a∣St+1) Q2(St+1,a), \begin{aligned} Q_1(S_t, A_t) &\leftarrow Q_1(S_t, A_t) + \alpha\bigl[Y_t - Q_1(S_t, A_t)\bigr], \\ Y_t &\doteq R_{t+1} + \gamma\sum_a \pi_1(a \mid S_{t+1})\,Q_2(S_{t+1}, a), \end{aligned}

where π1(a∣s)=ε/∣𝒜(s)∣+(1−ε) 𝟏{a=arg⁡max⁡a′Q1(s,a′)}\pi_1(a \mid s) = \varepsilon/|\mathcal{A}(s)| + (1 - \varepsilon)\,\mathbf{1}\{a = \arg\max_{a'}Q_1(s, a')\}; otherwise apply the same update with Q1Q_1 and Q2Q_2 exchanged. Behavior can be ε\varepsilon-greedy in Q1+Q2Q_1 + Q_2. The selection, the only place where a maximum enters, uses one estimate and the evaluation the other, which is what removes the maximization bias of Proposition 6.8; for ε=0\varepsilon = 0 this is Double Q-learning.