Off-Policy Importance Sampling
Evaluate a target policy without ever running it by observing a different behavior policy and re-weighting returns by action probability ratios.
Why Does This Exist?
In reinforcement learning, learning on-policy creates a persistent conflict between exploration and control. To find an optimal policy, an agent must take exploratory, potentially suboptimal actions. But to evaluate or execute an optimal policy, the agent must act greedily.
In on-policy methods, an agent evaluates the very policy that dictates its behavior. If that behavior explores, the agent evaluates an exploratory policy rather than the true optimal policy. Furthermore, all historical data collected under previous policies becomes obsolete and must be discarded whenever the agent updates its policy.
Off-policy prediction resolves this dilemma by decoupling the learning process into two distinct roles:
- Target Policy (): The policy being evaluated, optimized, or learned (often a deterministic, greedy, or candidate control policy).
- Behavior Policy (): The policy used to generate actions and gather experience in the environment (often exploratory, safe, or an existing legacy controller).
Because the agent follows behavior policy , the raw observed returns reflect the distribution induced by , not . Without correction, averaging these returns yields a heavily biased estimate of 's value. Importance sampling provides the exact statistical re-weighting needed to transform sample returns gathered under into an unbiased estimate of the value under .
Think of It Like This
Demographic Polling Adjustments
Imagine a polling organization wants to predict how the entire voting electorate (the target policy ) will vote on upcoming referendums. Due to collection constraints, their field survey only managed to interview college students on campus (the behavior policy ).
In the surveyed student sample, 80% support public transit expansion and 20% support highway expansions. However, historical census data reveals that in the general electorate, only 40% prioritize public transit while 60% prioritize highway expansions.
If the pollsters simply averaged the raw student responses, their forecast for the general election would be hopelessly skewed. To correct for this sampling bias, they apply an adjustment factor to each response:
- A vote for public transit is multiplied by (down-weighted because transit supporters were overrepresented).
- A vote for highway expansion is multiplied by (up-weighted because highway supporters were underrepresented).
By multiplying every recorded response by the ratio , the pollsters compute an unbiased estimate of the general population's preferences using data from a completely different group.
Where the analogy stops: Demographic polling evaluates a single, independent choice per respondent. In reinforcement learning, an episode is a sequential chain of decisions over time. The agent must multiply these probability ratios across every successive time step of the trajectory, creating a compounding product that can rapidly fluctuate.
How It Actually Works
Target Policy vs. Behavior Policy and the Importance Sampling Ratio
Let denote the probability of choosing action in state under the target policy, and let denote the corresponding probability under the behavior policy.
To estimate the value function from episodes generated by , we must satisfy the coverage assumption:
If the target policy could take an action in a state that the behavior policy never attempts (), the agent will never observe data for that transition, making it impossible to evaluate .
Consider an episode trajectory segment starting at time step and terminating at time :
Under behavior policy , the probability of observing this sequence of actions and states given starting state is: where represents the environment's transition dynamics.
Under target policy , the probability of that identical trajectory would be:
The importance sampling ratio is defined as the relative probability of the trajectory under compared to :
The transition probabilities are identical in numerator and denominator and cancel out completely. This makes importance sampling fully model-free: we do not need to know the environment's transition probabilities.
The expected value of the return under behavior policy , scaled by , matches the true expectation under target policy :
In ordinary importance sampling, an agent samples episodes starting from state under behavior policy and computes the empirical mean:
Worked numerical example
Consider a 3-step episode generated under behavior policy with discount factor :
The observed unweighted return from is:
The target policy and behavior policy assign the following probabilities to the actions chosen at each time step:
-
Step at state taking action :
-
Step at state taking action :
-
Step at state taking action :
The cumulative trajectory importance sampling ratio is the product across all three steps:
The re-weighted return contribution from this trajectory is:
Now suppose a second episode starting from yields raw return with cumulative ratio , giving a re-weighted return of .
The ordinary importance sampling estimate of across these two episodes is:
Even though the target policy was never executed in the environment, the scaled returns provide an unbiased estimate of how well performs.
Code
from typing import List, NamedTuple
class Transition(NamedTuple): state: str action: str reward: float pi_prob: float # Target policy probability: pi(a|s) b_prob: float # Behavior policy probability: b(a|s)
def evaluate_trajectory_importance_sampling( trajectory: List[Transition], gamma: float = 1.0) -> tuple[float, float, float]: """ Computes raw return G_0, cumulative importance sampling ratio rho, and the re-weighted return rho * G_0 for off-policy prediction. """ rho = 1.0 for step in trajectory: assert step.b_prob > 0.0, "Coverage violation: b(a|s) must be > 0" ratio = step.pi_prob / step.b_prob rho *= ratio
# Calculate discounted return G_0 g = 0.0 for t, step in enumerate(trajectory): g += (gamma ** t) * step.reward
weighted_return = rho * g return g, rho, weighted_return
def ordinary_importance_sampling_estimate( episodes: List[List[Transition]], gamma: float = 1.0) -> float: """Computes the sample average of weighted returns across episodes.""" total_weighted = sum( evaluate_trajectory_importance_sampling(ep, gamma)[2] for ep in episodes ) return total_weighted / len(episodes)
# Episode 1 (from worked example)ep1 = [ Transition(state="S0", action="A0", reward=2.0, pi_prob=0.80, b_prob=0.50), Transition(state="S1", action="A1", reward=1.0, pi_prob=0.40, b_prob=0.80), Transition(state="S2", action="A2", reward=5.0, pi_prob=0.50, b_prob=0.25),]
# Episode 2ep2 = [ Transition(state="S0", action="A1", reward=1.0, pi_prob=0.30, b_prob=0.40), Transition(state="S1", action="A0", reward=3.0, pi_prob=1.00, b_prob=1.00),]
g1, rho1, weighted1 = evaluate_trajectory_importance_sampling(ep1)g2, rho2, weighted2 = evaluate_trajectory_importance_sampling(ep2)
print(f"Episode 1: Raw Return = {g1:.2f}, rho = {rho1:.2f}, Weighted = {weighted1:.2f}")print(f"Episode 2: Raw Return = {g2:.2f}, rho = {rho2:.2f}, Weighted = {weighted2:.2f}")
v_estimate = ordinary_importance_sampling_estimate([ep1, ep2])print(f"Estimated V^pi(S0) = {v_estimate:.2f}")
# -> Expected output:# Episode 1: Raw Return = 8.00, rho = 1.60, Weighted = 12.80# Episode 2: Raw Return = 4.00, rho = 0.75, Weighted = 3.00# Estimated V^pi(S0) = 7.90Watch Out For
Exponential Variance Explosion Along Long Trajectories
Ordinary importance sampling is strictly unbiased, but its variance can be astronomically high or even theoretically infinite. Because the trajectory weight is a product of ratios, small differences between and compound exponentially with trajectory length .
In long horizons, most trajectories under take at least one action that considers unlikely, causing to drop to . Conversely, an occasional trajectory aligns with high-probability actions under , producing an enormous value. The resulting empirical average oscillates wildly, requiring impractical numbers of samples to converge.
The Fix:
- Switch to Weighted Importance Sampling (WIS), which divides by the sum of importance ratios () rather than the episode count . WIS introduces a mild bias but guarantees bounded weights and dramatically lower variance.
- Use discounting-aware importance sampling or temporal-difference (TD) methods (such as Q-learning or Expected SARSA), which bootstrap after 1 step to avoid cumulative multi-step product expansion.
The Quick Version
- Off-policy prediction evaluates a target policy using trajectory data generated by a separate behavior policy .
- The coverage assumption requires for every state-action pair where .
- The importance sampling ratio cancels environment transition dynamics, enabling model-free re-weighting.
- Ordinary importance sampling is strictly unbiased (), but suffers from extreme variance over long horizons due to compounding products of ratios.