AI Wiki中文/EN

Backpropagation through time: accumulate across steps

时间反向传播

Execute full and detached-boundary BPTT with exact rational gradients, a real update and an independent forward-sensitivity check.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A state receives a local loss and a future loss

The loss at time three can depend on a weight used at times one, two and three. Backpropagation through time, or BPTT, accumulates these routes through the unfolded computation. It does not create separate trainable weights for each time step, and it does not update a weight as soon as the backward loop reaches one occurrence.

Deep Learning, Section 10.2.2 derives reverse accumulation on an unrolled RNN. Pascanu, Mikolov and Bengio’s 2013 paper, Section 2.1 analyzes the temporal derivative products that make recurrent training difficult. Here a linear scalar recurrence lets us verify the whole algorithm with exact fractions, including a deliberately truncated gradient.

Add the direct error and the later-state contribution

Use inputs xₜ, targets yₜ, shared parameters w,u,b and fixed initial state h₀. The model and mean loss are:

ht=wht−1+uxt+b,L=12T∑t=1T(ht−yt)2.h_t=wh_{t-1}+ux_t+b,\qquad L=\frac1{2T}\sum_{t=1}^T(h_t-y_t)^2.

The output is the state itself. This is a linear RNN used to isolate differentiation, not the tanh model from the preceding chapter. All forward states are computed at the same parameter values before any update.

Let δₜ be the derivative of the total loss with respect to hₜ, and set δₜ₊₁ to zero beyond the final step. Reverse accumulation gives:

δt=ht−ytT+wδt+1,∂L∂w=∑tδtht−1,∂L∂u=∑tδtxt,∂L∂b=∑tδt.\delta_t=\frac{h_t-y_t}{T}+w\delta_{t+1},\qquad \frac{\partial L}{\partial w}=\sum_t\delta_th_{t-1},\quad \frac{\partial L}{\partial u}=\sum_t\delta_tx_t,\quad \frac{\partial L}{\partial b}=\sum_t\delta_t.

The first term is the current loss’s direct derivative. The second accounts for all later losses through the next state. Each shared-parameter derivative sums its use-site contributions. Input derivatives are uδₜ, and the initial-state derivative is wδ₁. If inputs come from a learnable embedding or encoder, these input derivatives must continue upstream.

For a tanh recurrence, the derivative through the activation must also be included. In a vector model, scalar multiplication by w becomes the appropriate transposed Jacobian multiplication. These changes follow the same chain rule; copying the linear formula without the activation derivative would be wrong.

Three steps, checked by hand

Take x=(1,2,−1), y=(0,1,0), w=1/2, u=1, b=0 and h₀=0. States are 1,5/2,1/4 and the loss is 53/96. Starting at the end gives δ₃=1/12, then δ₂=13/24 and δ₁=29/48.

The parameter gradients are dw=3/4, du=77/48 and db=59/48; dh₀=29/96. A single update with rate 1/10 gives w=17/40, u=403/480 and b=−59/480. The program evaluates the full new loss after applying the completed gradient.

Change the backward boundary without resetting values

The complete Python 3.12 program executes the forward recurrence and a reverse loop. Optional cuts name boundaries after particular time steps. At a cut, it keeps the state value for subsequent forward computation but removes the future adjoint contribution into that state:

δtC=ht−ytT+1[t∉C]wδt+1C.\delta_t^{\mathcal C}=\frac{h_t-y_t}{T} +\mathbf1[t\notin\mathcal C]w\delta_{t+1}^{\mathcal C}.

The set C contains interior boundary indices. This explicit policy models a detached state boundary; it is not a general implementation of every truncated-BPTT schedule. The teaching program still stores all states so the full and cut calculations can be compared directly.

from fractions import Fraction as F


def scalar(x):
    if type(x) not in (int,F) or abs(x)>32:raise ValueError('bounded rational required')
    return F(x)


def bptt(inputs,targets,w,u,b,h0=0,cuts=()):
    x,y=[tuple(scalar(v) for v in seq) for seq in (inputs,targets)]
    if not 1<=len(x)<=16 or len(x)!=len(y):raise ValueError('matching sequences of length 1 through 16 required')
    w,u,b,h0=[scalar(v) for v in (w,u,b,h0)];n=len(x)
    if any(type(t) is not int or not 1<=t<n for t in cuts) or len(set(cuts))!=len(cuts):raise ValueError('unique interior cut boundaries required')
    h=[h0]
    for value in x:h.append(w*h[-1]+u*value+b)
    loss=sum(((h[t+1]-y[t])**2 for t in range(n)),F(0))/(2*n)
    gw=gu=gb=carry=F(0);deltas=[F(0)]*n
    for t in range(n,0,-1):
        delta=(h[t]-y[t-1])/n+(F(0) if t in cuts else w*carry)
        gw+=delta*h[t-1];gu+=delta*x[t-1];gb+=delta
        deltas[t-1]=delta;carry=delta
    return dict(states=h[1:],loss=loss,w=gw,u=gu,b=gb,h0=w*carry,
                inputs=[u*d for d in deltas],deltas=deltas)


if __name__=='__main__':
    x,y=[1,2,-1],[0,1,0];w,u,b=F(1,2),F(1),F(0)
    full=bptt(x,y,w,u,b);cut=bptt(x,y,w,u,b,cuts=(1,))
    print('states:',[str(v) for v in full['states']],'loss:',full['loss'])
    print('full adjoints:',[str(v) for v in full['deltas']])
    print('full gradients w,u,b,h0:',*[full[k] for k in ('w','u','b','h0')])
    print('cut after1 gradients w,u,b,h0:',*[cut[k] for k in ('w','u','b','h0')])
    updated=[value-F(1,10)*full[k] for value,k in zip((w,u,b),('w','u','b'))]
    print('updated parameters:',[str(v) for v in updated])
    print('new full loss:',f'{float(bptt(x,y,*updated)["loss"]):.9f}')

Actual output:

states: ['1', '5/2', '1/4'] loss: 53/96
full adjoints: ['29/48', '13/24', '1/12']
full gradients w,u,b,h0: 3/4 77/48 59/48 29/96
cut after1 gradients w,u,b,h0: 3/4 4/3 23/24 1/6
updated parameters: ['17/40', '403/480', '-59/480']
new full loss: 0.214017905

Cutting after time one leaves states and loss unchanged but changes du to 4/3 and db to 23/24. The recurrent-weight gradient happens to remain 3/4 in this example because h₀ is zero; unchanged values for one parameter do not imply the whole gradient is unchanged.

Tests compare the full gradient with an independently propagated forward-sensitivity recurrence and with finite differences. They also compare the cut gradient to a surrogate calculation that freezes the boundary state at its baseline value. Finite differences of the original fully recomputed objective should match full BPTT, not the deliberately detached gradient.

For this scalar example, forward and backward work are O(T), with O(T) saved state. A practical truncated implementation can reduce stored history by processing chunks, but this audit does not claim that memory optimization. It uses exact rational arithmetic and bounded inputs; no automatic-differentiation library is required.

Truncation changes which dependencies can teach the weights

A detached boundary can preserve forward context while preventing a later error from directly updating earlier computations across that boundary. This can make training manageable, but the resulting gradient is generally not the full gradient of the original sequence loss. It need not guarantee a descent step for that full objective.

Cutting derivative history, resetting hidden values and performing an optimizer update are three separate operations. Different schedules can combine them differently. Record the chunk length, loss placement, boundary policy and update timing before comparing “truncated BPTT” implementations.

Long products can make gradients small or large; clipping addresses their magnitude under a chosen rule but does not restore paths removed by truncation. A shared gradient must be accumulated before applying an update, and a mean loss should not be divided by sequence length a second time.

BPTT is reverse-mode differentiation of an unfolded graph, not the only way to compute recurrent derivatives. Forward sensitivities provide an independent check here; other recurrent differentiation methods have different computational tradeoffs. The small loss reduction in this program does not establish performance on a sequence-learning task.

Which loss paths remain?

  1. What is the full gradient with respect to u in the three-step example?

Answer 1: 77/48.

  1. What happens to it when the derivative path is cut after time one?

Answer 2: It becomes 4/3, while forward states and the displayed loss remain unchanged.

  1. Does setting a cut automatically reset the numerical hidden state?

Answer 3: No. This program detaches the derivative path only.

  1. Which finite-difference objective should match the cut gradient?

Answer 4: The local surrogate with the cut boundary value frozen, rather than the original objective that recomputes that value after perturbing parameters.

The unrolled graph is the specification

The textbook supplies the reverse recurrence and summation over shared weights. The recurrent-gradient paper supplies the temporal-product analysis. Our exact three-step calculation, forward-sensitivity check, state-detachment surrogate and completed parameter update are original, with no reproduction of a source training benchmark.

Read RNNs for forward state carry, parameter sharing for accumulation and gradient clipping for magnitude control. Each addresses a different part of recurrent training.

Make a prediction, then check

What is the full gradient with respect to u in the example?

Choose one answer

Learning objectives

  • Accumulate local and future loss contributions over shared parameters.
  • Distinguish hidden-state values from detached derivative history.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Chapter 10: Sequence Modeling: Recurrent and Recursive Nets
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. On the difficulty of training recurrent neural networks
    Razvan Pascanu; Tomas Mikolov; Yoshua Bengio · 2013

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Recurrent state carry, full/cut BPTT and LSTM/GRU state Jacobians are checked against literal references, independent forward sensitivities, frozen-boundary surrogates and finite differences. RNN/GRU use NumPy1.26.4; BPTT/LSTM use the standard library.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

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