Chapter 5

Monte Carlo Methods

Dynamic programming needs the full distribution p(s′,r∣s,a)p(s', r \mid s, a); 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 Gt=Rt+1+γRt+2+⋯+γT−t−1RTG_t = R_{t+1} + \gamma R_{t+2} + \dots + \gamma^{T-t-1}R_T 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 π\pi and a state ss. Each occurrence of ss in an episode is a visit; the first occurrence is the first visit. First-visit Monte Carlo estimates vπ(s)v_\pi(s) by averaging the returns that follow first visits to ss; every-visit Monte Carlo averages the returns that follow all visits.

Algorithm 5.1 (First-visit Monte Carlo prediction). Input: a policy π\pi. Initialize: V(s)∈ℝV(s) \in \mathbb{R} arbitrary and N(s)←0N(s) \leftarrow 0 for all s∈𝒮s \in \mathcal{S}.

Loop for each episode:

  1. Generate an episode following π\pi: S0,A0,R1,S1,…,ST−1,AT−1,RTS_0, A_0, R_1, S_1, \dots, S_{T-1}, A_{T-1}, R_T.
  2. G←0G \leftarrow 0.
  3. For t=T−1,T−2,…,0t = T-1, T-2, \dots, 0:
    • G←γG+Rt+1G \leftarrow \gamma G + R_{t+1};
    • if St∉{S0,…,St−1}S_t \notin \{S_0, \dots, S_{t-1}\}: N(St)←N(St)+1N(S_t) \leftarrow N(S_t) + 1 and V(St)←V(St)+1N(St)[G−V(St)]V(S_t) \leftarrow V(S_t) + \frac{1}{N(S_t)}\bigl[G - V(S_t)\bigr].

Every-visit Monte Carlo omits the test in step 3.

The backward loop computes all returns of an episode in one pass using Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}, 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 V(s)V(s) 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 𝒮\mathcal{S}, 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 ss is distributed as an episode started in ss, whatever happened before. This is the Markov property applied at a random time (a stopping time, since whether time tt is the jj-th visit is decided by S0,…,StS_0, \dots, S_t).

Proposition 5.2 (First-visit and every-visit Monte Carlo). Suppose 𝔼π[Gt2∣St=s]<∞\mathbb{E}_\pi[G_t^2 \mid S_t = s] < \infty and that ss is visited in infinitely many of the episodes.

  1. The returns after first visits are independent and identically distributed with mean vπ(s)v_\pi(s). Hence the first-visit estimate after nn first visits is unbiased, has variance σ2/n\sigma^2/n with σ2=Var⁡π[Gt∣St=s]\sigma^2 = \operatorname{Var}_\pi[G_t \mid S_t = s], and converges to vπ(s)v_\pi(s) with probability one.
  2. Let NiN_i be the number of visits to ss in episode ii and Σi\Sigma_i the sum of the returns after them, and suppose 𝔼[Ni]<∞\mathbb{E}[N_i] < \infty. The every-visit estimate ∑i≤nΣi/∑i≤nNi\sum_{i \le n}\Sigma_i / \sum_{i \le n}N_i converges to vπ(s)v_\pi(s) with probability one, but for finite nn 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 GtG_t given St=sS_t = s, so its mean is vπ(s)v_\pi(s). The sample mean of nn such variables has mean vπ(s)v_\pi(s) and variance σ2/n\sigma^2/n, 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 (Σi,Ni)(\Sigma_i, N_i) are, however, independent across episodes, so by the strong law the ratio converges to 𝔼[Σi]/𝔼[Ni]\mathbb{E}[\Sigma_i]/\mathbb{E}[N_i]. The jj-th visit, when it occurs, is again a stopping time, so the return after it has mean vπ(s)v_\pi(s) and 𝔼[Σi]=∑j≥1Pr⁡{Ni≥j} vπ(s)=𝔼[Ni] vπ(s)\mathbb{E}[\Sigma_i] = \sum_{j \ge 1}\Pr\{N_i \ge j\}\,v_\pi(s) = \mathbb{E}[N_i]\,v_\pi(s). The limit is therefore vπ(s)v_\pi(s). A ratio of averages is not the average of ratios, and the example below shows that its expectation differs from vπ(s)v_\pi(s) for n=1n = 1. □

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 1−p1 - p at each step, collecting reward +1+1 on every step, with γ=1\gamma = 1. The return from ss is the episode length LL, a geometric random variable with Pr⁡{L=k}=(1−p)pk−1\Pr\{L = k\} = (1-p)p^{k-1}, so vπ(s)=𝔼[L]v_\pi(s) = \mathbb{E}[L]. In one episode ss is visited LL times, with returns L,L−1,…,1L, L-1, \dots, 1.

The one-episode estimates: first visit gives LL, every visit gives the mean of L,L−1,…,1L, L-1, \dots, 1, that is (L+1)/2(L+1)/2. Their expectations are vπ(s)=1/(1−p)v_\pi(s) = 1/(1-p) 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]]`
(𝔼[first visit], 𝔼[every visit])={11−p,−2+p2(−1+p)} \bigl(\mathbb{E}[\text{first visit}],\ \mathbb{E}[\text{every visit}]\bigr) = \left\{\frac{1}{1-p},\frac{-2+p}{2 (-1+p)}\right\} With many episodes every visit converges to 𝔼[Σ]/𝔼[N]\mathbb{E}[\Sigma]/\mathbb{E}[N], here 𝔼[L(L+1)/2]/𝔼[L]\mathbb{E}[L(L+1)/2]/\mathbb{E}[L]: the bias disappears in the limit, as the proposition says.
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]]`
lim⁡n→∞∑i≤nΣi∑i≤nNi=𝔼[L(L+1)/2]𝔼[L]=11−p \lim_{n \to \infty} \frac{\sum_{i \le n}\Sigma_i}{\sum_{i \le n} N_i} = \frac{\mathbb{E}[L(L+1)/2]}{\mathbb{E}[L]} = \frac{1}{1-p}

5.2Action Values and Exploring Starts

With a model, state values suffice for control: one step of lookahead with pp turns VV into a greedy policy. Without a model, that lookahead is impossible, and the useful object is the action-value function qπ(s,a)q_\pi(s, a), the expected return after taking aa in ss and following π\pi thereafter. Its Monte Carlo estimation is the same as before with pairs (s,a)(s, a) in place of states: a pair is visited when ss occurs and aa is taken there.

The trouble is that a deterministic π\pi 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 (S0,A0)(S_0, A_0) chosen so that every pair has positive probability, after which π\pi 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 qπq_\pi. The improvement step needs no model: given qπkq_{\pi_k}, the greedy policy πk+1(s)≐arg⁡max⁡aqπk(s,a)\pi_{k+1}(s) \doteq \arg\max_a q_{\pi_k}(s, a) satisfies

qπk(s,πk+1(s))=max⁡aqπk(s,a)≥∑aπk(a∣s) qπk(s,a)=vπk(s) q_{\pi_k}\bigl(s, \pi_{k+1}(s)\bigr) = \max_a q_{\pi_k}(s, a) \ge \sum_a \pi_k(a \mid s)\,q_{\pi_k}(s, a) = v_{\pi_k}(s)

for every ss, so the policy improvement theorem (Theorem 4.6) gives vπk+1≥vπkv_{\pi_{k+1}} \ge v_{\pi_k}, 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: π(s)∈𝒜(s)\pi(s) \in \mathcal{A}(s) arbitrary; Q(s,a)∈ℝQ(s, a) \in \mathbb{R} arbitrary and N(s,a)←0N(s, a) \leftarrow 0 for all s,as, a.

Loop for each episode:

  1. Choose S0,A0S_0, A_0 so that every pair has positive probability; generate S0,A0,R1,…,ST−1,AT−1,RTS_0, A_0, R_1, \dots, S_{T-1}, A_{T-1}, R_T following π\pi from S1S_1 on.
  2. G←0G \leftarrow 0. For t=T−1,…,0t = T-1, \dots, 0:
    • G←γG+Rt+1G \leftarrow \gamma G + R_{t+1};
    • if the pair (St,At)(S_t, A_t) does not occur among (S0,A0),…,(St−1,At−1)(S_0, A_0), \dots, (S_{t-1}, A_{t-1}): N(St,At)←N(St,At)+1N(S_t, A_t) \leftarrow N(S_t, A_t) + 1, Q(St,At)←Q(St,At)+1N(St,At)[G−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \frac{1}{N(S_t, A_t)}\bigl[G - Q(S_t, A_t)\bigr], and π(St)←arg⁡max⁡aQ(St,a)\pi(S_t) \leftarrow \arg\max_a Q(S_t, a).

Monte Carlo ES cannot settle on a suboptimal policy: if it did, QQ 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 q∗q_* 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 γ<1\gamma < 1. 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 ε\varepsilon-soft if π(a∣s)≥ε/∣𝒜(s)∣\pi(a \mid s) \ge \varepsilon/|\mathcal{A}(s)| for all ss and aa. The ε\varepsilon-greedy policy with respect to qq gives every action ε/∣𝒜(s)∣\varepsilon/|\mathcal{A}(s)| and the rest, 1−ε1 - \varepsilon, to a greedy action; among ε\varepsilon-soft policies it is the closest to greedy.

Algorithm 5.4 (On-policy first-visit Monte Carlo control). Parameter: ε>0\varepsilon > 0. Initialize: π\pi an arbitrary ε\varepsilon-soft policy; Q(s,a)Q(s, a) arbitrary, N(s,a)←0N(s, a) \leftarrow 0.

Loop for each episode:

  1. Generate an episode following π\pi.
  2. G←0G \leftarrow 0. For t=T−1,…,0t = T-1, \dots, 0: G←γG+Rt+1G \leftarrow \gamma G + R_{t+1}, and if (St,At)(S_t, A_t) is a first visit,
    • update Q(St,At)Q(S_t, A_t) toward GG by the sample average, as in Algorithm 5.3;
    • A∗←arg⁡max⁡aQ(St,a)A^* \leftarrow \arg\max_a Q(S_t, a) (ties broken arbitrarily);
    • for all a∈𝒜(St)a \in \mathcal{A}(S_t): π(a∣St)←1−ε+ε/∣𝒜(St)∣\pi(a \mid S_t) \leftarrow 1 - \varepsilon + \varepsilon/|\mathcal{A}(S_t)| if a=A∗a = A^*, and ε/∣𝒜(St)∣\varepsilon/|\mathcal{A}(S_t)| otherwise.

Generalized policy iteration only requires the policy to move toward the greedy one, and the next theorem says that moving to the ε\varepsilon-greedy policy is an improvement, ending only at the best ε\varepsilon-soft policy.

Theorem 5.5 (Policy improvement within ε-soft policies). Let π\pi be ε\varepsilon-soft and let π′\pi' be ε\varepsilon-greedy with respect to qπq_\pi. Then vπ′(s)≥vπ(s)v_{\pi'}(s) \ge v_\pi(s) for all ss. Equality holds for all ss if and only if π\pi is optimal among the ε\varepsilon-soft policies.

Proof. Write m=∣𝒜(s)∣m = |\mathcal{A}(s)|. Because π\pi is ε\varepsilon-soft, the numbers wa=(π(a∣s)−ε/m)/(1−ε)w_a = \bigl(\pi(a \mid s) - \varepsilon/m\bigr)/(1 - \varepsilon) are nonnegative and sum to one, and a maximum dominates any weighted average:

∑aπ′(a∣s) qπ(s,a)=εm∑aqπ(s,a)+(1−ε)max⁡aqπ(s,a)≥εm∑aqπ(s,a)+(1−ε)∑awa qπ(s,a)=∑aπ(a∣s) qπ(s,a)=vπ(s). \begin{aligned} &\sum_a \pi'(a \mid s)\,q_\pi(s, a) \\ &\quad= \frac{\varepsilon}{m}\sum_a q_\pi(s, a) + (1 - \varepsilon)\max_a q_\pi(s, a) \\ &\quad\ge \frac{\varepsilon}{m}\sum_a q_\pi(s, a) + (1 - \varepsilon)\sum_a w_a\,q_\pi(s, a) \\ &\quad= \sum_a \pi(a \mid s)\,q_\pi(s, a) = v_\pi(s). \end{aligned} (5.1)

The policy improvement theorem, which holds for stochastic policies, gives vπ′≥vπv_{\pi'} \ge v_\pi.

For the equality case, move the constraint into the environment. Let ℳ̃\widetilde{\mathcal{M}} behave like the original MDP, except that when action aa is chosen, with probability ε\varepsilon the environment replaces it by an action drawn uniformly from 𝒜(s)\mathcal{A}(s). Choosing aa deterministically in ℳ̃\widetilde{\mathcal{M}} is the same as playing the ε\varepsilon-soft policy with greedy mass on aa in the original MDP, and every ε\varepsilon-soft policy is a mixture of such choices, so the best that can be done in ℳ̃\widetilde{\mathcal{M}} equals the best that can be done with ε\varepsilon-soft policies. The optimal value v~∗\tilde v_* of ℳ̃\widetilde{\mathcal{M}} is the unique solution of

v~∗(s)=(1−ε)max⁡a∑s′,rp(s′,r∣s,a)[r+γv~∗(s′)]+εm∑a∑s′,rp(s′,r∣s,a)[r+γv~∗(s′)]. \begin{aligned} \tilde v_*(s) = {}&(1 - \varepsilon)\max_a \sum_{s', r} p(s', r \mid s, a)\bigl[r + \gamma \tilde v_*(s')\bigr] \\ &+ \frac{\varepsilon}{m}\sum_a \sum_{s', r} p(s', r \mid s, a)\bigl[r + \gamma \tilde v_*(s')\bigr]. \end{aligned}

If vπ′=vπv_{\pi'} = v_\pi, then π′\pi' is also ε\varepsilon-greedy with respect to qπ′=qπq_{\pi'} = q_\pi, and the equality in the first line of (5.1) becomes, after expanding qπq_\pi with the dynamics, the same equation with vπv_\pi in place of v~∗\tilde v_*. By uniqueness vπ=v~∗v_\pi = \tilde v_*. Conversely, if vπ=v~∗v_\pi = \tilde v_* no ε\varepsilon-soft policy is better, so vπ′=vπv_{\pi'} = v_\pi. □

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 π∗\pi_*. Off-policy learning removes that compromise.

5.4.1In Wolfram Language

The improvement inequality is checked on one state with three actions, ordered q1≥q2≥q3q_1 \ge q_2 \ge q_3. Any ε\varepsilon-soft policy has the form π(a)=ε/3+(1−ε)μa\pi(a) = \varepsilon/3 + (1 - \varepsilon)\mu_a for a distribution μ\mu.

The gain of the ε\varepsilon-greedy policy over an arbitrary ε\varepsilon-soft policy, ∑a(π′(a)−π(a)) qa\sum_a (\pi'(a) - \pi(a))\,q_a, divided by 1−ε1 - \varepsilon and written with μ1=1−μ2−μ3\mu_1 = 1 - \mu_2 - \mu_3: 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]]`
∑a(π′(a)−π(a)) qa1−ε=(q1−q2)μ2+(q1−q3)μ3 \frac{\sum_a \bigl(\pi'(a) - \pi(a)\bigr)\,q_a}{1-\varepsilon} = \left(q_1-q_2\right) \mu _2+\left(q_1-q_3\right) \mu _3

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 π\pi is the one being learned about, possibly deterministic and greedy; the behavior policy bb generates the data and keeps exploring. For prediction, both are fixed and we want vπv_\pi from episodes of bb. This is possible only under coverage: π(a∣s)>0\pi(a \mid s) > 0 must imply b(a∣s)>0b(a \mid s) > 0, so that everything π\pi might do is seen sometimes.

Starting from StS_t, the probability under π\pi of the remaining trajectory At,St+1,Rt+1,At+1,…,ST,RTA_t, S_{t+1}, R_{t+1}, A_{t+1}, \dots, S_T, R_T is

∏k=tT−1π(Ak∣Sk) p(Sk+1,Rk+1∣Sk,Ak), \prod_{k=t}^{T-1}\pi(A_k \mid S_k)\,p(S_{k+1}, R_{k+1} \mid S_k, A_k),

and the same with bb in place of π\pi under the behavior policy. Their ratio is the importance-sampling ratio

ρt:T−1≐∏k=tT−1π(Ak∣Sk) p(Sk+1,Rk+1∣Sk,Ak)∏k=tT−1b(Ak∣Sk) p(Sk+1,Rk+1∣Sk,Ak)=∏k=tT−1π(Ak∣Sk)b(Ak∣Sk). \rho_{t:T-1} \doteq \frac{\prod_{k=t}^{T-1}\pi(A_k \mid S_k)\,p(S_{k+1}, R_{k+1} \mid S_k, A_k)}{\prod_{k=t}^{T-1}b(A_k \mid S_k)\,p(S_{k+1}, R_{k+1} \mid S_k, A_k)} = \prod_{k=t}^{T-1}\frac{\pi(A_k \mid S_k)}{b(A_k \mid S_k)}. (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, 𝔼b[ρt:T−1 Gt∣St=s]=vπ(s)\mathbb{E}_b[\rho_{t:T-1}\,G_t \mid S_t = s] = v_\pi(s), and 𝔼b[ρt:T−1∣St=s]=1\mathbb{E}_b[\rho_{t:T-1} \mid S_t = s] = 1.

Proof. Sum over the possible trajectories τ\tau from ss, writing Pr⁡π(τ)\Pr_\pi(\tau) and Pr⁡b(τ)\Pr_b(\tau) for their probabilities and G(τ)G(\tau) for the return. By (5.2), ρ=Pr⁡π(τ)/Pr⁡b(τ)\rho = \Pr_\pi(\tau)/\Pr_b(\tau) whenever Pr⁡b(τ)>0\Pr_b(\tau) > 0, and coverage guarantees that every τ\tau with Pr⁡π(τ)>0\Pr_\pi(\tau) > 0 has Pr⁡b(τ)>0\Pr_b(\tau) > 0. Hence

𝔼b[ρ G]=∑τ: Pr⁡b(τ)>0Pr⁡b(τ) Pr⁡π(τ)Pr⁡b(τ) G(τ)=∑τPr⁡π(τ) G(τ)=𝔼π[Gt∣St=s]=vπ(s), \begin{aligned} \mathbb{E}_b[\rho\,G] &= \sum_{\tau:\,\Pr_b(\tau) > 0} \Pr_b(\tau)\,\frac{\Pr_\pi(\tau)}{\Pr_b(\tau)}\,G(\tau) \\ &= \sum_{\tau} \Pr_\pi(\tau)\,G(\tau) = \mathbb{E}_\pi[G_t \mid S_t = s] = v_\pi(s), \end{aligned}

and the same computation with G≡1G \equiv 1 gives 𝔼b[ρ]=1\mathbb{E}_b[\rho] = 1. □

Number time steps consecutively across episodes, let 𝒯(s)\mathcal{T}(s) be the set of times at which ss is visited (first visits only, for a first-visit method), and let T(t)T(t) be the end of the episode containing tt. Two estimators follow:

VO(s)≐∑t∈𝒯(s)ρt:T(t)−1 Gt∣𝒯(s)∣,VW(s)≐∑t∈𝒯(s)ρt:T(t)−1 Gt∑t∈𝒯(s)ρt:T(t)−1, V^{\mathrm{O}}(s) \doteq \frac{\sum_{t \in \mathcal{T}(s)}\rho_{t:T(t)-1}\,G_t}{|\mathcal{T}(s)|}, \qquad V^{\mathrm{W}}(s) \doteq \frac{\sum_{t \in \mathcal{T}(s)}\rho_{t:T(t)-1}\,G_t}{\sum_{t \in \mathcal{T}(s)}\rho_{t:T(t)-1}}, (5.3)

ordinary importance sampling and weighted importance sampling (with VW=0V^{\mathrm{W}} = 0 when the denominator vanishes). After a single first visit with ratio ρ>0\rho > 0, the weighted estimate is the observed return itself, whose expectation is a behavior-policy quantity, not vπ(s)v_\pi(s); the ordinary estimate is ρG\rho G, unbiased but possibly ten times the observed return when ρ=10\rho = 10.

Proposition 5.7 (Ordinary versus weighted importance sampling). Consider first-visit estimates from nn independent episodes, with ρi\rho_i and GiG_i the ratio and return after the first visit to ss in episode ii.

  1. VnOV^{\mathrm{O}}_n is unbiased, with variance Var⁡b(ρG)/n\operatorname{Var}_b(\rho G)/n, which is infinite whenever 𝔼b[ρ2G2]=∞\mathbb{E}_b[\rho^2 G^2] = \infty.
  2. VnWV^{\mathrm{W}}_n is biased for finite nn but consistent: VnW→vπ(s)V^{\mathrm{W}}_n \to v_\pi(s) with probability one. If ∣G∣≤gmax⁡|G| \le g_{\max}, then ∣VnW∣≤gmax⁡|V^{\mathrm{W}}_n| \le g_{\max} and its mean squared error tends to zero, even when Var⁡b(ρ)=∞\operatorname{Var}_b(\rho) = \infty.
  3. If 𝔼b[ρ2(1+G2)]<∞\mathbb{E}_b[\rho^2(1 + G^2)] < \infty, then n (VnW−vπ(s))\sqrt{n}\,(V^{\mathrm{W}}_n - v_\pi(s)) is asymptotically normal with variance 𝔼b[ρ2 (G−vπ(s))2]\mathbb{E}_b\bigl[\rho^2\,(G - v_\pi(s))^2\bigr], whereas Var⁡b(ρG)=𝔼b[ρ2G2]−vπ(s)2\operatorname{Var}_b(\rho G) = \mathbb{E}_b[\rho^2 G^2] - v_\pi(s)^2.

Proof. (1) follows from Proposition 5.6 and independence. (2) Divide numerator and denominator by nn; by the strong law they converge to 𝔼b[ρG]=vπ(s)\mathbb{E}_b[\rho G] = v_\pi(s) and 𝔼b[ρ]=1\mathbb{E}_b[\rho] = 1, and the ratio converges to vπ(s)v_\pi(s). A weighted average with nonnegative weights lies between the smallest and the largest GiG_i, which gives the bound, and bounded convergence turns almost sure convergence into convergence of the mean squared error. (3) Write VnW−vπ=1n∑iρi(Gi−vπ)/1n∑iρiV^{\mathrm{W}}_n - v_\pi = \frac{1}{n}\sum_i \rho_i(G_i - v_\pi) \big/ \frac{1}{n}\sum_i \rho_i. The numerator is an average of independent terms with mean zero and variance 𝔼b[ρ2(G−vπ)2]\mathbb{E}_b[\rho^2(G - v_\pi)^2], and the denominator tends to 11; 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 ρ2\rho^2, but the weighted one pays it on the centered return G−vπG - v_\pi, 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 p1,p2p_1, p_2 the probabilities of the two observed transitions and πk,bk\pi_k, b_k the probabilities of the two observed actions.

The trajectory probability under π\pi divided by the one under bb: the transition factors p1,p2p_1, p_2 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]`
ρ0:1=π0p1π1p2b0p1b1p2=π0π1b0b1 \rho_{0:1} = \frac{\pi_0 p_1 \pi_1 p_2}{b_0 p_1 b_1 p_2} = \frac{\pi _0 \pi _1}{b_0 b_1}

Next, the bias of the weighted estimator. Take a single state with two actions ending the episode with rewards r1,r2r_1, r_2, target π=(x,1−x)\pi = (x, 1-x) and behavior b=(y,1−y)b = (y, 1-y), so that vπ=xr1+(1−x)r2v_\pi = x r_1 + (1-x) r_2. With one episode the weighted estimate is the return, with bias (y−x)(r1−r2)(y - x)(r_1 - r_2).

Exact bias of V2WV^{\mathrm{W}}_2: average the weighted estimate over the four equally structured outcomes of two episodes, weighted by their bb-probabilities, and subtract vπv_\pi.
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])]]`
𝔼b[V2W]−vπ=−(x−y)(−x+2xy−y2)(r1−r2)−x−y+2xy \mathbb{E}_b\bigl[V^{\mathrm{W}}_2\bigr] - v_\pi = -\frac{(x-y) \left(-x+2 x y-y^2\right) \left(r_1-r_2\right)}{-x-y+2 x y} The variance of a single ordinary importance-sampling term ρG\rho G in the same bandit. It vanishes only when x=yx = y or when the scaled returns xr1/yx r_1/y and (1−x)r2/(1−y)(1-x) r_2/(1-y) coincide.
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]]`
Var⁡b(ρG)=−(−xr1+xyr1+yr2−xyr2)2(−1+y)y \operatorname{Var}_b(\rho G) = -\frac{\left(-x r_1+x y r_1+y r_2-x y r_2\right){}^2}{(-1+y) y}

The bias of the weighted estimator shrinks with nn (it is halved, roughly, between one and two episodes when xx and yy are close), while the ordinary estimator’s variance is fixed per episode. Figure 5.1 compares the exact mean squared errors as functions of nn for a concrete case, computed by summing over the binomial number of times the first action is taken.

Figure 5.1: Exact mean squared error of ordinary (black) and weighted (blue) importance sampling for the two-action bandit with r1=1r_1 = 1, r2=0r_2 = 0, target π=(0.9,0.1)\pi = (0.9, 0.1) and uniform behavior, so vπ=0.9v_\pi = 0.9. The ordinary error is 0.81/n0.81/n. The weighted error starts at 0.410.41 (the estimate is just the return) and approaches the delta-method value 𝔼b[ρ2(G−vπ)2]/n=0.0324/n\mathbb{E}_b[\rho^2(G - v_\pi)^2]/n = 0.0324/n, twenty-five times smaller; the dashed gray curve is its squared bias, which falls faster than the variance and is a small part of the error after a few episodes.Log-log plot of exact mean squared error against number of episodes from 1 to 200: ordinary importance sampling is a straight line 0.81 over n; weighted importance sampling starts at 0.41 and quickly falls below it, approaching 0.0324 over n; the squared bias of the weighted estimator falls much faster

5.5.2Infinite Variance

Example 5.8 (Infinite variance). A single nonterminal state ss has two actions. Right terminates with reward 00. Left returns to ss with probability pp and reward 00, and terminates with probability 1−p1 - p and reward +1+1; γ=1\gamma = 1. Sutton and Barto take p=0.9p = 0.9, target π(left∣s)=1\pi(\text{left} \mid s) = 1, so vπ(s)=1v_\pi(s) = 1, and uniform behavior. Ordinary importance sampling with first visits then fails to settle even after millions of episodes, while weighted importance sampling is exactly 11 from the first episode that ends with left, since every return with nonzero weight equals 11.

The explanation is that ρG\rho G has infinite variance. Let us do the computation in general, with π(left)=x\pi(\text{left}) = x and b(left)=yb(\text{left}) = y. An episode in which left is taken kk times without leaving and then once more to terminate has bb-probability (yp)k y(1−p)(yp)^k\,y(1-p), ratio (x/y)k+1(x/y)^{k+1} and return 11; episodes ending with right have return 00. So

𝔼b[ρG]=∑k≥0(yp)k y(1−p)(xy)k+1,𝔼b[ρ2G2]=∑k≥0(yp)k y(1−p)(xy)2k+2=x2(1−p)y∑k≥0(p x2y)k. \begin{aligned} \mathbb{E}_b[\rho G] &= \sum_{k \ge 0} (yp)^k\,y(1-p)\Bigl(\frac{x}{y}\Bigr)^{k+1}, \\ \mathbb{E}_b[\rho^2 G^2] &= \sum_{k \ge 0} (yp)^k\,y(1-p)\Bigl(\frac{x}{y}\Bigr)^{2k+2} \\ &= \frac{x^2(1-p)}{y}\sum_{k \ge 0}\Bigl(\frac{p\,x^2}{y}\Bigr)^k. \end{aligned} (5.4)The first moment: the series sums to vπ(s)=x(1−p)/(1−xp)v_\pi(s) = x(1-p)/(1-xp), the probability of eventually terminating by left under π\pi.
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}]]]`
𝔼b[ρG]=(−1+p)x−1+px \mathbb{E}_b[\rho G] = \frac{(-1+p) x}{-1+p x} The second moment is a geometric series in px2/yp x^2/y; Wolfram’s convergence test returns the exact condition.
const loopConv = await show`SumConvergence[(p x^2/y)^k, k]`
∑k≥0(px2y)k<∞  ⟺  ∣px2y∣<1 \sum_{k \ge 0}\Bigl(\frac{p x^2}{y}\Bigr)^k < \infty \iff \left| \frac{p x^2}{y}\right| <1 For the book’s numbers, p x2/y=0.9/0.5=1.8p\,x^2/y = 0.9/0.5 = 1.8: the series diverges.
const loopConvBook = await show`SumConvergence[(p x^2/y)^k /. {p -> 9/10, x -> 1, y -> 1/2}, k]`
∑k≥01.8k<∞ is False \sum_{k \ge 0} 1.8^k < \infty \text{ is } \text{False}

So the variance of the ordinary estimator is finite exactly when p x2<yp\,x^2 < y. The behavior policy must take left more often than p π(left)2p\,\pi(\text{left})^2, which for π(left)=1\pi(\text{left}) = 1 means more often than the loop returns. The geometric growth of ρ\rho 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 Vn=∑k<nWkGk/∑k<nWkV_n = \sum_{k<n} W_k G_k / \sum_{k<n} W_k of returns GkG_k with weights WkW_k needs a running sum of weights Cn=∑k≤nWkC_n = \sum_{k \le n} W_k:

Vn+1=Vn+WnCn[Gn−Vn],Cn+1=Cn+Wn+1,C0=0. V_{n+1} = V_n + \frac{W_n}{C_n}\bigl[G_n - V_n\bigr], \qquad C_{n+1} = C_n + W_{n+1}, \qquad C_0 = 0. (5.5)

Indeed CnVn+1=Cn−1Vn+WnGnC_n V_{n+1} = C_{n-1}V_n + W_n G_n is the definition, and dividing by Cn=Cn−1+WnC_n = C_{n-1} + W_n gives (5.5). The step size Wn/CnW_n/C_n replaces the 1/n1/n of plain averaging.

Fold the update over three returns with symbolic weights, starting from an arbitrary V1=v0V_1 = v_0 and C0=0C_0 = 0: the first step overwrites v0v_0, 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}]]]]`
V4=G1W1+G2W2+G3W3W1+W2+W3 V_4 = \frac{G_1 W_1+G_2 W_2+G_3 W_3}{W_1+W_2+W_3}

Algorithm 5.9 (Off-policy Monte Carlo prediction (every visit, weighted)). Input: a target policy π\pi. Initialize: Q(s,a)Q(s, a) arbitrary and C(s,a)←0C(s, a) \leftarrow 0 for all s,as, a.

Loop for each episode:

  1. Choose any bb with coverage of π\pi; generate an episode following bb.
  2. G←0G \leftarrow 0, W←1W \leftarrow 1.
  3. For t=T−1,…,0t = T-1, \dots, 0, while W≠0W \ne 0:
    • G←γG+Rt+1G \leftarrow \gamma G + R_{t+1};
    • C(St,At)←C(St,At)+WC(S_t, A_t) \leftarrow C(S_t, A_t) + W;
    • Q(St,At)←Q(St,At)+WC(St,At)[G−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \frac{W}{C(S_t, A_t)}\bigl[G - Q(S_t, A_t)\bigr];
    • W←W π(At∣St)/b(At∣St)W \leftarrow W\,\pi(A_t \mid S_t)/b(A_t \mid S_t).

The weight is updated after Q(St,At)Q(S_t, A_t): an action value conditions on AtA_t, so its ratio is ρt+1:T−1\rho_{t+1:T-1}, not ρt:T−1\rho_{t:T-1}. With π=b\pi = b every weight is 11 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 QQ and let the behavior policy be any soft policy, for instance ε\varepsilon-greedy with respect to the same QQ. Since π\pi is deterministic, π(At∣St)\pi(A_t \mid S_t) is 11 when the behavior action agrees with it and 00 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: Q(s,a)Q(s, a) arbitrary, C(s,a)←0C(s, a) \leftarrow 0, π(s)←arg⁡max⁡aQ(s,a)\pi(s) \leftarrow \arg\max_a Q(s, a) (ties broken consistently).

Loop for each episode:

  1. Choose any soft policy bb; generate an episode following bb.
  2. G←0G \leftarrow 0, W←1W \leftarrow 1.
  3. For t=T−1,…,0t = T-1, \dots, 0:
    • G←γG+Rt+1G \leftarrow \gamma G + R_{t+1};
    • C(St,At)←C(St,At)+WC(S_t, A_t) \leftarrow C(S_t, A_t) + W;
    • Q(St,At)←Q(St,At)+WC(St,At)[G−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \frac{W}{C(S_t, A_t)}\bigl[G - Q(S_t, A_t)\bigr];
    • π(St)←arg⁡max⁡aQ(St,a)\pi(S_t) \leftarrow \arg\max_a Q(S_t, a) (ties broken consistently);
    • if At≠π(St)A_t \ne \pi(S_t), end the episode’s updates;
    • W←W/b(At∣St)W \leftarrow W/b(A_t \mid S_t).

The algorithm learns only from the tails of episodes in which all remaining actions are greedy. With an ε\varepsilon-greedy bb over mm actions, the chance that the last kk actions are all greedy is about (1−ε+ε/m)k(1 - \varepsilon + \varepsilon/m)^k, 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 GtG_t 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 ρt:T−1Gt=∑k=1T−tγk−1ρt:T−1Rt+k\rho_{t:T-1}G_t = \sum_{k=1}^{T-t}\gamma^{k-1}\rho_{t:T-1}R_{t+k}, 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 1≤k≤T−t1 \le k \le T - t,

𝔼b[ρt:T−1Rt+k∣St]=𝔼b[ρt:t+k−1Rt+k∣St]. \mathbb{E}_b[\rho_{t:T-1}R_{t+k} \mid S_t] = \mathbb{E}_b[\rho_{t:t+k-1}R_{t+k} \mid S_t]. (5.6)

Hence G~t≐∑k=1T−tγk−1ρt:t+k−1Rt+k\tilde G_t \doteq \sum_{k=1}^{T-t}\gamma^{k-1}\rho_{t:t+k-1}R_{t+k} has the same expectation as ρt:T−1Gt\rho_{t:T-1}G_t, namely vπ(St)v_\pi(S_t).

Proof. Let ℱj\mathcal{F}_j be the history up to SjS_j. For j≥t+kj \ge t + k, ρt:j−1Rt+k\rho_{t:j-1}R_{t+k} is determined by ℱj\mathcal{F}_j, and 𝔼b[π(Aj∣Sj)/b(Aj∣Sj)∣ℱj]=∑ab(a∣Sj) π(a∣Sj)/b(a∣Sj)=1\mathbb{E}_b[\pi(A_j \mid S_j)/b(A_j \mid S_j) \mid \mathcal{F}_j] = \sum_a b(a \mid S_j)\,\pi(a \mid S_j)/b(a \mid S_j) = 1. By the tower property, 𝔼b[ρt:jRt+k]=𝔼b[ρt:j−1Rt+k]\mathbb{E}_b[\rho_{t:j}R_{t+k}] = \mathbb{E}_b[\rho_{t:j-1}R_{t+k}], and peeling off the factors j=T−1,T−2,…,t+kj = T-1, T-2, \dots, t+k one at a time gives (5.6). (A terminated episode contributes no further factors.) □

The per-decision estimator ∑t∈𝒯(s)G~t/∣𝒯(s)∣\sum_{t \in \mathcal{T}(s)}\tilde G_t/|\mathcal{T}(s)| 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, G~t=ρt(Rt+1+γG~t+1)\tilde G_t = \rho_t(R_{t+1} + \gamma\tilde G_{t+1}) with ρt≐ρt:t\rho_t \doteq \rho_{t:t}, 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 π0=(x,1−x)\pi_0 = (x, 1-x), b0=(y,1−y)b_0 = (y, 1-y) and reward rar_a; second action in the state reached after aa with π1=(ua,1−ua)\pi_1 = (u_a, 1-u_a), b1=(wa,1−wa)b_1 = (w_a, 1-w_a). The pair is 𝔼b[ρ0:1R1]\mathbb{E}_b[\rho_{0:1}R_1] and 𝔼b[ρ0:0R1]\mathbb{E}_b[\rho_{0:0}R_1].
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}]}]]`
(𝔼b[ρ0:1R1], 𝔼b[ρ0:0R1])={xr1−(−1+x)r2,xr1−(−1+x)r2} \bigl(\mathbb{E}_b[\rho_{0:1}R_1],\ \mathbb{E}_b[\rho_{0:0}R_1]\bigr) = \left\{x r_1-(-1+x) r_2,x r_1-(-1+x) r_2\right\}

5.8.2Discounting-aware Importance Sampling

If γ=0\gamma = 0 and episodes last 100100 steps, G0=R1G_0 = R_1 but the ordinary estimator multiplies it by 100100 ratios, 9999 of them irrelevant. Read the discount as a probability of termination: the return terminates after one step with degree 1−γ1 - \gamma, after two with degree (1−γ)γ(1-\gamma)\gamma, and so on. With the undiscounted flat partial returns G¯t:h≐Rt+1+⋯+Rh\bar G_{t:h} \doteq R_{t+1} + \dots + R_h,

Gt=(1−γ)∑h=t+1T−1γh−t−1 G¯t:h+γT−t−1 G¯t:T, G_t = (1 - \gamma)\sum_{h=t+1}^{T-1}\gamma^{h-t-1}\,\bar G_{t:h} + \gamma^{T-t-1}\,\bar G_{t:T}, (5.7)

and each G¯t:h\bar G_{t:h} needs only the ratio ρt:h−1\rho_{t:h-1}. Replacing ρt:T−1Gt\rho_{t:T-1}G_t by (1−γ)∑hγh−t−1ρt:h−1G¯t:h+γT−t−1ρt:T−1G¯t:T(1-\gamma)\sum_h \gamma^{h-t-1}\rho_{t:h-1}\bar G_{t:h} + \gamma^{T-t-1}\rho_{t:T-1}\bar G_{t:T} 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 γ=1\gamma = 1 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]]]`
(1−γ)∑h=13γh−1G¯0:h+γ3G¯0:4=R1+γR2+γ2R3+γ3R4 (1-\gamma)\sum_{h=1}^{3}\gamma^{h-1}\bar G_{0:h} + \gamma^3\bar G_{0:4} = R_1+\gamma R_2+\gamma ^2 R_3+\gamma ^3 R_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 q^=qπ\hat q = q_\pi; 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 q^\hat q of qπq_\pi, fitted on separate data, and v^(s)≐∑aπ(a∣s) q^(s,a)\hat v(s) \doteq \sum_a \pi(a \mid s)\,\hat q(s, a), define backwards along an episode, with ρt≐π(At∣St)/b(At∣St)\rho_t \doteq \pi(A_t \mid S_t)/b(A_t \mid S_t) and VTDR≐0V^{\mathrm{DR}}_T \doteq 0,

VtDR≐v^(St)+ρt(Rt+1+γVt+1DR−q^(St,At)). V^{\mathrm{DR}}_t \doteq \hat v(S_t) + \rho_t\bigl(R_{t+1} + \gamma V^{\mathrm{DR}}_{t+1} - \hat q(S_t, A_t)\bigr). (5.8)

With q^≡0\hat q \equiv 0 this is exactly the recursive per-decision estimator of Section 5.8.1. In general, since 𝔼b[ρt q^(St,At)∣St]=v^(St)\mathbb{E}_b[\rho_t\,\hat q(S_t, A_t) \mid S_t] = \hat v(S_t), the two model terms cancel in conditional expectation, so V0DRV^{\mathrm{DR}}_0 is unbiased for any q^\hat q, while its variance shrinks as q^\hat q approaches qπq_\pi. Jiang and Li show that with q^=qπ\hat q = q_\pi the remaining variance is only that of the environment’s own randomness, weighted by ρ0:t−12\rho_{0:t-1}^2, 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 (q^1,q^2)(\hat q_1, \hat q_2): the expectation under bb is vπv_\pi, 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))]]`
𝔼b[v^+ρ (R−q^(A))]=xr1−(−1+x)r2 \mathbb{E}_b\bigl[\hat v + \rho\,(R - \hat q(A))\bigr] = x r_1-(-1+x) r_2

5.9.2Marginalized Importance Sampling

The variance of ρ0:T−1\rho_{0:T-1} 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 dπ(s)d_\pi(s) be the normalized discounted (or, for γ=1\gamma = 1, stationary) visitation distribution of π\pi and dbd_b that of the data. Then the normalized value is

(1−γ) 𝔼π[∑tγtRt+1]=𝔼s∼db,  a∼b[w(s) π(a∣s)b(a∣s) r(s,a)],w(s)≐dπ(s)db(s), \begin{aligned} (1-\gamma)\,\mathbb{E}_\pi\Bigl[\sum_t \gamma^t R_{t+1}\Bigr] &= \mathbb{E}_{s \sim d_b,\; a \sim b}\Bigl[w(s)\,\frac{\pi(a \mid s)}{b(a \mid s)}\,r(s, a)\Bigr], \\ w(s) &\doteq \frac{d_\pi(s)}{d_b(s)}, \end{aligned}

where the importance weight involves one action ratio and a state ratio ww whose size does not grow with the horizon. The difficulty moves to estimating ww. Liu et al. characterize it by a balance condition: in the average-reward case, ww is the ratio (up to a constant) if and only if 𝔼[w(S) π(A∣S)/b(A∣S)−w(S′)∣S′=s′]=0\mathbb{E}\bigl[w(S)\,\pi(A \mid S)/b(A \mid S) - w(S') \bigm| S' = s'\bigr] = 0 for all s′s', under transitions (S,A,S′)(S, A, S') drawn from the data, a “backward” flow-conservation equation that is solved as a minimax problem. DualDICE avoids the action ratios altogether: minimizing

J(ν)=12 𝔼(s,a)∼d𝒟[(ν−ℬπν)(s,a)2]−(1−γ) 𝔼s0,  a0∼π[ν(s0,a0)],ℬπν(s,a)≐γ 𝔼[ν(S′,A′)∣s,a], \begin{aligned} J(\nu) &= \tfrac{1}{2}\,\mathbb{E}_{(s,a) \sim d_{\mathcal{D}}}\bigl[(\nu - \mathcal{B}^\pi\nu)(s, a)^2\bigr] \\ &\quad - (1-\gamma)\,\mathbb{E}_{s_0,\;a_0 \sim \pi}\bigl[\nu(s_0, a_0)\bigr], \\ \mathcal{B}^\pi\nu(s, a) &\doteq \gamma\,\mathbb{E}\bigl[\nu(S', A') \mid s, a\bigr], \end{aligned}

over functions ν\nu of state–action pairs gives an optimum whose zero-reward Bellman residual is exactly the correction, (ν∗−ℬπν∗)(s,a)=dπ(s,a)/d𝒟(s,a)(\nu^* - \mathcal{B}^\pi\nu^*)(s, a) = d_\pi(s, a)/d_{\mathcal{D}}(s, a). The proof is a one-line change of variables: the minimizer of 12𝔼d𝒟[x2]−𝔼dπ[x]\frac{1}{2}\mathbb{E}_{d_{\mathcal{D}}}[x^2] - \mathbb{E}_{d_\pi}[x] is x=dπ/d𝒟x = d_\pi/d_{\mathcal{D}}, and substituting x=ν−ℬπνx = \nu - \mathcal{B}^\pi\nu telescopes 𝔼dπ[x]\mathbb{E}_{d_\pi}[x] 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 pp and terminates otherwise; every reward is +1+1 and γ=1\gamma = 1. One observed episode lasts 1010 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 t=0,1,…,9t = 0, 1, \dots, 9 with returns 10,9,…,110, 9, \dots, 1. First visit uses only G0=10G_0 = 10. Every visit averages all ten returns, (10+9+⋯+1)/10=5.5=(L+1)/2(10 + 9 + \dots + 1)/10 = 5.5 = (L+1)/2 with L=10L = 10. Since vπ=1/(1−p)v_\pi = 1/(1-p), the every-visit estimate from one episode has expectation 2−p2(1−p)\frac{2-p}{2(1-p)}, the biased value found in Section 5.1.1. For long episodes (p→1p \to 1) 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 ∑Σi/∑Ni\sum\Sigma_i/\sum N_i nevertheless converges to 1/(1−p)1/(1-p).

Exercise 5.13. In Example 5.8 keep π(left)=1\pi(\text{left}) = 1 but let b(left)=βb(\text{left}) = \beta. For which β\beta is the variance of the one-episode ordinary importance-sampling estimate finite, what is it, and which β\beta minimizes it?

Solution

By (5.4) with x=1x = 1, y=βy = \beta, the second moment is 1−pβ∑k(p/β)k\frac{1-p}{\beta}\sum_k (p/\beta)^k, finite if and only if β>p\beta > p; then the variance is the second moment minus vπ2=1v_\pi^2 = 1.

The variance of ρG\rho G for π(left)=1\pi(\text{left}) = 1 and b(left)=β>pb(\text{left}) = \beta > p.
const exVarBeta = await show`Assuming[0 < p < \[Beta] < 1, FullSimplify[(1 - p)/\[Beta] Sum[(p/\[Beta])^k, {k, 0, Infinity}] - 1]]`
Var⁡b(ρG)=−1+βp−β \operatorname{Var}_b(\rho G) = \frac{-1+\beta }{p-\beta }

The variance (1−β)/(β−p)(1-\beta)/(\beta - p) decreases in β\beta, blows up as β↓p\beta \downarrow p, and vanishes at β=1\beta = 1, the on-policy case. For p=0.9p = 0.9 even β=0.95\beta = 0.95 gives variance 11 per episode, and the uniform β=0.5\beta = 0.5 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 kk returns to ss followed by termination via left has probability 120(0.45)k\frac{1}{20}(0.45)^k under bb. It visits ss at times j=0,…,kj = 0, \dots, k, each with return 11 and ratio ρj:k=2k+1−j\rho_{j:k} = 2^{k+1-j}, so the every-visit estimate is (∑m=1k+12m)/(k+1)=(2k+2−2)/(k+1)\bigl(\sum_{m=1}^{k+1}2^m\bigr)/(k+1) = (2^{k+2} - 2)/(k+1); episodes ending with right contribute 00. The terms of 𝔼b[V2]\mathbb{E}_b[V^2] grow like 1.8k/(k+1)21.8^k/(k+1)^2.

The series of squared every-visit estimates, weighted by their bb-probabilities, fails the convergence test.
const exEvery = await show`SumConvergence[(1/20) (45/100)^k ((2^(k + 2) - 2)/(k + 1))^2, k]`
𝔼b[(Vevery)2]<∞ is False \mathbb{E}_b\bigl[(V^{\text{every}})^2\bigr] < \infty \text{ is } \text{False}

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 W←W/b(At∣St)W \leftarrow W/b(A_t \mid S_t) rather than by the ratio π(At∣St)/b(At∣St)\pi(A_t \mid S_t)/b(A_t \mid S_t). 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 π(At∣St)∈{0,1}\pi(A_t \mid S_t) \in \{0, 1\}. The weight is multiplied only after the test At=π(St)A_t = \pi(S_t) has passed, where π(At∣St)=1\pi(A_t \mid S_t) = 1 and the ratio equals 1/b(At∣St)1/b(A_t \mid S_t); when the test fails the ratio would be 00, every earlier pair of the episode would receive weight 00, and the loop exits instead.

(b) In Sutton and Barto’s blackjack experiment the estimates start at V=0V = 0, close to the true value −0.277-0.277, so the initial squared error is only about 0.080.08. After the first episode with nonzero weight the weighted estimate is that episode’s return, −1-1, 00 or +1+1 (as in Section 5.5.1), whose squared distance from −0.277-0.277 is on average much larger. Episodes whose actions are inconsistent with the target policy have weight zero and change nothing, so across the 100100 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 1/n1/n) and the variance of the weighted average shrink.