Importance Sampling for Off-Policy Methods
Imagine a self-driving car company that has logged millions of miles under an old, conservative policy. They want to know how a new, more aggressive policy would perform. They don't want to deploy it and risk crashes. This is the central problem off-policy evaluation solves: estimating the value of one policy using data generated by another. The tool that makes this mathematically honest, rather than just a hopeful approximation, is importance sampling. Off-policy learning matters because collecting fresh on-policy data is often expensive, slow, or dangerous. Recommendation engines, robotics, healthcare treatment policies, and dialogue systems all accumulate massive logs of interactions. These logs form under some existing behavior policy. Reusing that data to evaluate or improve alternative policies is enormously valuable. But naively averaging returns from behavior-policy trajectories gives a biased estimate of the target policy's value. Importance sampling corrects this bias by reweighting each observed return. The reweighting reflects how much more (or less) likely the target policy is to have produced that trajectory, compared to the behavior policy. This article builds importance sampling for off-policy Monte Carlo prediction from first principles. We derive the reweighting formula from the definitions of expected return. We distinguish ordinary from weighted importance sampling. We show how both connect to incremental, computationally efficient update rules suitable for streaming data. We also confront the central tension in this area: unbiasedness versus variance, and exact versus practical estimators. By the end, you will be able to write the importance-sampling ratio for any pair of policies. You will be able to implement incremental off-policy Monte Carlo prediction. You will be able to reason about when importance sampling estimators are trustworthy. You will also see how the same reweighting machinery generalizes to off-policy temporal-difference methods. This lays groundwork for understanding instability issues that appear once function approximation enters the picture.
- Off-policy prediction estimates the value of a target policy π using episodes generated by a different behavior policy b.
- The importance-sampling ratio ρ reweights each trajectory's return so its expectation matches Eπ[G] rather than Eb[G].
- Ordinary importance sampling (OIS) is unbiased but can have unbounded variance; weighted importance sampling (WIS) trades a vanishing bias for much lower variance.
- Both estimators admit incremental, O(1)-per-step update rules, making them practical for streaming Monte Carlo control.
- Coverage (b(a|s) > 0 whenever π(a|s) > 0) is required; without it some target-policy behavior is simply never observed.
- Importance sampling is the conceptual seed for off-policy TD methods, and its variance problems foreshadow instability issues in The Deadly Triad.
To evaluate a target policy from behavior-policy data, reweight each return by the ratio of the probabilities the two policies assign to the observed action sequence.
The idea
In Monte Carlo Prediction, we estimate by averaging observed returns from episodes generated by following itself. In the off-policy setting, episodes are instead generated by a behavior policy , and we want to estimate or , the value functions of a different target policy . This is exactly the scenario in On-Policy vs Off-Policy Learning: the policy generating data differs from the policy being evaluated or improved. The key mathematical fact is that returns generated under are samples from the wrong distribution. If we simply averaged them, we would be estimating , not . Importance sampling is the general statistical technique for correcting exactly this kind of distribution mismatch: given samples from distribution , reweight them to estimate an expectation under distribution . Concretely, consider a trajectory starting at state and following the policy for steps until termination:
The probability of this trajectory under a policy (either or ), given the shared environment dynamics , is
The environment transition probabilities are identical for both policies, since the environment does not change — only the policy does. This is crucial: it means the ratio of trajectory probabilities under versus depends only on the policies, not on unknown environment dynamics:
This quantity is the importance-sampling ratio. It is computable purely from the two policies' action probabilities along the observed trajectory, which is exactly the information available to the learner. The reweighting identity then follows directly from the change-of-measure formula for expectations:
So if we take episodes generated under , multiply each return by its corresponding ratio , and average, the result is an unbiased estimator of . A necessary condition underlies all of this: coverage. We require whenever . If ever assigns positive probability to an action that never takes in some state, that portion of 's behavior is simply never observed in the data, and no reweighting scheme can recover it — the ratio would involve a division by zero.
How it works
There are two standard estimators built on the ratio , applied to episodes collected from . Suppose we have collected several episodes and, for a given state , we let be the set of all time steps at which was visited (using every-visit MC for simplicity), with corresponding returns and ratios , where is the termination time of that episode.
Ordinary importance sampling (OIS) simply averages the reweighted returns:
This is an unbiased estimate of by the identity above, but its variance can be extremely large or even unbounded, since is a product of ratios that can blow up.
Weighted importance sampling (WIS) instead normalizes by the sum of ratios rather than the count:
WIS is biased for finite samples (the bias vanishes asymptotically as more data arrives) but has dramatically lower variance in practice, because the denominator adapts to how much "evidence weight" the sample carries. If a trajectory has ratio 0, it is naturally down-weighted rather than allowed to contribute an unbounded value divided by a fixed count. Both estimators can be computed incrementally, one episode at a time, without storing all past returns — critical for streaming and control settings. For WIS applied to action values, the classic incremental update (used in Sutton & Barto-style off-policy MC control) processes an episode backward from termination, since ratios and returns naturally compose backward in time. ```pseudocode
# Off-policy every-visit Monte Carlo prediction with Weighted Importance Sampling
# Estimates Q ≈ q_pi using episodes generated by behavior policy b (with coverage of pi) Initialize: Q(s, a) ← arbitrary, for all s, a C(s, a) ← 0 # cumulative sum of importance weights loop forever (for each episode, generated by following b): Generate an episode: S_0, A_0, R_1, S_1, A_1, R_2, ..., S_{T-1}, A_{T-1}, R_T G ← 0 W ← 1 # importance-sampling ratio, accumulated backward for t = T-1, T-2, ..., 0: G ← γ G + R_{t+1} C(S_t, A_t) ← C(S_t, A_t) + W Q(S_t, A_t) ← Q(S_t, A_t) + (W / C(S_t, A_t)) (G - Q(S_t, A_t)) W ← W * ( pi(A_t | S_t) / b(A_t | S_t) ) if W == 0: break # ratio for all earlier steps in this episode is 0 ``` The `break` on `W == 0` is not merely an optimization: once for some visited action, the ratio for every earlier time step in that episode is exactly zero (since is a product including that factor), so there is nothing left to accumulate — this is why the loop can safely stop early. For ordinary importance sampling, the analogous incremental update tracks a plain running count and a running sum, since the estimator normalizes by the number of samples rather than the accumulated weight: ```pseudocode
# Off-policy every-visit Monte Carlo prediction with Ordinary Importance Sampling Initialize: Q(s, a) ← arbitrary N(s, a) ← 0 # visit count SumRG(s, a) ← 0 # running sum of weighted returns loop forever (for each episode, generated by following b): Generate an episode as above G ← 0 W ← 1 for t = T-1, T-2, ..., 0: G ← γ G + R_{t+1} N(S_t, A_t) ← N(S_t, A_t) + 1 SumRG(S_t, A_t) ← SumRG(S_t, A_t) + W G Q(S_t, A_t) ← SumRG(S_t, A_t) / N(S_t, A_t) W ← W * ( pi(A_t | S_t) / b(A_t | S_t) ) if W == 0: break ``` The diagram below traces how a single episode's ratio accumulates backward and feeds the incremental WIS update.
Complexity & correctness
Time complexity. Each episode of length is processed once, backward, in time: every step performs a constant number of arithmetic operations (update , update or , update , update ). Over episodes with average length , total time is , matching ordinary on-policy every-visit Monte Carlo exactly — importance sampling adds no asymptotic overhead, only a constant number of extra multiplications per step.
Space complexity. The algorithm needs space for the tables , and (or , ), independent of the number of episodes processed, because updates are incremental rather than requiring storage of every past return. This is the same space bound as on-policy tabular Monte Carlo.
Correctness of OIS (unbiasedness). The identity
was derived directly from the environment-independent cancellation of transition probabilities in the trajectory-probability ratio. Since each sampled pair is drawn i.i.d. (across independent episodes) from the distribution induced by , the sample average
is an unbiased estimator of this expectation by the law of large numbers / linearity of expectation — this is exactly what makes OIS unbiased for every finite , not just asymptotically.
Why OIS has high (sometimes infinite) variance. The ratio is a product of independent factors . Products of independent random ratios have variance that grows, in the worst case multiplicatively, with the number of factors. A single episode where happened to choose a low-probability-under- but relevant-under- action sequence can produce a ratio orders of magnitude larger than typical, dominating the average. In degenerate cases (e.g., a policy with an action of probability unbounded as ), the variance of can be literally infinite even though its mean is finite — a textbook example of a heavy-tailed estimator.
Correctness of WIS (consistency, with bias). WIS is a ratio estimator:
By the strong law of large numbers, both numerator and denominator (each divided by ) converge almost surely to and respectively (the latter because is itself a likelihood ratio, whose expectation under is always exactly 1). By the continuous mapping theorem, the ratio converges to , so WIS is a consistent estimator: its bias vanishes as , even though for any finite it is generally biased (since in general). In exchange, WIS's variance is bounded even when individual ratios are large, because the same large ratio that inflates the numerator also inflates the denominator, canceling out much of the fluctuation. This bias–variance trade is the central practical reason WIS is preferred in almost all applied off-policy Monte Carlo work.
Coverage as a correctness precondition. The derivation of implicitly assumes for every action actually taken; if in addition for all (coverage), then every trajectory that could generate has nonzero probability under , so no part of is systematically missing from the support of the sampling distribution. Without coverage, importance sampling is not merely noisy — it is definitionally unable to estimate the missing mass.
Worked example
Consider a trivial one-state, two-action bandit-like episode to make the arithmetic fully transparent (state only, then terminate). Let . Behavior policy : . Target policy : . Suppose the reward for taking is always , and for is always . We collect 4 episodes under :
| Episode | Action taken | Reward | ||
|---|---|---|---|---|
| 1 | 2 | 1.25 | ||
| 2 | 2 | 0.625 | 1.25 | |
| 3 | 2 | 0.625 | 1.25 | |
| 4 | 8 | 20.0 |
The true value under is .
OIS estimate:
WIS estimate:
Both are in the right neighborhood of the true value 5.0 with only 4 samples, but notice the sensitivity: episode 4 (the rare action) carries a ratio of 2.5, five times heavier than the episodes' 0.625. If by chance had produced two episodes instead of one (plausible with 20% probability per draw), OIS would jump dramatically because it still divides by a fixed count of episodes, while WIS's denominator also grows, partially absorbing the shock. This is the variance-damping mechanism made concrete: WIS self-normalizes against the very quantity that would otherwise make an unlucky sample dominate. Running the incremental WIS pseudocode step by step for this data (processing episodes 1–4 in order, updating and after each):
| After episode | (cumulative) | (running WIS estimate) | |
|---|---|---|---|
| 1 | 0.625 | 0.625 | |
| 2 | 0.625 | 1.25 | |
| 3 | 0.625 | 1.875 | |
| 4 | 2.5 | 4.375 |
The incremental computation lands exactly on the batch WIS value , confirming the update rule is algebraically equivalent to recomputing the ratio estimator from scratch after each episode — this equivalence is exactly why the incremental form is correct and not just a heuristic shortcut.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Missing coverage check | Forgetting to verify wherever | Division by zero in , or systematic underestimation from unrepresented target-policy behavior |
| Using OIS in high-variance regimes without variance reduction | Treating unbiasedness as sufficient for practical reliability | Wild, unstable estimates; occasional astronomically large sample values |
| Forgetting WIS is biased for small samples | Assuming "consistent" means "unbiased" | Systematic small-sample error, especially with few episodes per state |
| Computing forward instead of backward in incremental code | Forward accumulation does not match the algebra of the incremental update derivation | Off-by-direction bug that silently produces wrong values |
| Not stopping when | Believing every step must be processed | Wasted computation; harmless numerically but a missed efficiency and clarity opportunity |
| Applying per-decision or per-step returns without adjusting the ratio's time range | Confusing (whole-trajectory ratio) with per-step ratios needed for finer-grained methods | Incorrect variance properties, mismatched weighting for TD-style bootstrapped updates |
Pioneers & history
Importance sampling as a general statistical technique predates reinforcement learning by decades, originating in Monte Carlo integration and rare-event simulation, where researchers needed to estimate expectations under distributions that were expensive or impossible to sample directly.
Origins · 1 minHerman Kahn and how this was discovered
Herman Kahn, working at RAND Corporation in the early 1950s alongside the broader Monte Carlo method community that grew out of the Manhattan Project, developed and formalized importance sampling as a variance-reduction technique for simulating rare events, such as neutron transport through shielding, where naive sampling would almost never hit the events of interest. His work established the mathematical foundation — reweighting samples from a convenient distribution to estimate expectations under a target distribution — that off-policy reinforcement learning would later adapt to the sequential decision-making setting.
Where this matters
Off-policy evaluation via importance sampling underlies offline reinforcement learning, where a company must estimate how a candidate policy would perform using only historical logs — critical in recommendation systems, ad placement, and healthcare treatment policy evaluation, where deploying an untested policy directly is costly or unethical. Contextual bandit platforms at large-scale internet companies (search ranking, ad auctions, content recommendation) routinely use importance-weighted estimators to A/B test new ranking policies against logged data before committing to a live rollout. In robotics and autonomous systems, importance sampling enables safe policy evaluation: engineers can estimate how an updated control policy would behave using data collected under a validated, safety-certified policy, without ever running the new policy on physical hardware. In classic reinforcement learning algorithms, importance-sampling ratios appear inside off-policy variants of TD(λ) and inside algorithms like Retrace(λ) and V-trace (used in large-scale distributed actor-learner architectures such as IMPALA), where clipped or truncated importance weights control variance while preserving asymptotic correctness. The tension this article surfaces — unbiased-but-high-variance versus consistent-but-biased — is precisely the tension that motivates truncated and clipped importance-sampling variants used throughout modern deep off-policy RL, and it is one strand of the broader instability phenomenon studied under The Deadly Triad, where off-policy learning, function approximation, and bootstrapping combine to threaten convergence guarantees.
Ask the tutor: How does the importance-sampling ratio change when using n-step returns instead of full Monte Carlo returns, and why does that matter for variance?
Why can't we just evaluate π directly by running it, instead of using importance sampling on b's data?
Sometimes we can, but often we cannot or should not. Running π directly may be expensive (real robots, real users), unsafe (untested medical or driving policies), or simply infeasible because we want to compare many candidate policies quickly using a single fixed dataset. Off-policy evaluation via importance sampling lets us reuse existing logged experience — collected once under a trusted behavior policy — to estimate the value of arbitrarily many candidate target policies without new interaction. This is the entire premise of offline and batch reinforcement learning: extracting maximal information from fixed data rather than paying for new rollouts.
Is importance sampling only usable for Monte Carlo methods, or does it extend to TD learning?
It extends naturally to TD learning, though the mechanics differ. In off-policy TD, importance-sampling ratios are applied per-step (or per n-step segment) to correct the bootstrapped target rather than the full Monte Carlo return. This appears in classical off-policy TD(λ) and in more modern algorithms like Retrace(λ) and V-trace, which additionally clip or truncate the ratios to control variance while retaining consistency guarantees. The Monte Carlo case discussed here is the cleanest setting to understand the core reweighting idea before these variance-controlled TD variants are introduced.
Why does weighted importance sampling divide by the sum of ratios instead of the count of samples?
Dividing by the sum of ratios makes the estimator self-normalizing: it treats each sample's contribution to the denominator proportionally to how much "evidence weight" that sample carries under the reweighting. If a sample's ratio is unusually large, it inflates both the numerator (weighted return) and the denominator (weight sum) together, so its overall influence on the ratio is dampened compared to dividing by a fixed count. This is precisely what reduces variance relative to ordinary importance sampling, at the cost of introducing bias for small sample sizes.
What happens if the importance-sampling ratio has expected value greater than 1, does that break the estimator?
No — the expectation of ρ_{t:T-1} under the behavior policy is always exactly 1, for any pair of policies satisfying coverage, because ρ is itself a likelihood ratio between two probability distributions over the same trajectory space, and likelihood ratios always have expectation 1 under the denominator distribution. This fact is precisely what makes the WIS denominator converge to 1 as sample size grows, ensuring the WIS estimator converges to the correct value. Individual sampled ratios can be much larger or smaller than 1, which is exactly the source of variance, but the underlying expectation is fixed by this general property.
Can importance sampling be used for policy control, not just prediction?
Yes. Off-policy Monte Carlo control combines the value estimation machinery here with policy improvement: after estimating Q(s,a) for a target policy using importance-sampled returns from behavior-policy episodes, the target policy is updated to be greedy (or ε-greedy) with respect to the estimated Q, and the process repeats using more data collected under the (possibly fixed or slowly evolving) behavior policy. This is the classical off-policy Monte Carlo control algorithm, and it requires the same coverage condition, now maintained continuously as the target policy is updated over iterations.
Why is the variance of ordinary importance sampling sometimes described as potentially infinite?
Because ρ is a product of per-step ratios, its distribution can have a heavy right tail: if b assigns very low probability to an action that π sometimes takes, the ratio π(a|s)/b(a|s) can be arbitrarily large, and the probability of drawing that action under b is correspondingly small. The product of a large value with a small probability need not vanish in the variance calculation — the second moment E[ρ²G²] can diverge even when the first moment E[ρG] (the mean) is perfectly finite. This is a classic example of a distribution with finite mean but infinite variance, analogous to certain heavy-tailed distributions studied in probability theory.
How does this relate to the Deadly Triad mentioned at the end?
Importance sampling introduces reweighting factors that can have high variance and, in some formulations, values far from 1, which becomes especially dangerous once combined with function approximation and bootstrapping. The Deadly Triad describes how off-policy learning, function approximation, and bootstrapped updates can jointly cause divergence of value estimates, even when each piece works correctly in isolation. Understanding plain importance-sampled Monte Carlo prediction — where at least unbiasedness or consistency is guaranteed — is the necessary first step before appreciating why adding bootstrapping and approximation together removes even those guarantees.