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 steps, sum the 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 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 , which contains both.
7.1The n-step Return#
Fix a policy and an episode generated by it. The Monte Carlo target for is the full return . The one-step TD target is : the first reward, plus an estimate that stands in for all the discounted rewards after it. The -step return keeps real rewards before it lets the estimate take over:
(7.1)for and .
The subscript says that the return starts at time and uses information up to time . The estimate used to bootstrap is , the most recent one available when and have been observed. If the episode ends before , there is nothing left to estimate, and we set when . With this is the TD target, and with it is the Monte Carlo return.
A target that looks steps ahead cannot be formed until steps have passed. The update of the state visited at time is therefore made at time :
(7.2)and all other states keep their values. This is -step TD. No update happens during the first steps of an episode, and the missing updates are made after termination, using returns that are then simply truncated at .
Algorithm 7.1 (n-step TD for Estimating ). Input: a policy . Parameters: step size , an integer . Initialization: arbitrary for all , with . The stored and need only be kept for the last steps (index modulo ).
For each episode:
- Observe a nonterminal and set .
- For :
- If : take , observe and store and ; if is terminal, set .
- Set , the time whose state is updated now.
- If : compute ; if , add ; then .
- If , 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 is a discounted sum of TD errors (6.2). The -step error is the same sum, cut off after terms.
Proposition 7.2 (The n-step Error Telescopes). If does not change during the episode and (with ), then
Proof. In the term of cancels the term of . What survives is the sum of the discounted rewards, the first , and the last with , which is if and otherwise. □
The cancellation is easy to watch. Write and for and and sum four TD errors.
A TD error as a pure function of its index, then expanded: every intermediate cancels, and the four-step return minus 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}]]`The identity is exact only while 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 , 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 for leaving on the left and on the right. After ten episodes, the error of -step TD is smallest for intermediate (around to for the best step size), and both and very large 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 propagates information faster: after an episode that ends in the right terminal state, one-step TD changes only the last state’s value, while -step TD moves the last . A larger also adds randomness: the target depends on more actions, transitions and rewards. With small the target is stable but leans on estimates that are still wrong. The next section shows how fast that reliance shrinks with .
7.2The Error-Reduction Property#
Why should bootstrapping from a wrong lead anywhere? Because the expected -step return is always closer to than is, by a factor in the worst state.
Theorem 7.3 (Error Reduction of n-step Returns). Let be any fixed function on with , and let bootstrap from . Then for every
(7.3)More precisely, on the nonterminal states, where is the state-transition matrix of among nonterminal states.
Proof. Index vectors by the nonterminal states. Let and . Rows of sum to minus the probability of terminating, so is nonnegative with row sums at most . After termination all rewards are and , so the convention for needs no special treatment. By the Markov property, and , hence
The Bellman equation (3.9) in matrix form is . Substituting it into itself times gives the same expression with in place of . Subtracting, . Each entry of this vector is times a combination of the entries of with nonnegative weights summing to at most , so its absolute value is at most . □
The proof says more than the statement. The weights in row of sum to , the probability that the episode is still running after steps. Termination therefore reduces errors even when . In operator language, the map is the Bellman operator applied times, a -contraction in the max norm. By Theorem A.3 it has as its unique fixed point. This is the property that convergence proofs of -step TD build on: the expected update moves every estimate toward , 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 -step return and its error-reduction property go back to Watkins’s thesis (1989). The first edition of Sutton and Barto treated -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 . From each state the walk steps right with probability and left with probability . Leaving on the left gives reward , and leaving on the right gives reward . The estimates are arbitrary symbols.
The substochastic matrix , the expected reward (only state can exit right), , and the expected three-step return built from powers of . The display is the gap between the two sides of the theorem’s identity, .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}]]`const rowSums3 = await show`Factor[${powP}[3, {1, 1, 1}]]`The worst-case factor is therefore times , and the theorem bounds the second factor by . Figure 7.1 computes it exactly for the random walks of Sutton and Barto’s examples, with and states. As long as is shorter than the distance from the center to either end, the factor is exactly , 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 .
7.3n-step Sarsa and n-step Expected Sarsa#
For control we switch from states to state–action pairs and let the policy be -greedy with respect to the current estimates, exactly as one-step Sarsa (Algorithm 6.6) did. The -step return now bootstraps from an action value:
(7.4)for , with if . The update is
(7.5)and this is -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. -step Sarsa has raised the last , so a single episode already sketches a path.
-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
(7.6)its return is for , used in the same update (7.5). The final random choice no longer adds variance.
Algorithm 7.4 (n-step Sarsa). Parameters: step size , small , an integer . Initialization: arbitrary for all , with ; is -greedy with respect to (or a fixed policy, for prediction).
For each episode:
- Observe a nonterminal , choose and store , and set .
- For :
- If : take , observe and store . If is terminal, set ; otherwise choose and store .
- Set .
- If : compute ; if , add (for Expected Sarsa, add instead); then , and keep -greedy with respect to .
- If , end the episode.
7.4Off-policy Learning with Importance Sampling#
Now let the data come from a behavior policy while we learn about a target policy , typically greedy with respect to . 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:
(7.7)The off-policy -step updates weight the error by the ratio of exactly those actions on which the target depends:
(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 is the one whose value we are learning: it has been taken, and how likely was to take it is irrelevant. The last action enters through , so it does need correcting. For -step Expected Sarsa the last action is averaged under anyway, and the ratio is . When all ratios are and we recover the on-policy algorithms.
Proposition 7.5 (Unbiasedness of the Weighted Targets). For fixed estimates, and . Hence the expected off-policy update of is , the expected on-policy update. The same holds for with , conditioning on .
Proof. is a function of the segment , truncated at . Its probability given is a product of policy factors and dynamics factors . The dynamics factors are the same under and , so whenever . We assume coverage, , so no segment of positive -probability is missed. Summing over gives , for and for . For action values, condition on and extend the segment to include (whose ratio is part of ) when . □
Unbiased, but often wildly variable: a product of ratios can be huge or zero. Sutton and Barto’s box for off-policy -step Sarsa is Algorithm 7.4 with actions drawn from , a greedy , and the step size multiplied by . 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 ,
Off-policy, the first action was chosen by , so everything that follows it, and the rest, needs the weight . The crude fix multiplies the right-hand side by . But then an action that would never take () yields the target , and the update pulls toward zero for no reason. The better fix adds a term that is zero in expectation and takes over when is small:
(7.9)for , with .
The added term is a control variate. When the target equals the current estimate and nothing changes, which is the right response to a sample that says nothing about . 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
(7.10)for , ending with if , and with if . Here the control variate is .
Proposition 7.6 (Control Variates Have Zero Mean). Fix the estimates and assume coverage. For any state , and . Consequently both control variates have zero conditional mean, and the returns (7.9) and (7.10) have the same expectation under as the on-policy returns under : , and likewise given .
Proof. . With this is , and with it is . So and . Unbiasedness of the whole return follows by backward induction on . If , then conditioning on , the Markov property and the identity above with give the claim for . The base case is not random given . □
The two identities used in the proof are checked below for three actions with arbitrary and .
With three actions and : the -expectation of , and of minus . The behavior probabilities 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]]`The control variate leaves the mean alone. Its job is the variance. Take two actions with and , and suppose that both lead to the same continuation value , so that the choice of action is irrelevant and is already correct. Then the crude target is still noisy, while the control-variate target is exactly right.
Variance under of the crude target and of the control-variate target , with or . The first is , 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]]}]`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 and 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 . 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 steps. Draw the sampled trajectory as a spine . 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 hanging from gets weight : its own probability under , 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 , the -step return is
(7.11)for and , with . It is used with the update (7.5), without any ratio.
Proposition 7.7 (Tree Backup as Weighted TD Errors). If does not change and is the Expected Sarsa TD error, then
Proof. Since , the recursion (7.11) reads
The recursion ends with , or with , since . Unrolling it gives the sum, with the product of the factors accumulated along the way. □
7.6.1In Wolfram Language#
We implement the recursion (7.11) as a fold from the horizon backwards. Write , , and for the quantities steps after . The sum over the untaken actions is then .
The three-step tree-backup return, written with , the -weighted value of the leaves (untaken actions) hanging from the th state of the spine. Reward and the leaves beside it are weighted by , the probability under 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]}]`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}])]`All weights are at most , so there is no variance explosion. The price is that the weights can be tiny. If is greedy and is -greedy, then at the first exploratory action, and everything after it is cut off. Tree backup then bootstraps after fewer than steps however large is (Exercise 7.13).
Algorithm 7.8 (n-step Tree Backup). Parameters: step size , an integer . Initialization: arbitrary, ; greedy with respect to (or fixed). Actions may be chosen by any policy at all.
For each episode:
- Observe a nonterminal , choose and store any , and set .
- For :
- If : take , observe and store . If is terminal, set ; otherwise choose and store some .
- Set .
- If :
- if , set ; else ;
- for down to : ;
- , and keep greedy with respect to .
- If , end the episode.
7.7Q(σ): Sampling or Expecting, Step by Step#
-step Sarsa samples an action at every step of the spine. Tree backup takes the expectation over actions at every step. -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 in (7.11),
This is (7.10) with in place of . The two methods differ in a single factor, and we may interpolate it. With a degree of sampling , chosen as any function of the state and action at time , the **** return is
(7.12)for . The recursion ends with if , or if , 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 , because the factor must vanish at the horizon. A loop that starts from instead adds a spurious to the target. The box below starts from the correct value.
Proposition 7.9 (The Two Ends of Q(σ)). For fixed and : (i) with , (7.12) is the tree-backup return (7.11). (ii) With it is the control-variate return (7.10). On-policy () this equals the -step Sarsa return (7.4) plus , a sum of terms with zero mean given , so its expectation equals that of -step Sarsa.
Proof. (i) and the first part of (ii) are substitutions. For the second part of (ii), with the recursion reads , and unrolling it down to gives the stated sum. Each term has zero conditional mean because on-policy. □
7.7.1In Wolfram Language#
The return (7.12) as a fold started at . With we subtract the tree-backup return, and with , we subtract the three-step Sarsa return. What remains is , and then exactly the zero-mean sum .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])}]`Algorithm 7.10 (Off-policy n-step Q(σ)). Input: a behavior policy with for all . Parameters: step size , an integer , a rule for choosing . Initialization: arbitrary, ; greedy (or -greedy) with respect to , or fixed.
For each episode:
- Observe a nonterminal , choose and store , and set .
- For :
- If : take , observe and store . If is terminal, set . Otherwise choose and store , select and store , and store .
- Set .
- If :
- if , set ;
- for down to : if , ; otherwise ;
- , and keep greedy with respect to .
- If , end the episode.
The whole chapter fits in this one box. 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 may cut short). With and it is on-policy Sarsa with control variates, and with it reduces to one-step Sarsa, Expected Sarsa, or Q-learning (Algorithm 6.7, greedy , ). All -step methods share two costs: updates are delayed by steps, and the last 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 and agree closely. Munos, Stepleton, Harutyunyan and Bellemare resolve it with an operator that adds to the -expectation of the Expected Sarsa TD errors of Proposition 7.7, weighted by products of general traces in place of ; Retrace takes , which never explodes, is not cut where agrees with , and makes the operator a -contraction around for any behavior policy (Section 12.11 gives the operator and its theorems).Beyond Sutton and Barto (2018). Retrace() 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 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 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 is a constant , the expected trace product after steps is with , and the series of weighted TD errors can be summed in closed form. For Retrace, .
The one-state operator, with , , traces and error . Each TD error is , and the series is summed symbolically. The display is the factor by which the error shrinks, written in terms of , followed by its values at (one-step Expected Sarsa) and (on-policy, ).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}`The factor decreases from to 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 -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
in its distributional form, with . 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 in Retrace’s terms, biased but low-variance, and it works well for small . 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 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 -step 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 on the 19-state random walk, a stochastic windy gridworld and a “mountain cliff” control task. Intermediate beat both extremes, and a decayed from toward (multiplied by after each episode) beat every fixed . On the random walk, pure sampling (, Sarsa) was best early in learning, and pure expectation (, tree backup) was best asymptotically. A that starts at and decays toward combined the strengths of both. It is the same bias–variance dial as 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 fixed, the control-variate return (7.9) can be written as
and verify the identity symbolically for . Compare with the crude off-policy target : which errors does each weight by which ratios?
Solution
From (7.9), . Unrolling until 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 , so early TD errors also carry ratios of actions taken after them, which can only add variance. Below, , and denote , and .
The recursion (7.9) as a fold from , 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}])]`Exercise 7.12. Consider a continuing chain in which the rewards are independent, each with mean and variance , so that in every state. Let the estimate be off by a constant, . Compute the mean squared error as a function of . Is there an intermediate optimal ? What does your answer say about where the advantage of intermediate in the random-walk experiment comes from?
Solution
The bias is (by Theorem 7.3, here with equality) and the variance is .
Mean squared error of the -step target, bias squared plus variance, collected in . It is affine in , hence monotone in .const mseN = await show`Collect[Simplify[(\[Gamma]^n e)^2 + \[Sigma]^2 Sum[\[Gamma]^(2 k), {k, 0, n - 1}]], \[Gamma]^(2 n), Simplify]`The error is . If the estimate’s error exceeds the return’s standard deviation, (Monte Carlo) is best; otherwise . There is never an interior optimum. So the intermediate optimum in the experiment cannot be explained by the quality of a single target with frozen. It comes from learning dynamics. improves as the episodes go by, so the best trade-off moves over time and an intermediate is a good compromise across the run. A larger also updates more states per episode. And the errors of neighboring states are correlated, which the independent-noise model ignores.
Exercise 7.13. Let be greedy and be -greedy over actions, and suppose the episode does not end within the next steps. The TD error keeps a nonzero weight only while the actions are all greedy. Show that the expected number of TD errors with nonzero weight in Proposition 7.7 is with , and evaluate its limit as for , .
Solution
The error has nonzero weight if and only if are all greedy, an event of probability under . Hence the expected count is .
The expected effective depth in closed form, its limit for in terms of and , and that limit at , : about steps, however large 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]}`The limit is . With more exploration, the depth shrinks quickly. This is why Retrace replaces by , which equals on greedy actions and is cut only by actions the target policy would not take.
Exercise 7.14. Prove that the -step Sarsa return (7.4) can be written exactly, with changing at every step, as
and check it symbolically for with .
Solution
The sum telescopes as in Proposition 7.2: the term of the th error cancels in the next. The novelty is the time index of . Each pair is evaluated with the same estimate in both places, because the th error uses for the successor and the st uses for its own pair. What remains is , the rewards, and , the bootstrap term of (7.4). If the episode ends first, the last term is .
Write as the symbol (with ), sum the three novel TD errors and subtract the Sarsa return : only 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])]`