AI Wiki中文/EN

TD(lambda): the conditions behind two views

TD(lambda)

Build finite lambda returns, verify offline forward/backward equality and compute an online counterexample.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Same lambda, different final values

Take the authored episode 0 → 1 → 0 → terminal, rewards 0,1.6,2, initial values [1,2,0], discount 0.9 and step size 0.5. With lambda 0.8, an offline lambda-return update produces [2.3392,2.61,0]. An offline accumulating-trace calculation gives exactly the same result. Ordinary online accumulating traces instead produce [1.93007168,2.534544,0].

No method changed the episode or lambda. What changed was whether intermediate updates were allowed to alter the table used for later targets. “The forward and backward views are equivalent” needs to specify that choice.

The working draft, Sections 7.2–7.4 distinguishes those versions. Van Seijen and Sutton 2014 motivates a different online forward view and an algorithm matching it. Here we derive the conventional offline identity and compute the ordinary-online counterexample; we do not implement the paper’s later true-online algorithm.

The finite lambda mixture retains its complete-return tail. Frozen-table forward and backward updates agree; ordinary online traces can differ.
The finite lambda mixture retains its complete-return tail. Frozen-table forward and backward updates agree; ordinary online traces can differ.

Mix horizons without losing the final weight

Consider a complete finite episode ending at T, and a table W held fixed throughout that episode, with terminal value zero. Let m=T−t be the transitions remaining from visit t. An n-step return includes n rewards and then bootstraps from W, unless termination comes first. For lambda in [0,1], use weights

wn={(1−λ)λn−1,1≤n<m,λm−1,n=m,∑n=1mwn=1.w_n=\begin{cases}(1-\lambda)\lambda^{n-1},&1\leq n<m,\\ \lambda^{m-1},&n=m,\end{cases} \qquad \sum_{n=1}^{m}w_n=1.

The final weight is the whole remaining geometric tail. It is not another copy of (1−lambda)×lambda^(m−1). With three transitions and lambda 0.8, the weights are 0.2, 0.16 and 0.64. With only one transition, the sole weight is 1 for every lambda.

The finite lambda return is the weighted target

Gtλ[W]=∑n=1mwnGt(n)[W]=(1−λ)∑n=1m−1λn−1Gt(n)[W]+λm−1Gt.G_t^\lambda[W]=\sum_{n=1}^{m}w_nG_t^{(n)}[W] =(1-\lambda)\sum_{n=1}^{m-1}\lambda^{n-1}G_t^{(n)}[W] +\lambda^{m-1}G_t.

Lambda zero selects the one-step target; lambda one selects the complete return. Intermediate values combine horizons rather than selecting one fixed horizon. The working draft’s finite-episode expression explicitly preserves the terminal tail.

Separate the first reward in every component. The remaining mixture starts at the next state, giving a useful backward recursion:

Gtλ[W]=Rt+1+γ[(1−λ)W(St+1)+λGt+1λ[W]],GTλ[W]=W(ST)=0.G_t^\lambda[W]=R_{t+1}+\gamma\left[(1-\lambda)W(S_{t+1})+\lambda G_{t+1}^\lambda[W]\right], \qquad G_T^\lambda[W]=W(S_T)=0.

“Backward recursion” here means calculating target numbers from the known episode’s end. It is not yet the backward eligibility-trace learning algorithm. At the last transition the formula keeps the final reward and adds no terminal continuation.

Derive the offline identity

Define a fixed-table TD error at every transition. Subtract W(S_t) from the recursion and repeatedly substitute the next error:

δt[W]=Rt+1+γW(St+1)−W(St),Gtλ[W]−W(St)=δt[W]+γλ(Gt+1λ[W]−W(St+1))=∑k=tT−1(γλ)k−tδk[W].\begin{aligned} \delta_t[W]&=R_{t+1}+\gamma W(S_{t+1})-W(S_t),\\ G_t^\lambda[W]-W(S_t) &=\delta_t[W]+\gamma\lambda\bigl(G_{t+1}^\lambda[W]-W(S_{t+1})\bigr)\\ &=\sum_{k=t}^{T-1}(\gamma\lambda)^{k-t}\delta_k[W]. \end{aligned}

The final continuation difference is zero. This is a pathwise algebraic identity for the stated finite episode, not an empirical convergence result. To interpret the learned table as a policy’s value, the sampling and prediction assumptions still matter.

Use a constant step size alpha and accumulate corrections without changing W during the episode. For each state, substitute the identity and exchange the two finite sums:

ΔW(s)=α∑t=0T−11[St=s](Gtλ[W]−W(s))=α∑k=0T−1δk[W]∑t=0k(γλ)k−t1[St=s]⏟ek(s).\begin{aligned} \Delta W(s) &=\alpha\sum_{t=0}^{T-1}\mathbf1[S_t=s]\bigl(G_t^\lambda[W]-W(s)\bigr)\\ &=\alpha\sum_{k=0}^{T-1}\delta_k[W] \underbrace{\sum_{t=0}^{k}(\gamma\lambda)^{k-t}\mathbf1[S_t=s]}_{e_k(s)}. \end{aligned}

The underbraced quantity is an accumulating eligibility trace. Therefore forward target corrections and backward trace-weighted errors give the same total update at the end of the episode. This includes repeated states: each visit contributes its correction relative to the same old W(s). It does not mean individual intermediate bookkeeping entries have to match.

What ordinary online updates change

An online algorithm changes values immediately:

et(s)=γλet−1(s)+1[St=s],δt=Rt+1+γVt(St+1)−Vt(St),Vt+1(s)=Vt(s)+αδtet(s).e_t(s)=\gamma\lambda e_{t-1}(s)+\mathbf1[S_t=s],\qquad \delta_t=R_{t+1}+\gamma V_t(S_{t+1})-V_t(S_t),\qquad V_{t+1}(s)=V_t(s)+\alpha\delta_t e_t(s).

Its delta now uses V_t, which can differ at every step. The fixed-table substitutions used in the preceding proof no longer apply unchanged. In the opening example the second offline delta is 0.5, but the second online delta is 0.86 because state 0 has already risen to 1.4. The resulting comparison at lambda 0.8 is

Vforward,offline=Vbackward,offline=[2.3392, 2.61, 0],Vbackward,online=[1.93007168, 2.534544, 0].V_{\mathrm{forward,offline}}=V_{\mathrm{backward,offline}} =[2.3392,\ 2.61,\ 0],\qquad V_{\mathrm{backward,online}}=[1.93007168,\ 2.534544,\ 0].

Van Seijen and Sutton makes this distinction part of the motivation for true-online TD. Its new online forward view is not the frozen-table offline target renamed, and ordinary accumulating traces are not the full true-online algorithm.

Check equality, then deliberately break its assumption

Save the standard-library program as td_lambda.py and run it with Python 3.12. forward_offline calculates lambda targets and sums corrections relative to the initial table. backward either holds that table fixed or updates it online, controlled by an explicit flag. All three calculations use identical input episodes.

"""Original td_lambda 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 lambda_targets(states,rewards,values,gamma=.9,lam=.8):
    unit(gamma,'gamma');unit(lam,'lambda');sequence(states,rewards,values,True)
    out=[0.]*len(rewards);tail=0.
    for t in range(len(rewards)-1,-1,-1):
        tail=rewards[t]+gamma*((1-lam)*values[states[t+1]]+lam*tail);out[t]=tail
    return out


def forward_offline(states,rewards,initial,alpha=.5,gamma=.9,lam=.8):
    unit(alpha,'alpha');targets=lambda_targets(states,rewards,initial,gamma,lam);out=list(initial)
    for s,g in zip(states[:-1],targets):out[s]+=alpha*(g-initial[s])
    return dict(values=out,targets=targets)


def backward(states,rewards,initial,alpha=.5,gamma=.9,lam=.8,online=False):
    unit(alpha,'alpha');unit(gamma,'gamma');unit(lam,'lambda');sequence(states,rewards,initial,True)
    if type(online) is not bool:raise ValueError('online must be a bool')
    v=list(initial);change=[0.]*len(v);e=[0.]*len(v);history=[]
    for t,r in enumerate(rewards):
        s=states[t];base=v if online else initial;delta=r+gamma*base[states[t+1]]-base[s]
        e=[gamma*lam*x for x in e];e[s]+=1
        for i in range(len(v)):
            if online:v[i]+=alpha*delta*e[i]
            else:change[i]+=alpha*delta*e[i]
        history.append(dict(time=t,delta=delta,trace=e.copy(),values=v.copy()))
    if not online:v=[x+c for x,c in zip(v,change)]
    return dict(values=v,history=history)


def weights(length,lam):
    unit(lam,'lambda')
    if type(length) is not int or length<1:raise ValueError('positive remaining length required')
    return [(1-lam)*lam**k for k in range(length-1)]+[lam**(length-1)]


def demo():
    states=[0,1,0,2];rewards=[0,1.6,2];initial=[1,2,0]
    rows=[]
    for lam in [0,.5,.8,1]:
        rows.append(dict(lam=lam,weights=weights(3,lam),forward=forward_offline(states,rewards,initial,lam=lam),
                         backward=backward(states,rewards,initial,lam=lam),online=backward(states,rewards,initial,lam=lam,online=True)))
    return dict(rows=rows,alpha=.5,gamma=.9,initial=initial)


if __name__=='__main__':
    print(json.dumps(demo(),indent=2,allow_nan=False))

At lambda 0.8, the first target is 0.2×1.8 + 0.16×2.25 + 0.64×3.06 = 2.6784. State 0 also occurs at the last transition with target 2. Its offline value is therefore 1 + 0.5×[(2.6784−1)+(2−1)] = 2.3392. The room target is 0.2×2.5+0.8×3.4=3.22, giving 2.61.

The demonstration repeats the comparison at lambda 0, 0.5, 0.8 and 1. At zero, online traces reduce to sequential TD(0), producing [1.7,2.43,0]; offline one-step corrections give [1.9,2.25,0]. There is no contradiction: both offline views still match each other. At one, offline lambda targets are complete returns, and the accumulated every-visit corrections produce [2.53,2.7,0]. This is not a claim that every online TD(1) implementation equals a Monte Carlo sample-mean estimator.

Independent checks enumerate the finite mixture using rational arithmetic and compare forward/backward offline totals on 30 random repeated-state episodes. Lambda endpoints, final residual weight, zero alpha, terminal consistency and input preservation are also checked. These are exact small calculation checks, not a performance study.

The forward recursion and correction accumulation take O(T+S) time and space for T transitions and an S-entry table. The dense backward method takes O(TS) time and O(S) working memory; this demonstration additionally stores O(TS) trace and value history. The point of an online backward mechanism is that it can operate with local transitions and a trace, without storing the full future episode. Keeping the histories here makes its actual calculations inspectable.

Which forward view, which trace, which step size?

The proof used complete episodes, terminal value zero, a frozen table, accumulating traces and a constant step size. Replacing traces, changing step sizes, function approximation or different boundary handling need their own derivation. Ordinary online updates may differ even when all traces and arithmetic are implemented correctly.

A collection cutoff is not the true terminal boundary used by this program. A continuing-task lambda-return construction needs a declared bootstrap at the cutoff; the code instead rejects an incomplete episode. This explicit restriction prevents zeroing an unknown future by accident.

The identity is about matching updates, not guaranteeing accurate values or optimal behavior. The chosen lambda and step size still affect learning. True-online methods provide a different exact online correspondence under their stated setting; their empirical superiority claims are the source authors’ results, not results reproduced here.

Find the assumption used by each equality

  1. For three transitions and lambda 0.8, why is the last weight 0.64 rather than 0.128?

    Answer: All horizons reaching or passing termination have the same complete return, so their remaining mass is combined. The first weights are 0.2 and 0.16; the remaining 0.64 makes the total one. Using 0.128 would leave most of the mass missing.

  2. Recalculate the first lambda target and offline state-0 value in the opening example.

    Answer: The target is 0.2×1.8+0.16×2.25+0.64×3.06=2.6784. Two visits to state 0 contribute corrections relative to initial value 1: 0.5×(2.6784−1) and 0.5×(2−1). Their sum added to 1 is 2.3392.

  3. At lambda zero, does the offline identity force its result to equal sequential online TD(0)?

    Answer: No. Offline forward and backward one-step corrections match each other using the same frozen table. Online TD(0) changes that table between transitions; the repeated-state example gives 1.7 instead of 1.9 for state 0.

  4. You replace accumulating traces with replacing traces but keep the offline forward target. Can you reuse the proof unchanged?

    Answer: No. Exchanging the sums produces a sum of all decayed visits, exactly the accumulating trace. A replacing trace retains only the latest visit, so that algebra no longer yields its update. Derive the appropriate relationship instead of relabeling the methods as equivalent.

An equivalence theorem identifies the objects it equates

The working draft describes offline equality and the limitations of the conventional online correspondence. Van Seijen and Sutton’s 2014 paper introduces a new online forward view; only its introductory framework and conventional-method pages were examined for this article. The detailed new algorithm, later proof and experiments were not audited here. The derivation above establishes the stated frozen-table tabular identity directly, with original numerical checks.

Make a prediction, then check

Does ordinary online TD(lambda) always equal the frozen-value offline lambda-return update?

Choose one answer

Learning objectives

  • Derive finite-episode lambda weights including the final residual mass.
  • Prove frozen-value accumulating-trace equivalence and show why ordinary online updates differ.

Prerequisites & connections

Explore related knowledge →

References

  1. Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
    Richard S. Sutton; Andrew G. Barto · 2015
  2. 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: PDF187 §7.2 finite lambda-return tail; PDF191–192 and195–196 §7.3–7.4 offline equality, online differences and true-online context. New algorithm theorem not independently audited. Read2026-09-23. 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. 7 paired equations and four explained exercises. Checked finite mixture tail weights and sum, all lambda endpoints, forward-backward equality under frozen values, Fraction return enumeration and ordinary online discrepancies. Complete episodes only; no equivalence claim for changing online tables or TD(1) sample means.

  • Checked finite mixture tail weights and sum, all lambda endpoints, forward-backward equality under frozen values, Fraction return enumeration and ordinary online discrepancies. Complete episodes only; no equivalence claim for changing online tables or TD(1) sample means.
  • 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) · PDF187 §7.2 finite lambda-return tail; PDF191–192 and195–196 §7.3–7.4 offline equality, online differences and true-online context. New algorithm theorem not independently audited. Read2026-09-23.
  • 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

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.