RNNs and LSTMs: reading one step at a time and passing memory on

Sentences, sound and sensor readings come in order, and you have to remember what came earlier to make sense of them. Put a plain RNN and an LSTM side by side and move the sliders to see how much of a signal from step 1 is left 20 steps later.

Short answer. An RNN (recurrent neural network) reads ordered data one step at a time and passes a summary of what it has read so far (the state) on to the next step: hₜ = tanh(W·hₜ₋₁ + U·xₜ + b). At every step it multiplies by the same kind of number again, so signals from the far past fade fast. An LSTM keeps a separate cell state and controls it with three gates (forget, input, output), which makes this problem much smaller: cₜ = fₜ·cₜ₋₁ + iₜ·gₜ.

The left side is a plain RNN whose state is a single number. Step 1 gets the input 1 and every other step gets 0. Each bar answers: "if you nudge the state at step 1, how many times that nudge shows up in the state at step t?" Training sends errors backward through the same product. The right side shows the same thing for an LSTM along the cell state path only, with the forget gate set to the same value f at every step. This is a scaled-down model. A real RNN state is a vector of hundreds of numbers and a matrix W takes the place of w. A real LSTM computes its forget gate again at every step from the input, and signals also travel by paths other than the cell state.

Definitions

The text below explains with diagrams and the lab. These are the textbook definitions. xt is the input at step t of the sequence, W and U are weight matrices, and b is a bias. ⊙ means multiplying entries in the same position (the same as · in the text).

recurrent neural network, hidden state
A neural network that reads a sequence one step at a time. From the hidden state ht−1 of the last step and the input xt of this step, it makes a new hidden state ht and passes it to the next step. Every step uses the same W, U and b, and the first state h0 is usually 0.

ht=tanh(Wht−1+Uxt+b)

backpropagation through time (BPTT)
A training method that unrolls a recurrent neural network over the steps of the sequence, treats it as a deep network that uses the same weights at every step, and runs backpropagation on it.
gate
A vector of values between 0 and 1 made with the sigmoid σ. It is multiplied, position by position, with another vector to decide how much passes through: 0 blocks and 1 lets everything through. The forget gate ft, input gate it and output gate ot of an LSTM are below, and each gate learns its own W, U and b.

σ(z)=11+e−z

ft=σ(Wfht−1+Ufxt+bf)

it=σ(Wiht−1+Uixt+bi)

ot=σ(Woht−1+Uoxt+bo)

LSTM, cell state (long short-term memory)
A recurrent neural network that keeps, apart from the hidden state ht, a memory passed to the next step called the cell state ct. The cell state keeps as much as the forget gate allows and adds the candidate value gt as much as the input gate allows. The hidden state is the cell state let out as much as the output gate allows.

gt=tanh(Wght−1+Ugxt+bg)

ct=ft⊙ct−1+it⊙gt

ht=ot⊙tanh(ct)

GRU (gated recurrent unit)
A recurrent neural network that cuts the gates to two, the update gate zt and the reset gate rt, and has no separate cell state. It mixes a new candidate nt, made with the reset gate, and the last state using the update gate (PyTorch nn.GRU notation).

ht=(1−zt)⊙nt+zt⊙ht−1

1. What an RNN is: read one step, pass the state on

A sentence is a row of words, sound is a row of readings taken a moment apart, and a stock price is a row of daily numbers. In data like this, order carries meaning. "The dog bit the man" and "The man bit the dog" use the same words to say different things. So you cannot look at each step on its own. You have to read while remembering what came before.

An RNN does this in the simplest way. It reads the row one step at a time and, at each step, updates a group of numbers called the state h. The state is "a summary of everything read so far". When a new step comes in, the RNN mixes the last state with the new input to make a new state, and passes that on to the next step.

hₜ = tanh(W·hₜ₋₁ + U·xₜ + b)

The key point is that every step uses the same W, U and b. So one network can read rows of any length, and the number of things to learn does not grow with the length. You can judge the whole row from the state after the last step (is it spam?), or use the state at each step to guess the next step (the next word). Training is the same as laying the row out step by step and running backpropagation, which is called backpropagation through time (BPTT).

The loop on the left is one cell with an arrow back to itself, and the right side lays it out as four steps. The green arrows W and the blue arrows U are the same weights at every step, and the loop cell shows the value of the current step. Press "Next" to compute one step at a time. The orange background marks the cell just computed, dashed cells are not computed yet, and the arithmetic is at the bottom. The numbers are the same as in section 2 (W = 1, U = 1, b = 0, input 1 at step 1 only, h₀ = 0). h₄ = 0.51 carries the section 2 table one step further. In the arithmetic the last step's value is written to three places, so working it by hand with that number gives the same result. The section 2 table is rounded to two places, and the computation uses the unrounded values. Pick a shape with the buttons above and the cells that get input (below) and output (above) arrows change.

2. By hand: three steps

Use the same numbers as the left side of the lab above. The state is one number, W = w = 1, U = 1 and b = 0. The input is 1 at step 1 and 0 after that, and the starting state is h₀ = 0.

  1. Step 1. h₁ = tanh(1·0 + 1·1) = tanh(1) = 0.76.
  2. Step 2. The input is 0, so only the last state goes in. h₂ = tanh(1·0.76) = 0.64.
  3. Step 3. h₃ = tanh(0.64) = 0.57.
  4. How much of step 1 reaches step 2. Nudge h₁ a little and h₂ moves by w × (slope of tanh) = w × (1 − h₂²) = 1 × (1 − 0.64²) = 0.59 times as much.
  5. On to step 3. Multiply once more. 1 × (1 − 0.57²) = 0.68, and 0.59 × 0.68 = 0.40.
Step t123
State hₜ0.760.640.57
Factor at this step, w × (1 − hₜ²)−0.590.68
Share of the step 1 signal left10.590.40

Every step multiplies by a number smaller than 1. Stack 20 of them and you get the 0.04 in the lab.

3. Why it forgets the far past: the same multiplication, over and over

To get from step 1 to step t, the signal is multiplied by w × (1 − hₖ²) once per step, t − 1 times in all. Going the other way, when training sends the error at step t back to step 1, it goes through the same product. Multiply by numbers of the same size many times and this happens:

The full story and other fixes are on the vanishing gradients page.

Try this. ① At the start (w = 1), 0.04 is left at step 20. ② Lower w to 0.5 and it is 1.6e−6, that is 0.0000016. ③ Raise w to 2 and you might expect more to be left, but it drops to 4.1e−15. The state moves toward 1 (h₂ = 0.91, h₃ = 0.95), so the slope of tanh gets small. If you step w by 0.1, w = 1 leaves the most, and that is still only 0.04. ④ On the right, the LSTM keeps 0.14 at f = 0.9, 0.38 at 0.95 and 0.83 at 0.99, and with f = 1 the full 1 stays. With w or f at 0, both drop to 0 from step 2.

4. LSTM: building the cell state formula

An LSTM (long short-term memory) splits the state in two: hₜ, which it shows to the outside, and the cell state cₜ, which it keeps inside and passes to the next step. Think of the cell state as a belt that carries memory. Three gates decide what to wipe from the belt and what to add. A gate is a number between 0 and 1 that you multiply by to decide "how much gets through". 0 blocks everything and 1 lets everything through.

Every gate is computed the same way: gate = σ(w·hₜ₋₁ + u·xₜ + b). σ (the sigmoid) turns any number into a number between 0 and 1, and each gate learns its own w, u and b. Below is a small fixed example: last state hₜ₋₁ = 0.5, input xₜ = 1, last cell state cₜ₋₁ = 2.

Whatw, u, bSum inside the bracketsValue
Forget gate fₜ1, 0.5, 01·0.5 + 0.5·1 + 0 = 1σ(1) = 0.73
Input gate iₜ0, 1, −10·0.5 + 1·1 − 1 = 0σ(0) = 0.5
Candidate gₜ2, 1, 02·0.5 + 1·1 + 0 = 2tanh(2) = 0.96
Output gate oₜ0, −1, 00·0.5 − 1·1 + 0 = −1σ(−1) = 0.27

The candidate gₜ is not a gate. It is "the new content to put in", so it uses tanh instead of σ and gives a value between −1 and 1.

Press "Next" to go one step at a time. A piece is added to the formula (the orange background marks the new piece), an arrow shows where a value goes along with the arithmetic, the bars change by that much, and the reason appears below. Faded gray is the last step, green is what was kept, the orange dashed box is what was removed, blue is what was added (the blue dashed box below is the place the new information left), and purple is hₜ, the value that goes out.

  1. Pass it on as is: cₜ = cₜ₋₁. The 2 goes through untouched. Nothing multiplies it, so it would not shrink over any number of steps. The plain RNN forgets because it multiplies at every step, so this is a good place to start. But this way the cell can never wipe anything or add anything.
  2. Take some away with the forget gate: cₜ = fₜ·cₜ₋₁. 0.73 × 2 = 1.46 stays and 0.54 is wiped. Why: memory that is no longer useful has to go to make room for new things. How much to wipe is decided by fₜ, at every step, from the input.
  3. Add new information through the input gate: cₜ = fₜ·cₜ₋₁ + iₜ·gₜ. Add 0.5 × 0.96 = 0.48 to get 1.46 + 0.48 = 1.94. Why: the new content gₜ does not all go in, only as much as the input gate iₜ allows. And because the new content is added, the only thing that multiplies the old memory is fₜ. The plain RNN multiplied by W and went through tanh at every step. On the cell state path, only fₜ multiplies. When fₜ is close to 1, the memory barely shrinks over many steps. That is the right side of the lab.
  4. Read it out through the output gate: hₜ = oₜ·tanh(cₜ). tanh(1.94) = 0.96, and 0.27 × 0.96 = 0.26. Why: there is no need to show everything you remember right now. The cell state passes 1.94 to the next step as is, while the outside (the next layer and the gates at the next step) only sees 0.26.

In a real LSTM, h, c and x are vectors, w and u are matrices, and the · with a gate means multiplying entry by entry. The formulas have the same shape as in the PyTorch nn.LSTM docs (see sources).

Try this. ① Press "Next" once and the middle bar splits into green 1.46 and an orange dashed 0.54. ② Press it again and blue 0.48 is added, for 1.94. That is a little less than the old 2, because the 0.54 removed is more than the 0.48 added. ③ In the last step the cell state is 1.94, but only 0.26 goes out, because the output gate is a small 0.27.

5. The three gates and the GRU at a glance

NameFormulaWhat it does
Forget gatefₜ = σ(W_f·hₜ₋₁ + U_f·xₜ + b_f)How much of the last cell state to keep
Input gateiₜ = σ(W_i·hₜ₋₁ + U_i·xₜ + b_i)How much new content to put in
Candidategₜ = tanh(W_g·hₜ₋₁ + U_g·xₜ + b_g)The new content
Output gateoₜ = σ(W_o·hₜ₋₁ + U_o·xₜ + b_o)How much of the cell state to show outside
Cell statecₜ = fₜ·cₜ₋₁ + iₜ·gₜThe memory passed to the next step
Output statehₜ = oₜ·tanh(cₜ)What the next layer and the next step see

A GRU (gated recurrent unit) cuts the gates down to two (update gate zₜ, reset gate rₜ) and has no separate cell state. It mixes a new candidate nₜ with the last state using the update gate: hₜ = (1 − zₜ)·nₜ + zₜ·hₜ₋₁ (as written in the PyTorch nn.GRU docs).

× + × × σ σ tanh σ tanh cₜ₋₁ = 2 cₜ = 1.94 1.46 0.48 fₜ = 0.73 iₜ = 0.5 gₜ = 0.96 oₜ = 0.27 0.96 hₜ = 0.26 hₜ₋₁ = 0.5 xₜ = 1
One LSTM cell (the numbers from section 4). The green band at the top is the path of the cell state cₜ. The only thing that multiplies on this path is the forget gate fₜ at the first × node, and iₜ·gₜ is added at the + node. On the band, 1.46 is fₜ·cₜ₋₁ and 0.48 is iₜ·gₜ. Below, hₜ₋₁ and xₜ split four ways into three σ gates (forget fₜ, input iₜ, output oₜ) and the tanh of the candidate gₜ. The 0.96 next to the tanh that hangs from the band is tanh(cₜ), and hₜ, that times oₜ, goes out.
× + × σ σ tanh 1 − hₜ₋₁ hₜ zₜ·hₜ₋₁ (1 − zₜ)·nₜ zₜ 1 − zₜ rₜ nₜ xₜ
One GRU cell. Drawn in the same frame as the LSTM. There is no separate cell state, so the green band at the top is the state h itself, and hₜ₋₁ also goes down into the branches. The one update gate zₜ sets both how much of the last state to keep (zₜ) and how much of the new candidate nₜ to put in (1 − zₜ): hₜ = (1 − zₜ)·nₜ + zₜ·hₜ₋₁. The reset gate rₜ goes into the tanh that makes the candidate nₜ (as in the PyTorch nn.GRU formulas). The page has no worked numbers for the GRU, so none are shown.

6. Properties worth knowing

PropertyIn plain wordsIn the lab
Same weights at every stepOne network reads rows of any length. The number of things to learn does not grow with the lengthThe same w for all 20 steps
The state has a fixed sizeAny row, however long, is summed up in one state of the same size. Memory use stays flat, but how much it can hold is limitedThe state is one number
Steps are computed in orderStep t needs the state from step t − 1 first. The steps in one row cannot be computed at the same timeThe bars are computed one by one from the left
Repeated multiplicationSignals and gradients from far steps shrink or grow as a productThe shrinking bars on the left
The LSTM cell state path only multiplies by fₜWith a forget gate close to 1, memory lasts long. The gate values are learnedThe bars on the right

7. Turning one row into another: the encoder and the decoder

In translation the input row and the output row differ in length, and the words come in a different order. Giving one answer per step cannot solve it. So two RNNs are joined.

encoder jesuisétudiant summary state Iamastudent〈end〉 decoder
Encoder and decoder. The encoder reads the input row one step at a time and passes on its last state (the green box, the summary state). The decoder takes that as its first state and writes the output row one step at a time.

This setup is called seq2seq (sequence to sequence). In 2014 one paper built it from two LSTMs and another from two GRUs (see sources). During training, even when the decoder writes a wrong word, the correct word is fed in at the next step, so one early mistake does not throw off everything after it.

The weak point is the single summary state. A sentence of five words and one of fifty have to fit in the same bundle of numbers, and the decoder writes from that alone. Another 2014 paper (see sources) saw this fixed-length vector as a bottleneck and let the decoder, each time it writes a word, look through all the states the encoder left at every step for the part it needs now. This is where attention began, and the next section looks at it closely. The move after that was to drop the RNN and keep only attention: the transformer (section 9).

The words encoder and decoder are not only for RNNs. The side that turns an input into a bundle of numbers is the encoder, and the side that produces an output from a bundle of numbers is the decoder. The same words appear in many models.

WhereWhat the encoder doesWhat the decoder does
seq2seq (this section)Reads the input sentence into a stateWrites the output sentence from that state
Autoencoders and VAEsShrinks the data to a few numbersRebuilds the data from those numbers
TransformerEvery input step looks at the others and builds a representation per stepLooks at what it has written and at the encoder output, and gives the next word
Language modelsEncoder-only models (BERT style): read text and judge itDecoder-only models (GPT style): continue text
Image segmentation (U-Net)Shrinks the image step by step to gather what is in itGrows it back to answer where, pixel by pixel

8. Adding attention to the encoder and decoder

The decoder in section 7 writes from the encoder's last state alone, however long the source is. Squeezing the whole source into one vector is the bottleneck (Bahdanau et al., see sources). Attention lets the decoder, each time it writes a word, look again at all the states the encoder left at every step. What follows is the global attention of Luong et al. (see sources). Global means it always attends to all source words. The name contrasts it with local attention, which only looks at a subset of source words at a time.

Each time the decoder writes word t, it does four things.

  1. Scores. It matches the current decoder state hₜ against every encoder state h̄ₛ, one by one, and gets a score. The simplest score is the dot product.
  2. Weights. Softmax turns the scores into alignment weights aₜ that add up to 1.
  3. Context vector. It mixes the encoder states by those weights (a weighted average) into the context vector cₜ.
  4. Word. It joins cₜ and hₜ into h̃ₜ, and from h̃ₜ gives the probability of the word yₜ.

For the next word the decoder state has changed, so it starts again from ①. The weights are chosen anew for every word.

score(hₜ, h̄ₛ) = hₜᵀ h̄ₛ
aₜ(s) = exp(score(hₜ, h̄ₛ)) ÷ Σₛ′ exp(score(hₜ, h̄ₛ′))
cₜ = Σₛ aₜ(s)·h̄ₛ
h̃ₜ = tanh(W_c [cₜ ; hₜ])
p(yₜ | y<t, x) = softmax(W_s h̃ₜ)
attention layer yₜ cₜ h̃ₜ aₜ hₜ encoder states h̄ₛ decoder
Global attention. Blue is the encoder states h̄ₛ, red the decoder states. The alignment weights aₜ come from the encoder cells (dashed lines) and the current decoder state hₜ (red line). The darker a small box, the larger the weight. The encoder cells are mixed by those weights and gather at the context vector cₜ (solid lines). In the attention layer, cₜ and hₜ combine into h̃ₜ, and the word yₜ comes out of it. The same structure as the figure in Luong et al. (see sources), drawn anew.

In the words of the attention page, it maps like this. The order of the computation (dot product → softmax → mix) is the same as section 3 there.

This sectionAttention pageWhat it does
Decoder state hₜQuery qWhat we are looking for now
Encoder state h̄ₛKey k and value vThe label to match against and the content to mix. Here the same vector plays both parts
Alignment weights aₜWeights (③ softmax)How much to use each source step
Context vector cₜThe mix (④ new vector)The information mixed by the weights

The difference is that the attention page makes q, k and v separately with different matrices and divides the dot product by √d. Dropping the RNN from this attention and keeping only attention gives the transformer (section 9).

The lab below is a made-up short translation from Korean: 나는 어제 사과를 먹었다 (word by word: I, yesterday, apples, ate) → I ate apples yesterday. Korean puts the verb at the end and English right after the subject, so the matching source step does not move along in order. The encoder and decoder states are made-up vectors of two numbers. Real states come from training and have hundreds of numbers. W_c and W_s are not learned here, so the word in ④ is the translation fixed in advance. The scores, weights and context vectors are really computed from these values.

Each press of Next moves through four steps per output word: ① scores ② weights ③ context vector ④ word. Blue cells are the source words and encoder states, red cells the decoder states (a dashed border means not reached yet). Red arrows go from the current decoder cell to the source cells (① number = score, ② thickness and number = weight). Blue arrows are the source cells gathering into the context vector in the green box by their weights (③), and black arrows take cₜ together with hₜ to the word (④). In the alignment table below, darker cells mean larger weights, and the red border marks the current word's row.

Try this. ① Press Next once to see the weights for I: 나는 0.76, 어제 0.17, 사과를 0.01, 먹었다 0.06. ② Press four more times: among the scores for ate, 먹었다 is the largest at 2. Press once more and the weights are 먹었다 0.7, 사과를 0.26. The attention jumps to the fourth source step. ③ The context vector leans toward the state with the largest weight: c₁ = (1.48, 0.21) leans toward 나는 at (2, 0), and c₂ = (−0.44, −1.37) toward 먹었다 at (0, −2). ④ At the end of all 16 steps, the darkest cells in the alignment table are I–나는, ate–먹었다, apples–사과를, yesterday–어제: crossed, not a diagonal.

9. Why transformers took over, and where RNNs are still used

The transformer paper (see sources) compares itself with RNNs in section 4 and points out two things.

In return, a transformer looks at every pair of steps, so its compute and memory grow with the square of the length, and it needs position information added separately to know the order (transformer).

RNNs and LSTMs are still used when data comes in one step at a time and has to be handled right away. The model only holds one state and waits for the next step, so the compute and memory per step stay the same however long the row gets. Live sensor readings, small sound and signal processing on a device, and time series forecasts where a small model is enough are cases like this.

10. When to use what

OptionGoodBadUse it for
Plain RNNThe simplest and smallest. Compute and memory per step are fixedForgets the past fast (vanishing and exploding gradients). Computes steps in order onlyShort rows where only the last few steps matter, learning the idea
LSTM · GRUThe gates let it hold on to a much longer past than a plain RNN. Fixed compute and memory per step, so it can handle data that never stops comingComputes steps in order, so training on long rows is slow. Very long distances are still hardLive signals and sensor readings, small devices, time series where a small model is enough
TransformerComputes all steps at once, so training is fast. Links any two steps directlyCompute and memory grow with the square of the length. Needs position information addedLong text, translation, language models: when far context matters and there is a lot of data
1D convolutionSlides a filter that finds patterns in a few nearby steps over every position at once. FastOne layer only sees as far as the filter width, so seeing far needs more layers or skipping stepsFinding short patterns in sound waves, sensor signals and character rows (convolution)

Where it is used

Frequently asked questions

Does an LSTM get rid of vanishing gradients completely?

No. On the cell state path the only thing that multiplies the memory is the forget gate, so a forget gate close to 1 keeps things for a long time. But even with a forget gate of 0.9, only 0.14 is left after 20 steps, and the other paths through the gates still shrink. It means an LSTM holds on to a much longer past than a plain RNN, not that it remembers no matter how far back.

Should I use an LSTM or a GRU?

A GRU has two gates, so at the same size it has three quarters of the learned numbers of an LSTM and runs a little lighter. Which one works better depends on the task and the data. The safe way is to try both and pick by the score on validation data.

We have transformers. Do I still need to know RNNs?

Yes. Reading while passing a state on, reusing the same weights at every step, and gradients fading when many factors are multiplied are the basic ideas for ordered data, and you need them to see what transformers fixed. RNNs are also still used where data arrives one step at a time and must be handled with a fixed amount of memory.

How is attention in an RNN different from attention in a transformer?

The skeleton is the same: compute scores, turn them into weights that add up to 1 with softmax, and mix by those weights. There are three differences. First, here the decoder RNN's state is the query and the encoder states are both the keys and the values, while a transformer multiplies each word vector by three different matrices to make separate queries, keys and values. Second, the dot score used here is the plain dot product, while a transformer divides the dot product by √d. Third, here an RNN reads the steps in order to build the states and attention sits on top, while a transformer drops the RNN and links the steps with attention alone.

Words

Words used hereWhat books call it
Ordered data, a rowSequence, time series
StepTime step t
State hₜHidden state
A network that reads one step at a time and passes a state onRecurrent neural network (RNN)
Laying the loop out in timeUnrolling (unfolding in time)
Input and output shape (many → one, one → many, many → many)Many-to-one, one-to-many, many-to-many
Recurrent ratio, the weight W on the last stateRecurrent weight
Backpropagation back across the stepsBackpropagation through time (BPTT)
Gradients fading, gradients blowing upVanishing gradient, exploding gradient
Putting a cap on the gradient sizeGradient clipping
GateGate
Forget gate, input gate, output gateForget gate, input gate, output gate
Cell state cₜCell state, memory cell
Candidate gₜCandidate cell state. The PyTorch docs call it the cell gate
σSigmoid
The variant with two gatesGated recurrent unit (GRU), with an update gate and a reset gate
Reading one row and writing anotherEncoder-decoder, seq2seq (sequence to sequence)
Summary state, cₜ in section 8Context vector. Section 7 uses one to the end; with attention a new one is built for every word
Alignment weights aₜAlignment weights
Attention that always looks at the whole sourceGlobal attention. The kind that looks at only part of it at a time is local attention
Feeding the decoder the correct word during trainingTeacher forcing
1D convolution1D convolution, temporal convolution

Sources

← Image segmentationVideo classification: convolution with a time axis →