Deep LearningDeep Learning Comparison Series

How do recurrent neural networks (RNNs) and Transformers differ for sequence modeling?

Question 309 of 314 · Updated

On this page

Recurrent Neural Networks (RNNs) process a sequence step by step, carrying a hidden state forward. Transformers process sequence positions using attention, allowing each position to combine information from other permitted positions. This makes standard Transformers easier to parallelize across positions during training, while recurrent models have compact state and naturally incremental processing. Standard full self-attention has a quadratic sequence-length cost, so the best architecture depends on task, sequence length, latency, memory, data, and deployment constraints.

1. The core difference: carried state vs direct attention#

A sequence is an ordered collection such as words in a sentence, sensor readings over time, or events in a log.

RNN: compress the past into a hidden state#

A basic RNN updates its hidden state at each time step:

LaTeX
  • is the current input vector.
  • is the summary carried from the previous step.
  • is the updated summary.
  • The same weights are reused at every time step.

The current state can influence later states, but earlier information must travel through the recurrent chain. The model has a fixed-width state vector, regardless of how many time steps have already been read. LSTM and GRU are gated RNN variants designed to improve preservation and control of that information.

Transformer: let positions retrieve relevant context#

A Transformer creates query, key, and value vectors from token representations. For a query at one position, attention scores how relevant each allowed key is, then combines the corresponding values.

LaTeX

Here is the key dimension and M represents an optional mask. Multi-head attention performs this operation in multiple learned representation subspaces, then combines the results. The original Transformer uses attention and feed-forward layers rather than recurrent connections.

Unlike a basic RNN, a Transformer position can directly access information from a distant permitted position in one attention layer. Its representation is not limited to a single fixed-size recurrent summary of the entire past.

2. Beginner-friendly example: remembering a name#

Imagine the sequence:

“Maya left her umbrella at the station because she was in a hurry.”

When processing “she,” the model should connect it to “Maya.”

RNN view

  1. Read “Maya” and update the hidden state.
  2. Read “left,” “her,” “umbrella,” and the remaining words, updating the same state repeatedly.
  3. At “she,” use the current state, which has carried forward a compressed trace of earlier context.

The relevant name must survive the intervening recurrent updates.

Transformer view

  1. Convert each token to a representation and add positional information.
  2. At “she,” calculate attention scores over allowed earlier tokens in a causal model, or over all tokens in a bidirectional encoder.
  3. If “Maya” is useful, its key can receive a high attention weight and its value contributes strongly to the updated “she” representation.

This is an intuition, not a guarantee that a model will resolve every pronoun correctly. Attention weights are learned internal operations and should not automatically be interpreted as faithful explanations.

3. Numerical example: one attention calculation#

Use a tiny one-dimensional example with query q=1, keys k₁=1 and k₂=2, and values v₁=10 and v₂=20. For simplicity, omit the usual scaling factor because d_k=1.

The scores are:

LaTeX

Softmax gives approximately:

LaTeX

The attention output is:

LaTeX

The query combines both values, but gives the second one more weight. In a real Transformer, queries, keys, and values are vectors, scores are computed for many positions and heads, and masks can forbid certain connections.

4. Why position information matters#

An RNN has an explicit order in its repeated update: the state at step t depends on the state at t−1. A standard self-attention operation, by itself, does not encode whether one token came before another. Without position information or another order-aware mechanism, permuting the input tokens can leave the attention operation unaware of the original order.

Transformers therefore add or otherwise incorporate positional information. Common approaches include:

  • Sinusoidal absolute positional encodings: deterministic sine and cosine functions at different frequencies, added to token embeddings in the original Transformer.
  • Learned absolute position embeddings: trainable vectors associated with positions.
  • Relative position methods: represent distances or relationships between positions.
  • Rotary position embeddings (RoPE): rotate query and key features according to position, making relative position information affect attention scores.

Numerical position example#

Suppose token embeddings are two-dimensional:

LaTeX

At position 1, the Transformer input becomes:

LaTeX

If the same token appears at position 4 with p₄=[0.0,0.2], its input becomes [0.2,0.7]. The token identity is the same, but its position-aware representation differs.

The exact position method is architecture-dependent. Do not assume every modern Transformer uses the original sinusoidal encoding.

5. Causal vs bidirectional context#

This distinction is essential when comparing sequence models.

Bidirectional RNN or Transformer encoder#

A bidirectional RNN runs one recurrence from left to right and another from right to left. A standard Transformer encoder without a causal mask lets each position attend to all positions, including tokens on both sides.

This is useful when the complete sequence is available:

  • Sentiment or document classification.
  • Named-entity recognition and offline sequence labeling.
  • Understanding a completed sensor window.
  • Encoding an input sentence before translating it.

Future context is available by design.

Causal RNN or Transformer decoder#

A unidirectional RNN naturally uses only the current and previous inputs. A causal Transformer applies a triangular attention mask so position t cannot attend to positions after t.

For a sequence of four tokens, the allowed causal attention pattern is:

LaTeX

A 1 means attention is allowed; a 0 means blocked. This prevents a next-token model from seeing the answer it is supposed to predict.

Do not confuse bidirectional understanding with causal generation. A standard unmasked Transformer encoder is not a drop-in autoregressive language model. A decoder-only language model uses causal self-attention; encoder-decoder models also use cross-attention from decoder positions to encoder outputs.

6. Sequential vs parallel computation#

RNN execution#

For a conventional RNN, depends on . Therefore, the forward computation for time step t cannot finish before the previous state is available.

For sequence length T:

  • The recurrent dependency chain has T sequential steps.
  • Training must preserve intermediate states for backpropagation through time.
  • Work across different examples in a batch can still be parallelized.
  • A unidirectional RNN can naturally process a live stream one new item at a time.

Transformer execution#

In a Transformer training pass, queries, keys, values, and attention outputs for many positions can be computed together (subject to the attention mask). This makes parallel processing across sequence positions possible.

  • All input positions can participate in a parallel matrix computation during training.
  • A causal mask restricts information flow but does not require the training forward pass to compute one token at a time.
  • Autoregressive generation still produces one new token after another because the next token depends on the preceding generated tokens.
  • KV caching avoids recomputing previous keys and values during generation, but the model still generates sequentially.

This is why Transformers can have high training throughput even though ordinary autoregressive generation is sequential token by token.

7. Computational and memory complexity#

Let T be sequence length, d the Transformer hidden width, and H the RNN hidden width. Exact costs depend on architecture, layer count, feed-forward width, batch size, hardware, and implementation.

Standard recurrent layer#

For a simple RNN with input width I and hidden width H, each time step performs matrix operations on the input and previous hidden state. A rough full-sequence compute scale is:

LaTeX

The recurrent dependency limits parallelism across time. The hidden-state sequence needed for training is typically O(TH) per example, apart from model weights, gradients, and implementation-specific saved activations. LSTM and GRU add gates and therefore larger constant factors.

Standard full self-attention#

For a Transformer layer with hidden width d:

  • Query/key/value projections and output projection scale roughly as O(Td²).
  • The attention score and value aggregation operations scale roughly as O(T²d).
  • Naively materializing attention scores/weights requires O(T²) memory per head and example.

The quadratic term becomes increasingly important as sequence length grows. For short or moderate sequences, parallel matrix operations and accelerator efficiency can make Transformers fast despite the larger theoretical attention term.

What efficient attention changes#

Memory-efficient attention algorithms such as FlashAttention avoid materializing the entire attention matrix in high-bandwidth memory, reducing memory traffic and practical memory use. They do not make exact dense global attention's pairwise arithmetic linear in T: standard full-attention compute still has a quadratic sequence-length term.

There are also sparse, local, and linear-attention variants with different trade-offs. Those are not the same complexity profile as standard dense full attention.

Numerical scale example#

Compare attention score counts for one head:

Increasing sequence length from 128 to 1,024 (8×) increases the pair count by 64×. Increasing from 1,024 to 4,096 (4×) increases it by 16×.

This count illustrates the dense attention matrix, not total model FLOPs or measured runtime. An RNN's recurrent computation grows approximately linearly with T for fixed dimensions, but its serial dependency can make it slower to train than a highly parallel Transformer on accelerators.

8. Long-context behavior and memory#

RNN strengths

  • A fixed-width recurrent state can summarize an arbitrarily long stream without retaining every prior token representation.
  • Online inference can update the state as new observations arrive.
  • The model's recurrent computation and state size do not grow with the number of past steps in the same way as a full attention cache.

RNN limitations

  • The fixed-size state is a compression bottleneck: details can be lost.
  • Information and gradients must travel through repeated state transitions.
  • Vanilla RNNs are especially vulnerable to vanishing/exploding gradients; LSTM and GRU help but do not remove every long-range learning difficulty.
  • Long sequential chains limit training parallelism.

Transformer strengths

  • Direct attention can connect distant positions without passing information through every intermediate recurrent state.
  • Training across positions is highly parallelizable.
  • Large-scale pretraining has made Transformer architectures highly effective across language, vision, audio, and multimodal tasks.

Transformer limitations

  • Standard dense attention has quadratic sequence-length compute and naive attention-memory costs.
  • Autoregressive KV caches grow with context length, number of layers, batch size, and key/value dimensions.
  • A fixed context window limits what can be attended to directly unless the architecture or serving system uses special long-context methods.
  • More context is not automatically better: irrelevant tokens, position handling, and retrieval quality still matter.

A Transformer with KV caching typically stores prior keys and values for each layer. The cache grows approximately linearly with the number of cached tokens for fixed model dimensions, even though full attention over those tokens has a quadratic pairwise compute component.

9. Training and inference trade-offs#

DimensionRNN familyStandard Transformer
Training across time positionsSequential dependencyPositions parallelizable
Long-range informationCarried through recurrent stateDirect attention between permitted positions
Dense sequence computeRoughly linear in T for fixed widthsIncludes quadratic attention term in T
State/cache for streamingFixed-width recurrent stateKV cache grows with generated context
Online input processingNatural step-by-step updatePossible, but architecture and cache strategy matter
Bidirectional contextRun forward and backward passesUnmasked encoder attention
Autoregressive generationOne step at a timeOne token at a time
Hardware utilizationSequential dependency can limit accelerator useLarge parallel matrix operations often map well to accelerators

For generation, do not compare only training throughput. Measure prefill latency, time to first token, inter-token latency, tokens per second, KV-cache memory, batch concurrency, and long-context behavior. RNNs may be attractive for streaming stateful tasks; Transformers often excel when broad contextual interaction and parallel training are valuable.

10. PyTorch implementations#

The examples below compare a vanilla RNN layer with a simple Transformer encoder. They are architectural demonstrations, not a claim that these two small models have matched capacity or accuracy.

A. Vanilla RNN#

PYTHON
import torch from torch import nn batch_size = 16 sequence_length = 40 input_size = 32 hidden_size = 64 x = torch.randn(batch_size, sequence_length, input_size) rnn = nn.RNN( input_size=input_size, hidden_size=hidden_size, num_layers=1, nonlinearity="tanh", batch_first=True, bidirectional=False ) rnn_output, final_hidden = rnn(x) print(rnn_output.shape) # [16, 40, 64] print(final_hidden.shape) # [1, 16, 64]

The output contains a hidden representation at every time step. final_hidden contains the final hidden state for each layer and direction.

B. Transformer encoder#

A Transformer encoder uses self-attention and feed-forward layers. The input feature width must equal d_model.

PYTHON
import torch from torch import nn batch_size = 16 sequence_length = 40 d_model = 64 nhead = 4 x = torch.randn(batch_size, sequence_length, d_model) encoder_layer = nn.TransformerEncoderLayer( d_model=d_model, nhead=nhead, dim_feedforward=128, batch_first=True ) encoder = nn.TransformerEncoder( encoder_layer, num_layers=2 ) encoder_output = encoder(x) print(encoder_output.shape) # [16, 40, 64]

This encoder is bidirectional by default: each position can attend to all positions unless a mask restricts it. For a production model, also add an appropriate input embedding/projection and positional representation. PyTorch notes that the reference Transformer modules provide a foundational implementation with limited features compared with newer specialized architectures.

C. Apply a causal mask#

To prevent position t from seeing future positions, use an upper-triangular boolean mask:

PYTHON
causal_mask = torch.triu( torch.ones(sequence_length, sequence_length, dtype=torch.bool), diagonal=1 ) causal_encoder_output = encoder(x, mask=causal_mask)

For PyTorch Transformer modules, boolean True entries in the attention mask indicate positions that are not allowed to participate. This is different from the boolean mask convention used by some other attention APIs. Check the exact API documentation for the module you use.

This code demonstrates causal masking in an encoder layer; a full decoder-only language model also requires shifted next-token inputs, an output vocabulary head, a suitable loss, and correct training/inference handling.

11. Common mistakes#

  1. Claiming Transformers are inherently parallel during autoregressive generation. Training positions can be parallelized, but generated tokens depend on previous generated tokens.
  2. Assuming RNNs cannot use future context. Bidirectional RNNs can, when the complete sequence is available.
  3. Assuming every Transformer is causal. Encoder-style Transformers are often bidirectional; decoder-style language models use causal masks.
  4. Forgetting positional information. Standard self-attention alone does not encode sequence order.
  5. Calling attention weights explanations. They show a computation's weighting, not necessarily a faithful causal explanation of the model's decision.
  6. Treating O(T²) as every Transformer operation. It describes the sequence-pair attention term; projections and feed-forward layers also matter.
  7. Claiming FlashAttention makes exact dense attention compute linear. It improves memory traffic and avoids materializing the full matrix, while dense pairwise arithmetic remains quadratic.
  8. Ignoring KV-cache memory. Autoregressive inference stores keys and values from prior tokens for each layer.
  9. Comparing unequal models or hardware runs. Match quality targets, dimensions, batch size, precision, sequence lengths, and hardware before comparing speed.
  10. Using a bidirectional model in a causal forecasting pipeline. It can leak future information unavailable at prediction time.
  11. Ignoring padding masks. Padded tokens should not be treated as valid content by attention or sequence pooling.
  12. Assuming long context guarantees long-range recall. Capacity, training, positional method, attention patterns, and input relevance all matter.

12. Practical selection guidance#

Consider an RNN, LSTM, or GRU when:

  • Inputs arrive continuously and you need a compact state update.
  • The task is streaming time-series or sensor processing.
  • Memory for historical context must remain bounded.
  • The sequence model is modest in size and the recurrent dependency is acceptable.
  • You need an online model that carries state between chunks.

Consider a Transformer when:

  • Relationships between distant positions are important.
  • You can benefit from parallel sequence processing during training.
  • You have accelerator capacity and a suitable attention implementation.
  • You need rich contextual representations for language, multimodal, or sequence tasks.
  • The context length and KV-cache footprint fit the deployment budget.

Evaluate both when:

  • Latency, throughput, and quality constraints are tight.
  • Sequences are long or highly variable.
  • The problem mixes streaming inputs with retrospective context.
  • A hybrid, local-attention, sparse-attention, or state-space/recurrent alternative may offer a better trade-off.

A fair experiment should use the same data splits, preprocessing, prediction target, and evaluation protocol. Compare validation quality, performance by sequence length, training throughput, peak memory, inference latency, and serving cost on the actual hardware. For online tasks, explicitly test that no future information enters the prediction.

13. Key takeaway#

An RNN moves information forward through a recurrent hidden state; a Transformer uses attention to connect sequence positions directly. RNNs offer natural streaming and compact state, but sequential computation can constrain training speed and long-range memory. Transformers parallelize training across positions and model direct contextual relationships, but standard dense attention has quadratic sequence-length costs and autoregressive inference requires sequential token generation with a growing KV cache. Choose based on the task's context needs and measured deployment constraints—not on the assumption that one architecture is always better.

14. Further reading and references#

  • Vaswani et al. (2017), *Attention Is All You Need*: https://arxiv.org/abs/1706.03762
  • PyTorch torch.nn.RNN: https://docs.pytorch.org/docs/stable/generated/torch.nn.RNN.html
  • PyTorch torch.nn.TransformerEncoder: https://docs.pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html
  • PyTorch torch.nn.TransformerEncoderLayer: https://docs.pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html
  • Katharopoulos et al. (2020), *Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention*: https://proceedings.mlr.press/v119/katharopoulos20a.html
  • Shaw et al. (2018), *Self-Attention with Relative Position Representations*: https://arxiv.org/abs/1803.02155
  • Dao et al. (2022), *FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness*: https://arxiv.org/abs/2205.14135

Related questions

Explore other topics:Machine LearningLarge Language Models