AI State of the Art
Fundamentals/Deep Learning: Fundamental Architectures/30 min
Section 20

Recurrent Neural Networks (RNN): Sequences and Memory

Listen as a podcast β†’

The Problem: Data That Has an Order

"The cat eats the mouse" vs "The mouse eats the cat". Same words. Opposite meaning. A classic network (dense, feedforward) doesn't understand order: it just sees a set of numbers as input, like a shuffled bag of words. Permuting the inputs changes nothing for it.

Yet real-world data is very often sequential: text is a sequence of words, speech is a sequence of sounds, a video is a sequence of images, a financial signal is a sequence of prices. Order isn't a detail, it's often the most important information.

Convolutional Neural Networks (CNNs, see CNN: seeing with convolutions) handle the spatial structure of images well. But for sequences where context accumulates over time ("this word refers to another word 10 positions earlier") you need a network with memory. That's exactly what Recurrent Neural Networks (RNNs) provide.

Read this as history

This page describes an architecture that has been superseded for language. Since 2017 it is the transformer that handles text sequences, and for a specific reason: an RNN must process words one at a time, in order, which rules out parallelizing training. The head-to-head comparison has its own lesson: Transformer vs RNN. What follows keeps two kinds of value: it is the conceptual foundation of sequence processing, and the recurrent idea is making a comeback in a new form with state space models (Mamba, S4).

How an RNN Works

Diagram of a Recurrent Neural Network (RNN)
This diagram illustrates the fundamental operation of a Recurrent Neural Network (RNN). It shows how inputs (x_t) and outputs (y_t) are linked through hidden states (h_t) that propagate through time, enabling the processing of data sequences.

The Hidden State = Memory

The central idea of the RNN is simple: the network processes the sequence element by element, and at each step it maintains a hidden state hh that summarizes everything it has seen so far. That's its memory.

At each time step tt, the RNN takes two inputs:

  • The current element xtx_t (for example the current word)
  • The hidden state from the previous step htβˆ’1h_{t-1} (the summary of everything that came before)

And it computes:

ht=tanh⁑(Whhβ‹…htβˆ’1+Wxhβ‹…xt+bh)h_t = \tanh(W_{hh} \cdot h_{t-1} + W_{xh} \cdot x_t + b_h) yt=Whyβ‹…ht+byy_t = W_{hy} \cdot h_t + b_y

Every symbol:

  • xtx_t: the input element at step tt (the current word, as a vector of numbers);
  • htβˆ’1h_{t-1} and hth_t: the hidden state before and after this step;
  • yty_t: the output produced at this step (for instance a score for every possible next word);
  • WxhW_{xh}, WhhW_{hh}, WhyW_{hy}: three weight matrices. Read the subscripts as "from ... to ...": WxhW_{xh} goes from the input to the hidden state, WhhW_{hh} from the hidden state back to itself, WhyW_{hy} from the hidden state to the output;
  • bhb_h and byb_y: two bias vectors, a constant offset added before the activation;
  • tanh⁑\tanh: the hyperbolic tangent, a function that squashes any number into the range -1 to 1, which keeps the hidden state from running off to infinity as steps accumulate.

In one sentence: the new hidden state is a blend of what the current input contributes and what the past contributes, squashed into -1 to 1; the output is simply a read-out of that state.

What is learned versus what is computed. The WW matrices and the bb biases are learned parameters: tuned during training, then frozen. They do not depend on the sentence being read. By contrast hth_t and yty_t are computed at each step, on the sequence at hand, and are discarded when you move to the next sentence. Conflating the two is the most common mistake when reading formulas like these.

A crucial point: the matrices WhhW_{hh}, WxhW_{xh}, WhyW_{hy} are the same at every time step. The same "module" is reused to process each element of the sequence. Whether the sequence is 5 words or 500 words, it's the same weights. This sharing is what allows the RNN to process sequences of any length.

The hidden state: an imperfect compressor

hth_t is a fixed-size vector (for example 256 or 512 dimensions) that must summarize everything the network has seen up to step tt. It's a necessarily imperfect summary: the most recent information is well represented, but older information is progressively "overwritten" by new information. It's like your working memory: you remember well what you were told 5 seconds ago, but not 5 minutes ago. This fundamental limitation is what motivated the two gated architectures that followed, the LSTM (Long Short-Term Memory) and the GRU (Gated Recurrent Unit), covered in LSTM and GRU.

Unrolling Through Time

To understand how an RNN trains, you need to "unroll" it through time. Imagine copying the same RNN module once for each element in the sequence. The module at step 1 sends its hidden state to the module at step 2, which sends it to step 3, etc.

Visually, an RNN unrolled over a 50-word sequence looks like a very deep network with 50 layers. The difference: all these "layers" share the same weights. And you train this deep network by classic backpropagation (see Backpropagation) applied through time: that's BPTT, Backpropagation Through Time.

This observation (an unrolled RNN is a deep network) immediately explains why the same deep network problems (vanishing gradient, exploding gradient) manifest here too. But before getting to that, let's look at the different possible configurations.

Types of RNN by Task

Diagram of RNN architectures by task type
The image illustrates the four main types of Recurrent Neural Network (RNN) architectures based on the nature of the input and output data: one-to-one, one-to-many, many-to-one, and many-to-many. Each diagram shows the data structure and recurrent connections between time steps.

The flexibility of the RNN allows several configurations depending on the problem.

In the many-to-one configuration, the network consumes an entire sequence to produce a single output. For example, it reads all the words of a movie review and, once it reaches the last word, uses the final hidden state to predict the sentiment (positive or negative).

The inverse configuration, one-to-many, starts from a single input to generate a complete sequence. A classic use case is image captioning: an image is encoded into a vector, then the RNN produces a description word by word, like "a black cat sleeping on a red couch".

In synchronous many-to-many mode, each element of the input sequence produces a corresponding output. This is particularly useful for POS tagging (Part-of-Speech tagging), where each word receives a label indicating whether it's a noun, verb, adjective, etc.

Finally, asynchronous many-to-many mode transforms an input sequence into an output sequence of potentially different length. Machine translation is the typical example: the network first reads the entire source sentence, then generates the translation token by token (a token is the unit the model manipulates: a word, or a piece of a word). This is the sequence-to-sequence, or seq2seq, architecture, also called encoder-decoder, detailed in Seq2Seq and the attention mechanism.

The Killer Problem: The Vanishing Gradient

Diagram of a recurrent neural network over 7 time steps
This diagram illustrates the architecture of a Recurrent Neural Network (RNN) deployed over 7 time steps. Each hidden layer passes its state to the next, enabling the feedback necessary for processing temporal sequences.Source : ResearchGate

Why the Gradient Vanishes

When you train an RNN with BPTT, the gradient must travel back through all time steps to reach the shared weights. At each step it traverses, the gradient is multiplied by the matrix WhhW_{hh} and by the derivative of the activation (tanh).

The problem: the derivative of tanh is at most 1, and it reaches that value at a single point, when its input is exactly 0; everywhere else it is strictly less than 1. If in addition the largest eigenvalue of WhhW_{hh} (in absolute value) is below 1, then at every step crossed the gradient is multiplied by a factor smaller than 1.

Take a factor of 0.9 per step, purely as an illustration. After 20 steps only 0.920β‰ˆ0.120.9^{20} \approx 0.12 of the original gradient is left. After 50 steps, 0.950β‰ˆ0.0050.9^{50} \approx 0.005. After 100 steps, nothing usable. The real factor depends on the learned weights; what matters is that it is raised to the power of the number of steps, so the decay is exponential.

The gradient becomes microscopic well before reaching the first elements of the sequence. The network cannot learn long-term dependencies because the error signal doesn't travel back far enough.

Practical Consequences

In practice a basic RNN only manages to link elements a few dozen steps apart at best, the order of magnitude usually reported is around ten, but there is no sharp cutoff: memory degrades gradually. Concretely, it's unable to:

  • Link a pronoun ("he") to a noun mentioned 5 sentences earlier
  • Capture the narrative structure of a long paragraph
  • Detect long cycles in a financial time series
  • Maintain context across a multi-turn conversation

For tasks with short dependencies (sentence sentiment, short-term next word prediction), a basic RNN works. For everything else, you need gated architectures like LSTM or GRU.

The exploding gradient exists too

The opposite is possible: if the multiplying factors are above 1, the gradient explodes instead of vanishing, and the weights run off to infinity. This is solved with gradient clipping: if the gradient norm, its overall length, see norms and distances exceeds a threshold (say 5), you scale it back to that threshold while keeping its direction. It's a simple and effective fix. The vanishing gradient, however, isn't solved as easily, you need to change the network architecture (LSTM, GRU), which is designed to let the gradient flow over long distances.

Training an RNN

Backpropagation Through Time (BPTT)

Training follows these steps:

  1. Unroll the network over the entire sequence (copy the module for each step)
  2. Forward pass: compute the outputs and hidden states for each step
  3. Compute the loss at each step (or only at the end, depending on the task)
  4. Backward pass: backpropagate the gradient through all time steps
  5. Update the shared weights (sum of gradients from all steps)
Diagram of backpropagation through time for RNN
This diagram illustrates the Backpropagation Through Time (BPTT) mechanism in a Recurrent Neural Network (RNN). Each hidden state s_i depends on the previous state and input x_i, with gradient propagation for learning.

An important practical point: regularizing RNNs, the techniques that stop a network from memorizing its training data. Applying classic dropout (randomly cutting connections during training) doesn't work well in an RNN, because the noise propagates through time steps and destroys sequential information. Zaremba, Sutskever, and Vinyals showed how to apply dropout correctly: only on the non-recurrent connections (between layers), leaving the recurrent connections intact. This became the standard method for regularizing RNNs.

Recurrent Neural Network Regularization (Zaremba et al., 2014)

Truncated BPTT

For very long sequences (thousands of steps), unrolling the entire network and computing the gradient over everything is prohibitive in memory. The pragmatic solution: cut the sequence into chunks of fixed length (for example 35 or 50 steps) and backpropagate only within each chunk.

The hidden state is passed from one chunk to the next (the forward pass is continuous), but the gradient is cut at chunk boundaries. It's a trade-off: you lose the ability to learn dependencies longer than the chunk size, but you gain memory efficiency and training speed.

Teacher forcing

During training of an RNN in generation mode (one-to-many or many-to-many), you have a choice: feed the network its own prediction from the previous step as input, or give it the correct answer (the correct token from the training set). The second option is called teacher forcing: the "teacher" forces the correct answer.

Teacher forcing considerably speeds up training because the network doesn't wander off into runs of bad predictions. But it creates a problem: in real use the network no longer has a teacher and must carry on from its own predictions, including the bad ones, a situation it never met during training. That gap between training conditions and usage conditions is called exposure bias. A common remedy is to mix the two regimes: sometimes the correct answer, sometimes the model's own prediction.

Bidirectional RNNs

Diagram of a bidirectional recurrent neural network
This diagram illustrates the architecture of a bidirectional Recurrent Neural Network (RNN). The arrows show the flow of information in both temporal directions: forward (left to right) and backward (right to left), enabling better context understanding.Source : Medium

A classic RNN reads the sequence from left to right: each hidden state only contains past context. But for certain tasks, future context is also important. To classify the sentiment of a sentence, knowing how it ends helps understand its beginning.

A BiRNN (Bidirectional RNN) uses two RNNs in parallel:

  • A forward RNN that reads left to right
  • A backward RNN that reads right to left

For each position, the hidden states from both directions are concatenated, giving a vector that captures both past and future. The hidden state size doubles, but the richness of the representation increases considerably.

Warning: BiRNNs are only usable when the complete sequence is available in advance, classification, POS tagging, or NER (Named Entity Recognition: spotting names of people, places and organizations in a text). For generation on the fly (word-by-word translation, dialogue), you don't know the future, so a BiRNN is impossible.

Historical Applications

Before the arrival of the transformer in 2017, RNNs (and especially their LSTM and GRU variants) dominated virtually all sequential tasks:

  • Machine translation (Google Translate 2014-2017, seq2seq architecture)
  • Speech recognition (DeepSpeech, dictation systems)
  • Text generation (character-level language models). To see how impressive RNNs could be at generation, read Andrej Karpathy's post The Unreasonable Effectiveness of Recurrent Neural Networks (2015). He trains character-level RNNs on Shakespeare, Linux source code, and LaTeX; the results are startling, and the piece became a classic for understanding what RNNs could do.
  • Sentiment analysis (review classification, short posts)
  • Time series prediction (finance, weather, IoT sensors, the Internet of Things)
  • Image captioning (CNN + RNN to describe photos)
RNNs Today

The transformer replaced RNNs for NLP (Natural Language Processing) for two reasons developed in Transformer vs RNN: it trains in parallel over the whole sequence, and it links two distant words in a single step.

But the recurrent idea is coming back through another door. State Space Models (SSMs) such as Mamba and S4, and RWKV (Receptance Weighted Key Value), pick recurrence back up while avoiding the vanishing gradient through a different mathematical construction: their recurrence is linear, which makes it possible both to train it in parallel and to unroll it step by step at inference. They thereby recover the RNN's historical advantage, a constant cost per generated token and a memory that does not grow with text length, where the transformer's attention cache keeps growing. Their authors claim performance comparable to the transformer at equal model size; as of 2026 that has been demonstrated on models substantially smaller than the largest language models in service.

Another research direction: Relational RNNs, which enrich the network's memory by letting it explicitly model relationships between the items it has stored, using an attention mechanism across its memory slots. The network can then reason about interactions between remembered items, not merely store them.

Relational Recurrent Neural Networks (Santoro et al., 2018)

Final Intuition

The RNN is the first architecture that gives memory to neural networks. It reads a sequence step by step, updates its hidden state as a running summary, and uses this summary to predict. Its fundamental limitation (the vanishing gradient, which destroys long-term memory) motivated the LSTM and GRU architectures, then the transformer. Understanding the basic RNN is still worth it: it's the conceptual foundation on which all sequence processing was built, and seeing what failed in it is what makes everything that followed look the way it does.

Check your understanding0 / 5

1. In the RNN formulas, what is learned during training, and what is computed for every sentence being read?

2. Why is a basic RNN unable to link a pronoun to a noun mentioned five sentences earlier?

3. Does gradient clipping solve the vanishing gradient problem?

4. During generation training, teacher forcing feeds the network the correct answer from the previous step instead of its own prediction. What problem does that create?

5. Why did the transformer supplant the RNN for language from 2017 onward?