Skip to the content

fatehi.devx2Learning

Deep learning

Recurrent networks

A network that reads a sequence one element at a time, carrying a state from each step to the next, with the same weights at every step.

A network for sequences

Many inputs are sequences: the words of a sentence, the samples of a sound, the prices of a market, the letters of a gene. Their length varies, and their meaning depends on order: “dog bites man” is not “man bites dog”. A plain neural network takes an input of fixed size. A recurrent network takes a sequence of any length by reading it one element at a time and carrying a summary from each step to the next.

The summary is a vector called the state, h. At every step the network takes two things, the next element of the sequence, xt, and the state it had after the step before, ht−1, and computes a new state from them. It uses the same weights at every step, so one small network, the cell, reads a sequence of any length. The state after the last element summarises the whole sequence, and the state at each step can also be turned into an output, such as a guess of the next word.

ht=tanh(Wxxt+Whht−1+b),yt=Wyht

xt is the input at step t, a vector of length din; ht the state after it, a vector of length d, with h0 = 0 before the first step; Wx a matrix of shape (d, din) and Wh one of shape (d, d), b a vector of length d; yt the output at step t, made from the state by a third matrix Wy. Multiply the input and the old state each by its matrix (vectors and matrices), add them and the bias, and squash every number of the sum into the range −1 to 1 with tanh (activation functions). The same Wx, Wh, b and Wy serve every step.

A worked example

Take the smallest possible network: a state of one number, the weights wx = 1 and wh = 0.5, no bias, and the input sequence 1, 0, 0, −1. The state starts at 0.

  • Step 1: 1 × 1 + 0.5 × 0 = 1, and tanh(1) = 0.7616.
  • Step 2: the input is 0, so only the old state counts: 0.5 × 0.7616 = 0.3808, and tanh(0.3808) = 0.3634.
  • Step 3: 0.5 × 0.3634 = 0.1817, and tanh(0.1817) = 0.1797.
  • Step 4: −1 + 0.5 × 0.1797 = −0.9101, and tanh(−0.9101) = −0.7212.

The state is the network’s memory. The first input, 1, still shows in the third state, but only as 0.18: each step passes half of the old state on, a little less after the tanh, so the memory of an input fades by about half per step. The fourth input, −1, overwrites what was left.

A recurrent network drawn two ways. Folded, it is one cell whose state loops back into it. Unrolled over the four steps of the example, it is a chain of copies of that cell, all sharing the same weights W, each taking one input and the state from the copy before it.

Training: backpropagation through time

A recurrent network is trained like any network, by gradient descent: the outputs are compared with the right answers, and every weight is moved a little in the direction that makes the error smaller. To find those directions, the network is unrolled, as in the figure, into one long chain with a copy of the cell per step. The chain rule then carries the error back through the chain, step by step from the last copy to the first, and since all copies share the same weights, each weight’s gradient is the sum of its gradients in all copies. This is called backpropagation through time.

One training step of a recurrent network, unrolled over four steps. Forward, the copies make their states one after another, and the last one gives a probability to each possible answer: the loss block marks the right one, and its loss is −ln p of the probability p the network gave it. Backward, the gradient (violet) runs from the loss through the copies, last to first. Each copy adds its share of the weights’ gradient to one bus, since all copies share the same W, and the optimiser scales the sum by the learning rate and rewrites W.

Going back one step, the gradient is multiplied by the derivative of one step with respect to the state before it: Wh, scaled by the slope of the tanh, 1 − h2, which lies between 0 and 1 (the Jacobian of the step). In the example this factor is 0.5 × (1 − h2), at most 0.5, so the effect of the first input on the state shrinks by at least half per step: from 0.42 on the first state to 0.18 on the second, 0.088 on the third and 0.011 on the sixth.

Why long sequences are hard

A gradient that travels back k steps has been multiplied by k such factors. If they are mostly smaller than 1, it shrinks exponentially, like 0.520 ≈ 10−6: the network gets almost no signal to connect an output with an input twenty steps earlier, so it never learns such links. This is the vanishing gradient. If the factors are mostly larger than 1, the gradient grows exponentially, like 1.520 ≈ 3,300: training steps become huge and the weights jump about. This is the exploding gradient. Which of the two happens depends on how large Wh is, in particular on its eigenvalues, and on how often the tanh is near its flat ends.

A recurrent network with 32 numbers of state and random weights of four sizes (the gain), run over 60 random inputs. The gradient of its last state is carried back step by step, and its size is drawn against how many steps back it has gone, on a logarithmic scale; the points of light flow back in time along each curve. Small weights forget within a few steps; large ones blow the gradient up; only a narrow band in between carries it far. Computed in your browser, as in the cell below.

Exploding gradients are easy to tame: if a gradient is too large, it is scaled down before the step (gradient clipping). Vanishing gradients are the harder problem, because a missing signal cannot be scaled up. Averaged over the five random networks of the cell below, the gradient 20 steps back is about 5 × 10−6 of its size at the end for a gain of 0.6, and 0.018 for a gain of 1; near a gain of 1 it varies much from one random network to another.

Gates: the LSTM and the GRU

The usual cure is a cell with gates. The long short-term memory, LSTM (Hochreiter and Schmidhuber, 1997), keeps a second vector, the cell memory c, beside the state. At each step three gates, each a vector of numbers between 0 and 1 computed from the input and the state, decide how much of the memory to keep (the forget gate), how much new content to write into it (the input gate) and how much of it to show as the state (the output gate). The memory is updated by addition: ct = ft ⊙ ct−1 + it ⊙ (new content), where ⊙ multiplies two vectors number by number. While the forget gate stays near 1, the memory and its gradient pass through a step almost unchanged, so information and gradients can travel hundreds of steps. The gated recurrent unit, GRU (Cho and colleagues, 2014), does much the same with two gates and no separate memory.

Through the 2010s, until 2017, LSTMs and GRUs were the standard networks for sequences: speech recognition, handwriting, language models and machine translation all used them.

What recurrence costs

Gates fix the gradient, but not the order of work. The state at step t needs the state at step t − 1, so the steps of one sequence must be computed one after another, however many processors are available; a graphics processor, built to do thousands of operations at once, waits for each step. And whatever the network remembers about an early element must survive in the state through every step in between. Both limits grow with the length of the sequence. Attention removes them by letting each position read every other position directly, and state space models keep a recurrence but one that can be computed in parallel.

Try it

The cell first repeats the worked example, then builds a network with 32 numbers of state and carries the gradient of its last state back through 60 steps, for four sizes of the weights, as in the figure. Change the gain or the length and run it again.

Python starts loading once the page is ready.

KEYMAP
How the code on this page runs

A recurrent network and its memory

Cell 1: A recurrent network and its memory

Test yourself

  1. A recurrent network has a state of 128 numbers and reads inputs of 50 numbers. What are the shapes of Wx and Wh, and does it need more weights for a longer sequence?

    Wx is 128 × 50 and Wh is 128 × 128. The same weights serve every step, so a longer sequence needs no more weights, only more steps.

  2. In the worked example, what would the fourth state be if the fourth input were 0 instead of −1?

    tanh(0.5 × 0.1797) = tanh(0.0899) ≈ 0.0896: the memory of the first input would simply keep fading.

  3. Why does the gradient vanish over many steps, and why do the LSTM’s gates help?

    Each step back multiplies the gradient by Wh times the slope of the tanh; if these factors are mostly below 1, the product shrinks exponentially with the number of steps. The LSTM updates its memory by addition, scaled by the forget gate: where that gate is near 1, a step passes the memory and its gradient on almost unchanged.

  4. A computer has a thousand processors. Can it compute the states of one 1,000-word sentence of a recurrent network in one step?

    No. Each state needs the one before it, so the 1,000 states take 1,000 steps in order; the processors can only share the work inside each step, or work on other sentences at the same time.

Where it leads

Kept in this browser only, never sent.

Paths through it