Recurrent networks, LSTM and GRU

Recurrent Neural Networks, LSTM and GRU

How a recurrent network processes sequences with a hidden state updated at every step, why it suffers from vanishing gradients, and how LSTM and GRU gates solve this, with the full equations, bidirectional and stacked networks, and their uses in NLP.

Lesson 20 of 38Intermediate45 minutes

Lesson objectives

  • Write the equations of a simple RNN and explain backpropagation through time.
  • Explain the vanishing and exploding gradient problem and its solutions.
  • Write the LSTM and GRU equations and the role of each gate.
Page contents
  1. Why a recurrent network?
  2. Backpropagation through time
  3. Vanishing and exploding gradients
  4. LSTM: long short-term memory
  5. GRU: a simpler version
  6. Common architectures
  7. Why did they decline in favor of transformers?

Why a recurrent network?

Text is a variable-length sequence, and each word depends on what came before it. An ordinary feedforward network takes a fixed-length input. A recurrent neural network (RNN) processes the sequence step by step and carries a hidden state \mathbf{h}_t that summarizes what it has seen so far, with weights shared across all steps (the Elman network, 1990):

\mathbf{h}_t = \tanh(W_{hh}\, \mathbf{h}_{t-1} + W_{xh}\, \mathbf{x}_t + \mathbf{b}_h)
\hat{\mathbf{y}}_t = \text{softmax}(W_{hy}\, \mathbf{h}_t + \mathbf{b}_y)

In language modeling, \hat{\mathbf{y}}_t is the distribution of the next word, and the loss is the sum of the cross-entropy over all steps.

Backpropagation through time

We unroll the network through time, so it becomes a deep network whose depth is the sequence length, and apply backpropagation (BPTT). The gradient of the loss at step t with respect to an earlier state \mathbf{h}_k contains a product of Jacobians:

\frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_k} = \prod_{j=k+1}^{t} \frac{\partial \mathbf{h}_j}{\partial \mathbf{h}_{j-1}} = \prod_{j=k+1}^{t} \text{diag}\left(\tanh'(\cdot)\right) W_{hh}

Vanishing and exploding gradients

Bengio et al. (1994), and later Pascanu et al. (2013), analyzed this repeated multiplication:

  • If the largest singular value of W_{hh} (multiplied by the tanh derivative term) is less than 1, the gradient vanishes exponentially, so the network cannot learn long-range dependencies: in “الطالبات اللواتي حضرن المحاضرة الطويلة أمس نجحن» (the female students who attended the long lecture yesterday passed), the verb must remember the feminine plural from the start of the sentence.
  • If it is greater than 1, the gradient may explode, so the weights jump and the loss becomes NaN.

Solutions: gradient clipping for explosion; gates (LSTM/GRU) for vanishing, together with good initialization.

LSTM: long short-term memory

Hochreiter and Schmidhuber (1997) proposed a cell with a cell state \mathbf{c}_t that is updated by addition, not multiplication, and three gates that learn what to forget, what to add and what to output (the formula below is the one common today, with the forget gate that Gers et al. added later):

\mathbf{f}_t = \sigma(W_f [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_f) \quad \text{(forget gate)}
\mathbf{i}_t = \sigma(W_i [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_i) \quad \text{(input gate)}
\tilde{\mathbf{c}}_t = \tanh(W_c [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_c) \quad \text{(candidate)}
\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t
\mathbf{o}_t = \sigma(W_o [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_o), \qquad \mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)

When \mathbf{f}_t \approx 1 and \mathbf{i}_t \approx 0, the cell state passes almost unchanged, so the gradient flows through time without vanishing. This resembles the idea of residual connections that you will see in transformers.

LSTM cell Long Short-Term Memory cell
LSTM cellc(t-1)c(t)×+σforget fσinput itanhcandidateσoutput o×tanhh(t)h(t-1), x(t)

Three gates (forget, input and output) control the memory cell c; the cell's horizontal path passes the gradient through time with only element-wise multiplication and addition.

GRU: a simpler version

Cho et al. (2014) proposed the GRU, with two gates and no separate cell state:

\mathbf{z}_t = \sigma(W_z [\mathbf{h}_{t-1}, \mathbf{x}_t]) \quad \text{(update gate)}, \qquad \mathbf{r}_t = \sigma(W_r [\mathbf{h}_{t-1}, \mathbf{x}_t]) \quad \text{(reset gate)}
\tilde{\mathbf{h}}_t = \tanh(W [\mathbf{r}_t \odot \mathbf{h}_{t-1}, \mathbf{x}_t]), \qquad \mathbf{h}_t = (1 - \mathbf{z}_t) \odot \mathbf{h}_{t-1} + \mathbf{z}_t \odot \tilde{\mathbf{h}}_t

Fewer parameters and performance close to the LSTM on many tasks; neither is an outright winner.

Common architectures

  • Bidirectional (BiLSTM): two networks, forward and backward, whose representations are concatenated: \mathbf{h}_t = [\overrightarrow{\mathbf{h}}_t; \overleftarrow{\mathbf{h}}_t]. Essential for tagging (entities, parts of speech, diacritization), where what follows the word matters. Not suitable for generation because the future is unknown.
  • Stacked: several layers on top of each other.
  • With a CRF layer: for sequence labeling (BiLSTM-CRF).
  • Character level: for diacritization, spelling correction and Arabizi.

Why did they decline in favor of transformers?

  1. Sequentiality: \mathbf{h}_t cannot be computed before \mathbf{h}_{t-1}, so there is no parallelism across time, and training is slow on huge corpora.
  2. The bottleneck: the whole history is compressed into a fixed-size vector.
  3. Distance: information from 50 words ago passes through 50 steps.

But the ideas partly came back: modern state space models (such as Mamba) and RWKV try to combine the efficiency of recurrent inference (constant memory per token) with parallel trainability.

Lesson summary

  • A recurrent network shares weights across time and carries memory in the hidden state.
  • The gradient vanishes or explodes over long sequences of steps because of repeated multiplication.
  • An LSTM cell adds an additive path (the cell state) controlled by gates, so it keeps information longer.

Check what you understood

Choose an answer for each question to see the correction and the reasoning. Your answers are not sent anywhere.

  1. What is the common solution to exploding gradients in recurrent networks?

  2. What is the role of the forget gate in an LSTM?

References

  1. Elman, J. L. (1990). Finding Structure in Time. Cognitive Science 14(2) doi.org/10.1207/s15516709cog1402_1
  2. Bengio, Y., Simard, P. & Frasconi, P. (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks 5(2) doi.org/10.1109/72.279181
  3. Hochreiter, S. & Schmidhuber, J. (1997). Long Short-Term Memory. Neural Computation 9(8) doi.org/10.1162/neco.1997.9.8.1735
  4. Cho, K. et al. (2014). Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation. EMNLP arxiv.org/abs/1406.1078
  5. Pascanu, R., Mikolov, T. & Bengio, Y. (2013). On the difficulty of training recurrent neural networks. ICML arxiv.org/abs/1211.5063