Deep learning and neural networksLoading progress…

Unrolling and backpropagation

Trace a recurrent state and explain memory loss, gating, sequence-to-sequence models and attention.

Unrolling shows the repeated use

To train a recurrent network, unroll it: draw one copy of the cell per time step, all sharing the same weights. The result is an ordinary deep network, and backpropagation works on it as before. Two rules follow.

  • A gradient travelling back along the states is multiplied by the local sensitivity of each step.
  • A weight used at every step collects a gradient contribution from every step, and these are added.

For the one-number recurrence with loss equal to the last state h_T, the gradient reaching the input at step k is exactly a^(T−k): the weight multiplied in once per step in between.

weight a0.8steps T8
inputdloss/dx_k = a^(T−k)
x_10.2097
x_20.2621
x_30.3277
x_40.4096
x_50.512
x_60.64
x_70.8
x_81

The loss is the last state. The gradient reaching x_1 passes through T−1 copies of the same weight, so its size is a^(T−1). The gradient on the shared weight itself is the sum of one term per use.

Move a and T. Early inputs get tiny gradients when a is below 1.

Predict first. Why can an early input have a tiny gradient?

Chapter context

A sequence model processes ordered observations. A recurrent state summarizes previous inputs, creating both a mechanism for memory and a long differentiation path whose sensitivity can decay or grow.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

A simple recurrence is ht=ϕ(Whht−1+Wxxt+b)h_t=\phi(W_hh_{t-1}+W_xx_t+b). In a scalar linear example ht=aht−1+xth_t=a h_{t-1}+x_t, sensitivity to the initial state is

∂hT∂h0=aT.\frac{\partial h_T}{\partial h_0}=a^T.

This illustrates gradient decay or growth; nonlinear multidimensional RNNs have Jacobian products instead.

Worked example

Set a=0.5 and h0=0. Input [1,0,0] produces states [1,0.5,0.25]. The initial impulse is still present but attenuated. Over ten subsequent multiplicative transitions, its factor is 0.5^10=0.0009765625.

Reference code

The following example uses the Python standard library and does not call a remote service.

state, states = 0.,[]
for x in [1,0,0]:
    state=.5*state+x
    states.append(state)
assert states == [1,.5,.25]
assert .5**10 == .0009765625

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

A recurrent model shares weights through time. Longer hidden vectors do not automatically prevent gradient decay. Training history and generated inference history can differ.