◆ AI All-in-One

Level 3 In-Depth AI · Deep Learning

Recurrent Neural Networks

Networks that read a sequence one step at a time and carry a memory, the hidden state, from each step to the next. The first neural networks that could generate text one character at a time.

Level
●●●●● Intermediate
Reading
12 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Neural Networks

This leads to

LSTMs and GRUsState Space Models and Mamba
The full path from zero — 14 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Linear Regression
  12. The Perceptron
  13. Logistic Regression
  14. Neural Networks
  15. Recurrent Neural Networks

Read them roughly in this order. See it on the concept map →

Why it matters

Much of the world arrives in order. Words in a sentence, notes in a melody, frames of video, readings from a heart monitor, daily stock prices. The meaning of each item depends on what came before: "bank" means something different after "river" than after "savings". And sequences come in every length, from a three-word query to a novel.

The networks of the earlier chapters take a fixed-size input and give a fixed-size output. They have no notion of order and no memory. A recurrent neural network (RNN) adds both. It reads a sequence one item at a time and keeps a running summary, its memory, which it updates after every item.

From roughly 2014 to 2017, RNNs and their gated cousins, LSTMs and GRUs, were the state of the art for machine translation, speech recognition, handwriting recognition and text generation. Google Translate switched to an LSTM-based system in 2016. Then the The Transformer replaced them for most language tasks. Yet the ideas in this chapter come back again and again: predicting the next token, generating text one step at a time, and the modern state-space models such as Mamba, which are recurrent networks in a new form.

The intuition

Think of reading a sentence. You don't hold every word you've seen in front of you. You keep a running impression of what the sentence is about, and you update it with each new word. By the end of "The trophy didn't fit in the suitcase because it was too", your impression already expects a word like "big" or "small".

An RNN does the same. At each time step tt it takes two things:

  • the new input xt\mathbf{x}_t (for example the current character), and
  • its own previous memory ht−1\mathbf{h}_{t-1}, a vector of numbers called the hidden state.

It combines them into a new hidden state ht\mathbf{h}_t and, if needed, makes a prediction yt\mathbf{y}_t from it. Then it moves on to the next step, carrying ht\mathbf{h}_t along. Crucially, the same weights are used at every step. The RNN is one small network applied over and over, a bit like a convolution that slides along time instead of across an image.

Drawn compactly, an RNN is a network with a loop. To see what happens during a sequence, you unroll the loop: draw one copy of the network per time step, with the hidden state passed from each copy to the next.

h xₜ yₜ Wₕfolded:a loop = h₁hidden state “t” “h” WₓWₒt = 1 Wₕ h₂hidden state “h” “e” WₓWₒt = 2 Wₕ h₃hidden state “e” “␣” WₓWₒt = 3 Wₕ h₄hidden state “␣” “c” WₓWₒt = 4 h₀ = 0 backpropagation through time gradients flow right to left through every copy, multiplied by Wₕ at each step every copy is the same cell: Wₓ, Wₕ and Wₒ are shared across all time steps target:nextcharinputchar
Fig. 1 An RNN folded (left) and unrolled over four time steps (right), reading "the " and learning to predict the next character at each step. All copies share the same weights. During training, gradients flow backwards through the whole chain.

Key idea An RNN is one small network applied at every step of a sequence. It passes a hidden state from step to step, so each output can depend on everything read so far. Training it means backpropagating through the unrolled chain.

How it works

The recurrence

The classic ("vanilla" or Elman) RNN updates its hidden state with one line. In words: multiply the input by one weight matrix and the previous hidden state by another, add a bias, and squash the result with tanh. Then a separate output layer reads the new hidden state.

ht=tanh⁡(Wxxt+Whht−1+b)\mathbf{h}_t = \tanh(\mathbf{W}_x \mathbf{x}_t + \mathbf{W}_h \mathbf{h}_{t-1} + \mathbf{b})
yt=Woht+c\mathbf{y}_t = \mathbf{W}_o \mathbf{h}_t + \mathbf{c}
  • xt\mathbf{x}_t is the input at step tt, for example an embedding of the current character.
  • ht−1\mathbf{h}_{t-1} is the previous hidden state. Before the first step, h0\mathbf{h}_0 is usually all zeros.
  • Wx\mathbf{W}_x (input-to-hidden), Wh\mathbf{W}_h (hidden-to-hidden) and Wo\mathbf{W}_o (hidden-to-output) are weight matrices, with biases b\mathbf{b} and c\mathbf{c}. The same ones are used at every step.
  • tanh⁡\tanh squashes each number into the range −1 to 1 (Activation Functions).
  • yt\mathbf{y}_t is the output, for example a score for every possible next character. Softmax turns these scores into probabilities.

The parameter count does not depend on the sequence length. A hidden size of 64 and input size of 16 means Wx\mathbf{W}_x is 64 × 16 and Wh\mathbf{W}_h is 64 × 64, whether the sequence has 5 steps or 5,000.

A worked example by hand

Take a one-number RNN with wx=0.5w_x = 0.5, wh=0.8w_h = 0.8, no bias, and feed it the sequence 1, 0, 0:

Step Input xtx_t Calculation Hidden state hth_t
1 1 tanh⁡(0.5⋅1+0.8⋅0)\tanh(0.5 \cdot 1 + 0.8 \cdot 0) 0.462
2 0 tanh⁡(0.5⋅0+0.8⋅0.462)\tanh(0.5 \cdot 0 + 0.8 \cdot 0.462) 0.354
3 0 tanh⁡(0.5⋅0+0.8⋅0.354)\tanh(0.5 \cdot 0 + 0.8 \cdot 0.354) 0.276

The input "1" arrived only at step 1, yet it is still visible in the hidden state two steps later. That is memory. It is also fading: each step multiplies it by about 0.8 and squashes it. Hold that thought for the section on long-range dependencies.

Shapes of problems

Because an RNN can read and write at every step, it fits many kinds of task:

many to onewhole review →positive / negative one to manyone image →a caption, word by word many to manyone output per input:next character, word tags sequence to sequenceread it all, then write:translation green: outputs · purple: hidden state carried left to right · blue: inputs
Fig. 2 Four ways to use a recurrent network. Many to one: read a whole review, then classify it. One to many: from one input (such as an image's features), generate a sequence. Many to many: one output per input, such as predicting the next character. Sequence to sequence: read the whole input, then write a different-length output, as in translation.

The last one, sequence to sequence, gets its own chapter: Sequence-to-Sequence Models.

Training: backpropagation through time

To train an RNN, unroll it over the sequence, compute the loss at every step that has a target, add them up, and run ordinary Backpropagation on the unrolled graph. Because the graph is a chain through time, this is called backpropagation through time (BPTT). There is nothing new in it. It is just the chain rule on a long, thin network. The one twist is weight sharing: Wh\mathbf{W}_h is used at every step, so its gradient is the sum of its gradients from every step.

For long sequences (a book has millions of characters), unrolling everything is impossible. Truncated backpropagation through time splits the sequence into chunks of, say, 100 steps. It carries the hidden state forward from chunk to chunk but only backpropagates within each chunk. The model can still use information from further back, but it is never directly trained to.

The problem with long-range dependencies

How much does h3h_3 depend on h1h_1 in the worked example? By the chain rule, ∂h3∂h1=∂h3∂h2⋅∂h2∂h1\frac{\partial h_3}{\partial h_1} = \frac{\partial h_3}{\partial h_2} \cdot \frac{\partial h_2}{\partial h_1}, and each factor is whw_h times the slope of tanh at that step, (1−ht2)(1 - h_t^2):

∂h3∂h1=0.8 (1−0.3542)⋅0.8 (1−0.2762)≈0.52\frac{\partial h_3}{\partial h_1} = 0.8 \,(1 - 0.354^2) \cdot 0.8\,(1 - 0.276^2) \approx 0.52

Each step back multiplies the gradient by roughly whw_h times a number at most 1. Over 20 steps with a factor of 0.8 that is 0.820≈0.0120.8^{20} \approx 0.012. Over 100 steps it is effectively zero. With a factor above 1, the product explodes instead. For matrices the same thing happens, governed by the size of Wh\mathbf{W}_h (its largest singular value). This is the vanishing and exploding gradient problem in its purest form. Sepp Hochreiter identified it in 1991, and Bengio, Simard and Frasconi analysed it in 1994.

In practice it means a vanilla RNN learns dependencies across maybe 10–20 steps but struggles beyond that. It can learn that "q" is followed by "u", but not that a quote opened 200 characters ago must be closed.

Two fixes are standard:

  • Gradient clipping handles explosions: if the gradient's overall size exceeds a threshold, scale it down. Every RNN training loop should have it.
  • Gates handle vanishing. The LSTM and GRU add a separate memory path that is updated by addition, not repeated multiplication. That is the next chapter.

Generating text

A character-level language model is an RNN trained to predict the next character at every position. To generate, you feed it a starting prompt, sample a character from its predicted probabilities, feed that character back in as the next input, and repeat, carrying the hidden state along. Andrej Karpathy's 2015 blog post The Unreasonable Effectiveness of Recurrent Neural Networks showed small RNNs of this kind writing fake Shakespeare, Wikipedia markup and C code that looked startlingly real. Today's large language models generate text in exactly the same loop, one token at a time (Decoding: Temperature, Top-k and Top-p).

Variations

  • Stacked (deep) RNNs feed the hidden states of one RNN layer as inputs to another. Two to four layers were common.
  • A bidirectional RNN runs one RNN forwards and another backwards over the sequence and joins their hidden states, so every position sees both its past and its future. That is useful for tagging and classification, but impossible for generation, where the future doesn't exist yet.

In code

A complete character-level RNN in PyTorch, trained on a tiny made-up corpus. It runs in a few seconds on a laptop CPU:

import torch
import torch.nn as nn

torch.manual_seed(0)
text = "the cat sat on the mat. the dog sat on the log. " * 20
chars = sorted(set(text))                       # the vocabulary: 14 characters
stoi = {c: i for i, c in enumerate(chars)}
data = torch.tensor([stoi[c] for c in text])

class CharRNN(nn.Module):
    def __init__(self, vocab, hidden=64):
        super().__init__()
        self.embed = nn.Embedding(vocab, 16)
        self.rnn = nn.RNN(16, hidden, batch_first=True)   # h_t = tanh(W x_t + U h_{t-1} + b)
        self.head = nn.Linear(hidden, vocab)              # hidden state -> next-char scores
    def forward(self, x, h=None):
        out, h = self.rnn(self.embed(x), h)
        return self.head(out), h

model = CharRNN(len(chars))
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
seq_len = 32
for step in range(301):
    starts = torch.randint(0, len(data) - seq_len - 1, (16,))
    x = torch.stack([data[s:s + seq_len] for s in starts])          # input characters
    y = torch.stack([data[s + 1:s + seq_len + 1] for s in starts])  # the next character at each position
    logits, _ = model(x)
    loss = nn.functional.cross_entropy(logits.reshape(-1, len(chars)), y.reshape(-1))
    opt.zero_grad(); loss.backward()
    nn.utils.clip_grad_norm_(model.parameters(), 1.0)                # guard against exploding gradients
    opt.step()
    if step % 100 == 0:
        print(f"step {step}  loss {loss.item():.3f}")

# Generate: feed one character at a time, carrying the hidden state forward
out = "the "
x, h = torch.tensor([[stoi[c] for c in out]]), None
with torch.no_grad():
    for _ in range(60):
        logits, h = model(x, h)
        nxt = torch.multinomial(torch.softmax(logits[0, -1], dim=0), 1).item()
        out += chars[nxt]
        x = torch.tensor([[nxt]])
print(out)

# step 0  loss 2.695
# step 100  loss 0.160
# step 200  loss 0.104
# step 300  loss 0.076
# the log. the cat sat on the log. the cat sat on the mat. the dog

The starting loss, 2.695, is close to ln⁡14≈2.64\ln 14 \approx 2.64: a uniform guess over 14 characters (the initial-loss check). Look at the generated text. "the cat sat on the log" never appears in the training data. The model learned the pattern the [animal] sat on the [thing], and the sampling recombined it. Notice also the line nn.utils.clip_grad_norm_: gradient clipping is standard in every recurrent training loop.

Common pitfalls

  • Forgetting to clip gradients. One exploding step can turn the weights into NaN. Use clip_grad_norm_ with a threshold around 1–5.
  • Batch layout. PyTorch's nn.RNN, nn.LSTM and nn.GRU expect (seq_len, batch, features) by default. Pass batch_first=True if your tensors are (batch, seq_len, features). Getting this wrong does not raise an error. It silently treats time as the batch.
  • Leaking the hidden state across unrelated sequences. Reset h to zeros for each new independent sequence. When carrying it across chunks of one long sequence, call h = h.detach() so backpropagation doesn't try to reach back to the very beginning.
  • Padding. When a batch holds sequences of different lengths, the padding steps must not count in the loss or feed garbage into the final hidden state. Use ignore_index in the loss and nn.utils.rnn.pack_padded_sequence.
  • Expecting long memory from a vanilla RNN. If the task needs information from more than a couple of dozen steps back, use an LSTM or GRU, or Attention.

Watch out RNNs are inherently sequential: step 100 cannot be computed before step 99. That makes them slow to train on GPUs, which are built to do many things at once. This, more than accuracy, is why Transformers, which process every position in parallel during training, replaced them for large-scale language modelling.

Where it leads

A bit of history

Recurrent connections are as old as neural networks themselves: John Hopfield's 1982 network and Michael Jordan's 1986 network both fed outputs back as inputs. Jeffrey Elman's 1990 paper Finding Structure in Time introduced the simple recurrent network used in this chapter and showed it learning word categories from raw sequences. Paul Werbos described backpropagation through time in detail in 1990. Sepp Hochreiter's 1991 thesis and Bengio, Simard and Frasconi's 1994 paper showed why long-range dependencies were so hard to learn. That led to the LSTM (1997). Around 2013–2015, with GPUs, gradient clipping (popularised by Pascanu, Mikolov and Bengio in 2013) and LSTMs, recurrent networks briefly ruled sequence modelling, until the Transformer arrived in 2017.

Try it

  1. Change nn.RNN to nn.GRU (one word) and compare the losses at step 300.
  2. Train on a text where memory matters: "(a) [b] {c} " * 50. Does the model learn to close each bracket with the right kind? Try making the gap longer, such as "(aaaaaaaaaa) ".
  3. By hand: in the worked example, change whw_h to 1.5 and feed 1, 0, 0, 0, 0. What happens to the hidden state? (tanh keeps it bounded, but what about the gradient factor wh(1−h2)w_h(1-h^2)?)

Hint for 3: the hidden state settles near a fixed value where h=tanh⁡(1.5h)h = \tanh(1.5h), about 0.86. There the factor is 1.5×(1−0.862)≈0.391.5 \times (1 - 0.86^2) \approx 0.39, so the gradient still shrinks.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. An RNN reads sequences of 5 steps. You switch to sequences of 5,000 steps. What happens to the number of parameters?

  2. A one-number RNN has w_x = 0.5, w_h = 0.8 and no bias. It reads input 1 and then 0. Roughly what is h₂?

  3. A vanilla RNN must close a quotation mark opened 200 characters earlier, and it fails. Why?

  4. You train on a long book with truncated backpropagation through time in chunks of 100 steps. What is true?

  5. Why can't a bidirectional RNN be used to generate text?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Course

Deep Learning Specialization

Andrew Ng (DeepLearning.AI) · Intermediate · free to audit

Five courses on neural networks, tuning, CNNs and sequence models, with very clear explanations of the maths.

Book

Deep Learning

Goodfellow, Bengio & Courville · 2016 · Advanced · Free

The classic deep learning textbook, especially strong on the maths foundations. Free to read online.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/rnn.md