n-Step Bootstrapping Methods
Imagine an agent learning to play a card game. A single misplay only reveals its cost several turns later. One-step Temporal-Difference Learning updates a value estimate using just one reward and the very next state. Credit for a delayed mistake trickles backward one step at a time. This happens painfully slowly. Monte Carlo methods swing to the opposite extreme. They wait for an entire episode to end before updating anything. They use the full, unbiased return. But they pay for it with high variance. They also lack any ability to learn online. Neither extreme is obviously right. Real systems — from robotic controllers to game-playing agents — often need something in between. n-step bootstrapping methods supply exactly that middle ground. Instead of bootstrapping after one reward or waiting for the complete return, an n-step method looks ahead n rewards. It then bootstraps off the value estimate at that horizon. This single design knob, the integer n, lets a practitioner slide continuously along the bias-variance spectrum. n = 1 recovers ordinary TD(0). n = ∞ (or n equal to the episode length) recovers Monte Carlo. Tuning n is often the difference between two outcomes. One is an algorithm that learns in a handful of episodes. The other never converges in a reasonable budget. The idea matters far beyond a textbook exercise. Multi-step returns are the computational backbone of practical deep reinforcement learning systems. Rainbow DQN uses n-step returns as one of its core components. A3C and IMPALA use n-step returns to reduce variance and enable parallelism. n-step SARSA and n-step Q-learning give control analogues. These let an agent choose actions using intermediate lookahead. Understanding n-step methods also builds essential intuition for the article's natural successor. That successor is TD(λ) and eligibility traces. It can be viewed as an efficient, continuous averaging over all values of n simultaneously. This article develops the n-step return precisely. It derives n-step TD prediction and n-step SARSA control. It gives working pseudocode for both. It analyzes the time/space cost and the bias-variance tradeoff rigorously. It traces a full worked numerical example. It surveys the common implementation traps. This includes especially the off-by-one errors that plague every first attempt at coding this family of algorithms.
- n-step methods interpolate between one-step TD (n=1) and Monte Carlo (n=∞) by bootstrapping n steps into the future.
- The n-step return sums n discounted rewards, then adds the discounted bootstrap estimate .
- Larger n reduces bias (closer to the true return) but increases variance and delays updates; there is usually an intermediate n that minimizes error empirically.
- n-step SARSA extends the idea to control by bootstrapping on action-values , preserving on-policy correctness.
- Off-policy n-step methods need importance-sampling correction across all n steps, which can inflate variance sharply.
- n-step methods are a discrete stepping stone to TD(λ), which computes a weighted average over all n simultaneously via eligibility traces.
The n-step return trades a tunable amount of Monte-Carlo-style accuracy for TD-style bootstrapping speed, controlled by a single integer n.
The idea
Consider a trajectory generated under a policy . The one-step TD target is : it uses exactly one real reward and then bootstraps, substituting the current value estimate for everything that would happen afterward. The Monte Carlo target is the full return , using every real reward until termination and no bootstrapping at all. The n-step return generalizes both by truncating the sum after n real rewards and bootstrapping there:
Here denotes the value function estimate available at time (subscripting the estimate this way is the standard convention that makes the update rule well-defined even mid-episode). If (the episode terminates before n steps elapse), the bootstrap term is simply dropped and , the ordinary return. The update rule mirrors one-step TD exactly, just applied n steps later:
This is still a form of Bootstrapping and the Bias-Variance Tradeoff: the target is not the true expected return, but an estimate contaminated by whatever error currently sits in . As n grows, that contamination shrinks — after n steps the bootstrapped term is discounted by , so its influence on the target decays geometrically — while the variance contributed by the n sampled rewards grows, since each reward is itself a random variable. The n-step return is a genuine statistical interpolation: it is provably less biased than the one-step target (whenever is inaccurate) and provably lower-variance than the full Monte Carlo return, for any finite n and . A crucial structural fact: because requires rewards and state , the update for cannot be performed until time . This delay is the price of looking further ahead, and it is the central bookkeeping challenge in implementing these algorithms correctly.
How it works
n-step TD prediction. The agent walks the trajectory, and at each time step once rewards have been observed (or the episode has ended), it computes and updates . A circular buffer of the last states and rewards is the natural implementation, since only that much history is needed at any moment. ``` Algorithm: n-step TD for estimating V ≈ v_π Input: policy π, step size α ∈ (0,1], integer n ≥ 1 Initialize V(s) arbitrarily for all states s for each episode: Initialize and store S_0 T ← ∞ # will hold the episode length once known for t = 0, 1, 2, ...: if t < T: take action A_t ~ π(·|S_t) observe and store R_{t+1}, S_{t+1} if S_{t+1} is terminal: T ← t + 1 τ ← t - n + 1 # time whose estimate is being updated if τ ≥ 0: G ← 0 for i = τ+1 to min(τ+n, T): G ← G + γ^(i-τ-1) R_i if τ + n < T: G ← G + γ^n V(S_{τ+n}) V(S_τ) ← V(S_τ) + α (G - V(S_τ)) if τ == T - 1: break # all remaining updates done, episode finished ``` Two indexing subtleties deserve emphasis. First, is the time step being updated, which lags the current simulation time by steps; this is the most common source of off-by-one bugs. Second, the loop must keep running for extra iterations after* the episode terminates at , because early time steps like still need their (now fully realized, no-bootstrap) n-step return computed — this is why the loop condition is on reaching , not on the episode-generation step reaching .
n-step SARSA for control. The same idea lifts directly to action-value control by bootstrapping on instead of , using the action actually selected by the current (on-policy) behavior:
``` Algorithm: n-step SARSA for estimating Q ≈ q_π (or q_ with GLIE policy) Input: step size α ∈ (0,1], small ε > 0, integer n ≥ 1 Initialize Q(s,a) arbitrarily for all s,a; policy π = ε-greedy w.r.t. Q for each episode: Initialize S_0; choose A_0 ~ π(·|S_0) T ← ∞ for t = 0, 1, 2, ...: if t < T: take action A_t, observe R_{t+1}, S_{t+1} if S_{t+1} is terminal: T ← t + 1 else: choose A_{t+1} ~ π(·|S_{t+1}) # on-policy next action τ ← t - n + 1 if τ ≥ 0: G ← 0 for i = τ+1 to min(τ+n, T): G ← G + γ^(i-τ-1) R_i if τ + n < T: G ← G + γ^n Q(S_{τ+n}, A_{τ+n}) Q(S_τ, A_τ) ← Q(S_τ, A_τ) + α (G - Q(S_τ, A_τ)) update π to be ε-greedy w.r.t. Q # policy improves online if τ == T - 1: break ``` Because is chosen before it is needed as the bootstrap action, the algorithm must select actions one step ahead of when they are consumed in the update — exactly analogous to ordinary SARSA: On-Policy TD Control, just with the bootstrap pushed n steps further down the trajectory.
Off-policy n-step control. If the behavior policy differs from the target policy , each of the n actions along the segment must be corrected by an importance-sampling ratio , and the update becomes . Each additional factor in the product can push the ratio toward 0 or blow it up, so variance grows multiplicatively with n — this is the direct control-side manifestation of the bias-variance cost analyzed below. (n-step tree-backup and are further refinements that reduce or eliminate this variance blow-up, but they are extensions beyond the scope of the core method.)
Complexity & correctness
Time complexity. Each n-step update requires summing n discounted rewards, an operation if computed naively as shown in the pseudocode. In practice this sum is almost always maintained incrementally: on each new time step, the buffered partial return can be updated in by adding the new discounted reward and removing the oldest bootstrap contribution, since and share common reward terms. With that optimization, each of the time steps in an episode costs amortized work, so a full episode is processed in total time, identical in order to one-step TD or Monte Carlo — the constant factor grows with n but the asymptotic behavior does not change. Space is : a sliding window must retain the last states, rewards, and (for SARSA) actions, versus for TD(0) and for a naive Monte Carlo implementation that stores an entire episode.
Bias–variance derivation. Fix a state and write for the true value. Decompose the error of the n-step target:
This holds because the real-reward prefix is, by the definition of as an expected return, an unbiased estimator of — the only source of bias is substituting the (possibly wrong) current estimate for the true at the horizon, and that substitution error is attenuated by . So:
- As (or fixed and reaches episode length), : bias vanishes, recovering the unbiased Monte Carlo return.
- As , bias equals , the full one-step TD bias, present whenever has not yet converged.
For variance, treat the reward random variables as (approximately, for a fixed policy) having bounded variance each and being suitably weakly correlated; the discounted-sum variance grows roughly as
a strictly increasing function of n for : every additional real reward folded into the target adds sampling noise that no bootstrap could have contributed, since the bootstrap only contracts the tail of the sum, not the prefix. This formalizes the intuitive tradeoff: larger n monotonically trades bias for variance.
Convergence. Under the standard stochastic-approximation conditions — a tabular representation, every state visited infinitely often, and step sizes satisfying , — n-step TD converges to with probability 1 for any fixed finite n, by the same Robbins–Monro argument used for one-step TD: the n-step operator is still a contraction in expectation toward under the sup-norm (composing n applications of the Bellman evaluation operator with one bootstrap step preserves the contraction property, since the Bellman operator itself is a -contraction and ). n-step SARSA converges to analogously under a fixed policy, and to under GLIE (greedy in the limit with infinite exploration) policy schedules, mirroring one-step SARSA's control convergence guarantee.
Empirical tradeoff. Neither nor is typically optimal in practice with function approximation and a finite number of episodes: an intermediate n minimizes root-mean-square error in classic benchmarks (e.g., the random walk task from Sutton & Barto), because the reduction in bias from moderate n outweighs the added variance until n grows too large, at which point variance dominates and error rises again — an empirical U-shaped curve in n that directly reflects the bias/variance decomposition above.
Worked example
Consider a 5-state random walk: states arranged left to right, with two terminal absorbing states at the far left (reward 0) and far right (reward +1); all other rewards are 0, , and the agent starts every episode at . Initialize . Suppose one episode runs: , giving rewards , so . Take , .
| segment used for | computation | update | |||
|---|---|---|---|---|---|
| 0 | — (τ<0, skip) | — | — | none | |
| 1 | 0 | ||||
| 2 | 1 | ; τ+n=3=T so no bootstrap | |||
| 3 | 2 | only; τ+n=4>T |
Trace notes: at (), is not yet terminal at the moment the update is computed (termination is discovered at ), so the bootstrap term correctly enters; because was still 0.5 at that point, the update happens to leave unchanged this episode. At , however, , so the algorithm correctly drops the bootstrap term entirely and uses the full realized 2-step sum of rewards, propagating the terminal reward two states backward in a single update — something one-step TD () could not do until at least two separate episodes of updates. This is precisely the mechanism by which larger n propagates delayed reward information faster: 's value moves from toward after just one episode, whereas one-step TD would need the +1 reward to first update , and only in a later episode update from the improved . The final loop iterations ( conceptually) handle (updating from alone, no bootstrap) and then terminate since .
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Off-by-one in | Confusing the current simulation index with the update index | Keep them as separate variables; verify with that it reduces exactly to TD(0) |
| Forgetting the post-termination tail | Loop stops as soon as the episode ends at , skipping updates for | Continue looping until , using the shrinking, bootstrap-free sum for the tail |
| Wrong bootstrap cutoff | Applying even when | Guard explicitly: only bootstrap if |
| Choosing too late in n-step SARSA | The bootstrap needs , which must already have been selected on-policy before the update fires | Select the next action immediately upon observing the next state, before any update logic |
| Naive resum every step | Recomputing the full n-term sum from scratch at each | Maintain the partial sum incrementally in using a sliding window |
| Ignoring importance-sampling blow-up off-policy | Treating off-policy n-step control like on-policy, or multiplying n ratios naively | Use variance-reduced variants (tree-backup, ) for large n off-policy |
Pioneers & history
n-step methods emerged from the same lineage that produced Temporal-Difference Learning itself, as researchers explored the design space between the two limiting cases of bootstrapped and unbootstrapped prediction.
Origins · 1 minRichard S. Sutton and how this was discovered
Sutton formalized temporal-difference learning and, with Andrew Barto, systematized the entire spectrum of n-step and eligibility-trace methods that unify TD and Monte Carlo prediction and control.
Where this matters
n-step returns are a default ingredient in modern deep reinforcement learning rather than a theoretical curiosity. Rainbow DQN combines n-step returns (typically n=3) with double Q-learning, prioritized replay, and distributional value functions, and ablations show n-step returns among the most impactful individual components for Atari performance. Actor-critic architectures such as A3C and IMPALA compute n-step (or truncated λ-return) advantage estimates to reduce the variance of policy-gradient updates while still enabling efficient rollout-based parallel training. Robotics and continuous-control agents commonly use short n-step horizons (n = 3 to 10) to balance sample efficiency against the instability that very long, high-variance rollouts introduce into function-approximated value learning. The concept also underlies generalized advantage estimation (GAE), which can be understood as a soft, exponentially-weighted average over n-step advantage estimates — directly foreshadowing how TD(lambda) and Eligibility Traces averages over all n simultaneously rather than committing to one fixed horizon.
Ask the tutor: How does the choice of n interact with function approximation error when the value network itself is inaccurate at long horizons?
Why not just always use a large n, since it reduces bias?
Because variance grows with n: every additional real reward folded into the n-step return contributes its own sampling noise, and unlike the bootstrap term (which is discounted and shrinks its own error contribution), the reward-sum prefix accumulates variance with each added term. Empirically, error as a function of n is typically U-shaped: an intermediate value minimizes total mean-squared error against the true value function, because the marginal bias reduction from adding one more real reward is eventually outweighed by the marginal variance it introduces. The "right" n is problem-dependent and is usually tuned as a hyperparameter, often n=3 to n=10 in practice for deep RL, though tabular problems can favor larger n depending on episode length and reward sparsity.
How does n-step TD relate to TD(λ)?
TD(λ) can be derived as a weighted average over all n-step returns simultaneously, with weight assigned to the n-step return of horizon n, normalized so weights sum to 1. Rather than committing to a single fixed n, TD(λ) blends every horizon, controlled by a single scalar : recovers pure one-step TD, and recovers the Monte Carlo return. Eligibility traces implement this averaged update efficiently online without literally computing every n-step return, achieving in per step what the λ-return definition would otherwise require work to compute directly.
Does n-step TD require waiting n steps before any learning happens?
Yes, structurally: the update for cannot fire until and have all been observed, so learning is delayed by n-1 steps relative to one-step TD. This delay is a genuine practical cost in online or real-time systems, since state 's value estimate is "stale" for n-1 extra decision points, potentially affecting exploration or control decisions made in the interim. The delay is bounded and fixed, though, unlike Monte Carlo's delay of a full (possibly very long or even unbounded) episode, which is precisely the practical advantage n-step methods retain over pure Monte Carlo.
Can n-step methods be used with function approximation instead of a table?
Yes — the update rule generalizes directly by replacing the tabular update with a gradient step on a parameterized value function: . The n-step return itself is computed identically; only the mechanism for reading and updating the value estimate changes. This is exactly how n-step returns are used inside deep RL systems like Rainbow DQN, where or is a neural network and the n-step target is computed from a short window of stored transitions in a replay buffer.
What is the practical effect of choosing n too large in a noisy environment?
Very large n in a highly stochastic environment causes the target to accumulate variance from many noisy reward samples before any bootstrap correction can stabilize it, which can slow or destabilize learning, especially with function approximation where updates also interact through shared parameters across states. In the extreme, n equal to the episode length degenerates fully into Monte Carlo, inheriting all of Monte Carlo's downsides: high variance, no online updates mid-episode, and no benefit from bootstrapping's implicit smoothing. Empirically this manifests as noisier learning curves and sometimes slower convergence despite the lower asymptotic bias, which is exactly the U-shaped tradeoff curve the bias-variance decomposition predicts.
Is n-step Q-learning the same as n-step SARSA?
No. n-step SARSA bootstraps using the action that the behavior policy actually selected, making it on-policy and directly analogous to one-step SARSA. n-step Q-learning-style methods instead bootstrap using , the greedy action, making the target off-policy with respect to whatever exploratory behavior generated the trajectory — and, critically, this max-based bootstrap makes the naive n-step generalization biased unless careful corrections (like tree-backup) are used, because intermediate actions along the n-step segment may not have been the greedy ones the target policy would have taken.