N-step returns: wait for rewards, then bootstrap
n 步回报
Compute delayed targets, flush pending updates at the boundary and track which value table supplies the bootstrap.
n-step-returnsHow long should a prediction wait?
A one-step learner sees the next reward, then fills the remaining future with a value estimate. A Monte Carlo learner waits for the whole episode. An n-step target waits for up to n rewards before using an estimate for whatever remains. The choice changes which information enters the target and when an update becomes possible.
Take an authored trajectory 0 → 1 → 0 → terminal, rewards 0, 1.6, 2, discount 0.9, and a fixed value table [1,2,0]. For the first visit, one-step, two-step and complete-return targets are 1.8, 2.25 and 3.06. None is computed by simply multiplying the one-step target by n.
Sutton and Barto, Section 7.1 presents the span from one-step to complete-return backups; Silver’s lecture writes the corresponding discounted sums. We will also track a detail that a target formula alone can hide: the table can change while an update waits.
Count observed rewards, then locate the bootstrap
Let an observed sequence end at state index H. It contains states S_0 through S_H and rewards R_1 through R_H. Its end may be true termination or a collection cutoff. For a positive integer n and start t, set h=min(t+n,H). Let z_h equal 1 only when h=H and that endpoint is truly terminal; otherwise it is zero. A fixed table W gives
The first reward has exponent zero. The bootstrap has exponent equal to the number of observed transitions in this target. When h lies before the observed boundary, bootstrap from that intermediate state. When the sequence ends only because collection stopped, retain the boundary continuation estimate even if fewer than n rewards were collected.
For a complete episode with true terminal time T, the special case is
All sufficiently long targets become the same complete return; they do not borrow rewards from the next episode. The working draft explains this endpoint rule. Its displayed Equation 7.1 has a missing reward factor after the gamma-squared term in the inspected draft page; the indexed sum above avoids that typographical error and agrees with Silver’s n-step formula.
A target and an update are different objects
The rewards needed for the target become available at state time u=min(t+n,H). Updating from the table current at that update time gives
Specify which table supplies both terms. Here they use the same pre-update table at the actual update time. An offline calculation that holds one table fixed for the whole episode is another convention. A stored-trajectory replay must still avoid using rewards later than its declared availability time.
At termination, several pending starts can become ready together. Flush them in chronological order and update each start once. That order can matter when a state appears repeatedly. A circular buffer can implement the streaming version, but the teaching code below keeps the complete input trajectory so the schedule is easy to inspect.
More rewards reduce one source of approximation, under stated conditions
For a fixed policy, a table W fixed before sampling, true terminal handling and discount below 1, subtract the corresponding n-step identity for the true value. Only the bootstrap error remains:
Here an absorbing terminal extension has zero value. The bound concerns expected targets and a fixed table, not every noisy sample. It does not directly prove a bound for a table adapted using the same future observations. A longer horizon may add sampling variance and delay learning; it need not improve finite-run accuracy. At gamma 1 the displayed factor no longer attenuates the bootstrap error.
Follow the numbers through a repeated state
With the opening trajectory and the table held fixed at [1,2,0], target vectors in visit order are
For instance the two-step first target is 0 + 0.9×1.6 + 0.9²×1 = 2.25. The bootstrap uses state 0 because the trajectory returns there after two transitions.
Now allow one-step updates with alpha 0.5. The first update changes state 0 from 1 to 1.4. The next target uses that new table:
This difference is not a discounting error. It is the consequence of choosing an online value-update convention rather than a frozen table.
Expose availability time and flush order
Save n_step.py and run it with Python 3.12 and the standard library. target evaluates one target on an explicitly supplied table. learn_episode replays a stored trajectory with delayed updates and records when each target became available. It simulates the timing; it is not a live environment or a ring-buffer implementation.
"""Original n_step teaching example; synthetic episodes, not benchmark reproduction."""
import json
import math
import random
def unit(x, name):
if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) or not 0 <= x <= 1:
raise ValueError(name+' must be finite in [0,1]')
def sequence(states, rewards, values, terminated):
if type(terminated) is not bool or len(values)<2 or any(not math.isfinite(x) for x in values) or values[-1]!=0:
raise ValueError('finite values with a zero terminal component required')
if not rewards or len(states)!=len(rewards)+1 or any(not math.isfinite(r) for r in rewards):
raise ValueError('nonempty finite rewards and one extra state required')
terminal=len(values)-1
if any(type(s) is not int or not 0<=s<=terminal for s in states):
raise ValueError('state index outside table')
if terminal in states[:-1] or (states[-1]==terminal)!=terminated:
raise ValueError('termination flag must match the final state only')
def target(states,rewards,values,t,n,gamma=.9,terminated=True):
unit(gamma,'gamma');sequence(states,rewards,values,terminated)
if type(n) is not int or n<1 or type(t) is not int or not 0<=t<len(rewards):raise ValueError('valid time and positive integer n required')
return _target(states,rewards,values,t,n,gamma,terminated)
def _target(states,rewards,values,t,n,gamma,terminated):
h=min(t+n,len(rewards));g=math.fsum(gamma**(k-t)*rewards[k] for k in range(t,h))
if h<len(rewards) or not terminated:g+=gamma**(h-t)*values[states[h]]
return g
def learn_episode(states,rewards,initial,n,alpha=.5,gamma=.9,terminated=True):
unit(alpha,'alpha');target(states,rewards,initial,0,n,gamma,terminated)
v=list(initial);trace=[];T=len(rewards)
def update(t,available):
g=_target(states,rewards,v,t,n,gamma,terminated);s=states[t];v[s]+=alpha*(g-v[s])
trace.append(dict(time=t,available=available,target=g,values=v.copy()))
for available in range(1,T+1):
t=available-n
if t>=0:update(t,available)
for t in range(max(0,T-n+1),T):update(t,T)
return dict(values=v,trace=trace)
def demo():
states=[0,1,0,2];rewards=[0,1.6,2];initial=[1,2,0]
fixed={str(n):[target(states,rewards,initial,t,n) for t in range(3)] for n in [1,2,3,10]}
learned={str(n):learn_episode(states,rewards,initial,n) for n in [1,2,3]}
return dict(fixed_value_targets=fixed,online=learned,
cutoff_target=target([0,1],[0],[0,4,0],0,5,terminated=False),
terminal_target=target([0,2],[0],[0,4,0],0,5,terminated=True))
if __name__=='__main__':
print(json.dumps(demo(),indent=2,allow_nan=False))
For n=2, starts 0, 1 and 2 update at availability times 2, 3 and 3. Their final values are [1.8125,2.7,0]. For n=1, sequential updates give [1.7,2.43,0]; for n=3, chronological flushing gives [2.015,2.7,0]. The latter uses complete returns but still changes the table between repeated-state updates. It is not the frozen-table sum of all corrections.
The two boundary tests use one observed reward 0. A cutoff at a nonterminal state with value 4 produces 3.6, even with n=5; true termination produces 0. The code refuses a flag inconsistent with its reserved final state ID.
The public target function validates a length-T sequence and an S-entry table, then directly sums at most n rewards: O(T+S+min(n,T)) time. The episode learner validates once, uses its internal sum function thereafter, and spends O(T min(n,T) + TS) time including copied table snapshots. The trace itself costs O(TS) space, in addition to input storage. An optimized streaming implementation can avoid those full snapshots and use a bounded buffer; that is not what this readable replay claims to do.
Horizon is not the only choice
You must also specify discount, terminal handling, bootstrap table timing, step size and behavior policy. Increasing n changes the amount of sampled reward and the update delay. A small model error bound on a frozen target does not settle the variance of its sampled version.
For off-policy data, a longer sequence may contain more actions from the wrong behavior distribution; uncorrected targets need not evaluate the desired policy. TD(lambda) mixes several horizons, while SARSA makes the next action explicit. Neither extension removes the need to define boundaries and update timing.
Mark when each reward becomes available
-
At the first visit of the opening trajectory, why does the two-step target bootstrap from state 0 rather than state 1?
Answer: Two transitions are
0→1and1→0. The target includes rewards 0 and 1.6, then usesgamma² × W(0). State 1 is only the one-step successor. -
Calculate the two-step target and its first update from
W(0)=1, with alpha 0.5.Answer: The target is
0+0.9×1.6+0.81×1=2.25. The updated state-0 value is1+0.5×(2.25−1)=1.625. -
With three transitions and
n=2, how many starts update at termination? Are any updated twice?Answer: Start 1 becomes ready at time 3, and start 2 is flushed at time 3; start 0 was updated at time 2. Each of the three starts is updated once. Flushing from start 1 again would duplicate an update.
-
Would increasing
nnecessarily improve a noisy task’s learning curve?Answer: No. The frozen-table bias bound shrinks with gamma to the power n, but longer targets can be noisier and arrive later. Compare complete learning protocols, including boundary rules, step sizes and evaluation policies, rather than just that bound.
The endpoint and the table version belong in the specification
The working draft discusses n-step backups and online versus offline updates; Silver’s prediction lecture places them between TD and Monte Carlo. The expectation bound above is derived for the explicitly fixed-table setting. The repeated-state replay and cutoff tests are original calculations, not a reproduction of a random-walk benchmark.
Make a prediction, then check
An episode ends before n rewards arrive. What happens to updates still waiting?
Learning objectives
- Compute a target whose horizon ends before, at or beyond termination.
- Schedule each update once, with no reward from beyond its availability time.
Prerequisites & connections
Explore related knowledge →References
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
Richard S. Sutton; Andrew G. Barto · 2015 - Lecture 4: Model-Free Prediction
David Silver · 2015
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: PDF183–184 §7.1, viewed183. Eq7.1 visibly omits the reward after gamma²; use the correct indexed sum, cross-checked with Silver PDF32 and direct arithmetic. Read2026-09-23. Author teaching page identifies the 2015 course; 2025 upload path is not the lecture year. Read PDF1,3–7,10–13,16–18,29,32,35,37,40–45. MC visit conventions, incremental means, TD targets, n-step returns, accumulating traces and explicitly offline equivalence. General bias/variance summaries are teaching heuristics, not unconditional variance or efficiency theorems. No slides/images copied. 6 paired equations and four explained exercises. Checked fixed-table target matrices, online bootstrap timing, terminal flush, large horizons, cutoff, integer-domain validation and update availability. Exact exhaustive paths verify a fixed-table bias bound; no adaptive-table theorem is claimed.
- Checked fixed-table target matrices, online bootstrap timing, terminal flush, large horizons, cutoff, integer-domain validation and update availability. Exact exhaustive paths verify a fixed-table bias bound; no adaptive-table theorem is claimed.
- Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. All twelve selected current captures directly viewed; browser inputs bound by SHA before integration. Full article acceptance recorded separately.
Source locations checked:
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF183–184 §7.1, viewed183. Eq7.1 visibly omits the reward after gamma²; use the correct indexed sum, cross-checked with Silver PDF32 and direct arithmetic. Read2026-09-23.
- Lecture 4: Model-Free Prediction · Author teaching page identifies the 2015 course; 2025 upload path is not the lecture year. Read PDF1,3–7,10–13,16–18,29,32,35,37,40–45. MC visit conventions, incremental means, TD targets, n-step returns, accumulating traces and explicitly offline equivalence. General bias/variance summaries are teaching heuristics, not unconditional variance or efficiency theorems. No slides/images copied.
Related topics