Monte Carlo Methods: Off-Policy Learning
On-policy Monte Carlo can only reach the best exploring policy, not the true optimum. Off-policy methods remove that ceiling by learning about a greedy target policy from data generated by a soft behavior policy, corrected with importance sampling.
╌╌╌╌
This builds on Monte Carlo Methods, which developed prediction by averaging returns and on-policy control with -soft policies. That on-policy approach pays a permanent price: it can only find the best policy among the exploring ones, never the unconstrained optimum. Off-policy learning removes that ceiling, and this lesson builds the machinery.
Off-policy prediction and importance sampling
Every learning-control method faces one dilemma: it wants the value of optimal behavior, but it must behave non-optimally to keep exploring. On-policy methods compromise — they learn a near-optimal policy that still explores. Off-policy methods split the difference into two policies outright.1
Off-policy methods are more general (on-policy is the special case ) and
more powerful — they can learn from a human demonstrator or an old controller's
logs — but they carry more variance and converge more slowly, since the data comes
from the wrong
distribution. For that machinery to work at all we need
coverage: every action might take must also be taken, at least
occasionally, by . Formally implies . Where
is deterministic, must be stochastic in exactly those states.
The importance-sampling ratio
The intuition first. We watched the agent behave under , but we want the value under . Some of the trajectories we saw are ones would have produced often; others are ones would rarely or never produce. So we weight each observed return by how much more (or less) likely its trajectory was under than under . Trajectories favors count for more; trajectories would never take count for nothing.
The returns we collect come from , so they have the wrong expectation: , not . Importance sampling is the general fix for estimating an expectation under one distribution from samples of another: reweight each sample by how much more likely it was under the target than under the behavior. For a whole trajectory the reweighting is the importance-sampling ratio. Given a start at , the probability of the subsequent action–state sequence under a policy is , so the ratio of that probability under to under is
The transition probabilities — the unknown part of the world — appear identically in numerator and denominator and cancel. The ratio depends only on the two policies and the action sequence, not on the MDP's dynamics. That cancellation is what makes off-policy Monte Carlo model-free. Multiplying a behavior-policy return by this ratio corrects its expectation:
Ordinary versus weighted importance sampling
To estimate we now scale the returns and average. Number time steps so they increase across episode boundaries; let be the set of steps at which is visited (first visits only, for a first-visit method), and let be the first termination after . Two averages are possible.1Ordinary importance sampling divides by the count:
Weighted importance sampling divides by the sum of the weights (or is zero if that sum is zero):
The two differ in bias and variance, and the difference is stark. Consider observing a single return from . In the weighted estimate the lone ratio cancels top and bottom, leaving exactly the observed return — expectation , so it is biased. The ordinary estimate for that single return is ; if the ratio is, say, ten, the estimate is ten times the observed return — unbiased in expectation but wildly off from one sample.1
That variance gap decides practice. Ordinary importance sampling can have infinite variance whenever the scaled returns do — easy to trigger when trajectories contain loops — so its estimates may fail to converge in any usable number of episodes even though they are unbiased. Weighted importance sampling has dramatically lower variance and is strongly preferred; on the off-policy blackjack estimation it reaches low error after roughly a thousand episodes where ordinary importance sampling is still far off.1
The two estimators on real numbers
Put numbers to the difference. Suppose the target is deterministic (it always takes the action it prefers) and the behavior is -greedy with over two actions, so takes 's action with probability and the other with probability . A three-step trajectory in which the behavior happened to follow at every step earns the ratio
because each on-target step was slightly more likely under (probability ) than under (probability ). Say this trajectory returned . If instead even one step had taken 's non-preferred action — an action gives probability — the ratio would be exactly : that trajectory is not something could have produced, so it is discarded.
Now collect three trajectories from with weights and returns , , and . Ordinary importance sampling divides the weighted sum by the count:
Weighted importance sampling divides by the sum of the weights:
The weighted estimate is the plain average of the two surviving returns, , unaffected by the magnitude of the ratio — the cancels top and bottom. The ordinary estimate, , is dragged down by dividing by even though the discarded trajectory contributed nothing to the numerator; had a rare trajectory carried a ratio of instead of , the ordinary estimate would have leapt while the weighted one stayed bounded. This is the variance gap in miniature: the weighted estimator caps any single return's influence at , the ordinary one does not.
Incremental implementation
Monte Carlo need not store every return. Just as bandit value estimates were kept as a running mean, MC estimates update episode-by-episode. For ordinary importance sampling (and for on-policy averaging) the update is the familiar sample-mean recursion applied to the scaled returns. Weighted importance sampling needs a slightly different rule, because it is a weighted average.2
Suppose returns all start in the same state, each with a weight (here ). The weighted average of the first is
Maintaining a running cumulative weight , a new return updates the estimate in constant time and memory:
with . This is the same error-correction shape as every other incremental update in the course — old estimate plus a step-size times a (return minus estimate) error — here with step size . The off-policy prediction algorithm walks each episode backward, accumulating , the cumulative weight , and the running product together.
- 1input: a target policy
- 2arbitrarily, , for all
- 3for each episode do
- 4any policy with coverage of
- 5generate an episode following :
- 6
- 7
- 8for do
- 9
- 10
- 11
- 12
- 13if then
- 14breakexit to next episode
Choosing makes and collapses this to on-policy evaluation, so one routine covers both cases. Swap the fixed target for the greedy policy in and add a policy-improvement step and this becomes off-policy MC control: it learns the deterministic optimal target while a soft behavior policy keeps exploring. Its known weakness is that it learns only from the tail of each episode — from the last point where the behavior policy happened to agree with greedy onward — so learning can be slow when nongreedy actions are common.1
Discounting-aware importance sampling
Every off-policy estimator so far has treated a return as an indivisible whole: form one ratio for the entire trajectory and scale the entire return by it. That ignores the return's internal structure as a sum of discounted rewards, and the oversight can inflate the variance enormously.3
For example, suppose episodes last steps and the discount is . Then the return from time is just the first reward, , because every later reward is multiplied by a power of zero. Its importance-sampling ratio, though, is the full product of per-step factors,
Ordinary importance sampling scales by that whole product. But only the first factor is relevant: after the first reward the return is already fully determined. The other factors are independent of the return, each has expected value , and so they leave the expected update unchanged — while contributing wildly to its variance. In some cases they can make the variance infinite. The remedy is to reweight only the part of the trajectory that actually influenced each piece of the return.
Discounting as partial termination
The clean way to isolate the relevant ratios is to reinterpret discounting.
Instead of viewing as a per-step attenuation of reward, view it as a
probability of continuing — equivalently, as a degree of
termination at each step. Under that reading the return is a mixture of
truncated returns. With degree the episode partly terminates
after
one step, yielding just ; with degree it partly
terminates after two steps, yielding ; and so on, the factor
in front of the -step piece recording that termination did
not occur on any of the first steps. The truncated pieces are the flat
partial returns.
Intuitively, the discount acts as a coin flipped each step that decides whether the episode keeps going. Then the true return is an average over all the places the episode might have stopped — stop after one reward, after two, after three, and so on — each weighted by the chance of stopping exactly there. Writing the decomposition out, the ordinary discounted return is exactly a weighted sum of flat partial returns:
The last term collects the probability mass that survives all the way to termination — the trajectory never terminated early, an event of degree — so it carries the full undiscounted tail with no factor. A quick check: at every mixture weight vanishes and only survives, recovering the undiscounted return.
The discounting-aware estimators
The payoff of the decomposition is that a flat partial return only involves rewards up through horizon , so correcting it requires only the truncated ratio — the product of policy ratios up to , and no further. Applying an appropriately truncated ratio to each piece and re-summing gives the ordinary discounting-aware importance-sampling estimator, the horizon-aware analogue of the ordinary estimator from earlier:
and the corresponding weighted estimator normalizes by the truncated ratios themselves in place of the count:
Each flat partial return is now multiplied only by the ratio of the segment that produced it, so the mean-1 tail factors that plagued the whole-return estimators never enter. In the example the first piece is scaled by the single factor and nothing else — exactly what the earlier argument said we should want — instead of by the full length- product.
The gain is real only when : the smaller the discount, the more the return is dominated by its early rewards, the more late ratios there are to discard, and the larger the variance reduction. At the mixture collapses onto the single full-tail term and the discounting-aware estimators are the ordinary and weighted estimators from off-policy prediction. A separate idea, per-decision importance sampling, removes still more variance by reweighting each reward by only , and works even at ; the two ideas are complementary, both mining the return's additive structure for ratios that are safe to drop.
Monte Carlo in modern reinforcement learning
The two ideas at the core of this lesson — average full sampled returns, and correct for the wrong distribution with importance sampling — both grew into machinery that carries much of modern reinforcement learning. Following each forward shows how little the underlying logic changed.
Monte Carlo tree search. The clean idea of estimating a value by averaging sampled returns becomes a decision-time planner when the samples are drawn from a learned or simulated model and used to build a search tree. Monte Carlo tree search (MCTS), introduced by Coulom (2006) and given its exploration rule by Kocsis and Szepesvári (2006, the UCT algorithm), runs many simulated games from the current state, averages their returns exactly as first-visit MC does, and grows the tree toward the branches those averages rate highly. Sutton and Barto treat it in §8.11 as a rollout method built on Monte Carlo control. Its consequences run past that treatment: AlphaGo (Silver et al., 2016, Nature) combined MCTS with deep value and policy networks to beat a professional Go player; AlphaZero (Silver et al., 2018, Science) learned Go, chess, and shogi from self-play with the same search; and MuZero (Schrittwieser et al., 2020, Nature) ran MCTS inside a learned model of the environment, so it needed no rules at all. Each is the Monte Carlo average of returns, wrapped in a search and scaled by a neural network.
Off-policy corrections in deep RL. Every deep reinforcement learner that reuses
stored experience is doing off-policy learning: the data in a replay buffer was
generated by an older version of the policy than the one being trained, so the
behavior and target policies differ, and the importance-sampling ratios of this
lesson reappear. Two problems the tabular case previewed became central. First, the
unbounded variance of ordinary importance sampling forces distributed learners to
clip or truncate the ratios: Retrace() (Munos et al., 2016,
NeurIPS) clips per-step ratios at to get a safe, low-variance off-policy return,
and the IMPALA actor-learner architecture (Espeholt et al., 2018, ICML) uses
truncated ratios (V-trace
) to correct for the lag between the actors generating
data and the learner consuming it. Second, whether to bootstrap or use full returns —
the very axis that separates Monte Carlo from temporal-difference learning — reappears
as a tunable parameter: generalized advantage estimation (Schulman et al., 2016, ICLR)
interpolates between a high-variance Monte Carlo return and a low-variance one-step
estimate with a single parameter , and R2D2 (Kapturowski et al., 2019,
ICLR) runs recurrent Q-learning over long stored sequences, managing exactly the
correlation-and-staleness issues that make replay off-policy. The names are new; the
tradeoffs are the ordinary-versus-weighted and Monte-Carlo-versus-bootstrap tensions
of this lesson, at scale.4
Where Monte Carlo sits
Monte Carlo departs from dynamic programming on two independent axes. It operates on sample experience, so it needs no model — a sample simulator suffices, or real interaction. And it does not bootstrap — each estimate rests on a full realized return, never on other states' estimates, which also makes it less sensitive to violations of the Markov property. Those two differences are separable, and separating them opens the next method.5
That empty corner — model-free and bootstrapping — is temporal-difference learning. It keeps Monte Carlo's freedom from a model but, like DP, updates each estimate from the reward on one sampled step plus the current estimate of the next state, rather than waiting for the full return. It need not wait for an episode to end, and it often learns faster. That is the subject of the next lesson.
Footnotes
- Sutton & Barto, §5.5 — Off-policy Prediction via Importance Sampling: target versus behavior policy, the coverage assumption, the importance-sampling ratio (5.3) with dynamics cancelling (5.4), ordinary (5.5) versus weighted (5.6) importance sampling and their bias/variance tradeoff, and (§5.7) off-policy MC control learning from episode tails. ↩ ↩2 ↩3 ↩4 ↩5
- Sutton & Barto, §5.6 — Incremental Implementation: episode-by-episode updates for MC prediction, the weighted-average recursion (5.7)–(5.8) with cumulative weight , and the off-policy MC prediction algorithm (page 110) that collapses to the on-policy case when . ↩
- Sutton & Barto, §5.8 — Discounting-aware Importance Sampling: the observation that whole-return importance sampling ignores the return's structure as a sum of discounted rewards; the , 100-step example where 99 mean-1 ratios only inflate variance; discounting reinterpreted as a probability of termination; the flat partial returns and the decomposition of into a -weighted mixture of them; the ordinary (5.9) and weighted (5.10) discounting-aware estimators with horizon-truncated ratios, reducing to the §5.5 estimators at ; and (§5.9) the complementary per-decision idea that reduces variance even at . ↩
- Modern descendants of Monte Carlo return-averaging and off-policy importance sampling. MCTS: R. Coulom,
Efficient selectivity and backup operators in Monte-Carlo tree search,
Computers and Games (2006); L. Kocsis and C. Szepesvári,Bandit based Monte-Carlo planning
(UCT), ECML (2006). AlphaGo/AlphaZero/MuZero: D. Silver et al., Nature 529 (2016), 484–489; D. Silver et al., Science 362 (2018), 1140–1144; J. Schrittwieser et al., Nature 588 (2020), 604–609. Off-policy corrections: R. Munos, T. Stepleton, A. Harutyunyan, M. Bellemare,Safe and efficient off-policy reinforcement learning
(Retrace), NeurIPS (2016); L. Espeholt et al.,IMPALA: Scalable distributed deep-RL with importance weighted actor-learner architectures
(V-trace), ICML (2018); S. Kapturowski et al.,Recurrent experience replay in distributed reinforcement learning
(R2D2), ICLR (2019). Return interpolation: J. Schulman et al.,High-dimensional continuous control using generalized advantage estimation,
ICLR (2016). Monte Carlo tree search is treated in Sutton & Barto itself, §8.11. ↩ - Sutton & Barto, §5.10 — Summary: the advantages of MC over DP (model-free learning from actual or simulated experience, focus on a subset of states, robustness to non-Markov violations), that MC does not bootstrap, and the preview of temporal-difference methods that learn from experience yet bootstrap. ↩
╌╌ END ╌╌