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
- Builds on
- 14 concepts →
- Quiz
- 5 questions ↓
Read first
Neural NetworksThe full path from zero — 14 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- 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 it takes two things:
- the new input (for example the current character), and
- its own previous memory , a vector of numbers called the hidden state.
It combines them into a new hidden state and, if needed, makes a prediction from it. Then it moves on to the next step, carrying 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.
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.
- is the input at step , for example an embedding of the current character.
- is the previous hidden state. Before the first step, is usually all zeros.
- (input-to-hidden), (hidden-to-hidden) and (hidden-to-output) are weight matrices, with biases and . The same ones are used at every step.
- squashes each number into the range −1 to 1 (Activation Functions).
- 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 is 64 × 16 and is 64 × 64, whether the sequence has 5 steps or 5,000.
A worked example by hand
Take a one-number RNN with , , no bias, and feed it the sequence 1, 0, 0:
| Step | Input | Calculation | Hidden state |
|---|---|---|---|
| 1 | 1 | 0.462 | |
| 2 | 0 | 0.354 | |
| 3 | 0 | 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:
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: 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 depend on in the worked example? By the chain rule, , and each factor is times the slope of tanh at that step, :
Each step back multiplies the gradient by roughly times a number at most 1. Over 20 steps with a factor of 0.8 that is . 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 (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 : 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. Useclip_grad_norm_with a threshold around 1–5. - Batch layout. PyTorch's
nn.RNN,nn.LSTMandnn.GRUexpect(seq_len, batch, features)by default. Passbatch_first=Trueif 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
hto zeros for each new independent sequence. When carrying it across chunks of one long sequence, callh = 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_indexin the loss andnn.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
- LSTMs and GRUs: gates and a cell state that keep information for hundreds of steps. Use these instead of vanilla RNNs in practice.
- Sequence-to-Sequence Models: two RNNs, an encoder and a decoder, for translation. This led directly to Attention.
- Language Modeling and Next-Token Prediction: the next-token prediction task an RNN learned above, now done by GPT-style Transformers.
- State Space Models and Mamba: Mamba and related models are recurrent at inference time but train in parallel, bringing RNN-style constant memory back to large models.
- Time Series Forecasting: forecasting with sequential models.
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
- Change
nn.RNNtonn.GRU(one word) and compare the losses at step 300.- 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) ".- By hand: in the worked example, change 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 ?)
Hint for 3: the hidden state settles near a fixed value where , about 0.86. There the factor is , so the gradient still shrinks.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
The Unreasonable Effectiveness of Recurrent Neural Networks
A famous, fun blog post showing what character-level language models learn from Shakespeare, Wikipedia and source code.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Deep Learning Specialization
Five courses on neural networks, tuning, CNNs and sequence models, with very clear explanations of the maths.
Deep Learning
The classic deep learning textbook, especially strong on the maths foundations. Free to read online.
On the difficulty of training Recurrent Neural Networks
Explains vanishing and exploding gradients in RNNs and popularised gradient-norm clipping as the fix for explosions.
Stanford CS224N: NLP with Deep Learning
Word vectors, RNNs, attention, Transformers and LLMs, with lecture videos on YouTube.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/rnn.md