Deep learning and neural networksLoading progress…

Vanishing and exploding memory

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

Long products shrink or blow up

A long product of the same factor does one of three things: if the factor is below 1 the result decays toward zero (vanishing), if it is above 1 it grows enormously (exploding), and only a factor close to 1 keeps it steady. For matrices the same story is told by the largest scale the matrix stretches vectors by.

factor per step0.5steps10
0.5^10 = 9.766e-4 (vanished)

Bars show the size of the signal after each step (log-compressed, capped for display).

gradient length50
gradient [30, 40] has length 50 clipped to length 5: [3, 4] (direction unchanged)
Pick a factor and a number of steps. Below: what gradient clipping does to a huge gradient.

The worked example: with a = 0.5, an impulse [1, 0, 0] gives states [1, 0.5, 0.25]. After ten further multiplications its share is 0.5¹⁰ = 0.0009765625, about a thousandth.

Predict first. What is ten repeated factors of 0.5?

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.