Chapter 7

n-step Bootstrapping

Monte Carlo waits for the end of the episode and uses the whole return; one-step TD uses a single reward and then trusts the current estimate for everything that follows. Nothing forces us to choose between these two. We can wait nn steps, sum the nn rewards we have seen, and only then bootstrap. This chapter studies the whole family of such methods. They are worth having for two reasons. Intermediate values of nn often learn faster than either extreme. And they decouple two time scales that one-step methods tie together: how often the agent acts, and how far ahead it looks before trusting its own estimates. Sutton and Barto call this escaping “the tyranny of the time step”.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 The chapter also takes off-policy learning further than Chapter 5 and Chapter 6 did. We meet three ideas, importance sampling with per-decision control variates, tree backups that need no importance sampling at all, and the algorithm Q(σ)Q(\sigma), which contains both.

7.1The n-step Return

Fix a policy π\pi and an episode S0,A0,R1,S1,…,RT,STS_0, A_0, R_1, S_1, \dots, R_T, S_T generated by it. The Monte Carlo target for V(St)V(S_t) is the full return Gt=Rt+1+γRt+2+⋯+γT−t−1RTG_t = R_{t+1} + \gamma R_{t+2} + \dots + \gamma^{T-t-1}R_T. The one-step TD target is Rt+1+γV(St+1)R_{t+1} + \gamma V(S_{t+1}): the first reward, plus an estimate that stands in for all the discounted rewards after it. The nn-step return keeps nn real rewards before it lets the estimate take over:

Gt:t+n≐Rt+1+γRt+2+⋯+γn−1Rt+n+γnVt+n−1(St+n) G_{t:t+n} \doteq R_{t+1} + \gamma R_{t+2} + \dots + \gamma^{n-1}R_{t+n} + \gamma^n V_{t+n-1}(S_{t+n}) (7.1)

for n≥1n \ge 1 and 0≤t<T−n0 \le t < T - n.

The subscript t:t+nt{:}t+n says that the return starts at time tt and uses information up to time t+nt+n. The estimate used to bootstrap is Vt+n−1V_{t+n-1}, the most recent one available when Rt+nR_{t+n} and St+nS_{t+n} have been observed. If the episode ends before t+nt+n, there is nothing left to estimate, and we set Gt:t+n≐GtG_{t:t+n} \doteq G_t when t+n≥Tt + n \ge T. With n=1n = 1 this is the TD target, and with n≥T−tn \ge T - t it is the Monte Carlo return.

A target that looks nn steps ahead cannot be formed until nn steps have passed. The update of the state visited at time tt is therefore made at time t+nt+n:

Vt+n(St)≐Vt+n−1(St)+α[Gt:t+n−Vt+n−1(St)],0≤t<T, V_{t+n}(S_t) \doteq V_{t+n-1}(S_t) + \alpha\bigl[G_{t:t+n} - V_{t+n-1}(S_t)\bigr], \qquad 0 \le t < T, (7.2)

and all other states keep their values. This is nn-step TD. No update happens during the first n−1n-1 steps of an episode, and the n−1n-1 missing updates are made after termination, using returns that are then simply truncated at TT.

Algorithm 7.1 (n-step TD for Estimating V≈vπV \approx v_\pi). Input: a policy π\pi. Parameters: step size α∈(0,1]\alpha \in (0, 1], an integer n≥1n \ge 1. Initialization: V(s)V(s) arbitrary for all s∈𝒮s \in \mathcal{S}, with V(terminal)=0V(\text{terminal}) = 0. The stored StS_t and RtR_t need only be kept for the last n+1n + 1 steps (index modulo n+1n+1).

For each episode:

  1. Observe a nonterminal S0S_0 and set T←∞T \leftarrow \infty.
  2. For t=0,1,2,…t = 0, 1, 2, \dots:
    1. If t<Tt < T: take At∼π(⋅∣St)A_t \sim \pi(\cdot \mid S_t), observe and store Rt+1R_{t+1} and St+1S_{t+1}; if St+1S_{t+1} is terminal, set T←t+1T \leftarrow t + 1.
    2. Set τ←t−n+1\tau \leftarrow t - n + 1, the time whose state is updated now.
    3. If τ≥0\tau \ge 0: compute G←∑i=τ+1min⁡(τ+n, T)γi−τ−1RiG \leftarrow \sum_{i=\tau+1}^{\min(\tau+n,\,T)} \gamma^{i-\tau-1}R_i; if τ+n<T\tau + n < T, add γnV(Sτ+n)\gamma^n V(S_{\tau+n}); then V(Sτ)←V(Sτ)+α [G−V(Sτ)]V(S_\tau) \leftarrow V(S_\tau) + \alpha\,[G - V(S_\tau)].
    4. If τ=T−1\tau = T - 1, end the episode.

7.1.1n-step Errors as Sums of TD Errors

In Chapter 6 we saw that, with the estimates held fixed, the Monte Carlo error Gt−V(St)G_t - V(S_t) is a discounted sum of TD errors (6.2). The nn-step error is the same sum, cut off after nn terms.

Proposition 7.2 (The n-step Error Telescopes). If VV does not change during the episode and δk=Rk+1+γV(Sk+1)−V(Sk)\delta_k = R_{k+1} + \gamma V(S_{k+1}) - V(S_k) (with V(terminal)=0V(\text{terminal}) = 0), then

Gt:t+n−V(St)=∑k=tmin⁡(t+n, T)−1γk−t δk. G_{t:t+n} - V(S_t) = \sum_{k=t}^{\min(t+n,\,T)-1} \gamma^{k-t}\,\delta_k .

Proof. In ∑kγk−tδk\sum_k \gamma^{k-t}\delta_k the term +γk−t+1V(Sk+1)+\gamma^{k-t+1}V(S_{k+1}) of δk\delta_k cancels the term −γk+1−tV(Sk+1)-\gamma^{k+1-t}V(S_{k+1}) of δk+1\delta_{k+1}. What survives is the sum of the discounted rewards, the first −V(St)-V(S_t), and the last +γm−tV(Sm)+\gamma^{m-t}V(S_m) with m=min⁡(t+n,T)m = \min(t+n, T), which is γnV(St+n)\gamma^nV(S_{t+n}) if t+n<Tt + n < T and V(terminal)=0V(\text{terminal}) = 0 otherwise. □

The cancellation is easy to watch. Write RkR_k and VkV_k for Rt+kR_{t+k} and V(St+k)V(S_{t+k}) and sum four TD errors.

A TD error as a pure function of its index, then ∑k=03γkδk\sum_{k=0}^{3}\gamma^k\delta_k expanded: every intermediate VkV_k cancels, and the four-step return minus V0V_0 remains.
const tdErr = await wl`Function[{k}, Subscript[R, k + 1] + \[Gamma] Subscript[V, k + 1] - Subscript[V, k]]`
const tdSum4 = await show`Expand[Sum[\[Gamma]^k ${tdErr}[k], {k, 0, 3}]]`
∑k=03γkδk=R1+γR2+γ2R3+γ3R4−V0+γ4V4 \sum_{k=0}^{3}\gamma^k\delta_k = R_1+\gamma R_2+\gamma ^2 R_3+\gamma ^3 R_4-V_0+\gamma ^4 V_4

The identity is exact only while VV is frozen. In Algorithm 7.1 the estimates change at every step, so an algorithm that accumulated TD errors instead of forming (7.1) would be a slightly different algorithm. The gap is of order α\alpha, and it is this gap that the eligibility-trace methods of Chapter 12 learn to manage.

7.1.2Which n Is Best?

Sutton and Barto’s test bed is a random walk on 19 states, with reward −1-1 for leaving on the left and +1+1 on the right. After ten episodes, the error of nn-step TD is smallest for intermediate nn (around 44 to 88 for the best step size), and both n=1n = 1 and very large nn are clearly worse.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 Two effects compete. A larger nn propagates information faster: after an episode that ends in the right terminal state, one-step TD changes only the last state’s value, while nn-step TD moves the last nn. A larger nn also adds randomness: the target depends on more actions, transitions and rewards. With small nn the target is stable but leans on estimates that are still wrong. The next section shows how fast that reliance shrinks with nn.

7.2The Error-Reduction Property

Why should bootstrapping from a wrong VV lead anywhere? Because the expected nn-step return is always closer to vπv_\pi than VV is, by a factor γn\gamma^n in the worst state.

Theorem 7.3 (Error Reduction of n-step Returns). Let VV be any fixed function on 𝒮+\mathcal{S}^+ with V(terminal)=0V(\text{terminal}) = 0, and let Gt:t+nG_{t:t+n} bootstrap from VV. Then for every n≥1n \ge 1

max⁡s∣𝔼π[Gt:t+n∣St=s]−vπ(s)∣  ≤  γnmax⁡s∣V(s)−vπ(s)∣. \max_{s}\bigl\lvert \mathbb{E}_\pi[G_{t:t+n} \mid S_t = s] - v_\pi(s) \bigr\rvert \;\le\; \gamma^n \max_{s}\bigl\lvert V(s) - v_\pi(s) \bigr\rvert. (7.3)

More precisely, 𝔼π[Gt:t+n∣St=⋅ ]−vπ=γn𝐏πn (V−vπ)\mathbb{E}_\pi[G_{t:t+n} \mid S_t = \cdot\,] - v_\pi = \gamma^n\mathbf{P}_\pi^n\,(V - v_\pi) on the nonterminal states, where 𝐏π\mathbf{P}_\pi is the state-transition matrix of π\pi among nonterminal states.

Proof. Index vectors by the nonterminal states. Let 𝐫π(s)=𝔼π[Rt+1∣St=s]\mathbf{r}_\pi(s) = \mathbb{E}_\pi[R_{t+1} \mid S_t = s] and 𝐏π(s,s′)=Pr⁡{St+1=s′∣St=s}\mathbf{P}_\pi(s, s') = \Pr\{S_{t+1} = s' \mid S_t = s\}. Rows of 𝐏π\mathbf{P}_\pi sum to 11 minus the probability of terminating, so 𝐏π\mathbf{P}_\pi is nonnegative with row sums at most 11. After termination all rewards are 00 and V(terminal)=0V(\text{terminal}) = 0, so the convention Gt:t+n=GtG_{t:t+n} = G_t for t+n≥Tt + n \ge T needs no special treatment. By the Markov property, 𝔼π[Rt+k+1∣St=s]=(𝐏πk𝐫π)(s)\mathbb{E}_\pi[R_{t+k+1} \mid S_t = s] = (\mathbf{P}_\pi^k\mathbf{r}_\pi)(s) and 𝔼π[V(St+n)∣St=s]=(𝐏πnV)(s)\mathbb{E}_\pi[V(S_{t+n}) \mid S_t = s] = (\mathbf{P}_\pi^nV)(s), hence

𝔼π[Gt:t+n∣St=⋅ ]=∑k=0n−1γk𝐏πk𝐫π+γn𝐏πnV. \mathbb{E}_\pi[G_{t:t+n} \mid S_t = \cdot\,] = \sum_{k=0}^{n-1}\gamma^k\mathbf{P}_\pi^k\mathbf{r}_\pi + \gamma^n\mathbf{P}_\pi^nV.

The Bellman equation (3.9) in matrix form is vπ=𝐫π+γ𝐏πvπv_\pi = \mathbf{r}_\pi + \gamma\mathbf{P}_\pi v_\pi. Substituting it into itself nn times gives the same expression with vπv_\pi in place of VV. Subtracting, 𝔼π[Gt:t+n∣St=⋅ ]−vπ=γn𝐏πn(V−vπ)\mathbb{E}_\pi[G_{t:t+n} \mid S_t = \cdot\,] - v_\pi = \gamma^n\mathbf{P}_\pi^n(V - v_\pi). Each entry of this vector is γn\gamma^n times a combination of the entries of V−vπV - v_\pi with nonnegative weights summing to at most 11, so its absolute value is at most γnmax⁡s∣V(s)−vπ(s)∣\gamma^n\max_s\lvert V(s) - v_\pi(s)\rvert. □

The proof says more than the statement. The weights in row ss of 𝐏πn\mathbf{P}_\pi^n sum to Pr⁡{T>t+n∣St=s}\Pr\{T > t + n \mid S_t = s\}, the probability that the episode is still running after nn steps. Termination therefore reduces errors even when γ=1\gamma = 1. In operator language, the map V↦∑k<nγk𝐏πk𝐫π+γn𝐏πnVV \mapsto \sum_{k<n}\gamma^k\mathbf{P}_\pi^k\mathbf{r}_\pi + \gamma^n\mathbf{P}_\pi^nV is the Bellman operator applied nn times, a γn\gamma^n-contraction in the max norm. By Theorem A.3 it has vπv_\pi as its unique fixed point. This is the property that convergence proofs of nn-step TD build on: the expected update moves every estimate toward vπv_\pi, and stochastic-approximation arguments (Theorem A.7) take care of the noise.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/406035The nn-step return and its error-reduction property go back to Watkins’s thesis (1989). The first edition of Sutton and Barto treated nn-step methods as of theoretical interest only, as a step toward eligibility traces. The second edition gives them a chapter of their own, because work by Cichosz and by van Seijen had shown them to be practical algorithms.

7.2.1In Wolfram Language

The identity in the proof can be checked on a random walk with three nonterminal states 1,2,31, 2, 3. From each state the walk steps right with probability pp and left with probability 1−p1-p. Leaving on the left gives reward 00, and leaving on the right gives reward 11. The estimates V1,V2,V3V_1, V_2, V_3 are arbitrary symbols.

The substochastic matrix 𝐏π\mathbf{P}_\pi, the expected reward 𝐫π\mathbf{r}_\pi (only state 33 can exit right), vπ=(𝐈−γ𝐏π)−1𝐫πv_\pi = (\mathbf{I} - \gamma\mathbf{P}_\pi)^{-1}\mathbf{r}_\pi, and the expected three-step return built from powers of 𝐏π\mathbf{P}_\pi. The display is the gap between the two sides of the theorem’s identity, 𝔼[Gt:t+3]−vπ−γ3𝐏π3(V−vπ)\mathbb{E}[G_{t:t+3}] - v_\pi - \gamma^3\mathbf{P}_\pi^3(V - v_\pi).
const chainP = await wl`{{0, p, 0}, {1 - p, 0, p}, {0, 1 - p, 0}}`
const chainR = await wl`{0, 0, p}`
const vChain = await wl`Simplify[Inverse[IdentityMatrix[3] - \[Gamma] ${chainP}] . ${chainR}]`
const vEst = await wl`{Subscript[V, 1], Subscript[V, 2], Subscript[V, 3]}`
const powP = await wl`Function[{k, x}, Nest[Function[y, ${chainP} . y], x, k]]`
const expG = await wl`Function[{n}, Sum[\[Gamma]^k ${powP}[k, ${chainR}], {k, 0, n - 1}] + \[Gamma]^n ${powP}[n, ${vEst}]]`
const gapCheck = await show`Simplify[${expG}[3] - ${vChain} - \[Gamma]^3 ${powP}[3, ${vEst} - ${vChain}]]`
𝔼π[Gt:t+3∣St=⋅ ]−vπ−γ3𝐏π3(V−vπ)={0,0,0} \mathbb{E}_\pi[G_{t:t+3} \mid S_t = \cdot\,] - v_\pi - \gamma^3\mathbf{P}_\pi^3(V - v_\pi) = \{0,0,0\} Row sums of 𝐏π3\mathbf{P}_\pi^3, the probabilities of still being in the walk after three steps. Each is at most 1/21/2 for every pp, so here the error shrinks by at least γ3/2\gamma^3/2.
const rowSums3 = await show`Factor[${powP}[3, {1, 1, 1}]]`
𝐏π3 𝟏={−2(−1+p)p2,−2(−1+p)p,2(−1+p)2p} \mathbf{P}_\pi^3\,\mathbf{1} = \left\{-2 (-1+p) p^2,-2 (-1+p) p,2 (-1+p)^2 p\right\}

The worst-case factor is therefore γn\gamma^n times max⁡sPr⁡{T>t+n∣St=s}\max_s\Pr\{T > t + n \mid S_t = s\}, and the theorem bounds the second factor by 11. Figure 7.1 computes it exactly for the random walks of Sutton and Barto’s examples, with 55 and 1919 states. As long as nn is shorter than the distance from the center to either end, the factor is exactly 11, and termination helps only for longer lookaheads. This bears on Sutton and Barto’s Exercise 7.3, which asks whether a smaller walk would have favored a different nn.

Figure 7.1: The factor max⁡s∑s′𝐏πn(s,s′)=max⁡sPr⁡{T>t+n∣St=s}\max_s\sum_{s'}\mathbf{P}_\pi^n(s, s') = \max_s\Pr\{T > t + n \mid S_t = s\} by which termination multiplies the bound γn\gamma^n of Theorem 7.3. It is computed exactly from matrix powers for the equiprobable random walks with 55 (blue) and 1919 (black) nonterminal states. The staircase comes from parity: from the center, an exit is possible only after an odd or only after an even number of steps.Two decreasing staircase curves of the maximum probability that a symmetric random walk has not terminated after n steps, for n from 1 to 200: the 5-state walk drops to nearly zero by n equal to 40, the 19-state walk stays at 1 until about n equal to 9 and then decays slowly to about 0.1 at n equal to 200

7.3n-step Sarsa and n-step Expected Sarsa

For control we switch from states to state–action pairs and let the policy be ε\varepsilon-greedy with respect to the current estimates, exactly as one-step Sarsa (Algorithm 6.6) did. The nn-step return now bootstraps from an action value:

Gt:t+n≐Rt+1+γRt+2+⋯+γn−1Rt+n+γnQt+n−1(St+n,At+n) G_{t:t+n} \doteq R_{t+1} + \gamma R_{t+2} + \dots + \gamma^{n-1}R_{t+n} + \gamma^nQ_{t+n-1}(S_{t+n}, A_{t+n}) (7.4)

for 0≤t<T−n0 \le t < T - n, with Gt:t+n≐GtG_{t:t+n} \doteq G_t if t+n≥Tt + n \ge T. The update is

Qt+n(St,At)≐Qt+n−1(St,At)+α[Gt:t+n−Qt+n−1(St,At)], Q_{t+n}(S_t, A_t) \doteq Q_{t+n-1}(S_t, A_t) + \alpha\bigl[G_{t:t+n} - Q_{t+n-1}(S_t, A_t)\bigr], (7.5)

and this is nn-step Sarsa. One-step Sarsa is now called Sarsa(0). The gain is easiest to see in a gridworld where every reward is zero except at a goal. After the first successful episode, one-step Sarsa has raised the value of only the last action before the goal. nn-step Sarsa has raised the last nn, so a single episode already sketches a path.

nn-step Expected Sarsa samples all the way down except at the last step, where it averages over the target policy. With the expected approximate value

V¯t(s)≐∑aπ(a∣s) Qt(s,a),V¯t(terminal)≐0, \bar V_t(s) \doteq \sum_a \pi(a \mid s)\,Q_t(s, a), \qquad \bar V_t(\text{terminal}) \doteq 0, (7.6)

its return is Gt:t+n≐Rt+1+⋯+γn−1Rt+n+γnV¯t+n−1(St+n)G_{t:t+n} \doteq R_{t+1} + \dots + \gamma^{n-1}R_{t+n} + \gamma^n\bar V_{t+n-1}(S_{t+n}) for t+n<Tt + n < T, used in the same update (7.5). The final random choice At+nA_{t+n} no longer adds variance.

Algorithm 7.4 (n-step Sarsa). Parameters: step size α∈(0,1]\alpha \in (0, 1], small ε>0\varepsilon > 0, an integer n≥1n \ge 1. Initialization: Q(s,a)Q(s, a) arbitrary for all s,as, a, with Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0; π\pi is ε\varepsilon-greedy with respect to QQ (or a fixed policy, for prediction).

For each episode:

  1. Observe a nonterminal S0S_0, choose and store A0∼π(⋅∣S0)A_0 \sim \pi(\cdot \mid S_0), and set T←∞T \leftarrow \infty.
  2. For t=0,1,2,…t = 0, 1, 2, \dots:
    1. If t<Tt < T: take AtA_t, observe and store Rt+1,St+1R_{t+1}, S_{t+1}. If St+1S_{t+1} is terminal, set T←t+1T \leftarrow t+1; otherwise choose and store At+1∼π(⋅∣St+1)A_{t+1} \sim \pi(\cdot \mid S_{t+1}).
    2. Set τ←t−n+1\tau \leftarrow t - n + 1.
    3. If τ≥0\tau \ge 0: compute G←∑i=τ+1min⁡(τ+n, T)γi−τ−1RiG \leftarrow \sum_{i=\tau+1}^{\min(\tau+n,\,T)}\gamma^{i-\tau-1}R_i; if τ+n<T\tau + n < T, add γnQ(Sτ+n,Aτ+n)\gamma^nQ(S_{\tau+n}, A_{\tau+n}) (for Expected Sarsa, add γnV¯(Sτ+n)\gamma^n\bar V(S_{\tau+n}) instead); then Q(Sτ,Aτ)←Q(Sτ,Aτ)+α [G−Q(Sτ,Aτ)]Q(S_\tau, A_\tau) \leftarrow Q(S_\tau, A_\tau) + \alpha\,[G - Q(S_\tau, A_\tau)], and keep π(⋅∣Sτ)\pi(\cdot \mid S_\tau) ε\varepsilon-greedy with respect to QQ.
    4. If τ=T−1\tau = T - 1, end the episode.

7.4Off-policy Learning with Importance Sampling

Now let the data come from a behavior policy bb while we learn about a target policy π\pi, typically greedy with respect to QQ. As in Chapter 5, the probability of a stretch of trajectory differs under the two policies only through the action probabilities. The transition probabilities cancel, and what is left is the importance-sampling ratio (5.2), here truncated at the end of the episode:

ρt:h≐∏k=tmin⁡(h, T−1)π(Ak∣Sk)b(Ak∣Sk). \rho_{t:h} \doteq \prod_{k=t}^{\min(h,\,T-1)} \frac{\pi(A_k \mid S_k)}{b(A_k \mid S_k)}. (7.7)

The off-policy nn-step updates weight the error by the ratio of exactly those actions on which the target depends:

Vt+n(St)≐Vt+n−1(St)+α ρt:t+n−1[Gt:t+n−Vt+n−1(St)],Qt+n(St,At)≐Qt+n−1(St,At)+α ρt+1:t+n[Gt:t+n−Qt+n−1(St,At)]. \begin{aligned} V_{t+n}(S_t) &\doteq V_{t+n-1}(S_t) + \alpha\,\rho_{t:t+n-1}\bigl[G_{t:t+n} - V_{t+n-1}(S_t)\bigr], \\ Q_{t+n}(S_t, A_t) &\doteq Q_{t+n-1}(S_t, A_t) \\ &\quad + \alpha\,\rho_{t+1:t+n}\bigl[G_{t:t+n} - Q_{t+n-1}(S_t, A_t)\bigr]. \end{aligned} (7.8)

The ratio for the action-value update starts one step later and ends one step later than the ratio for the state-value update. The first action AtA_t is the one whose value we are learning: it has been taken, and how likely π\pi was to take it is irrelevant. The last action At+nA_{t+n} enters through Q(St+n,At+n)Q(S_{t+n}, A_{t+n}), so it does need correcting. For nn-step Expected Sarsa the last action is averaged under π\pi anyway, and the ratio is ρt+1:t+n−1\rho_{t+1:t+n-1}. When b=πb = \pi all ratios are 11 and we recover the on-policy algorithms.

Proposition 7.5 (Unbiasedness of the Weighted Targets). For fixed estimates, 𝔼b[ρt:t+n−1Gt:t+n∣St=s]=𝔼π[Gt:t+n∣St=s]\mathbb{E}_b[\rho_{t:t+n-1}G_{t:t+n} \mid S_t = s] = \mathbb{E}_\pi[G_{t:t+n} \mid S_t = s] and 𝔼b[ρt:t+n−1∣St=s]=1\mathbb{E}_b[\rho_{t:t+n-1} \mid S_t = s] = 1. Hence the expected off-policy update of V(s)V(s) is α(𝔼π[Gt:t+n∣St=s]−V(s))\alpha\bigl(\mathbb{E}_\pi[G_{t:t+n} \mid S_t = s] - V(s)\bigr), the expected on-policy update. The same holds for Q(s,a)Q(s, a) with ρt+1:t+n\rho_{t+1:t+n}, conditioning on St=s,At=aS_t = s, A_t = a.

Proof. Gt:t+nG_{t:t+n} is a function of the segment ω=(At,Rt+1,St+1,…,At+n−1,Rt+n,St+n)\omega = (A_t, R_{t+1}, S_{t+1}, \dots, A_{t+n-1}, R_{t+n}, S_{t+n}), truncated at TT. Its probability given St=sS_t = s is a product of policy factors and dynamics factors p(Sk+1,Rk+1∣Sk,Ak)p(S_{k+1}, R_{k+1} \mid S_k, A_k). The dynamics factors are the same under bb and π\pi, so Pr⁡π(ω)=ρt:t+n−1(ω)Pr⁡b(ω)\Pr_\pi(\omega) = \rho_{t:t+n-1}(\omega)\Pr_b(\omega) whenever Pr⁡b(ω)>0\Pr_b(\omega) > 0. We assume coverage, π(a∣s)>0⇒b(a∣s)>0\pi(a \mid s) > 0 \Rightarrow b(a \mid s) > 0, so no segment of positive π\pi-probability is missed. Summing f(ω)Pr⁡b(ω)ρ(ω)f(\omega)\Pr_b(\omega)\rho(\omega) over ω\omega gives 𝔼π[f]\mathbb{E}_\pi[f], for f=Gt:t+nf = G_{t:t+n} and for f=1f = 1. For action values, condition on At=aA_t = a and extend the segment to include At+nA_{t+n} (whose ratio is part of ρt+1:t+n\rho_{t+1:t+n}) when t+n<Tt + n < T. □

Unbiased, but often wildly variable: a product of nn ratios can be huge or zero. Sutton and Barto’s box for off-policy nn-step Sarsa is Algorithm 7.4 with actions drawn from bb, a greedy π\pi, and the step size multiplied by ρτ+1:τ+n\rho_{\tau+1:\tau+n}. We do not repeat it, because the next two sections improve on it.

7.5Per-decision Importance Sampling with Control Variates

Every return can be written recursively. With horizon h=t+nh = t + n,

Gt:h=Rt+1+γGt+1:h,t<h<T,Gh:h≐Vh−1(Sh). G_{t:h} = R_{t+1} + \gamma G_{t+1:h}, \qquad t < h < T, \qquad G_{h:h} \doteq V_{h-1}(S_h).

Off-policy, the first action AtA_t was chosen by bb, so everything that follows it, Rt+1R_{t+1} and the rest, needs the weight ρt=π(At∣St)/b(At∣St)\rho_t = \pi(A_t \mid S_t)/b(A_t \mid S_t). The crude fix multiplies the right-hand side by ρt\rho_t. But then an action that π\pi would never take (ρt=0\rho_t = 0) yields the target 00, and the update pulls V(St)V(S_t) toward zero for no reason. The better fix adds a term that is zero in expectation and takes over when ρt\rho_t is small:

Gt:h≐ρt(Rt+1+γGt+1:h)+(1−ρt) Vh−1(St) G_{t:h} \doteq \rho_t\bigl(R_{t+1} + \gamma G_{t+1:h}\bigr) + (1 - \rho_t)\,V_{h-1}(S_t) (7.9)

for t<h<Tt < h < T, with Gh:h≐Vh−1(Sh)G_{h:h} \doteq V_{h-1}(S_h).

The added term (1−ρt)Vh−1(St)(1-\rho_t)V_{h-1}(S_t) is a control variate. When ρt=0\rho_t = 0 the target equals the current estimate and nothing changes, which is the right response to a sample that says nothing about π\pi. The target is used with the plain update (7.2). The ratios are now applied per decision, inside the recursion, instead of as one product outside it. For action values the first action needs no correction, and the recursion becomes

Gt:h≐Rt+1+γρt+1(Gt+1:h−Qh−1(St+1,At+1))+γV¯h−1(St+1) \begin{aligned} G_{t:h} \doteq{}& R_{t+1} + \gamma\rho_{t+1}\bigl(G_{t+1:h} - Q_{h-1}(S_{t+1}, A_{t+1})\bigr) \\ &+ \gamma\bar V_{h-1}(S_{t+1}) \end{aligned} (7.10)

for t<h≤Tt < h \le T, ending with Gh:h≐Qh−1(Sh,Ah)G_{h:h} \doteq Q_{h-1}(S_h, A_h) if h<Th < T, and with GT−1:h≐RTG_{T-1:h} \doteq R_T if h≥Th \ge T. Here the control variate is V¯h−1(St+1)−ρt+1Qh−1(St+1,At+1)\bar V_{h-1}(S_{t+1}) - \rho_{t+1}Q_{h-1}(S_{t+1}, A_{t+1}).

Proposition 7.6 (Control Variates Have Zero Mean). Fix the estimates and assume coverage. For any state ss, 𝔼b[ρt∣St=s]=1\mathbb{E}_b[\rho_t \mid S_t = s] = 1 and 𝔼b[ρt Q(s,At)∣St=s]=V¯(s)\mathbb{E}_b[\rho_t\,Q(s, A_t) \mid S_t = s] = \bar V(s). Consequently both control variates have zero conditional mean, and the returns (7.9) and (7.10) have the same expectation under bb as the on-policy returns under π\pi: 𝔼b[Gt:h∣St=s]=𝔼π[Gt:h∣St=s]\mathbb{E}_b[G_{t:h} \mid S_t = s] = \mathbb{E}_\pi[G_{t:h} \mid S_t = s], and likewise given St=s,At=aS_t = s, A_t = a.

Proof. 𝔼b[ρt f(At)∣St=s]=∑ab(a∣s)π(a∣s)b(a∣s)f(a)=∑aπ(a∣s)f(a)\mathbb{E}_b[\rho_t\,f(A_t) \mid S_t = s] = \sum_a b(a \mid s)\frac{\pi(a \mid s)}{b(a \mid s)}f(a) = \sum_a\pi(a \mid s)f(a). With f=1f = 1 this is 11, and with f=Q(s,⋅)f = Q(s, \cdot) it is V¯(s)\bar V(s). So 𝔼b[(1−ρt)V(St)∣St]=0\mathbb{E}_b[(1-\rho_t)V(S_t) \mid S_t] = 0 and 𝔼b[V¯(St+1)−ρt+1Q(St+1,At+1)∣St+1]=0\mathbb{E}_b[\bar V(S_{t+1}) - \rho_{t+1}Q(S_{t+1}, A_{t+1}) \mid S_{t+1}] = 0. Unbiasedness of the whole return follows by backward induction on h−th - t. If 𝔼b[Gt+1:h∣St+1]=𝔼π[Gt+1:h∣St+1]\mathbb{E}_b[G_{t+1:h} \mid S_{t+1}] = \mathbb{E}_\pi[G_{t+1:h} \mid S_{t+1}], then conditioning on (St,At)(S_t, A_t), the Markov property and the identity above with f(a)=𝔼[Rt+1+γGt+1:h∣St,At=a]f(a) = \mathbb{E}[R_{t+1} + \gamma G_{t+1:h} \mid S_t, A_t = a] give the claim for Gt:hG_{t:h}. The base case Gh:hG_{h:h} is not random given ShS_h. □

The two identities used in the proof are checked below for three actions with arbitrary bb and π\pi.

With three actions and π3=1−π1−π2\pi_3 = 1 - \pi_1 - \pi_2: the bb-expectation of ρ\rho, and of ρ qA\rho\,q_A minus V¯=∑aπaqa\bar V = \sum_a\pi_aq_a. The behavior probabilities bab_a cancel completely.
const cvMean = await show`Simplify[{Sum[Subscript[b, a] Subscript[\[Pi], a]/Subscript[b, a], {a, 3}], Sum[Subscript[b, a] (Subscript[\[Pi], a]/Subscript[b, a]) Subscript[q, a], {a, 3}] - Sum[Subscript[\[Pi], a] Subscript[q, a], {a, 3}]} /. Subscript[\[Pi], 3] -> 1 - Subscript[\[Pi], 1] - Subscript[\[Pi], 2]]`
(𝔼b[ρ],  𝔼b[ρ qA]−V¯)={1,0} \bigl(\mathbb{E}_b[\rho],\; \mathbb{E}_b[\rho\,q_A] - \bar V\bigr) = \{1,0\}

The control variate leaves the mean alone. Its job is the variance. Take two actions with b=(β,1−β)b = (\beta, 1-\beta) and π=(p,1−p)\pi = (p, 1-p), and suppose that both lead to the same continuation value xx, so that the choice of action is irrelevant and V(s)=xV(s) = x is already correct. Then the crude target ρtx\rho_tx is still noisy, while the control-variate target is exactly right.

Variance under bb of the crude target ρ x\rho\,x and of the control-variate target ρ x+(1−ρ) x\rho\,x + (1-\rho)\,x, with ρ=p/β\rho = p/\beta or (1−p)/(1−β)(1-p)/(1-\beta). The first is x2Var⁡b(ρ)x^2\operatorname{Var}_b(\rho), the second vanishes.
const varB = await wl`Function[{f}, Module[{m = \[Beta] f[1] + (1 - \[Beta]) f[2]}, \[Beta] (f[1] - m)^2 + (1 - \[Beta]) (f[2] - m)^2]]`
const rhoAct = await wl`Function[{a}, If[a == 1, p/\[Beta], (1 - p)/(1 - \[Beta])]]`
const cvVar = await show`Factor[{${varB}[Function[{a}, ${rhoAct}[a] x]], ${varB}[Function[{a}, ${rhoAct}[a] x + (1 - ${rhoAct}[a]) x]]}]`
(Var⁡b(ρx),  Var⁡b(ρx+(1−ρ)x))={−x2(p−β)2(−1+β)β,0} \bigl(\operatorname{Var}_b(\rho x),\; \operatorname{Var}_b(\rho x + (1-\rho)x)\bigr) = \left\{-\frac{x^2 (p-\beta )^2}{(-1+\beta ) \beta },0\right\}

Control variates are one way to tame importance sampling. Sutton and Barto also mention adapting step sizes to the observed variance (Autostep) and “invariant” updates. Each helps, and none removes the basic difficulty: when π\pi and bb differ a lot, long products of ratios are unreliable. The next idea avoids the ratios altogether.

7.6Tree Backup: Off-policy Learning without Importance Sampling

Q-learning and Expected Sarsa learn off-policy in one step without any ratio. They never use the sampled next action to form the target: they average over all next actions under π\pi. The tree-backup algorithm of Precup, Sutton and SinghDoina Precup, Richard S. Sutton, and Satinder Singh. Eligibility Traces for Off-Policy Policy Evaluation. In Proceedings of the Seventeenth International Conference on Machine Learning (ICML 2000), pages 759–766, San Francisco, CA, 2000. Morgan Kaufmann extends this to nn steps. Draw the sampled trajectory as a spine St,At,Rt+1,St+1,At+1,…S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}, \dots. At each state of the spine, hang all the actions that were not taken, as leaves. We have no data about them, so we use their current estimates. The target is a weighted sum of the rewards on the spine and of the estimates on the leaves. A leaf action aa hanging from St+kS_{t+k} gets weight γkπ(a∣St+k)∏i=t+1t+k−1π(Ai∣Si)\gamma^k\pi(a \mid S_{t+k})\prod_{i=t+1}^{t+k-1}\pi(A_i \mid S_i): its own probability under π\pi, times the probabilities of the spine actions above it. The spine actions themselves contribute only through the subtrees below them.

Recursively, with the one-step tree-backup return equal to the Expected Sarsa target Gt:t+1≐Rt+1+γ∑aπ(a∣St+1)Qt(St+1,a)G_{t:t+1} \doteq R_{t+1} + \gamma\sum_a\pi(a \mid S_{t+1})Q_t(S_{t+1}, a), the nn-step return is

Gt:t+n≐Rt+1+γ∑a≠At+1π(a∣St+1) Qt+n−1(St+1,a)+γ π(At+1∣St+1) Gt+1:t+n, \begin{aligned} G_{t:t+n} \doteq{}& R_{t+1} + \gamma\sum_{a \ne A_{t+1}}\pi(a \mid S_{t+1})\,Q_{t+n-1}(S_{t+1}, a) \\ &+ \gamma\,\pi(A_{t+1} \mid S_{t+1})\,G_{t+1:t+n}, \end{aligned} (7.11)

for t<T−1t < T - 1 and n≥2n \ge 2, with GT−1:t+n≐RTG_{T-1:t+n} \doteq R_T. It is used with the update (7.5), without any ratio.

Proposition 7.7 (Tree Backup as Weighted TD Errors). If QQ does not change and δk≐Rk+1+γV¯(Sk+1)−Q(Sk,Ak)\delta_k \doteq R_{k+1} + \gamma\bar V(S_{k+1}) - Q(S_k, A_k) is the Expected Sarsa TD error, then

Gt:t+n=Q(St,At)+∑k=tmin⁡(t+n, T)−1δk∏i=t+1kγ π(Ai∣Si). G_{t:t+n} = Q(S_t, A_t) + \sum_{k=t}^{\min(t+n,\,T)-1}\delta_k\prod_{i=t+1}^{k}\gamma\,\pi(A_i \mid S_i).

Proof. Since ∑a≠At+1π(a∣St+1)Q(St+1,a)=V¯(St+1)−π(At+1∣St+1)Q(St+1,At+1)\sum_{a \ne A_{t+1}}\pi(a \mid S_{t+1})Q(S_{t+1}, a) = \bar V(S_{t+1}) - \pi(A_{t+1} \mid S_{t+1})Q(S_{t+1}, A_{t+1}), the recursion (7.11) reads

Gt:t+n−Q(St,At)=δt+γ π(At+1∣St+1)(Gt+1:t+n−Q(St+1,At+1)). G_{t:t+n} - Q(S_t, A_t) = \delta_t + \gamma\,\pi(A_{t+1} \mid S_{t+1})\bigl(G_{t+1:t+n} - Q(S_{t+1}, A_{t+1})\bigr).

The recursion ends with Gt+n−1:t+n−Q(St+n−1,At+n−1)=δt+n−1G_{t+n-1:t+n} - Q(S_{t+n-1}, A_{t+n-1}) = \delta_{t+n-1}, or with RT−Q(ST−1,AT−1)=δT−1R_T - Q(S_{T-1}, A_{T-1}) = \delta_{T-1}, since V¯(terminal)=0\bar V(\text{terminal}) = 0. Unrolling it gives the sum, with the product of the factors γπ(Ai∣Si)\gamma\pi(A_i \mid S_i) accumulated along the way. □

7.6.1In Wolfram Language

We implement the recursion (7.11) as a fold from the horizon backwards. Write RkR_k, πk=π(At+k∣St+k)\pi_k = \pi(A_{t+k} \mid S_{t+k}), qk=Q(St+k,At+k)q_k = Q(S_{t+k}, A_{t+k}) and V¯k=V¯(St+k)\bar V_k = \bar V(S_{t+k}) for the quantities kk steps after tt. The sum over the untaken actions is then V¯k−πkqk\bar V_k - \pi_kq_k.

The three-step tree-backup return, written with Lk=V¯k−πkqkL_k = \bar V_k - \pi_kq_k, the π\pi-weighted value of the leaves (untaken actions) hanging from the kkth state of the spine. Reward RkR_k and the leaves Lk−1L_{k-1} beside it are weighted by γk−1π1⋯πk−1\gamma^{k-1}\pi_1\cdots\pi_{k-1}, the probability under π\pi of the spine actions that lead to them. There is no importance-sampling ratio anywhere.
const treeG = await wl`Function[{n}, Fold[Function[{g, k}, Subscript[R, k] + \[Gamma] (Subscript[OverBar[V], k] - Subscript[\[Pi], k] Subscript[q, k]) + \[Gamma] Subscript[\[Pi], k] g], Subscript[R, n] + \[Gamma] Subscript[OverBar[V], n], Range[n - 1, 1, -1]]]`
const tree3 = await show`Expand[${treeG}[3] /. {Subscript[OverBar[V], 1] -> Subscript[L, 1] + Subscript[\[Pi], 1] Subscript[q, 1], Subscript[OverBar[V], 2] -> Subscript[L, 2] + Subscript[\[Pi], 2] Subscript[q, 2]}]`
Gt:t+3=γL1+γ2L2π1+R1+γπ1R2+γ2π1π2R3+γ3π1π2V¯3 G_{t:t+3} = \gamma L_1+\gamma ^2 L_2 \pi _1+R_1+\gamma \pi _1 R_2+\gamma ^2 \pi _1 \pi _2 R_3+\gamma ^3 \pi _1 \pi _2 \bar{V}_3 Proposition 7.7 for n=3n = 3: the recursive return minus q0+∑k=02δk∏i=1kγπiq_0 + \sum_{k=0}^{2}\delta_k\prod_{i=1}^{k}\gamma\pi_i, with δk=Rk+1+γV¯k+1−qk\delta_k = R_{k+1} + \gamma\bar V_{k+1} - q_k.
const treeDelta = await wl`Function[{k}, Subscript[R, k + 1] + \[Gamma] Subscript[OverBar[V], k + 1] - Subscript[q, k]]`
const treeSumCheck = await show`Simplify[${treeG}[3] - (Subscript[q, 0] + Sum[${treeDelta}[k] Product[\[Gamma] Subscript[\[Pi], i], {i, 1, k}], {k, 0, 2}])]`
Gt:t+3−(q0+∑k=02δk∏i=1kγπi)=0 G_{t:t+3} - \Bigl(q_0 + \sum_{k=0}^{2}\delta_k\prod_{i=1}^{k}\gamma\pi_i\Bigr) = 0

All weights are at most γk−t\gamma^{k-t}, so there is no variance explosion. The price is that the weights can be tiny. If π\pi is greedy and bb is ε\varepsilon-greedy, then π(Ai∣Si)=0\pi(A_i \mid S_i) = 0 at the first exploratory action, and everything after it is cut off. Tree backup then bootstraps after fewer than nn steps however large nn is (Exercise 7.13).

Algorithm 7.8 (n-step Tree Backup). Parameters: step size α∈(0,1]\alpha \in (0, 1], an integer n≥1n \ge 1. Initialization: Q(s,a)Q(s, a) arbitrary, Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0; π\pi greedy with respect to QQ (or fixed). Actions may be chosen by any policy at all.

For each episode:

  1. Observe a nonterminal S0S_0, choose and store any A0A_0, and set T←∞T \leftarrow \infty.
  2. For t=0,1,2,…t = 0, 1, 2, \dots:
    1. If t<Tt < T: take AtA_t, observe and store Rt+1,St+1R_{t+1}, S_{t+1}. If St+1S_{t+1} is terminal, set T←t+1T \leftarrow t + 1; otherwise choose and store some At+1A_{t+1}.
    2. Set τ←t+1−n\tau \leftarrow t + 1 - n.
    3. If τ≥0\tau \ge 0:
      • if t+1≥Tt + 1 \ge T, set G←RTG \leftarrow R_T; else G←Rt+1+γ∑aπ(a∣St+1)Q(St+1,a)G \leftarrow R_{t+1} + \gamma\sum_a\pi(a \mid S_{t+1})Q(S_{t+1}, a);
      • for k=min⁡(t,T−1)k = \min(t, T-1) down to τ+1\tau + 1: G←Rk+γ∑a≠Akπ(a∣Sk)Q(Sk,a)+γ π(Ak∣Sk) GG \leftarrow R_k + \gamma\sum_{a \ne A_k}\pi(a \mid S_k)Q(S_k, a) + \gamma\,\pi(A_k \mid S_k)\,G;
      • Q(Sτ,Aτ)←Q(Sτ,Aτ)+α [G−Q(Sτ,Aτ)]Q(S_\tau, A_\tau) \leftarrow Q(S_\tau, A_\tau) + \alpha\,[G - Q(S_\tau, A_\tau)], and keep π\pi greedy with respect to QQ.
    4. If τ=T−1\tau = T - 1, end the episode.

7.7Q(σ): Sampling or Expecting, Step by Step

nn-step Sarsa samples an action at every step of the spine. Tree backup takes the expectation over actions at every step. nn-step Expected Sarsa samples at every step except the last. Nothing prevents us from deciding step by step, or even from mixing.Kristopher De Asis, J. Fernando Hernandez-Garcia, G. Zacharias Holland, and Richard S. Sutton. Multi-Step Reinforcement Learning: A Unifying Algorithm. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 32, pages 2902–2909. AAAI Press, 2018. doi: 10.1609/aaai.v32i1.11631 The key is to write the tree-backup recursion in the same shape as the control-variate recursion (7.10). Using ∑a≠Aπ(a∣S)Q(S,a)=V¯(S)−π(A∣S)Q(S,A)\sum_{a \ne A}\pi(a \mid S)Q(S, a) = \bar V(S) - \pi(A \mid S)Q(S, A) in (7.11),

Gt:h=Rt+1+γ π(At+1∣St+1)(Gt+1:h−Qh−1(St+1,At+1))+γV¯h−1(St+1). \begin{aligned} G_{t:h} ={}& R_{t+1} + \gamma\,\pi(A_{t+1} \mid S_{t+1})\bigl(G_{t+1:h} - Q_{h-1}(S_{t+1}, A_{t+1})\bigr) \\ &+ \gamma\bar V_{h-1}(S_{t+1}). \end{aligned}

This is (7.10) with π(At+1∣St+1)\pi(A_{t+1} \mid S_{t+1}) in place of ρt+1\rho_{t+1}. The two methods differ in a single factor, and we may interpolate it. With a degree of sampling σt∈[0,1]\sigma_t \in [0, 1], chosen as any function of the state and action at time tt, the **Q(σ)Q(\sigma)** return is

Gt:h≐Rt+1+γ(σt+1ρt+1+(1−σt+1) π(At+1∣St+1))×(Gt+1:h−Qh−1(St+1,At+1))+γV¯h−1(St+1), \begin{aligned} G_{t:h} \doteq{}& R_{t+1} + \gamma\bigl(\sigma_{t+1}\rho_{t+1} + (1 - \sigma_{t+1})\,\pi(A_{t+1} \mid S_{t+1})\bigr) \\ &\times\bigl(G_{t+1:h} - Q_{h-1}(S_{t+1}, A_{t+1})\bigr) + \gamma\bar V_{h-1}(S_{t+1}), \end{aligned} (7.12)

for t<h≤Tt < h \le T. The recursion ends with Gh:h≐Qh−1(Sh,Ah)G_{h:h} \doteq Q_{h-1}(S_h, A_h) if h<Th < T, or GT−1:T≐RTG_{T-1:T} \doteq R_T if h=Th = T, and the target is used in the plain update (7.5), with no further ratio, since the ratios are already inside the recursion.The recursion has to start from Gh:h=Q(Sh,Ah)G_{h:h} = Q(S_h, A_h), because the factor (Gh:h−Q(Sh,Ah))(G_{h:h} - Q(S_h, A_h)) must vanish at the horizon. A loop that starts from G=0G = 0 instead adds a spurious −γ(σhρh+(1−σh)πh)Q(Sh,Ah)-\gamma(\sigma_h\rho_h + (1-\sigma_h)\pi_h)Q(S_h, A_h) to the target. The box below starts from the correct value.

Proposition 7.9 (The Two Ends of Q(σ)). For fixed QQ and h<Th < T: (i) with σ≡0\sigma \equiv 0, (7.12) is the tree-backup return (7.11). (ii) With σ≡1\sigma \equiv 1 it is the control-variate return (7.10). On-policy (ρ≡1\rho \equiv 1) this equals the nn-step Sarsa return (7.4) plus ∑k=1nγk(V¯(St+k)−Q(St+k,At+k))\sum_{k=1}^{n}\gamma^k\bigl(\bar V(S_{t+k}) - Q(S_{t+k}, A_{t+k})\bigr), a sum of terms with zero mean given St+kS_{t+k}, so its expectation equals that of nn-step Sarsa.

Proof. (i) and the first part of (ii) are substitutions. For the second part of (ii), with σ=ρ=1\sigma = \rho = 1 the recursion reads Gt:h=Rt+1+γGt+1:h+γ(V¯(St+1)−Q(St+1,At+1))G_{t:h} = R_{t+1} + \gamma G_{t+1:h} + \gamma\bigl(\bar V(S_{t+1}) - Q(S_{t+1}, A_{t+1})\bigr), and unrolling it down to Gh:h=Q(Sh,Ah)G_{h:h} = Q(S_h, A_h) gives the stated sum. Each term has zero conditional mean because At+k∼π(⋅∣St+k)A_{t+k} \sim \pi(\cdot \mid S_{t+k}) on-policy. □

7.7.1In Wolfram Language

The Q(σ)Q(\sigma) return (7.12) as a fold started at Gh:h=qnG_{h:h} = q_n. With σk→0\sigma_k \to 0 we subtract the tree-backup return, and with σk→1\sigma_k \to 1, ρk→1\rho_k \to 1 we subtract the three-step Sarsa return. What remains is 00, and then exactly the zero-mean sum ∑k=13γk(V¯k−qk)\sum_{k=1}^{3}\gamma^k(\bar V_k - q_k).
const qSigmaG = await wl`Function[{n}, Fold[Function[{g, k}, Subscript[R, k] + \[Gamma] (Subscript[\[Sigma], k] Subscript[\[Rho], k] + (1 - Subscript[\[Sigma], k]) Subscript[\[Pi], k]) (g - Subscript[q, k]) + \[Gamma] Subscript[OverBar[V], k]], Subscript[q, n], Range[n, 1, -1]]]`
const qSigmaEnds = await show`Simplify[{(${qSigmaG}[3] /. Subscript[\[Sigma], _] -> 0) - ${treeG}[3], (${qSigmaG}[3] /. {Subscript[\[Sigma], _] -> 1, Subscript[\[Rho], _] -> 1}) - (Sum[\[Gamma]^(k - 1) Subscript[R, k], {k, 3}] + \[Gamma]^3 Subscript[q, 3])}]`
(Gt:t+3σ=0−Gt:t+3TB,  Gt:t+3σ=1, ρ=1−Gt:t+3Sarsa)={0,γ(−q1−γq2−γ2q3+V¯1+γV¯2+γ2V¯3)} \begin{aligned} &\bigl(G^{\sigma = 0}_{t:t+3} - G^{\mathrm{TB}}_{t:t+3},\; G^{\sigma = 1,\,\rho = 1}_{t:t+3} - G^{\mathrm{Sarsa}}_{t:t+3}\bigr) \\ &= \left\{0,\gamma \left(-q_1-\gamma q_2-\gamma ^2 q_3+\bar{V}_1+\gamma \bar{V}_2+\gamma ^2 \bar{V}_3\right)\right\} \end{aligned}

Algorithm 7.10 (Off-policy n-step Q(σ)). Input: a behavior policy bb with b(a∣s)>0b(a \mid s) > 0 for all s,as, a. Parameters: step size α∈(0,1]\alpha \in (0, 1], an integer n≥1n \ge 1, a rule for choosing σt∈[0,1]\sigma_t \in [0, 1]. Initialization: Q(s,a)Q(s, a) arbitrary, Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0; π\pi greedy (or ε\varepsilon-greedy) with respect to QQ, or fixed.

For each episode:

  1. Observe a nonterminal S0S_0, choose and store A0∼b(⋅∣S0)A_0 \sim b(\cdot \mid S_0), and set T←∞T \leftarrow \infty.
  2. For t=0,1,2,…t = 0, 1, 2, \dots:
    1. If t<Tt < T: take AtA_t, observe and store Rt+1,St+1R_{t+1}, S_{t+1}. If St+1S_{t+1} is terminal, set T←t+1T \leftarrow t + 1. Otherwise choose and store At+1∼b(⋅∣St+1)A_{t+1} \sim b(\cdot \mid S_{t+1}), select and store σt+1\sigma_{t+1}, and store ρt+1=π(At+1∣St+1)/b(At+1∣St+1)\rho_{t+1} = \pi(A_{t+1} \mid S_{t+1})/b(A_{t+1} \mid S_{t+1}).
    2. Set τ←t−n+1\tau \leftarrow t - n + 1.
    3. If τ≥0\tau \ge 0:
      • if t+1<Tt + 1 < T, set G←Q(St+1,At+1)G \leftarrow Q(S_{t+1}, A_{t+1});
      • for k=min⁡(t+1,T)k = \min(t + 1, T) down to τ+1\tau + 1: if k=Tk = T, G←RTG \leftarrow R_T; otherwise G←Rk+γ(σkρk+(1−σk)π(Ak∣Sk))(G−Q(Sk,Ak))+γ∑aπ(a∣Sk)Q(Sk,a)G \leftarrow R_k + \gamma\bigl(\sigma_k\rho_k + (1-\sigma_k)\pi(A_k \mid S_k)\bigr)\bigl(G - Q(S_k, A_k)\bigr) + \gamma\sum_a\pi(a \mid S_k)Q(S_k, a);
      • Q(Sτ,Aτ)←Q(Sτ,Aτ)+α [G−Q(Sτ,Aτ)]Q(S_\tau, A_\tau) \leftarrow Q(S_\tau, A_\tau) + \alpha\,[G - Q(S_\tau, A_\tau)], and keep π\pi greedy with respect to QQ.
    4. If τ=T−1\tau = T - 1, end the episode.

The whole chapter fits in this one box. σ\sigma decides, at each step, whether to correct the sampled action by its ratio (low bias, possibly high variance) or to replace it by an expectation (no ratio, but a trace that π\pi may cut short). With b=πb = \pi and σ≡1\sigma \equiv 1 it is on-policy Sarsa with control variates, and with n=1n = 1 it reduces to one-step Sarsa, Expected Sarsa, or Q-learning (Algorithm 6.7, greedy π\pi, σ=0\sigma = 0). All nn-step methods share two costs: updates are delayed by nn steps, and the last nn transitions must be stored. Eligibility traces (Chapter 12) remove most of both.

7.8Beyond the Book: Safe and Efficient Multi-step Off-policy Learning

7.8.1Retrace(λ)

Section 7.5 and Section 7.6 leave a dilemma: importance sampling uses all of the data but its products of ratios can explode, while tree backup never explodes but cuts its traces even when bb and π\pi agree closely. Munos, Stepleton, Harutyunyan and Bellemare resolve it with an operator that adds to Q(s,a)Q(s, a) the bb-expectation of the Expected Sarsa TD errors of Proposition 7.7, weighted by products γtc1⋯ct\gamma^t c_1 \cdots c_t of general traces cic_i in place of γtπ(A1∣S1)⋯π(At∣St)\gamma^t\pi(A_1 \mid S_1)\cdots\pi(A_t \mid S_t); Retrace takes ci=λmin⁡(1,ρi)c_i = \lambda\min(1, \rho_i), which never explodes, is not cut where bb agrees with π\pi, and makes the operator a γ\gamma-contraction around qπq_\pi for any behavior policy (Section 12.11 gives the operator and its theorems).Beyond Sutton and Barto (2018). Retrace(λ\lambda) was published at NeurIPS 2016 (Munos et al., 2016). It is the first return-based off-policy control algorithm shown to converge almost surely to q∗q_* for arbitrary behavior policies, with no “GLIE” assumption.Rémi Munos, Tom Stepleton, Anna Harutyunyan, and Marc G. Bellemare. Safe and Efficient Off-Policy Reinforcement Learning. In Advances in Neural Information Processing Systems 29 (NIPS 2016), volume 29, pages 1054–1062. Curran Associates, Inc., 2016. URL https://proceedings.neurips.cc/paper/2016/hash/c3992e9a68c5ae12bd18488bc579b30d-Abstract.html

The contraction factor γ\gamma is a worst case, and longer traces do better. The simplest example shows how much better: one state, two actions, both returning to the same state. If Q−qπQ - q_\pi is a constant dd, the expected trace product after tt steps is c¯ t\bar c^{\,t} with c¯=𝔼b[c]\bar c = \mathbb{E}_b[c], and the series of weighted TD errors can be summed in closed form. For Retrace, c¯=λ∑amin⁡(π(a),b(a))\bar c = \lambda\sum_a\min\bigl(\pi(a), b(a)\bigr).

The one-state operator, with π=(π1,1−π1)\pi = (\pi_1, 1-\pi_1), b=(μ1,1−μ1)b = (\mu_1, 1-\mu_1), traces c1,c2c_1, c_2 and error Q−qπ=(d,d)Q - q_\pi = (d, d). Each TD error is γ π⋅(Q−qπ)−(Q−qπ)a\gamma\,\pi\cdot(Q - q_\pi) - (Q - q_\pi)_a, and the series is summed symbolically. The display is the factor by which the error shrinks, written in terms of c¯=μ1c1+(1−μ1)c2\bar c = \mu_1c_1 + (1-\mu_1)c_2, followed by its values at c¯=0\bar c = 0 (one-step Expected Sarsa) and c¯=1\bar c = 1 (on-policy, λ=1\lambda = 1).
const piOne = await wl`{Subscript[\[Pi], 1], 1 - Subscript[\[Pi], 1]}`
const muOne = await wl`{Subscript[\[Mu], 1], 1 - Subscript[\[Mu], 1]}`
const cOne = await wl`{Subscript[c, 1], Subscript[c, 2]}`
const errOne = await wl`{d, d}`
const deltaOne = await wl`\[Gamma] ${piOne} . ${errOne} - ${errOne}`
const tailOne = await wl`Sum[\[Gamma]^t (${muOne} . ${cOne})^(t - 1), {t, 1, Infinity}, Assumptions -> 0 <= \[Gamma] < 1 && 0 <= ${muOne} . ${cOne} <= 1] (${muOne} . (${cOne} ${deltaOne}))`
const shrink = await wl`Simplify[((${errOne} + ${deltaOne} + ${tailOne})/d)[[1]] /. Subscript[c, 2] -> (OverBar[c] - Subscript[\[Mu], 1] Subscript[c, 1])/(1 - Subscript[\[Mu], 1])]`
const retraceShrink = await show`{${shrink}, ${shrink} /. OverBar[c] -> 0, ${shrink} /. OverBar[c] -> 1}`
(η(c¯),  η(0),  η(1))={γ(−1+c¯)−1+γc¯,γ,0} \bigl(\eta(\bar c),\; \eta(0),\; \eta(1)\bigr) = \left\{\frac{\gamma \left(-1+\bar{c}\right)}{-1+\gamma \bar{c}},\gamma ,0\right\}

The factor γ(1−c¯)/(1−γc¯)\gamma(1-\bar c)/(1-\gamma\bar c) decreases from γ\gamma to 00 as the traces lengthen. Long traces make the expected update converge faster, and Retrace keeps them as long as safety allows.

7.8.2Multi-step Targets in Deep Reinforcement Learning

Truncated nn-step returns became a standard part of value-based deep RL. Rainbow combined six extensions of DQN (Section 15.5) and replaced the one-step target with

Rt(n)+γnmax⁡a′Q𝜽¯(St+n,a′),Rt(n)=∑k=0n−1γkRt+k+1, R^{(n)}_t + \gamma^{n}\max_{a'}Q_{\bar{\boldsymbol{\theta}}}(S_{t+n}, a'), \qquad R^{(n)}_t = \sum_{k=0}^{n-1}\gamma^kR_{t+k+1},

in its distributional form, with n=3n = 3. In its ablations, multi-step learning was, with prioritized replay, the component whose removal hurt most.Matteo Hessel, Joseph Modayil, Hado van Hasselt, Tom Schaul, Georg Ostrovski, Will Dabney, Dan Horgan, Bilal Piot, Mohammad Azar, and David Silver. Rainbow: Combining Improvements in Deep Reinforcement Learning. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 32, pages 3215–3222. AAAI Press, 2018. doi: 10.1609/aaai.v32i1.11796Beyond Sutton and Barto (2018). Rainbow (Hessel et al., AAAI 2018) appeared after the book went to press. Its multi-step target ignores the off-policy correction entirely: the replayed actions came from older, more exploratory policies. This is the uncorrected choice c=λc = \lambda in Retrace’s terms, biased but low-variance, and it works well for small nn. In a systematic DQN-style study, Hernandez-Garcia and Sutton (2019) found that longer backups helped every algorithm they tried, and that off-policy corrections could even hurt. The ratios are missing, so the target is biased toward the value of the behavior policy. With a small nn and a replay buffer of recent data, the bias is small and the faster propagation of reward pays for it. This is the bias–variance trade-off of this chapter, settled empirically in favor of a little bias.J. Fernando Hernandez-Garcia and Richard S. Sutton. Understanding Multi-Step Deep Reinforcement Learning: A Systematic Study of the DQN Target. arXiv preprint arXiv:1901.07510, 2019. URL https://arxiv.org/abs/1901.07510

7.8.3What Is σ For?

De Asis, Hernandez-Garcia, Holland and Sutton analyzed nn-step Q(σ)Q(\sigma) empirically.Kristopher De Asis, J. Fernando Hernandez-Garcia, G. Zacharias Holland, and Richard S. Sutton. Multi-Step Reinforcement Learning: A Unifying Algorithm. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 32, pages 2902–2909. AAAI Press, 2018. doi: 10.1609/aaai.v32i1.11631Beyond Sutton and Barto (2018). The AAAI 2018 paper of De Asis et al. (arXiv 2017) tested on-policy Q(σ)Q(\sigma) on the 19-state random walk, a stochastic windy gridworld and a “mountain cliff” control task. Intermediate σ\sigma beat both extremes, and a σ\sigma decayed from 11 toward 00 (multiplied by 0.950.95 after each episode) beat every fixed σ\sigma. On the random walk, pure sampling (σ=1\sigma = 1, Sarsa) was best early in learning, and pure expectation (σ=0\sigma = 0, tree backup) was best asymptotically. A σ\sigma that starts at 11 and decays toward 00 combined the strengths of both. It is the same bias–variance dial as nn itself, now turned at the level of single actions.

Every method of this chapter learns from experience as it arrives and uses each transition only for the updates whose horizon covers it. Chapter 8 removes that limitation: with a model, the same updates can be fed with simulated experience, as often and in whatever order is most useful.

7.9Exercises

Exercise 7.11. Show that, with VV fixed, the control-variate return (7.9) can be written as

Gt:h=V(St)+∑k=th−1γk−tρt:k δk,δk=Rk+1+γV(Sk+1)−V(Sk), G_{t:h} = V(S_t) + \sum_{k=t}^{h-1}\gamma^{k-t}\rho_{t:k}\,\delta_k, \qquad \delta_k = R_{k+1} + \gamma V(S_{k+1}) - V(S_k),

and verify the identity symbolically for h−t=3h - t = 3. Compare with the crude off-policy target ρt:h−1Gt:h\rho_{t:h-1}G_{t:h}: which errors does each weight by which ratios?

Solution

From (7.9), Gt:h−V(St)=ρt(Rt+1+γGt+1:h−V(St))=ρtδt+γρt(Gt+1:h−V(St+1))G_{t:h} - V(S_t) = \rho_t\bigl(R_{t+1} + \gamma G_{t+1:h} - V(S_t)\bigr) = \rho_t\delta_t + \gamma\rho_t\bigl(G_{t+1:h} - V(S_{t+1})\bigr). Unrolling until Gh:h−V(Sh)=0G_{h:h} - V(S_h) = 0 gives the sum, each TD error carrying the ratios of the actions up to and including its own. The crude target multiplies all errors by the full product ρt:h−1\rho_{t:h-1}, so early TD errors also carry ratios of actions taken after them, which can only add variance. Below, ρk\rho_k, RkR_k and VkV_k denote ρt+k\rho_{t+k}, Rt+kR_{t+k} and V(St+k)V(S_{t+k}).

The recursion (7.9) as a fold from G3:3=V3G_{3:3} = V_3, minus the ratio-weighted TD-error sum. The difference vanishes identically.
const cvG = await wl`Fold[Function[{g, k}, Subscript[\[Rho], k] (Subscript[R, k + 1] + \[Gamma] g) + (1 - Subscript[\[Rho], k]) Subscript[V, k]], Subscript[V, 3], {2, 1, 0}]`
const cvSumCheck = await show`Simplify[${cvG} - (Subscript[V, 0] + Sum[\[Gamma]^k Product[Subscript[\[Rho], i], {i, 0, k}] ${tdErr}[k], {k, 0, 2}])]`
G0:3−(V0+∑k=02γkρ0:k δk)=0 G_{0:3} - \Bigl(V_0 + \sum_{k=0}^{2}\gamma^k\rho_{0:k}\,\delta_k\Bigr) = 0

Exercise 7.12. Consider a continuing chain in which the rewards Rt+1,Rt+2,…R_{t+1}, R_{t+2}, \dots are independent, each with mean μ\mu and variance σ2\sigma^2, so that vπ=μ/(1−γ)v_\pi = \mu/(1-\gamma) in every state. Let the estimate be off by a constant, V=vπ+eV = v_\pi + e. Compute the mean squared error 𝔼[(Gt:t+n−vπ)2]\mathbb{E}[(G_{t:t+n} - v_\pi)^2] as a function of nn. Is there an intermediate optimal nn? What does your answer say about where the advantage of intermediate nn in the random-walk experiment comes from?

Solution

The bias is γne\gamma^ne (by Theorem 7.3, here with equality) and the variance is σ2∑k<nγ2k=σ2(1−γ2n)/(1−γ2)\sigma^2\sum_{k<n}\gamma^{2k} = \sigma^2(1-\gamma^{2n})/(1-\gamma^2).

Mean squared error of the nn-step target, bias squared plus variance, collected in γ2n\gamma^{2n}. It is affine in γ2n\gamma^{2n}, hence monotone in nn.
const mseN = await show`Collect[Simplify[(\[Gamma]^n e)^2 + \[Sigma]^2 Sum[\[Gamma]^(2 k), {k, 0, n - 1}]], \[Gamma]^(2 n), Simplify]`
𝔼[(Gt:t+n−vπ)2]=−σ2−1+γ2+γ2n(e2+σ2−1+γ2) \mathbb{E}\bigl[(G_{t:t+n} - v_\pi)^2\bigr] = -\frac{\sigma ^2}{-1+\gamma ^2}+\gamma ^{2 n} \left(e^2+\frac{\sigma ^2}{-1+\gamma ^2}\right)

The error is σ2/(1−γ2)+γ2n(e2−σ2/(1−γ2))\sigma^2/(1-\gamma^2) + \gamma^{2n}\bigl(e^2 - \sigma^2/(1-\gamma^2)\bigr). If the estimate’s error exceeds the return’s standard deviation, n=∞n = \infty (Monte Carlo) is best; otherwise n=1n = 1. There is never an interior optimum. So the intermediate optimum in the experiment cannot be explained by the quality of a single target with VV frozen. It comes from learning dynamics. VV improves as the episodes go by, so the best trade-off moves over time and an intermediate nn is a good compromise across the run. A larger nn also updates more states per episode. And the errors of neighboring states are correlated, which the independent-noise model ignores.

Exercise 7.13. Let π\pi be greedy and bb be ε\varepsilon-greedy over mm actions, and suppose the episode does not end within the next nn steps. The TD error δt+k\delta_{t+k} keeps a nonzero weight only while the actions At+1,…,At+kA_{t+1}, \dots, A_{t+k} are all greedy. Show that the expected number of TD errors with nonzero weight in Proposition 7.7 is (1−gn)/(1−g)(1 - g^n)/(1 - g) with g=1−ε+ε/mg = 1 - \varepsilon + \varepsilon/m, and evaluate its limit as n→∞n \to \infty for ε=0.1\varepsilon = 0.1, m=4m = 4.

Solution

The error δt+k\delta_{t+k} has nonzero weight if and only if At+1,…,At+kA_{t+1}, \dots, A_{t+k} are all greedy, an event of probability gkg^k under bb. Hence the expected count is ∑k=0n−1gk\sum_{k=0}^{n-1}g^k.

The expected effective depth in closed form, its limit 1/(1−g)1/(1-g) for n→∞n \to \infty in terms of ε\varepsilon and mm, and that limit at ε=1/10\varepsilon = 1/10, m=4m = 4: about 1313 steps, however large nn is.
const tbDepth = await wl`Sum[g^k, {k, 0, n - 1}]`
const tbDepthVals = await show`{Simplify[${tbDepth}], Simplify[1/(1 - g) /. g -> 1 - \[Epsilon] + \[Epsilon]/m], Limit[${tbDepth} /. g -> 1 - 1/10 + 1/40, n -> Infinity]}`
(∑k=0n−1gk,  lim⁡n→∞∑k=0n−1gk,  its value at ε=110,m=4)={−1+gn−1+g,m(−1+m)ϵ,403} \begin{aligned} &\Bigl(\sum_{k=0}^{n-1}g^k,\; \lim_{n\to\infty}\sum_{k=0}^{n-1}g^k,\; \text{its value at } \varepsilon = \tfrac{1}{10}, m = 4\Bigr) \\ &= \left\{\frac{-1+g^n}{-1+g},\frac{m}{(-1+m) \epsilon },\frac{40}{3}\right\} \end{aligned}

The limit is 1/(ε(1−1/m))=40/31/(\varepsilon(1 - 1/m)) = 40/3. With more exploration, the depth shrinks quickly. This is why Retrace replaces π(A∣S)\pi(A \mid S) by min⁡(1,ρ)\min(1, \rho), which equals 11 on greedy actions and is cut only by actions the target policy would not take.

Exercise 7.14. Prove that the nn-step Sarsa return (7.4) can be written exactly, with QQ changing at every step, as

Gt:t+n=Qt−1(St,At)+∑k=tmin⁡(t+n, T)−1γk−t[Rk+1+γQk(Sk+1,Ak+1)−Qk−1(Sk,Ak)], \begin{aligned} G_{t:t+n} &= Q_{t-1}(S_t, A_t) \\ &\quad + \sum_{k=t}^{\min(t+n,\,T)-1}\gamma^{k-t}\bigl[R_{k+1} + \gamma Q_k(S_{k+1}, A_{k+1}) - Q_{k-1}(S_k, A_k)\bigr], \end{aligned}

and check it symbolically for n=3n = 3 with t+n<Tt + n < T.

Solution

The sum telescopes as in Proposition 7.2: the term +γk−t+1Qk(Sk+1,Ak+1)+\gamma^{k-t+1}Q_k(S_{k+1}, A_{k+1}) of the kkth error cancels −γk+1−tQk(Sk+1,Ak+1)-\gamma^{k+1-t}Q_k(S_{k+1}, A_{k+1}) in the next. The novelty is the time index of QQ. Each pair is evaluated with the same estimate QkQ_k in both places, because the kkth error uses QkQ_k for the successor and the (k+1)(k+1)st uses Q(k+1)−1=QkQ_{(k+1)-1} = Q_k for its own pair. What remains is −Qt−1(St,At)-Q_{t-1}(S_t, A_t), the rewards, and γnQt+n−1(St+n,At+n)\gamma^nQ_{t+n-1}(S_{t+n}, A_{t+n}), the bootstrap term of (7.4). If the episode ends first, the last term is Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0.

Write Qk(Sj,Aj)Q_k(S_j, A_j) as the symbol Qk,jQ_{k,j} (with t=0t = 0), sum the three novel TD errors and subtract the Sarsa return R1+γR2+γ2R3+γ3Q2,3R_1 + \gamma R_2 + \gamma^2R_3 + \gamma^3Q_{2,3}: only −Q−1,0-Q_{-1,0} is left.
const sarsaErr = await wl`Function[{k}, Subscript[R, k + 1] + \[Gamma] Subscript[Q, k, k + 1] - Subscript[Q, k - 1, k]]`
const sarsaSumCheck = await show`Expand[Sum[\[Gamma]^k ${sarsaErr}[k], {k, 0, 2}] - (Subscript[R, 1] + \[Gamma] Subscript[R, 2] + \[Gamma]^2 Subscript[R, 3] + \[Gamma]^3 Subscript[Q, 2, 3])]`
∑k=02γk[Rk+1+γQk,k+1−Qk−1,k]−G0:3=−Q−1,0 \sum_{k=0}^{2}\gamma^k\bigl[R_{k+1} + \gamma Q_{k,k+1} - Q_{k-1,k}\bigr] - G_{0:3} = -Q_{-1,0}