Eligibility traces: which earlier visits still receive credit?
资格迹
Compare accumulating and replacing traces on repeated visits, then propagate an actual TD error through both.
eligibility-tracesDoes returning to a state add another claim on credit?
A learner visits states 0, 1, 0 before termination. When a later TD error arrives, should state 0 receive credit for both visits, or should the latest visit replace the earlier trace?
Eligibility traces provide a small memory for that decision. With discount 0.9 and trace parameter 0.8, old traces decay by 0.72 per transition. At the third visit, state 0 has accumulating trace 1 + 0.72² = 1.5184, but replacing trace 1. The number is not a probability: an accumulating trace can exceed one.
The working draft’s Section 7.3 introduces this backward-looking mechanism. Silver’s lecture connects its decay to recency and repeated visits. This article studies the mechanism and actual updates; TD(lambda) separately explains its relation to mixtures of future returns.
Choose the trace convention before applying an error
Use a tabular value function, a constant discount gamma and a trace parameter lambda, both in [0,1]. Write rho=gamma×lambda. Before the first visit of an episode, initialize all traces to zero. Define e_t as the trace used for the TD error of the transition leaving S_t. An accumulating trace obeys
Decay the previous trace, then add the current visit. Expanding this recurrence shows precisely what it remembers:
Each earlier visit has its own decayed contribution. The trace forgets details about rewards and actions; it only records this weighted visitation history. In the repeated-state example the traces are [1,0], [0.72,1], then [1.5184,0.72].
A replacing trace changes only the visited component’s rule:
Let I_t(s) indicate whether the state has been visited by time t, and let ell_t(s) be its most recent visit time when one exists. Then the replacing trace has the explicit form
At a current visit the exponent is zero and the value is 1, including when rho is zero. Replacing remembers the latest visit rather than summing all visits. In this nonnegative tabular setting it stays between zero and one. Sutton and Barto distinguish these rules; they are not two names for the same algorithm.
Turn a local error into several updates
Use the pre-update value table to compute one TD error, then apply it to all nonterminal entries in proportion to their traces:
A terminal successor has value zero. Compute delta once, before changing any table entry; do not recompute it partway through the loop over states. The resulting updates are simultaneous in that sense.
Some presentations add the visit first, update, and decay traces at the end of the step. That stores a decayed trace between transitions and is equivalent to the indexing above if used consistently. Decaying both before and after would count time twice. Van Seijen and Sutton’s conventional TD discussion folds the constant step size into the trace; here alpha stays outside. With constant alpha these are equivalent scaling conventions, not permission to mix formulas when step sizes vary.
For rho<1, even visiting a state at every step bounds the accumulating trace:
At rho 1, it instead counts visits and can keep growing. Replacing caps a component at one, but that alone does not prove learning stability. Alpha times a large accumulating trace can produce a large update; a trace is a credit weight, not a normalized distribution over states.
Run both rules on exactly the same trajectory
Save traces.py and run it with Python 3.12; only the standard library is required. The complete authored episode is 0 → 1 → 0 → terminal, rewards 0,1.6,2, initial values [1,2,0], alpha 0.5, gamma 0.9 and lambda 0.8. The code implements ordinary online tabular TD updates with either accumulating or replacing traces.
"""Original traces 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 trace_step(trace,state,gamma=.9,lam=.8,mode='accumulating'):
unit(gamma,'gamma');unit(lam,'lambda')
if mode not in ('accumulating','replacing'):raise ValueError('unknown trace convention')
if not trace or type(state) is not int or not 0<=state<len(trace) or any(not math.isfinite(e) or e<0 for e in trace):raise ValueError('valid nonnegative trace required')
out=[gamma*lam*e for e in trace]
out[state]=out[state]+1 if mode=='accumulating' else 1.0
return out
def learn_episode(states,rewards,initial,alpha=.5,gamma=.9,lam=.8,mode='accumulating'):
unit(alpha,'alpha');unit(gamma,'gamma');unit(lam,'lambda');sequence(states,rewards,initial,True)
if mode not in ('accumulating','replacing'):raise ValueError('unknown trace convention')
v=list(initial);e=[0.]*(len(v)-1);history=[]
for t,r in enumerate(rewards):
s=states[t];delta=r+gamma*v[states[t+1]]-v[s];e=trace_step(e,s,gamma,lam,mode)
for i in range(len(e)):v[i]+=alpha*delta*e[i]
history.append(dict(time=t,delta=delta,trace=e.copy(),values=v.copy()))
return dict(values=v,history=history)
def demo():
states=[0,1,0,2];rewards=[0,1.6,2];initial=[1,2,0]
return dict(results={mode:learn_episode(states,rewards,initial,mode=mode) for mode in ['accumulating','replacing']},
lambda_zero=learn_episode(states,rewards,initial,lam=0),
next_episode=learn_episode([1,2],[4],[0,0,0]),decay=.9*.8)
if __name__=='__main__':
print(json.dumps(demo(),indent=2,allow_nan=False))
The first error is 0.8, moving state 0 to 1.4. The second is 1.6+0.9×1.4−2=0.86; both variants then have values [1.7096,2.43,0]. Before the final update they have the same error, 2−1.7096=0.2904, but different state-0 traces. Accumulating gives final values [1.93007168,2.534544,0]; replacing gives [1.8548,2.534544,0].
The difference arises at a repeated visit; until then the trace rules agree in this example. Replacing is not “the accumulating result clipped after updating”: it changes the trace before the error is distributed.
With lambda zero, only the current state has a nonzero trace, and the result [1.7,2.43,0] matches sequential TD(0). Starting a new episode resets traces. A separate 1 → terminal episode with reward 4 and zero initial values updates only state 1 to 2; state 0 does not inherit credit from the preceding episode.
For S tabular states and T transitions, the dense trace decay and value updates take O(TS) time and O(S) working space. This demonstration also records each trace and value table, using O(TS) output storage. Sparse implementations can prune small traces, but that approximation changes the exact updates. The program requires complete episodes and rejects inconsistent terminal states; it does not silently treat a cutoff as termination.
A trace has to match the learner using it
Accumulating and replacing traces can behave differently on repeated visits and at larger step sizes. There is no general rule that replacing always learns better. A bounded trace component is not a bound on value error, and a larger trace is not necessarily more reliable evidence.
These are nonnegative tabular state traces. Action-value traces, off-policy corrections and feature-gradient traces require their own definitions. Replacing arbitrary neural features componentwise is not justified by this table example. Dutch traces and true-online TD use additional conventions; swapping one trace line alone does not implement the complete true-online method described by van Seijen and Sutton.
Ordinary online accumulating traces do not generally reproduce the frozen-value offline lambda-return update. That equivalence needs the conditions developed in the next article, not just a matching lambda symbol.
Trace the visits before distributing the error
-
Is an accumulating trace of 1.5184 invalid because it exceeds one?
Answer: No. It sums decayed visits. It is a credit weight, not a probability or a normalized share of total credit.
-
With rho 0.72 and visits
0,1,0, calculate the final traces under both conventions.Answer: Accumulating gives state 0
1+0.72²=1.5184and state 10.72. Replacing sets the revisited state 0 to 1 and leaves state 1 at 0.72. -
If gamma and lambda both equal 1 and state 0 is repeatedly visited, what happens?
Answer: The accumulating trace increases by one each visit; it has no finite geometric bound. A replacing trace stays at one on each visit. Neither observation by itself proves the value-learning process converges.
-
An implementation carries traces across independent reset episodes. How can you expose the error with a tiny test?
Answer: End one episode with state 0 traced, then begin a new one that visits only state 1 before reward and termination. With properly reset traces, state 0 should receive no update from the second episode.
Indexing and scaling are part of the algorithm
The working draft provides accumulating and replacing rules and distinguishes online from offline updates. Silver’s lecture motivates their backward view. Van Seijen and Sutton 2014 discusses conventional traces before introducing a different online equivalence. Only its introductory framework and conventional-method pages were examined here; this code does not claim to reproduce the later true-online algorithm or experiments.
Make a prediction, then check
A state is revisited while its decayed trace is0.5184. What does a replacing trace become?
Learning objectives
- Derive a tabular trace from visit history and distinguish accumulation from replacement.
- Apply trace-weighted TD updates in the correct order and reset traces at a new episode.
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 - True Online TD(lambda)
Harm van Seijen; Richard S. Sutton · 2014
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: PDF191–192 §7.3/Fig7.7 decay, accumulating traces, TD updates; PDF194–195 replacing traces and online/offline distinction. 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. Read PDF1–3, with PDF2–3 visually inspected, and PMLR publication metadata. Frozen-within-episode forward/backward equality, changed online estimates, conventional accumulating/replacing traces and alpha folded into the paper's trace. New online equivalence is an author claim from the introduction; algorithm/proof later in the paper and empirical comparisons were not audited or implemented here. 6 paired equations and four explained exercises. Checked accumulating versus replacing traces at repeated states, nonzero initial values, shared final TD errors, lambda zero, trace decay and episode reset. Tabular conventional traces only; no Dutch trace or true-online implementation.
- Checked accumulating versus replacing traces at repeated states, nonzero initial values, shared final TD errors, lambda zero, trace decay and episode reset. Tabular conventional traces only; no Dutch trace or true-online implementation.
- 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) · PDF191–192 §7.3/Fig7.7 decay, accumulating traces, TD updates; PDF194–195 replacing traces and online/offline distinction. 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.
- True Online TD(lambda) · Read PDF1–3, with PDF2–3 visually inspected, and PMLR publication metadata. Frozen-within-episode forward/backward equality, changed online estimates, conventional accumulating/replacing traces and alpha folded into the paper's trace. New online equivalence is an author claim from the introduction; algorithm/proof later in the paper and empirical comparisons were not audited or implemented here.
Related topics