Chapter 5
Monte Carlo Methods
Dynamic programming needs the full distribution ; the methods of this chapter need only episodes. A value is an expected return, so it can be estimated the way any expectation is estimated: run the policy, record what happened, and average.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 That idea, applied state by state, is all of Monte Carlo prediction. Turning it into a control method requires two more ingredients met in earlier chapters. From Chapter 2 comes the need to keep exploring, because an action that is never tried is never evaluated. From Chapter 4 comes generalized policy iteration (Section 4.7), the alternation of evaluation and improvement that works even when neither is carried out completely. The new difficulty, and the theme of the second half of the chapter, is learning about one policy while behaving according to another. Its tool is importance sampling, and its two variants, ordinary and weighted, trade bias against variance in a way that will reappear in every off-policy method of the book.
Throughout, tasks are episodic and every episode terminates, so that every return is a finite sum ((3.5)). Monte Carlo methods change their estimates only at the end of an episode: they are incremental episode by episode, not step by step.
5.1Monte Carlo Prediction#
Fix a policy and a state . Each occurrence of in an episode is a visit; the first occurrence is the first visit. First-visit Monte Carlo estimates by averaging the returns that follow first visits to ; every-visit Monte Carlo averages the returns that follow all visits.
Algorithm 5.1 (First-visit Monte Carlo prediction). Input: a policy . Initialize: arbitrary and for all .
Loop for each episode:
- Generate an episode following : .
- .
- For :
- ;
- if : and .
Every-visit Monte Carlo omits the test in step 3.
The backward loop computes all returns of an episode in one pass using , and the update is the incremental sample average of Chapter 2. Compared with the backup diagrams of Chapter 4, the Monte Carlo diagram is a single path: one sampled branch at every level, all the way to termination. Two consequences follow. First, the estimate of never uses the estimate of any other state: Monte Carlo does not bootstrap. Second, the cost of estimating one state is independent of the size of , so a few states of interest can be evaluated by starting many episodes there and ignoring the rest.This is the original use of the method. Kakutani (1945) observed that the solution of the Dirichlet problem at a point equals the expected boundary value hit by a Brownian motion started there; Sutton and Barto’s soap-bubble example is a discrete version, in which the height of a soap film at a grid point is the average boundary height reached by a symmetric random walk.
How good are the two estimators? The answer depends on a single fact: what happens after a visit to is distributed as an episode started in , whatever happened before. This is the Markov property applied at a random time (a stopping time, since whether time is the -th visit is decided by ).
Proposition 5.2 (First-visit and every-visit Monte Carlo). Suppose and that is visited in infinitely many of the episodes.
- The returns after first visits are independent and identically distributed with mean . Hence the first-visit estimate after first visits is unbiased, has variance with , and converges to with probability one.
- Let be the number of visits to in episode and the sum of the returns after them, and suppose . The every-visit estimate converges to with probability one, but for finite it is in general biased.
Proof. (1) Episodes are independent, and within an episode the first visit is a stopping time; by the Markov property the return after it has the conditional law of given , so its mean is . The sample mean of such variables has mean and variance , and the strong law of large numbers gives convergence.
(2) Within one episode the returns after successive visits share a common tail and are dependent, which is why every-visit Monte Carlo is not a plain sample mean. The pairs are, however, independent across episodes, so by the strong law the ratio converges to . The -th visit, when it occurs, is again a stopping time, so the return after it has mean and . The limit is therefore . A ratio of averages is not the average of ratios, and the example below shows that its expectation differs from for . □
Singh and SuttonSatinder P. Singh and Richard S. Sutton. Reinforcement Learning with Replacing Eligibility Traces. Machine Learning, 22(1–3):123–158, 1996. doi: 10.1007/BF00114726 analyzed both estimators and showed that every-visit Monte Carlo can have lower mean squared error in the first few episodes despite its bias; every-visit is also the variant that extends to function approximation and eligibility traces (Chapter 9, Chapter 12).
5.1.1In Wolfram Language#
The cleanest example has a single nonterminal state that the policy leaves with probability at each step, collecting reward on every step, with . The return from is the episode length , a geometric random variable with , so . In one episode is visited times, with returns .
The one-episode estimates: first visit gives , every visit gives the mean of , that is . Their expectations are and something smaller.const geomEst = await show`Module[{pr = (1 - p) p^(k - 1)}, FullSimplify[{Sum[pr k, {k, 1, Infinity}], Sum[pr (k + 1)/2, {k, 1, Infinity}]}, 0 < p < 1]]`const geomLimit = await show`Module[{pr = (1 - p) p^(k - 1)}, FullSimplify[Sum[pr k (k + 1)/2, {k, 1, Infinity}]/Sum[pr k, {k, 1, Infinity}], 0 < p < 1]]`5.2Action Values and Exploring Starts#
With a model, state values suffice for control: one step of lookahead with turns into a greedy policy. Without a model, that lookahead is impossible, and the useful object is the action-value function , the expected return after taking in and following thereafter. Its Monte Carlo estimation is the same as before with pairs in place of states: a pair is visited when occurs and is taken there.
The trouble is that a deterministic takes only one action in each state, so the returns of all other actions are never observed and their estimates never improve. This is the exploration problem of Chapter 2, now in every state at once. One remedy is to assume exploring starts: every episode begins in a pair chosen so that every pair has positive probability, after which is followed. In a simulator this costs nothing; in the real world it is rarely possible, and the rest of the chapter removes it in two different ways.
5.3Monte Carlo Control#
Monte Carlo control is generalized policy iteration with Monte Carlo evaluation of . The improvement step needs no model: given , the greedy policy satisfies
for every , so the policy improvement theorem (Theorem 4.6) gives , with equality only if both are optimal. Two idealizations make this argument airtight: exploring starts, and an infinite number of episodes per evaluation. The second one is dropped exactly as value iteration drops it in dynamic programming: evaluation is not completed, but merely advanced by one episode before the policy is improved at the states that episode visited. With exploring starts this gives Monte Carlo ES.
Algorithm 5.3 (Monte Carlo ES (exploring starts)). Initialize: arbitrary; arbitrary and for all .
Loop for each episode:
- Choose so that every pair has positive probability; generate following from on.
- . For :
- ;
- if the pair does not occur among : , , and .
Monte Carlo ES cannot settle on a suboptimal policy: if it did, would converge to that policy’s action values and the greedy step would change it. Yet, because the averages mix returns of many different policies, convergence to resisted proof for decades; Sutton and Barto call it one of the most fundamental open theoretical questions of the field.Beyond Sutton and Barto (2018). Bertsekas and Tsitsiklis had shown that a variant updating all pairs at different rates can fail, and Tsitsiklis (2002) proved convergence when all pairs are updated at the same rate and . Wang, Yuan, Shao and Ross (ICLR 2022) proved almost sure convergence of the original algorithm for optimal policy feed-forward MDPs, in which no state is revisited within an episode under an optimal policy, with an induction based only on the strong law of large numbers; Liu (2020) treats undiscounted stochastic shortest path problems. The general case is still open.John N. Tsitsiklis. On the Convergence of Optimistic Policy Iteration. Journal of Machine Learning Research, 3:59–72, 2002; Che Wang, Shuhan Yuan, Kai Shao, and Keith Ross. On the Convergence of the Monte Carlo Exploring Starts Algorithm for Reinforcement Learning. In International Conference on Learning Representations (ICLR 2022), 2022; and Jun Liu. On the Convergence of Reinforcement Learning with Monte Carlo Exploring Starts, 2020. arXiv preprint arXiv:2007.10916 On blackjack, with 200 states and exploring starts that deal random cards, Monte Carlo ES finds a policy that matches Thorp’s basic strategy except for one cell.
5.4On-Policy Control without Exploring Starts#
The only general way to make sure every action is tried infinitely often is for the agent to keep trying them. On-policy methods evaluate and improve the very policy that generates the data, which must therefore remain exploratory; off-policy methods, treated next, evaluate one policy while following another.
A policy is -soft if for all and . The -greedy policy with respect to gives every action and the rest, , to a greedy action; among -soft policies it is the closest to greedy.
Algorithm 5.4 (On-policy first-visit Monte Carlo control). Parameter: . Initialize: an arbitrary -soft policy; arbitrary, .
Loop for each episode:
- Generate an episode following .
- . For : , and if is a first visit,
- update toward by the sample average, as in Algorithm 5.3;
- (ties broken arbitrarily);
- for all : if , and otherwise.
Generalized policy iteration only requires the policy to move toward the greedy one, and the next theorem says that moving to the -greedy policy is an improvement, ending only at the best -soft policy.
Theorem 5.5 (Policy improvement within ε-soft policies). Let be -soft and let be -greedy with respect to . Then for all . Equality holds for all if and only if is optimal among the -soft policies.
Proof. Write . Because is -soft, the numbers are nonnegative and sum to one, and a maximum dominates any weighted average:
(5.1)The policy improvement theorem, which holds for stochastic policies, gives .
For the equality case, move the constraint into the environment. Let behave like the original MDP, except that when action is chosen, with probability the environment replaces it by an action drawn uniformly from . Choosing deterministically in is the same as playing the -soft policy with greedy mass on in the original MDP, and every -soft policy is a mixture of such choices, so the best that can be done in equals the best that can be done with -soft policies. The optimal value of is the unique solution of
If , then is also -greedy with respect to , and the equality in the first line of (5.1) becomes, after expanding with the dynamics, the same equation with in place of . By uniqueness . Conversely, if no -soft policy is better, so . □
The theorem is a statement about exact action values; with Monte Carlo estimates it describes where generalized policy iteration is heading, not a step-by-step guarantee. The price of dropping exploring starts is visible in the statement: the method converges to the best policy that still explores, not to . Off-policy learning removes that compromise.
5.4.1In Wolfram Language#
The improvement inequality is checked on one state with three actions, ordered . Any -soft policy has the form for a distribution .
The gain of the -greedy policy over an arbitrary -soft policy, , divided by and written with : a sum of nonnegative terms.const epsGain = await show`Module[{q = {Subscript[q, 1], Subscript[q, 2], Subscript[q, 3]}, mu = {1 - Subscript[\[Mu], 2] - Subscript[\[Mu], 3], Subscript[\[Mu], 2], Subscript[\[Mu], 3]}}, Collect[Simplify[(({\[Epsilon]/3 + 1 - \[Epsilon], \[Epsilon]/3, \[Epsilon]/3} - (\[Epsilon]/3 + (1 - \[Epsilon]) mu)) . q)/(1 - \[Epsilon])], {Subscript[\[Mu], 2], Subscript[\[Mu], 3]}, Factor]]`5.5Off-Policy Prediction via Importance Sampling#
All learning control methods face a dilemma: they want the values of optimal behavior, but must behave suboptimally to find it. The off-policy answer is to use two policies. The target policy is the one being learned about, possibly deterministic and greedy; the behavior policy generates the data and keeps exploring. For prediction, both are fixed and we want from episodes of . This is possible only under coverage: must imply , so that everything might do is seen sometimes.
Starting from , the probability under of the remaining trajectory is
and the same with in place of under the behavior policy. Their ratio is the importance-sampling ratio
(5.2)The unknown dynamics appear once upstairs and once downstairs and cancel: the ratio depends only on the two policies and the observed actions. This is what makes off-policy learning possible without a model.
Proposition 5.6 (Importance sampling corrects the expectation). Under coverage, , and .
Proof. Sum over the possible trajectories from , writing and for their probabilities and for the return. By (5.2), whenever , and coverage guarantees that every with has . Hence
and the same computation with gives . □
Number time steps consecutively across episodes, let be the set of times at which is visited (first visits only, for a first-visit method), and let be the end of the episode containing . Two estimators follow:
(5.3)ordinary importance sampling and weighted importance sampling (with when the denominator vanishes). After a single first visit with ratio , the weighted estimate is the observed return itself, whose expectation is a behavior-policy quantity, not ; the ordinary estimate is , unbiased but possibly ten times the observed return when .
Proposition 5.7 (Ordinary versus weighted importance sampling). Consider first-visit estimates from independent episodes, with and the ratio and return after the first visit to in episode .
- is unbiased, with variance , which is infinite whenever .
- is biased for finite but consistent: with probability one. If , then and its mean squared error tends to zero, even when .
- If , then is asymptotically normal with variance , whereas .
Proof. (1) follows from Proposition 5.6 and independence. (2) Divide numerator and denominator by ; by the strong law they converge to and , and the ratio converges to . A weighted average with nonnegative weights lies between the smallest and the largest , which gives the bound, and bounded convergence turns almost sure convergence into convergence of the mean squared error. (3) Write . The numerator is an average of independent terms with mean zero and variance , and the denominator tends to ; the central limit theorem and Slutsky’s lemma finish the proof. □
Item 3 explains why weighted importance sampling is “strongly preferred” in practice. Both estimators pay for the ratio , but the weighted one pays it on the centered return , so it is invariant to adding a constant to all rewards while the ordinary one is not. The ordinary estimator remains important because it is a plain average of unbiased terms, the form that extends to semi-gradient methods in Chapter 11. With every-visit counting both estimators are biased, and both remain consistent.Doina Precup, Richard S. Sutton, and Sanjoy Dasgupta. Off-Policy Temporal-Difference Learning with Function Approximation. In Proceedings of the 18th International Conference on Machine Learning (ICML 2001), pages 417–424. Morgan Kaufmann, 2001
5.5.1In Wolfram Language#
The first check confirms the cancellation in (5.2) for a two-step trajectory, with the probabilities of the two observed transitions and the probabilities of the two observed actions.
The trajectory probability under divided by the one under : the transition factors cancel.const rho2 = await show`With[{num = Subscript[\[Pi], 0]*Subscript[p, 1]*Subscript[\[Pi], 1]*Subscript[p, 2], den = Subscript[b, 0]*Subscript[p, 1]*Subscript[b, 1]*Subscript[p, 2]}, num/den]`Next, the bias of the weighted estimator. Take a single state with two actions ending the episode with rewards , target and behavior , so that . With one episode the weighted estimate is the return, with bias .
Exact bias of : average the weighted estimate over the four equally structured outcomes of two episodes, weighted by their -probabilities, and subtract .const wisBias2 = await show`Module[{pb = {y, 1 - y}, rho = {x/y, (1 - x)/(1 - y)}, g = {Subscript[r, 1], Subscript[r, 2]}}, Factor[Total[Map[Function[ij, Times @@ pb[[ij]]*(rho[[ij]] . g[[ij]])/Total[rho[[ij]]]], Tuples[{1, 2}, 2]]] - (x Subscript[r, 1] + (1 - x) Subscript[r, 2])]]`const oisVar1 = await show`Module[{pb = {y, 1 - y}, rho = {x/y, (1 - x)/(1 - y)}, g = {Subscript[r, 1], Subscript[r, 2]}}, Factor[pb . (rho g)^2 - (pb . (rho g))^2]]`The bias of the weighted estimator shrinks with (it is halved, roughly, between one and two episodes when and are close), while the ordinary estimator’s variance is fixed per episode. Figure 5.1 compares the exact mean squared errors as functions of for a concrete case, computed by summing over the binomial number of times the first action is taken.
5.5.2Infinite Variance#
Example 5.8 (Infinite variance). A single nonterminal state has two actions. Right terminates with reward . Left returns to with probability and reward , and terminates with probability and reward ; . Sutton and Barto take , target , so , and uniform behavior. Ordinary importance sampling with first visits then fails to settle even after millions of episodes, while weighted importance sampling is exactly from the first episode that ends with left, since every return with nonzero weight equals .
The explanation is that has infinite variance. Let us do the computation in general, with and . An episode in which left is taken times without leaving and then once more to terminate has -probability , ratio and return ; episodes ending with right have return . So
(5.4)The first moment: the series sums to , the probability of eventually terminating by left under .const loopMean = await show`Assuming[0 < x < 1 && 0 < y < 1 && 0 < p < 1, FullSimplify[Sum[(y p)^k y (1 - p) (x/y)^(k + 1), {k, 0, Infinity}]]]`const loopConv = await show`SumConvergence[(p x^2/y)^k, k]`const loopConvBook = await show`SumConvergence[(p x^2/y)^k /. {p -> 9/10, x -> 1, y -> 1/2}, k]`So the variance of the ordinary estimator is finite exactly when . The behavior policy must take left more often than , which for means more often than the loop returns. The geometric growth of along a loop is the mechanism, and it is generic: long episodes make products of ratios explode. This curse of horizon motivates everything in Section 5.8 and Section 5.9.
5.6Incremental Implementation#
On-policy and ordinary importance-sampling estimates are sample averages and use the incremental rule of Chapter 2. The weighted average of returns with weights needs a running sum of weights :
(5.5)Indeed is the definition, and dividing by gives (5.5). The step size replaces the of plain averaging.
Fold the update over three returns with symbolic weights, starting from an arbitrary and : the first step overwrites , and the result is the weighted average.const incWis = await show`Together[First[Fold[Function[{vc, wg}, With[{c = vc[[2]] + wg[[1]]}, {vc[[1]] + wg[[1]]/c (wg[[2]] - vc[[1]]), c}]], {Subscript[v, 0], 0}, Table[{Subscript[W, k], Subscript[G, k]}, {k, 3}]]]]`Algorithm 5.9 (Off-policy Monte Carlo prediction (every visit, weighted)). Input: a target policy . Initialize: arbitrary and for all .
Loop for each episode:
- Choose any with coverage of ; generate an episode following .
- , .
- For , while :
- ;
- ;
- ;
- .
The weight is updated after : an action value conditions on , so its ratio is , not . With every weight is and the algorithm is every-visit on-policy evaluation.
5.7Off-Policy Monte Carlo Control#
For control, make the target policy greedy with respect to and let the behavior policy be any soft policy, for instance -greedy with respect to the same . Since is deterministic, is when the behavior action agrees with it and otherwise; in the second case the weight of every earlier step is zero and the episode can be abandoned.
Algorithm 5.10 (Off-policy Monte Carlo control). Initialize: arbitrary, , (ties broken consistently).
Loop for each episode:
- Choose any soft policy ; generate an episode following .
- , .
- For :
- ;
- ;
- ;
- (ties broken consistently);
- if , end the episode’s updates;
- .
The algorithm learns only from the tails of episodes in which all remaining actions are greedy. With an -greedy over actions, the chance that the last actions are all greedy is about , so states early in long episodes are rarely updated, and learning is slow. The cure is to bootstrap, as temporal-difference methods do in Chapter 6, or to exploit the structure of the return, as in the next section.
5.8Using the Structure of the Return#
So far the ratio multiplies the return as a whole. But is a sum of rewards, and a reward that arrives early cannot depend on actions taken after it. Two refinements exploit this.
5.8.1Per-decision Importance Sampling#
Expanding , each term carries factors for actions taken after its reward. They are useless in expectation.
Proposition 5.11 (Per-decision importance sampling). Under coverage, for ,
(5.6)Hence has the same expectation as , namely .
Proof. Let be the history up to . For , is determined by , and . By the tower property, , and peeling off the factors one at a time gives (5.6). (A terminated episode contributes no further factors.) □
The per-decision estimator is unbiased like ordinary importance sampling and often has smaller variance.Doina 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 Its recursive form, with , is the seed of off-policy temporal-difference learning (Chapter 7, Chapter 12). No consistent per-decision version of weighted importance sampling is known.
A two-step check of (5.6): first action with , and reward ; second action in the state reached after with , . The pair is and .const perDecision = await show`Module[{b0 = {y, 1 - y}, p0 = {x, 1 - x}, r = {Subscript[r, 1], Subscript[r, 2]}, b1 = {{Subscript[w, 1], 1 - Subscript[w, 1]}, {Subscript[w, 2], 1 - Subscript[w, 2]}}, p1 = {{Subscript[u, 1], 1 - Subscript[u, 1]}, {Subscript[u, 2], 1 - Subscript[u, 2]}}}, Simplify[{Sum[b0[[a]] b1[[a, c]] (p0[[a]]/b0[[a]]) (p1[[a, c]]/b1[[a, c]]) r[[a]], {a, 2}, {c, 2}], Sum[b0[[a]] b1[[a, c]] (p0[[a]]/b0[[a]]) r[[a]], {a, 2}, {c, 2}]}]]`5.8.2Discounting-aware Importance Sampling#
If and episodes last steps, but the ordinary estimator multiplies it by ratios, of them irrelevant. Read the discount as a probability of termination: the return terminates after one step with degree , after two with degree , and so on. With the undiscounted flat partial returns ,
(5.7)and each needs only the ratio . Replacing by in the ordinary estimator, and normalizing by the analogous sum of truncated ratios in the weighted one, gives the discounting-aware estimators of Sutton, Mahmood, Precup and van Hasselt; for they reduce to the originals.
The identity (5.7) for an episode of four steps: expand the right-hand side, built from flat partial returns, and recover the discounted return.const flatPartial = await show`Module[{rr = Table[Subscript[R, k], {k, 4}], gbar}, gbar = Function[h, Total[Take[rr, h]]]; Expand[(1 - \[Gamma]) Sum[\[Gamma]^(h - 1) gbar[h], {h, 1, 3}] + \[Gamma]^3 gbar[4]]]`5.9Beyond the Book: Off-Policy Evaluation since 2016#
Off-policy evaluation from logged data became a field of its own after 2015, driven by recommendation, healthcare and the rise of offline reinforcement learning. Two ideas dominate, and both answer the variance problem of Section 5.5.2.
5.9.1Doubly Robust Estimators#
Importance sampling is unbiased but noisy; a learned model is low-variance but biased. A doubly robust estimator uses the model as a control variate inside importance sampling.Beyond Sutton and Barto (2018). Dudík, Langford and Li (2011) introduced doubly robust estimation for contextual bandits; Jiang and Li (ICML 2016) extended it to sequential decisions and proved a Cramér–Rao-type lower bound that it attains when ; Thomas and Brunskill (ICML 2016) gave its weighted version (WDR) and the MAGIC estimator, which blends model-based and importance-sampling estimates to minimize an estimate of mean squared error.Miroslav Dudík, John Langford, and Lihong Li. Doubly Robust Policy Evaluation and Learning. In Proceedings of the 28th International Conference on Machine Learning (ICML 2011), pages 1097–1104, 2011; Nan Jiang and Lihong Li. Doubly Robust Off-policy Value Evaluation for Reinforcement Learning. In Proceedings of the 33rd International Conference on Machine Learning, volume 48 of Proceedings of Machine Learning Research, pages 652–661. PMLR, 2016; and Philip S. Thomas and Emma Brunskill. Data-Efficient Off-Policy Policy Evaluation for Reinforcement Learning. In Proceedings of the 33rd International Conference on Machine Learning, volume 48 of Proceedings of Machine Learning Research, pages 2139–2148. PMLR, 2016 Given any estimate of , fitted on separate data, and , define backwards along an episode, with and ,
(5.8)With this is exactly the recursive per-decision estimator of Section 5.8.1. In general, since , the two model terms cancel in conditional expectation, so is unbiased for any , while its variance shrinks as approaches . Jiang and Li show that with the remaining variance is only that of the environment’s own randomness, weighted by , and that no unbiased estimator can do better on tree-structured MDPs.
One step of (5.8) in the two-action bandit, with an arbitrary model : the expectation under is , whatever the model.const drMean = await show`Module[{pb = {y, 1 - y}, rho = {x/y, (1 - x)/(1 - y)}, g = {Subscript[r, 1], Subscript[r, 2]}, qh = {Subscript[OverHat[q], 1], Subscript[OverHat[q], 2]}}, Simplify[pb . ({x, 1 - x} . qh + rho (g - qh))]]`5.9.2Marginalized Importance Sampling#
The variance of grows exponentially with the horizon, and Example 5.8 shows that it can be infinite. Liu, Li, Tang and Zhou named this the curse of horizon and proposed to reweight states rather than trajectories.Beyond Sutton and Barto (2018). Marginalized (stationary) importance sampling: Liu, Li, Tang and Zhou (NeurIPS 2018) for a known behavior policy, then Nachum, Chow, Dai and Li (DualDICE, NeurIPS 2019) for data from unknown and possibly multiple behavior policies; a family of “DICE” estimators followed.Qiang Liu, Lihong Li, Ziyang Tang, and Dengyong Zhou. Breaking the Curse of Horizon: Infinite-Horizon Off-Policy Estimation. In Advances in Neural Information Processing Systems 31 (NeurIPS 2018), pages 5356–5366, 2018; and Ofir Nachum, Yinlam Chow, Bo Dai, and Lihong Li. DualDICE: Behavior-Agnostic Estimation of Discounted Stationary Distribution Corrections. In Advances in Neural Information Processing Systems 32 (NeurIPS 2019), pages 2318–2328, 2019 Let be the normalized discounted (or, for , stationary) visitation distribution of and that of the data. Then the normalized value is
where the importance weight involves one action ratio and a state ratio whose size does not grow with the horizon. The difficulty moves to estimating . Liu et al. characterize it by a balance condition: in the average-reward case, is the ratio (up to a constant) if and only if for all , under transitions drawn from the data, a “backward” flow-conservation equation that is solved as a minimax problem. DualDICE avoids the action ratios altogether: minimizing
over functions of state–action pairs gives an optimum whose zero-reward Bellman residual is exactly the correction, . The proof is a one-line change of variables: the minimizer of is , and substituting telescopes into an expectation over initial states. These methods trade the exponential variance of trajectory ratios for the bias of a learned function, the same trade that temporal-difference learning makes in the next chapter.
5.10Exercises#
Exercise 5.12. (Sutton and Barto, Exercise 5.5.) A single nonterminal state has a single action that returns to it with probability and terminates otherwise; every reward is and . One observed episode lasts steps. What are the first-visit and every-visit estimates of the state’s value? Relate your answer to Proposition 5.2.
Solution
The state is visited at with returns . First visit uses only . Every visit averages all ten returns, with . Since , the every-visit estimate from one episode has expectation , the biased value found in Section 5.1.1. For long episodes () it is about half the true value, because most visits occur late in the episode, when little return remains; averaging over many episodes the ratio nevertheless converges to .
Exercise 5.13. In Example 5.8 keep but let . For which is the variance of the one-episode ordinary importance-sampling estimate finite, what is it, and which minimizes it?
Solution
By (5.4) with , , the second moment is , finite if and only if ; then the variance is the second moment minus .
The variance of for and .const exVarBeta = await show`Assuming[0 < p < \[Beta] < 1, FullSimplify[(1 - p)/\[Beta] Sum[(p/\[Beta])^k, {k, 0, Infinity}] - 1]]`The variance decreases in , blows up as , and vanishes at , the on-policy case. For even gives variance per episode, and the uniform of the book is far inside the divergent region.
Exercise 5.14. (Sutton and Barto, Exercise 5.8.) In Example 5.8 with the book’s numbers, suppose every-visit ordinary importance sampling is used instead. Is the variance of the estimate from one episode still infinite?
Solution
Yes. An episode with returns to followed by termination via left has probability under . It visits at times , each with return and ratio , so the every-visit estimate is ; episodes ending with right contribute . The terms of grow like .
The series of squared every-visit estimates, weighted by their -probabilities, fails the convergence test.const exEvery = await show`SumConvergence[(1/20) (45/100)^k ((2^(k + 2) - 2)/(k + 1))^2, k]`Dividing by the number of visits tames the growth only polynomially, while the ratios grow geometrically, so the second moment, and with it the variance, is still infinite.
Exercise 5.15. (Sutton and Barto, Exercises 5.7 and 5.11.) (a) In Algorithm 5.10 the weight is updated by rather than by the ratio . Why is this correct? (b) In learning curves for weighted importance sampling the error sometimes first increases and then decreases. Why?
Solution
(a) The target policy is greedy and deterministic, so . The weight is multiplied only after the test has passed, where and the ratio equals ; when the test fails the ratio would be , every earlier pair of the episode would receive weight , and the loop exits instead.
(b) In Sutton and Barto’s blackjack experiment the estimates start at , close to the true value , so the initial squared error is only about . After the first episode with nonzero weight the weighted estimate is that episode’s return, , or (as in Section 5.5.1), whose squared distance from is on average much larger. Episodes whose actions are inconsistent with the target policy have weight zero and change nothing, so across the runs this replacement happens at different times, and the averaged error rises over the first episodes as more runs trade the lucky initial value for a raw return. Only then does it decay, as the bias (of order ) and the variance of the weighted average shrink.