On-Policy vs Off-Policy Learning

Imagine a robot that must learn to walk without falling too often. It must also occasionally try risky new moves to discover better gaits. Should it learn only from the cautious policy it actually executes? Or can it learn about a bold, ideal policy while behaving cautiously? This question — who generates the experience versus whose value we are estimating — is one of the most consequential design choices in reinforcement learning. The distinction between on-policy and off-policy learning determines something important. It decides whether an agent can safely separate exploration from the policy it ultimately wants to optimize. It matters enormously in real systems. A self-driving car simulator can log data from a safe human-driving policy. Meanwhile it can train an aggressive optimal policy offline. A recommendation engine can reuse historical logs generated by an old algorithm. This lets it evaluate a brand-new one, without ever deploying it live. Off-policy learning enables data reuse, safety, and offline evaluation. On-policy learning offers simplicity and often more stable, lower-variance updates. The big picture is this: every Model-Free Prediction and control method updates value estimates from sampled trajectories. The identity of the policy that produced those trajectories — the behavior policy — matters. So does the policy whose values we care about — the target policy. These two are either the same (on-policy) or different (off-policy). This single structural fact ripples through convergence guarantees, variance, and sample efficiency. It even affects which algorithms are safe to use with function approximation. This article builds the conceptual scaffolding. It offers precise definitions and the mechanics of how each type of learning updates its estimates. It explains why off-policy learning requires correction machinery. It also covers the tradeoffs in bias, variance, and stability. It sets up the machinery — SARSA: On-Policy TD Control, Q-Learning: Off-Policy TD Control, and Importance Sampling for Off-Policy Methods — used throughout the rest of model-free control.

Key takeaways
  • On-policy learning estimates and improves the same policy that generates behavior; off-policy learning estimates a target policy from data generated by a different behavior policy.
  • The behavior policy must maintain exploration (e.g., ε-greedy); the target policy can be deterministic and greedy.
  • Off-policy methods need a correction — often importance sampling — to account for the mismatch between the two policies' action distributions.
  • On-policy methods (e.g., SARSA) tend to be safer and lower-variance but converge to the best policy reachable under exploration constraints.
  • Off-policy methods (e.g., Q-learning) can learn the true optimal policy while behaving very differently, enabling reuse of old data and offline learning.
  • Off-policy learning with function approximation and bootstrapping risks divergence — the so-called "deadly triad."
The core insight

On-policy learning evaluates the policy generating the data, while off-policy learning evaluates a different target policy — trading simplicity for the power (and instability risk) of decoupling exploration from optimization.

The idea

In reinforcement learning, an agent interacts with an environment by following some policy — a mapping from states to a distribution over actions. When we ask "what is the value of policy π?" we must specify whose actions generated the data used to estimate that value. This gives rise to two policies that a learning algorithm may juggle simultaneously: the behavior policy bb, which actually selects actions and generates the observed trajectory, and the target policy π\pi, whose value function or action-value function we are trying to learn.

On-policy learning occurs when b=πb = \pi: the agent learns about the exact policy it is following. Classic examples include first-visit Monte Carlo control with ε-greedy policies, and SARSA: On-Policy TD Control. Because the data-generating policy and the evaluated policy coincide, updates directly reflect the returns the agent will actually experience, and no correction for distributional mismatch is needed. The tradeoff is that since bb must explore (e.g., be ε-greedy), the learned value function is only guaranteed to reflect the best exploratory policy, not the true optimal deterministic policy.

Off-policy learning occurs when b≠πb \neq \pi: the agent behaves according to bb (which explores) while learning about π\pi (often the greedy, optimal policy). This decoupling is powerful — it permits learning purely from historical logs, from a human demonstrator, or from a completely different exploration strategy — but it introduces a fundamental estimation problem. Returns observed under bb are samples from the wrong distribution of trajectories relative to π\pi; naively averaging them estimates bb's value, not π\pi's. The standard fix is importance sampling, which reweights observed returns by the ratio of probabilities that π\pi versus bb would have produced the observed action sequence, covered in depth in Importance Sampling for Off-Policy Methods. Alternatively, some off-policy TD methods (like Q-learning) sidestep explicit importance sampling by directly bootstrapping off the target policy's greedy action-value, exploiting the structure of the Bellman optimality equation rather than reweighting whole trajectories. A key requirement for either paradigm to work is coverage: every state-action pair with nonzero probability under π\pi must have nonzero probability of being visited under bb. Formally, π(a∣s)>0  ⟹  b(a∣s)>0\pi(a\mid s) > 0 \implies b(a\mid s) > 0. Without this, off-policy learning cannot observe the data needed to estimate π\pi's value at all — a structural precondition, not a numerical nicety.

How it works

Both paradigms slot into the same general model-free prediction/control loop; the difference lies in which policy chooses actions and which policy's values get updated.

On-policy control (as in Monte Carlo control or SARSA) improves the policy it is currently following. It alternates between (1) generating experience with the current (soft, exploratory) policy and (2) updating the value estimates and then policy toward greediness with respect to those estimates — but only within the space of policies that still explore.

Off-policy control maintains two policies explicitly: a behavior policy bb used to act (and explore), and a target policy π\pi (often deterministic-greedy) whose action-value function QπQ_\pi we accumulate estimates of. The update rule must correct for the fact that actions were chosen by bb, not π\pi.

General on-policy TD control template

``` Initialize Q(s, a) arbitrarily for all s, a Initialize policy π to be ε-greedy with respect to Q repeat for each episode: s ← initial state a ← action chosen from s using π (ε-greedy on Q) repeat for each step of episode: take action a, observe reward r and next state s' a' ← action chosen from s' using π (ε-greedy on Q) # SAME policy used for update Q(s, a) ← Q(s, a) + α [ r + γ Q(s', a') − Q(s, a) ] s ← s' ; a ← a' until s is terminal ``` This is exactly the SARSA update — note that the action `a'` used inside the TD target is the actual next action the agent will take, sampled from the same ε-greedy policy that generated the trajectory. That is the hallmark of on-policy learning: the update target is consistent with the data-generating process.

General off-policy TD control template (Q-learning style)

``` Initialize Q(s, a) arbitrarily for all s, a Behavior policy b: e.g., ε-greedy with respect to Q (keeps exploring) repeat for each episode: s ← initial state repeat for each step of episode: a ← action chosen from s using b (ε-greedy, exploratory) take action a, observe reward r and next state s' Q(s, a) ← Q(s, a) + α [ r + γ max_{a'} Q(s', a') − Q(s, a) ] s ← s' until s is terminal ``` Here the TD target uses max⁡a′Q(s′,a′)\max_{a'} Q(s', a') — the value under the greedy target policy — regardless of which action bb actually takes next. The behavior policy explores freely; the bootstrap target always looks toward the greedy policy. This is why Q-learning is off-policy: the update evaluates πgreedy\pi_{\text{greedy}}, but the trajectory was generated by bb.

General off-policy Monte Carlo template with importance sampling

For episodic Monte Carlo prediction of π\pi using data from bb, the update requires reweighting the return by the importance-sampling ratio: ``` Initialize Q(s, a) arbitrarily, C(s, a) ← 0 for all s, a b ← any soft policy with coverage of π (b(a|s) > 0 whenever π(a|s) > 0) repeat for each episode: generate an episode using b: s0, a0, r1, s1, a1, r2, ..., sT G ← 0 W ← 1 for t = T-1 downto 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 * π(a_t | s_t) / b(a_t | s_t) if W == 0: break # no more correction possible, stop early ``` This is weighted importance sampling applied backward through the trajectory; the ratio WW accumulates the likelihood ratio of the whole suffix under π\pi versus bb, and the loop terminates early once WW hits zero (i.e., π\pi would never have taken an action that bb did).

Figure
On-policy vs off-policy data flow: who acts, who is evaluated
On-Policy (SARSA) Policy π = b (ε-greedy on Q) Env: take a, observe r, s′, a′~π Update Q(s,a) using r + γQ(s′,a′) — same π policy improves itself Off-Policy (Q-learning) Behavior b ε-greedy, explores Target π greedy, max Q Env: b takes a, observe r, s′ Update Q(s,a) using r + γ·max_a′Q(s′,a′) — different π

Complexity & correctness

Time and space complexity. Both on-policy and off-policy tabular TD control have identical per-step cost: O(1)O(1) time and O(1)O(1) additional memory per update (beyond the O(∣S∣∣A∣)O(|S||A|) table itself), since each step touches one Q(s,a)Q(s,a) entry and performs a constant number of arithmetic operations. Off-policy Monte Carlo with importance sampling is also O(T)O(T) per episode of length TT, same as on-policy Monte Carlo — the importance-sampling ratio is a single running product computed in O(1)O(1) per step. So off-policy correction does not change the asymptotic per-step complexity; it changes the statistical properties of the estimator (variance) and the structural requirements (coverage).

Correctness of on-policy TD control (SARSA). SARSA's target r+γQ(s′,a′)r + \gamma Q(s',a') is an unbiased sample of the Bellman expectation equation for the current ε-greedy policy π\pi, because a′a' is drawn from exactly that policy:

Es′,a′∼π[r+γQ(s′,a′)∣s,a]=Qπ(s,a).\mathbb{E}_{s',a'\sim \pi}\big[r + \gamma Q(s',a') \mid s,a\big] = Q_\pi(s,a).

Under standard stochastic-approximation conditions (Robbins–Monro step sizes ∑tαt=∞\sum_t \alpha_t = \infty, ∑tαt2<∞\sum_t \alpha_t^2 < \infty, plus GLIE — greedy in the limit with infinite exploration — policy updates), SARSA provably converges to the optimal action-value function Q∗Q_* with probability 1 in the tabular case. The proof follows the same fixed-point contraction argument used for TD(0): the Bellman operator for a fixed policy is a γ\gamma-contraction in sup-norm, and as the policy becomes greedy in the limit, the sequence of policy evaluations tracks an increasingly optimal policy.

Correctness of off-policy TD control (Q-learning). Q-learning's target r+γmax⁡a′Q(s′,a′)r + \gamma \max_{a'} Q(s',a') is a sample of the Bellman optimality equation, independent of which policy chose the next action in the actual trajectory:

Es′[r+γmax⁡a′Q(s′,a′) ∣ s,a]=(T∗Q)(s,a),\mathbb{E}_{s'}\Big[r + \gamma \max_{a'} Q(s',a') \,\Big|\, s,a\Big] = (T_* Q)(s,a),

where T∗T_* is the Bellman optimality operator, a γ\gamma-contraction with unique fixed point Q∗Q_*. Because this target does not depend on the behavior policy's action-selection distribution at all (only that s,as,a pairs are visited infinitely often), Q-learning converges to Q∗Q_* under the same step-size conditions, regardless of what the behavior policy is, so long as it guarantees infinite visits to every state-action pair (coverage). This is the deep reason Q-learning needs no explicit importance-sampling ratio: the max operator already "hard-codes" the target policy into the update, sidestepping distributional correction.

Correctness of importance-sampling Monte Carlo. For off-policy Monte Carlo prediction, ordinary importance sampling gives an unbiased estimator of vπ(s)v_\pi(s):

Eb[ρt:T−1 Gt ∣ St=s]=vπ(s),ρt:T−1=∏k=tT−1π(Ak∣Sk)b(Ak∣Sk).\mathbb{E}_b\Big[ \rho_{t:T-1}\, G_t \,\Big|\, S_t = s\Big] = v_\pi(s), \qquad \rho_{t:T-1} = \prod_{k=t}^{T-1} \frac{\pi(A_k\mid S_k)}{b(A_k\mid S_k)}.

The proof is a direct change-of-measure computation: the probability of a trajectory under π\pi equals its probability under bb times ρt:T−1\rho_{t:T-1}, so reweighting returns by this ratio exactly compensates for sampling from the wrong distribution. Weighted importance sampling (normalizing by cumulative WW) trades a small bias for dramatically reduced variance, and is consistent (bias → 0 as sample count → ∞).

Tradeoffs, honestly stated.

  • Variance: On-policy updates have bounded variance tied only to environment stochasticity. Off-policy importance sampling ratios ρ\rho can have unbounded variance — if π\pi and bb diverge sharply, a single trajectory's weight can explode, making naive off-policy Monte Carlo estimators wildly noisy despite being unbiased.
  • What is learned: On-policy control learns the best policy within the exploratory family (e.g., best ε-greedy policy), never quite reaching the fully greedy optimum while ε > 0. Off-policy control can learn the fully greedy optimal policy while the agent behaves however is convenient or safe.
  • Stability with function approximation: Off-policy learning combined with bootstrapping (TD-style updates) and function approximation forms the deadly triad — the combination can diverge (Q-values blow up) even though each ingredient is individually well-behaved. On-policy TD with function approximation has stronger (though not unconditional) convergence guarantees for linear approximators.

Worked example

Consider a tiny 1-D gridworld: states {A,B,C}\{A, B, C\} with CC terminal, reward +1+1 on entering CC and 00 otherwise, γ=1\gamma = 1. Two actions: `right` (intended direction) and `left`. Suppose the agent's true optimal policy is "always go right," but behavior policy bb is ε-greedy with ε = 0.5 (uniform over both actions half the time). Behavior policy bb generates one episode: `A →(right) B →(left) A →(right) B →(right) C`, with rewards `0, 0, 0, 1`.

On-policy (SARSA) update, using the actual next action taken by bb:

Stepssaarrs′s'a′a' (actually taken)Target r+γQ(s′,a′)r+\gamma Q(s',a')
1Aright0Bleft0+Q(B,left)0 + Q(B,\text{left})
2Bleft0Aright0+Q(A,right)0 + Q(A,\text{right})
3Aright0Bright0+Q(B,right)0 + Q(B,\text{right})
4Bright1C—11 (terminal)

SARSA's targets are contaminated by the exploratory `left` moves — e.g. step 1's target bootstraps off Q(B,left)Q(B,\text{left}), a genuinely bad action, because that's what the agent is actually going to do next. SARSA is honestly estimating the ε-soft policy's value, warts and all.

Off-policy (Q-learning) update, using max⁡a′Q(s′,a′)\max_{a'} Q(s',a') regardless of what bb actually does next:

Stepssaarrs′s'Target r+γmax⁡a′Q(s′,a′)r + \gamma\max_{a'}Q(s',a')
1Aright0B0+max⁡(Q(B,left),Q(B,right))0 + \max(Q(B,\text{left}), Q(B,\text{right}))
2Bleft0A0+max⁡(Q(A,left),Q(A,right))0 + \max(Q(A,\text{left}), Q(A,\text{right}))
3Aright0B0+max⁡(Q(B,left),Q(B,right))0 + \max(Q(B,\text{left}), Q(B,\text{right}))
4Bright1C11

Even though step 2's action was the exploratory (suboptimal) `left`, the target still looks toward the best action from AA — Q-learning always bootstraps toward the greedy policy, so its Q-values converge toward Q∗Q_* (the value of "always go right") even while behavior wanders. This is the concrete cash-value of the on-policy/off-policy distinction: same data, two different estimators, converging to two different (though related) objects.

Common pitfalls & traps

PitfallWhy it happensFix
Forgetting the coverage conditionOff-policy correction is undefined if π(a∣s)>0\pi(a\mid s) > 0 but b(a∣s)=0b(a\mid s) = 0 for some visited stateEnsure bb is soft (all actions probability > 0) wherever π\pi might act
Confusing SARSA's `a'` with the greedy actionMixing SARSA's on-policy bootstrap with Q-learning's max bootstrap gives an inconsistent hybridBe explicit: SARSA samples a′∼πa'\sim\pi; Q-learning uses max⁡a′\max_{a'}
Ignoring importance-sampling varianceOrdinary importance sampling is unbiased but can have huge or infinite variancePrefer weighted importance sampling, or restrict π,b\pi, b to be close
Assuming off-policy learning is "free"Off-policy control can diverge under function approximation + bootstrapping (deadly triad)Use target networks, careful step sizes, or on-policy-adjacent corrections (e.g., truncated IS) in deep RL
Evaluating ε too aggressively to zeroOn-policy control needs GLIE (ε → 0 in the limit, but infinite exploration first) for convergence proofs to applyDecay ε slowly, or use optimistic initialization to sustain exploration
Treating "off-policy" as always safer to reuse old dataOld logs from a very different bb may violate coverage or amplify variance for a very different target π\piCheck overlap between bb and π\pi's action distributions before reusing logs

Pioneers & history

Origins · 1 minRichard S. Sutton and how this was discovered
RS
Richard S. Sutton
born 1957 · Reinforcement learning pioneer, University of Alberta and DeepMind

Sutton co-developed temporal-difference learning and, with Andrew Barto, formalized the modern on-policy/off-policy distinction that structures nearly all model-free RL algorithms, including the SARSA/Q-learning contrast used throughout this article.

History
1988
Sutton introduces temporal-difference (TD) learning, the ancestor of both SARSA and Q-learning.
1989
Chris Watkins introduces Q-learning, the canonical off-policy TD control algorithm, and proves its convergence.
1994
Rummery and Niranjan introduce "Modified Connectionist Q-Learning," later renamed SARSA, the canonical on-policy TD control algorithm.
1998
Sutton and Barto's Reinforcement Learning: An Introduction codifies the on-policy/off-policy taxonomy for the field.
2015
DeepMind's DQN combines off-policy Q-learning with deep function approximation, forcing renewed attention to the deadly triad and stability tricks.

Watkins's 1989 doctoral thesis proved that Q-learning converges to the optimal action-value function under mild conditions — remarkably, without requiring the behavior policy to be related to the target policy beyond ensuring adequate exploration. This was a conceptually striking result at the time: it showed learning could be fully decoupled from acting, a property that later became essential for reusing large offline datasets and human demonstration data in modern reinforcement learning systems.

Where this matters

Off-policy learning underlies almost all modern deep reinforcement learning at scale. DQN and its successors (Double DQN, Rainbow) rely on off-policy Q-learning to reuse a replay buffer of past experience many times, dramatically improving sample efficiency versus on-policy methods that must discard data after one use. Offline (batch) reinforcement learning — training entirely from fixed historical logs, common in recommendation systems, healthcare, and industrial control — is only possible because off-policy learning permits behavior and target policies to differ arbitrarily (subject to coverage). Off-policy actor-critic methods like DDPG, TD3, and SAC power continuous-control robotics research and simulated locomotion benchmarks. On-policy methods remain dominant where stability matters more than sample efficiency: PPO and TRPO, used heavily in RLHF pipelines for large language models, are on-policy precisely because they need reliable, low-variance policy-gradient estimates and are willing to pay the cost of discarding old rollouts. The choice between on-policy and off-policy design is, in effect, a choice between sample efficiency and stability — a tradeoff engineers make explicitly when choosing an algorithm for a production system.

Ask the tutor: Can you walk through why Q-learning's convergence proof does not depend on the behavior policy, using the Bellman optimality operator's contraction property?

Is Monte Carlo control on-policy or off-policy?

It can be either. Classic Monte Carlo control (as typically introduced) is on-policy: it generates episodes with an ε-soft policy and updates value estimates for that same policy, gradually making it greedier while retaining exploration. However, Monte Carlo methods can equally be run off-policy: generate episodes with a behavior policy bb, then reweight returns by the importance-sampling ratio π(a∣s)/b(a∣s)\pi(a\mid s)/b(a\mid s) to estimate the value of a different target policy π\pi, often the fully greedy policy. The algorithm family (Monte Carlo vs TD) and the on-policy/off-policy distinction are independent design axes.

Why can't on-policy methods learn the fully greedy optimal policy directly?

On-policy control must keep exploring to gather more evidence about all actions, typically via an ε-soft policy. If it switched to purely greedy action selection, it would stop visiting some state-action pairs, breaking the "infinite visits" requirement needed for convergence, and it could get stuck exploiting a suboptimal action it happened to overestimate early on. So on-policy methods (like SARSA) converge to the best policy achievable within the constraint of continual exploration — e.g., "optimal ε-greedy policy" — not the unconstrained optimal deterministic policy, unless ε is explicitly annealed to zero under GLIE conditions.

Does off-policy learning always have higher variance than on-policy learning?

Not universally, but importance-sampling-based off-policy estimators (as in off-policy Monte Carlo) typically do have higher variance, because the importance ratio ρ=∏π/b\rho = \prod \pi/b can grow very large or even be unbounded when π\pi and bb differ substantially. Off-policy TD control methods like Q-learning, which avoid explicit trajectory-level importance sampling by bootstrapping directly off the max-action value, tend to have variance closer to on-policy TD methods. The variance cost of off-policy learning is thus method-dependent, not an unavoidable law.

How does the choice of behavior policy affect off-policy learning in practice?

The behavior policy determines what states and actions get explored, which in turn determines how quickly and reliably the target policy's value function converges. A behavior policy that rarely visits important states will make learning slow, even if it satisfies coverage in principle (nonzero probability everywhere). In practice, "off-policy-ness" is a spectrum: behavior policies close to the target policy generally yield lower-variance, faster-converging estimates than behavior policies far from it, since the importance-sampling ratios stay closer to one and less correction is needed.

Why do modern deep RL systems like PPO choose on-policy learning despite the sample-efficiency downside?

PPO and TRPO prioritize training stability and reliable policy improvement over raw sample efficiency, which matters heavily when training large models (e.g., in RLHF for language models) where a divergent update can be catastrophic and expensive to recover from. On-policy updates avoid the instability risks of the deadly triad (off-policy + bootstrapping + function approximation), and their trust-region or clipped-objective mechanisms only have clean theoretical justification when data comes from the current policy. The tradeoff is discarding data after one gradient step, but the resulting stability is often worth the cost at scale.

Is Expected SARSA on-policy or off-policy?

Expected SARSA can be used in both modes, which nicely illustrates that the update rule and the on/off-policy distinction are separate concerns. Its target replaces the sampled next action with an expectation over the current policy's action distribution: r+γ∑a′π(a′∣s′)Q(s′,a′)r + \gamma \sum_{a'} \pi(a'|s') Q(s',a'). If π\pi is the same ε-greedy policy generating behavior, it's on-policy; if π\pi is instead the greedy policy while behavior remains ε-greedy, it becomes off-policy and, in fact, reduces exactly to Q-learning when π\pi is fully greedy (the expectation collapses to the max term).

What role does GLIE play in on-policy convergence guarantees?

GLIE (Greedy in the Limit with Infinite Exploration) is the condition requiring that every state-action pair be visited infinitely often, while the policy becomes increasingly greedy (ε → 0) as time goes to infinity. It formalizes the tension in on-policy control: you need exploration for correctness in early learning, but you need convergence to greediness for the final policy to be optimal. Without GLIE, on-policy methods like SARSA can only be guaranteed to converge to the best policy within a fixed exploration constraint, not the true optimum.

Before this

Where this leads