4.1.1Transformer Architecture

Limitations of RNNs motivating transformers

3,308 words15 min readdifficulty · medium

Overview

Recurrent Neural Networks (RNNs) were the dominant architecture for sequence modeling from the 1990s through 2016, but they suffer from fundamental architectural constraints that transformers were explicitly designed to overcome. Understanding why RNNs fail is critical to appreciating why the transformer architecture works.

Figure — Limitations of RNNs motivating transformers

Core Problem: Sequential Processing Bottleneck

Limitation 1: Cannot Parallelize Across Time

The Math: Why Paralelization is Impossible

Starting from the RNN recurrence relation:

ht=tanh(Whhht1+Wxhxt+bh)h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)

Let's try to compute h3h_3 directly. We need: h3=tanh(Whhh2+Wxhx3+bh)h_3 = \tanh(W_{hh} h_2 + W_{xh} x_3 + b_h)

But h2h_2 requires: h2=tanh(Whhh1+Wxhx2+bh)h_2 = \tanh(W_{hh} h_1 + W_{xh} x_2 + b_h)

And h1h_1 requires: h1=tanh(Whhh0+Wxhx1+bh)h_1 = \tanh(W_{hh} h_0 + W_{xh} x_1 + b_h)

Conclusion: To compute hth_t, we MUST sequentially compute h1,h2,,ht1h_1, h_2, \ldots, h_{t-1} first. There is no way to "skip ahead" because each hidden state is a non-linear function of the previous one.

Limitation 2: Vanishing Gradient Problem

Deriving the Gradient Flow

During backpropagation through time (BPTT), gradients must flow backward through the recurrence:

Lh1=LhThThT1hT1hT2h2h1\frac{\partial \mathcal{L}}{\partial h_1} = \frac{\partial \mathcal{L}}{\partial h_T} \cdot \frac{\partial h_T}{\partial h_{T-1}} \cdot \frac{\partial h_{T-1}}{\partial h_{T-2}} \cdots \frac{\partial h_2}{\partial h_1}

For a vanilla RNN with ht=tanh(Whhht1+Wxhxt+bh)h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h):

htht1=diag(tanh(Whhht1+Wxhxt+bh))Whh\frac{\partial h_t}{\partial h_{t-1}} = \text{diag}(\tanh'(W_{hh} h_{t-1} + W_{xh} x_t + b_h)) \cdot W_{hh}

Since tanh(z)=1tanh2(z)(0,1]\tanh'(z) = 1 - \tanh^2(z) \in (0, 1], and typically tanh(z)<1\tanh'(z) < 1 for most values:

htht1σmax(Whh)γ\left\| \frac{\partial h_t}{\partial h_{t-1}} \right\| \approx \sigma_{\max}(W_{hh}) \cdot \gamma

where γ<1\gamma < 1 is the average derivative of tanh\tanh.

OverT$ timesteps:

hTh1(σmax(Whh)γ)T1\left\| \frac{\partial h_T}{\partial h_1} \right\| \approx (\sigma_{\max}(W_{hh}) \cdot \gamma)^{T-1}

Limitation 3: Fixed Compression Bottleneck

The Information Theory Perspective

An RNN encoder must compress an entire input sequence x1,,xTx_1, \ldots, x_T into a single fixed-size vector hTh_T (the final hidden state).

Attention Mechanism: A Partial Solution

The attention mechanism (Bahdanau et al., 2014) was introduced specifically to address the fixed bottleneck:

αij=exp(eij)k=1Texp(eik),eij=score(hidec,hjenc)\alpha_{ij} = \frac{\exp(e_{ij})}{\sum_{k=1}^T \exp(e_{ik})}, \quad e_{ij} = \text{score}(h_i^{\text{dec}}, h_j^{\text{enc}})

ci=j=1Tαijhjencc_i = \sum_{j=1}^T \alpha_{ij} h_j^{\text{enc}}

The decoder can now "look back" at ALL encoder hidden states h1,,hTh_1, \ldots, h_T, not just the final hTh_T.

Limitation 4: Difficulty with Long-Range Dependencies

Quantifying the Long-Range Problem

Consider learning the dependency between tokens at positions ii and jj where ij=k|i - j| = k.

In an RNN:

  • The gradient path has length kk (must propagate through kk intermediate steps)
  • Gradient magnitude scales as γk\gamma^k where γ<1\gamma < 1
  • Effective learning diminishes exponentially with distance kk

In a Transformer:

  • Direct connection via self-attention: position ii attends to position jj directly
  • Gradient path has length 1 (plus the depth of the network, but not the sequence length)
  • Learning is equally effective for all distances

Limitation 5: Memory and Computation Inefficiency

Training Complexity

RNN Training:

  • Must store all hidden states h1,,hTh_1, \ldots, h_T for backpropagation (BPTT)
  • Memory: O(Td)O(T \cdot d) where dd is hidden size
  • Cannot checkpoint efficiently because each hth_t depends on ht1h_{t-1}

Transformer Training:

  • No sequential dependency; can use activation checkpointing
  • Recompute activations during backward pass instead of storing
  • Memory: O(Td)O(\sqrt{T} \cdot d) with checkpointing

Why Transformers Were Revolutionary

Recall Explain to a 12-year-old

Imagine you're trying to understand a long story by listening to it one word at a time, but you have a really bad memory. By the time you hear word 100, you've forgotten what word 1 was about. That's how RNNs work - they have to process words in order and they forget stuff from a long time ago.

Now imagine instead you could see the ENTIRE story written down, and you could look at any part of it whenever you want. You could see word 1 and word 100 at the same time! You could even have multiple people reading different parts simultaneously. That's how transformers work - they can "see" all the words at once and pay attention to any word they need, no matter how far apart the words are.

The result? Transformers are:

  1. Way faster - like having 100 people read different parts vs. 1 person reading word-by-word
  2. Better memory - they can remember connections between words even if they're really far apart
  3. Smarter understanding - they can see how ALL the words relate to each other, not just nearby words

The Transformer Solution: Three Key Innovations

  1. Self-Attention: Every position directly connects to every other position Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

  2. Positional Encoding: Since there's no sequential processing, positions are encoded explicitly PE(pos,2i)=sin(pos/100002i/d)PE_{(pos, 2i)} = \sin(pos / 10000^{2i/d})

  3. Parallel Processing: All positions compute simultaneously

    • Position 1 computes its representation while position 1000 computes its representation
    • No waiting for previous timesteps

Connections


Flashcards

#flashcards/ai-ml

What is the sequential processing bottleneck in RNNs? :: RNNs compute hidden states iteratively as ht=f(ht1,xt)h_t = f(h_{t-1}, x_t), creating a causal chain where hth_t cannot be computed until ht1h_{t-1} is available. This makes computation O(T)O(T) sequential steps that cannot be parallelized.

Why't RNNs parallelize computation across time?
Because each hidden state hth_t is a non-linear function of the previous state ht1h_{t-1}, there's no way to compute hth_t without first computing all h1,h2,,ht1h_1, h_2, \ldots, h_{t-1} in sequence.

Derive the vanishing gradient formula for RNNs over T timesteps :: Starting from htht1=diag(tanh())Whh\frac{\partial h_t}{\partial h_{t-1}} = \text{diag}(\tanh'(\cdot)) \cdot W_{hh}, we have htht1σmax(Whh)γ\left\|\frac{\partial h_t}{\partial h_{t-1}}\right\| \approx \sigma_{\max}(W_{hh}) \cdot \gamma where γ<1\gamma < 1. Over TT steps, gradients decay as (σmax(Whh)γ)T1(\sigma_{\max}(W_{hh}) \cdot \gamma)^{T-1}. If this product is less than 1, gradients vanish exponentially.

What is the compression bottleneck in encoder-decoder RNNs?
The encoder must compress the entire input sequence x1,,xTx_1, \ldots, x_T into a single fixed-size hidden state hTRdh_T \in \mathbb{R}^d. This creates an information bottleneck: a dd-dimensional vector has limited capacity while the sequence may contain Tlog2VT \log_2 V bits of information.
How much faster can transformers be than RNNs on long sequences?
Transformers have O(1)O(1) parallel time complexity compared to RNNs' O(T)O(T) sequential time. On sequences of length T=1000T=1000 with sufficient parallel hardware, transformers can be ~1000× faster in wall-clock time.

Why do LSTMs NOT fully solve the vanishing gradient problem? :: LSTMs mitigate but don't eliminate the problem. The forget gate ftf_t still multiplies the gradient: ctct1=ft\frac{\partial c_t}{\partial c_{t-1}} = f_t. If ft<1f_t < 1 at most steps, gradients still decay exponentially, just more slowly. LSTMs extend effective range from ~10 to ~100 steps, but problems return for1000+ token sequences.

What is the effective context window formula for RNNs?
Define effective context as distance kk where gradient decays to 1%: γk=0.01\gamma^k = 0.01, so k=log(0.01)log(γ)k = \frac{\log(0.01)}{\log(\gamma)}. For vanilla RNN with γ=0.95\gamma=0.95: k90k \approx 90 steps. For LSTM with γ=0.99\gamma=0.99: k459k \approx 459 steps.
How does self-attention solve the long-range dependency problem?
Self-attention creates direct connections between all positions: position ii attends to position jj with a single matrix operation, regardless of distance ij|i-j|. The gradient path has length 1 (not length ij|i-j|), eliminating exponential decay with distance.

Concept Map

uses

creates

causes

causes

causes

results in

leads to

motivates

motivates

relies on

enables

solves

RNNs for sequences

Recurrence ht=f h t-1, xt

Causal dependency chain

No parallelization

Long-range info loss

Training inefficiency

Sequential time O of T

GPUs sit idle

Transformers

Self-attention

Parallel time O of 1

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Chalो is concept ko simple tarike se samajhte hain. RNN ka sabse bada problem ye hai ki wo sequence ko ek-ek karke, order mein process karta hai - jaise tum ek book ko word-by-word padho aur word 1000 tak pahunchne ke liye pehle 1 se 999 tak saare words padhne padein. Iska matlab hai ki har step ka answer previous step par depend karta hai (yaad rakho: ht=f(ht1,xt)h_t = f(h_{t-1}, x_t)). Isse do badi problems aati hain - ek to parallelization possible nahi hai, kyunki har step ko previous step ka wait karna padta hai; aur doosra, jab sequence lambi ho jaati hai to shuruaat ki information dheere-dheere "fuzzy" ho jaati hai, matlab long-range dependencies kamzor pad jaati hain.

Ab ye matter kyun karta hai? Aajkal humaare paas powerful GPUs hain jinme hazaaron CUDA cores hote hain jo ek saath kaam kar sakte hain. Lekin RNN mein, kyunki processing sequential hai, ye saare cores idle baithe rehte hain - sirf ek timestep hi ek time par compute ho sakta hai. Socho, 5000 cores mein se sirf 32 use ho rahe hain aur baaki 4968 khaali! Yahi wajah hai ki RNN training bahut slow ho jaati hai. Transformer isi problem ko solve karta hai - self-attention ki madad se saari positions ek saath, simultaneously compute ho jaati hain, jisse position 512 direct position 1 ko "dekh" sakti hai bina beech ke saare steps ka wait kiye. Isse training kai guna tez ho jaati hai.

Doosra important point hai vanishing gradient problem. Jab RNN train hota hai, gradients ko backward flow karna padta hai poore sequence ke through - matlab agar 1000 timesteps hain to gradient ko 1000 multiplications se guzarna padta hai. Har multiplication mein value thodi chhoti hoti jaati hai, aur end tak gradient itna chhota ho jaata hai ki network shuruaat ke words se effectively kuch seekh hi nahi paata. Yahi teen limitations - no parallelization, information loss, aur vanishing gradients - transformer architecture ke banne ki asli motivation hain. Jab tum transformer ka design samajhoge, to har feature isi problem ka solution nazar aayega, isliye ye foundation samajhna zaroori hai.

Go deeper — visual, from zero

Test yourself — Transformer Architecture

Connections