Simple Algorithm
Deep Learning · Activation · 17 min

Recurrent Networks & Sequence Models

Networks with memory: recurrence, gating and the state space models that rival attention.

Words arrive one at a time, speech is a pressure wave sampled thousands of times a second, and a heart monitor never stops streaming. A recurrent network reads such data the way you read a sentence: one piece after another, carrying a running memory forward. This lesson builds that memory, shows why it fades, and follows the ideas that repaired it: gates, attention and state space models.

What you’ll learn

  • Explain why sequences (variable length, meaningful order) fit a fixed-size network badly, and how a recurrent network reuses one set of weights at every step.
  • Describe how a recurrent network is trained by backpropagation through time, and why its gradient vanishes or explodes over long spans.
  • Explain how the gates of LSTMs and GRUs let memories and gradients survive many steps.
  • Describe the encoder–decoder model, the attention mechanism that removed its bottleneck, and how state space models run like recurrent networks yet train in parallel.

Data that comes in order

Much of the world's data is a sequence: a sentence is a sequence of tokens (words or pieces of words), recorded speech is a sequence of air-pressure samples (16,000 per second is common for speech recognition), a fitness tracker logs your pulse every few seconds, and a genome is a sequence of the letters A, C, G and T. A sequence model is a network built for such data. Two properties set sequences apart from the fixed-size inputs of an MLP:

  • The length varies. A review can have five words or five hundred.
  • Order carries meaning. "Dog bites man" and "man bites dog" contain the same words and report different events.

Why not pad every sentence to a maximum length and feed it to an ordinary network all at once? Three problems appear. The network needs separate weights for "a word in position 3" and "a word in position 7", so a pattern it learns in one place does not carry over to another. Anything longer than the maximum does not fit. And the number of weights grows with the maximum length, even though the rules of language do not change from position to position.

Think first A bag-of-words model counts how often each word appears and ignores the order. Which sentences can it never tell apart?

Any two sentences made of the same words in a different order: "dog bites man" and "man bites dog" have identical counts, and so do "not bad, actually good" and "not good, actually bad". Order is information, and a model of sequences has to use it.

A network with a memory

A recurrent neural network (RNN) reads one element xt\mathbf x_t at a time and keeps a hidden state ht\mathbf h_t, a vector that summarizes what it has read so far. At every step it combines the previous state with the new input through the same small layer:

ht=tanh⁡(Wht−1+Uxt+b),t=1,2,…,T,h0=0\mathbf h_t=\tanh\big(W\mathbf h_{t-1}+U\mathbf x_t+\mathbf b\big),\qquad t=1,2,\dots,T,\qquad \mathbf h_0=\mathbf 0
WW mixes in the old memory, UU brings in the new input and b\mathbf b is a bias. The tanh squashes every entry into the range (−1,1)(-1,1). The same WW, UU and b\mathbf b are used at every step: this is weight sharing across time.

Draw the network once per time step and you get its unrolled form: a deep feed-forward network with one layer per step, all layers sharing the same weights. Because the weights do not depend on tt, the network can read a sequence of any length, and a pattern learned at one position applies at every other.

Jeffrey Elman's "simple recurrent network" (Elman, 1990) had exactly this shape. Trained only to predict the next word of short sentences, its hidden states for different words clustered into groups such as nouns and verbs, and animate and inanimate nouns, although no one had told it those categories existed.

OutputExampleHow the RNN is used
One output at the endIs this review positive?Read the whole sequence, then classify the final state hT\mathbf h_T
One output per stepPredict the next character; tag each word as noun, verb…Read out a prediction from every state ht\mathbf h_t
A new sequence of a different lengthTranslate a sentenceAn encoder reads, a decoder writes (later in this lesson)
Check your understanding

An RNN has a 100-dimensional hidden state and reads 50-dimensional inputs, so WW is 100×100100\times100, UU is 100×50100\times50 and b\mathbf b has 100 entries. How many of these parameters does it need to read a 1,000-step sequence, compared with a 10-step one?

  1. 100 times as many for the long sequence, since every step needs its own weights
  2. The same 15,100 for both, because WW, UU and b\mathbf b are reused at every step
  3. 15,100 per step: 151,000 for 10 steps and 15.1 million for 1,000
  4. None for the long sequence: it is too long for a 100-dimensional state
Show the answer

B. The same 15,100 for both, because WW, UU and b\mathbf b are reused at every step

100×100+100×50+100=15,100100\times100+100\times50+100=15{,}100 numbers, whatever the length. Weight sharing is what lets one RNN read sequences of any length. What does grow with the length is the work: one layer's worth of computation per step.

Learning through time, and why it fails

To train an RNN, unroll it over a training sequence, add up its losses at every step (for example the cross-entropy of each next-word prediction), and run backpropagation through the unrolled graph. This is backpropagation through time (BPTT), worked out by Paul Werbos (1990) among others. Because the weights are shared, each weight's gradient is a sum of contributions from every step.

Now suppose the output at step 50 depends on the input at step 1. To learn that, the error signal must travel back through 49 steps, and at each step it is multiplied by the network's local sensitivity: the recurrent weights times the slope of tanh. Multiply 49 numbers smaller than one and almost nothing is left: a vanishing gradient. Multiply numbers larger than one and the signal blows up: an exploding gradient. Sepp Hochreiter analyzed this in his 1991 diploma thesis, and Bengio, Simard & Frasconi (1994) showed why it makes long-range dependencies hard to learn with gradient descent.

Predict before you look

Suppose each step backward multiplies the error signal by 0.90.9. After how many steps has it fallen below 1% of its starting size?

Show the answer

44

You need 0.9k<0.010.9^k<0.01, that is k>ln⁡0.01/ln⁡0.9≈43.7k>\ln0.01/\ln0.9\approx43.7, so 44 steps. A factor that looks harmless, losing 10% per step, wipes out the signal within a few dozen steps. A factor of 1.11.1 does the opposite: after 50 steps the signal is 1.150≈1171.1^{50}\approx117 times larger.

Gates: deciding what to keep

The long short-term memory (LSTM) network of Hochreiter & Schmidhuber (1997) adds a second memory, the cell state ct\mathbf c_t, which is updated by addition rather than by passing through a squashing layer. Access to it is controlled by gates: small layers with sigmoid outputs between 0 and 1 that multiply other signals entry by entry.

  • The forget gate ft\mathbf f_t decides how much of the old memory to keep.
  • The input gate it\mathbf i_t decides how much new content to write.
  • The output gate ot\mathbf o_t decides how much of the memory to reveal in ht\mathbf h_t.
ct=ft⊙ct−1+it⊙gt,ht=ot⊙tanh⁡(ct)\mathbf c_t=\mathbf f_t\odot\mathbf c_{t-1}+\mathbf i_t\odot\mathbf g_t,\qquad \mathbf h_t=\mathbf o_t\odot\tanh(\mathbf c_t)
⊙\odot multiplies entry by entry, and gt\mathbf g_t is the candidate content, a tanh layer of the input and the previous state. A forget gate near 1 keeps the memory; an input gate near 0 ignores the current input. (The forget gate was added by Gers, Schmidhuber & Cummins in 2000.)

Why does this rescue the gradient? Along the cell's memory lane, one step backward multiplies the error signal by the forget gate ft\mathbf f_t, numbers the network chooses, instead of by a weight matrix and a tanh slope. When the forget gates sit near 1, the signal survives for many steps. The gated recurrent unit (GRU; Cho et al., 2014) is a leaner variant with two gates and no separate cell: its update gate decides how much of the old state to keep at each step.

Predict before you look

A forget gate holds steady at 0.990.99 and nothing new is written. What percentage of the cell's memory is left after 100 steps?

Show the answer

37 %

0.99100≈0.3660.99^{100}\approx0.366, about 37%, close to 1/e1/e. A gate at ff keeps a memory for roughly 1/(1−f)1/(1-f) steps: 100 steps at f=0.99f=0.99, but only about 2 steps at f=0.5f=0.5, where 10 steps leave 0.510≈0.1%0.5^{10}\approx0.1\%. That is why the bias of the forget gate matters so much.

From translation to attention

Some tasks turn one sequence into another of a different length: translating a sentence, summarizing an article, transcribing speech. The encoder–decoder, or sequence-to-sequence, model (Sutskever, Vinyals & Le, 2014; Cho et al., 2014) splits the job between two RNNs. The encoder reads the source sentence and hands its final hidden state to the decoder, which writes the output one token at a time, feeding each token it produces back in as its next input until it emits an end-of-sentence token.

Sutskever and colleagues, using deep LSTMs, found that simply reversing the order of the source words improved their translations, because it put the first source words close to the first target words. That hinted at the real weakness: the decoder sees the source only through one fixed-size vector, however long the sentence. Bahdanau, Cho & Bengio (2015) showed that such models degrade on long sentences and proposed the fix that changed the field: let the decoder look back at all the encoder's hidden states at every step.

αt,j=e st,j∑ke st,k,ct=∑jαt,j hj\alpha_{t,j}=\frac{e^{\,s_{t,j}}}{\sum_{k}e^{\,s_{t,k}}},\qquad \mathbf c_t=\sum_j\alpha_{t,j}\,\mathbf h_j
At output step tt a small network scores how relevant each source position jj is (st,js_{t,j}). The softmax turns the scores into weights that sum to 1, and the context vector ct\mathbf c_t is the weighted average of the encoder states hj\mathbf h_j. This is the attention mechanism; its weights act as a soft alignment between target and source words.
Check your understanding

What problem did attention solve in RNN encoder–decoders?

  1. The models could not be trained by backpropagation until attention made them differentiable
  2. The decoder could not produce an output of a different length from the input
  3. The decoder saw the source only through one fixed-size summary, which loses detail on long sentences; attention lets it consult every encoder state
  4. Attention removed vanishing gradients from the encoder, so gated cells were no longer needed
Show the answer

C. The decoder saw the source only through one fixed-size summary, which loses detail on long sentences; attention lets it consult every encoder state

Squeezing a 50-word sentence into one vector is a bottleneck. With attention the decoder builds a fresh context vector at every step from all the encoder states, and each output gets a short path to every source word.

State space models: recurrence returns

Attention has a price. When a transformer generates text, each new token attends to all the earlier ones, so the work per token grows with the length of the context, and so does the memory holding every earlier token's keys and values (the KV cache). An RNN's state has a fixed size, so every new token costs the same. Could a recurrent network also be trained in parallel, as a transformer is?

For one kind of recurrence the answer is yes. A state space model (SSM) updates its state linearly, with no squashing function:

ht=Aˉ ht−1+Bˉ xt,yt=C⊤ht⟹yt=∑k=0t−1C⊤Aˉ kBˉ⏟Kk xt−k\mathbf h_t=\bar A\,\mathbf h_{t-1}+\bar{\mathbf B}\,x_t,\quad y_t=\mathbf C^\top\mathbf h_t\qquad\Longrightarrow\qquad y_t=\sum_{k=0}^{t-1}\underbrace{\mathbf C^\top\bar A^{\,k}\bar{\mathbf B}}_{K_k}\,x_{t-k}
Unrolling the linear recurrence (from h0=0\mathbf h_0=\mathbf 0, one input and one output channel) writes the output as the input convolved with a fixed kernel KkK_k. During training the kernel is computed once and applied to the whole sequence in parallel; during generation the same model runs step by step like an RNN, with a state of fixed size.

The matrices come from a continuous-time system ddsh(s)=Ah(s)+Bx(s)\tfrac{d}{ds}\mathbf h(s)=A\mathbf h(s)+\mathbf Bx(s) that is chopped into steps of size Δ\Delta, a discretization: for example Aˉ=eΔA\bar A=e^{\Delta A}. The eigenvalues of AA decide how fast each part of the state decays or oscillates, and Δ\Delta decides how much continuous time one step covers. S4 (Gu, Goel & Ré, 2022) made this work with a carefully structured AA, and was the first model to solve Path-X, a benchmark task whose sequences are over 16,000 steps long.

Selection, and the road ahead

A fixed kernel treats every input alike: it cannot decide that one token matters and the next is noise. Mamba (Gu & Dao, 2023) makes the state space model selective: the step size Δ\Delta and the matrices B\mathbf B and C\mathbf C are computed from the current input. A large Δ\Delta resets the state and writes the current token; a tiny Δ\Delta holds the state and ignores the token. The convolution view is lost, but the update is still linear in the state, so a parallel scan can still compute all the steps in parallel during training. A selective SSM is, once again, a gated recurrent network.

Think first Selective SSMs and transformers both model language well. What can a transformer do easily that any model with a fixed-size state finds hard?

Recall an earlier token exactly. A transformer keeps every token's key and value, so its memory grows with the context; a fixed-size state must compress what it has read. Copying a long string verbatim, or retrieving a phone number seen thousands of tokens earlier, is easy for attention and hard for a fixed state. The Emergence lesson Hybrid Models & the Limits of Fixed-Size Memory makes this precise.

In the Representation lessons you'll derive all of this. Recurrent Neural Networks covers the Elman network, backpropagation through time and the mathematics of vanishing and exploding gradients. LSTMs & GRUs writes out the gated cells, counts their parameters and shows why gates keep gradients alive. Encoder–Decoder Models & Attention builds sequence-to-sequence models, attention and decoding. State Space Models derives discretization and the convolution view, then S4 and Mamba. The Emergence lessons go to the research frontier: training without unrolling, recurrent networks as dynamical systems, what they can compute, fast weights and memories that learn at test time, parallel RNNs such as xLSTM, beam search and its pathologies, alignment-free training for speech, and the limits of a fixed-size memory.

Key takeaways

  • Sequences vary in length and their order carries meaning. An RNN reads one element at a time, updates a hidden state ht=tanh⁡(Wht−1+Uxt+b)\mathbf h_t=\tanh(W\mathbf h_{t-1}+U\mathbf x_t+\mathbf b) and reuses the same weights at every step, so it handles any length.
  • Training unrolls the network and backpropagates through time. The gradient that reaches early steps is a product of many per-step factors, so it vanishes or explodes; clipping tames explosions, but vanishing needs a different design.
  • LSTMs and GRUs add sigmoid gates that decide what to keep, write and reveal. Along the LSTM's cell the gradient is scaled by the forget gates, so gates near 1 keep both memories and gradients alive.
  • Encoder–decoder RNNs translate by reading into a state and writing from it. Attention lets the decoder consult every encoder state at every step, and transformers kept the attention and dropped the recurrence.
  • State space models use a linear recurrence: a convolution with a fixed kernel for parallel training, a fixed-size state for cheap generation. Mamba computes the step size from the input, which turns the model back into a gated RNN.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why can one trained RNN process both a 10-word message and a 10,000-word essay?

  1. It applies the same weights at every step and carries a fixed-size hidden state forward
  2. It pads every input to 10,000 words before reading it
  3. It adds a new layer for every new word it reads
  4. It reads only the last 10 words of any input
Show the answer

A. It applies the same weights at every step and carries a fixed-size hidden state forward

The recurrence ht=tanh⁡(Wht−1+Uxt+b)\mathbf h_t=\tanh(W\mathbf h_{t-1}+U\mathbf x_t+\mathbf b) uses the same WW, UU, b\mathbf b at every step, so the parameter count does not depend on the length. Longer inputs simply take more steps.

Question 2

An RNN must learn that the first word of a 100-word review decides its label. During training, what typically goes wrong?

  1. The forward pass cannot carry any information for 100 steps
  2. The loss becomes negative on long reviews
  3. The gradient reaching the first word has been multiplied by about 100 per-step factors, so it vanishes (or explodes) and the dependency is barely learned
  4. Backpropagation through time only works for sequences shorter than the hidden state
Show the answer

C. The gradient reaching the first word has been multiplied by about 100 per-step factors, so it vanishes (or explodes) and the dependency is barely learned

Backpropagation through time multiplies one factor per step. If the factors are mostly below 1, the signal from step 100 back to step 1 shrinks exponentially; if above 1, it explodes. Gated cells, careful initialization and clipping are the standard remedies.

Question 3

In an LSTM, what does a forget gate value near 1 do?

  1. It erases the cell state at every step
  2. It keeps the previous cell content and lets the error signal pass back along the cell with little loss
  3. It stops new input from being written into the cell
  4. It makes the gradient explode along the cell
Show the answer

B. It keeps the previous cell content and lets the error signal pass back along the cell with little loss

The cell update is ct=ft⊙ct−1+it⊙gt\mathbf c_t=\mathbf f_t\odot\mathbf c_{t-1}+\mathbf i_t\odot\mathbf g_t. With ft≈1\mathbf f_t\approx1 the old content stays, and one step backward along the cell multiplies the gradient by about 1, so it survives many steps.

Question 4

In an RNN encoder–decoder with attention, what is the context vector at an output step?

  1. The encoder's final hidden state, the same at every step
  2. The embedding of the previous output token
  3. The decoder's own hidden state
  4. A weighted average of all the encoder's hidden states, with weights from a softmax over relevance scores
Show the answer

D. A weighted average of all the encoder's hidden states, with weights from a softmax over relevance scores

At each output step the decoder scores every source position, turns the scores into weights with a softmax and averages the encoder states. The context changes from step to step, following the part of the source that matters now.

Question 5

Why can a state space model such as S4 be trained in parallel over the whole sequence, unlike a classic RNN?

  1. It has no hidden state at all
  2. It compares every pair of positions with attention
  3. Its state update is linear, so its output is the input convolved with a fixed kernel that can be applied to the whole sequence at once
  4. It reads only every other token
Show the answer

C. Its state update is linear, so its output is the input convolved with a fixed kernel that can be applied to the whole sequence at once

Unrolling ht=Aˉht−1+Bˉxt\mathbf h_t=\bar A\mathbf h_{t-1}+\bar{\mathbf B}x_t gives yt=∑kKkxt−ky_t=\sum_kK_kx_{t-k} with Kk=C⊤AˉkBˉK_k=\mathbf C^\top\bar A^k\bar{\mathbf B}. The tanh of a classic RNN breaks this: each state then depends nonlinearly on the previous one and must be computed in order.

Go deeper

Further reading

  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, ch. 10 "Sequence Modeling: Recurrent and Recursive Nets" (MIT Press, 2016), free at deeplearningbook.org.
  • J. L. Elman, "Finding structure in time," Cognitive Science 14(2), 179–211 (1990).
  • S. Hochreiter & J. Schmidhuber, "Long short-term memory," Neural Computation 9(8), 1735–1780 (1997).
  • D. Bahdanau, K. Cho & Y. Bengio, "Neural machine translation by jointly learning to align and translate," ICLR (2015).
  • A. Gu & T. Dao, "Mamba: Linear-time sequence modeling with selective state spaces," arXiv:2312.00752 (2023).