Skip to content
E
Educatum

What limitations of RNNs are addressed by transformer models?

Curated by Educatum AI teamLast updated:
Large Language Models (LLMs)
Direct Answer

Transformers overcome the sequential computation bottleneck and O(n) maximum dependency path length of Recurrent Neural Networks (RNNs) by using self-attention to process all training tokens in parallel and connect any two positions in O(1) path length. This mitigates vanishing gradients across long sequences and removes the fixed-size hidden-state information bottleneck, though Transformers trade RNNs' constant-memory O(1) inference state for O(n^2) prefill compute and an O(n) growing KV cache.

Study Card: Limitations of RNNs Addressed by Transformers

Direct Answer

Transformers (Vaswani et al., 2017) resolve three structural limitations inherent to Recurrent Neural Networks (RNNs, including LSTMs and GRUs):

  1. Sequential Training Bottleneck: Because an RNN computes ht=f(ht−1,xt)h_t = f(h_{t-1}, x_t), step tt cannot run until step t−1t-1 completes (O(n)O(n) sequential operations). Transformers compute all positions simultaneously during training and prefill via matrix multiplications (O(1)O(1) sequential steps), unlocking massive GPU/TPU parallelism and scaling to trillion-token corpora.
  2. O(n) Path Length & Vanishing/Exploding Gradients: Information between tokens separated by distance kk must traverse kk recurrent nonlinear steps via Backpropagation Through Time (BPTT), causing gradients to decay or explode even with LSTM/GRU gating. Self-attention creates an O(1)O(1) direct path length between every pair of tokens regardless of distance.
  3. Fixed-Size Hidden-State Information Bottleneck: RNNs compress an arbitrarily long history into one fixed-width state vector ht∈Rdh_t \in \mathbb{R}^d, overwriting older details. Transformers retain direct random-access retrieval over all past token keys and values.

Important Architectural Trade-offs: In exchange for O(1)O(1) path length and parallel training, vanilla Transformers require explicit positional encodings (since self-attention without a mask is permutation-equivariant), incur O(n2d)O(n^2 d) prefill complexity, and accumulate an O(n)O(n) growing KV cache during autoregressive inference (unlike an RNN’s O(1)O(1) per-step hidden state—a trade-off revisited by modern State-Space Models like Mamba).

Key Terms

  • Maximum Path Length: Number of forward/backward steps signals must traverse between two positions (O(n)O(n) in RNNs vs. O(1)O(1) in self-attention).
  • Training Parallelizability: Ability to compute representations across all sequence positions concurrently rather than serially.
  • Information Bottleneck: Compression loss from forcing an unbounded prefix into a single fixed-dimensional hidden vector hth_t.
  • Scaled Dot-Product Self-Attention: Direct content-based pairwise interactions scaled by 1/dk1/\sqrt{d_k} to keep softmax gradients healthy.
  • KV Cache vs. Recurrent State: Transformers trade RNNs’ constant O(1)O(1) inference state for O(n)O(n) cached keys/values to prevent information loss.

Example

In "The cat, which had been sleeping quietly on the warm sunlit mat for hours, suddenly purred", an RNN must propagate "cat" (singular subject) through more than a dozen intermediate recurrent updates before reaching "purred". A Transformer lets "purred" directly attend to "cat" in a single O(1)O(1) attention hop during both forward pass and gradient backpropagation, while computing all token representations in parallel.

Code Implementation

import torch
import torch.nn as nn
import torch.nn.functional as F

torch.manual_seed(0)

class ScaledSelfAttention(nn.Module):
    """Computes representations across all sequence positions in parallel (O(1) path length)."""
    def __init__(self, input_dim: int, hidden_dim: int):
        super().__init__()
        self.hidden_dim = hidden_dim
        self.query = nn.Linear(input_dim, hidden_dim)
        self.key = nn.Linear(input_dim, hidden_dim)
        self.value = nn.Linear(input_dim, hidden_dim)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # x: (batch_size, seq_len, input_dim)
        Q = self.query(x)
        K = self.key(x)
        V = self.value(x)

        # Scaled dot-product prevents softmax saturation for large hidden_dim
        scores = torch.bmm(Q, K.transpose(1, 2)) / (self.hidden_dim ** 0.5)
        attn_weights = F.softmax(scores, dim=-1)
        return torch.bmm(attn_weights, V)  # (batch_size, seq_len, hidden_dim)

batch_size, seq_len, input_dim, hidden_dim = 32, 10, 512, 256
x = torch.randn(batch_size, seq_len, input_dim)

attn_layer = ScaledSelfAttention(input_dim, hidden_dim)
attn_out = attn_layer(x)
print("Parallel Self-Attention Output Shape:", attn_out.shape)  # (32, 10, 256)

# Compare with sequential RNN (processes tokens step-by-step along seq_len)
rnn = nn.RNN(input_dim, hidden_dim, batch_first=True)
rnn_out, _ = rnn(x)
print("Sequential RNN Output Shape:", rnn_out.shape)             # (32, 10, 256)
  • Positional Encodings (Sinusoidal, RoPE, ALiBi): Required by Transformers to restore sequence order since attention itself lacks recurrence.
  • State-Space Models & Linear RNNs (Mamba, RWKV): Modern architectures combining Transformer-like parallel training (parallel scan) with RNN-like O(1)O(1) inference memory.
  • FlashAttention & KV Caching: Kernel and memory optimizations addressing Transformers’ O(n2)O(n^2) memory and decoding bottlenecks.
  • LSTMs & GRUs: Gated recurrent variants that mitigated—but did not eliminate—vanishing gradients and sequential training limits.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.