3.5.9Sequence Models

The attention mechanism intuition

2,793 words13 min readdifficulty · medium6 backlinks

WHY attention solves the bottleneck: Fixed-length context vectors lose information for long sequences. Attention creates a dynamic, weighted summary of the input for each decoder step.

What Is Attention?

WHAT it does functionally:

  1. At decoder timestep tt, compute an alignment score between the previous decoder state st1s_{t-1} and each encoder hidden state hih_i
  2. Convert scores to attention weights via softmax (they sum to 1)
  3. Compute context vector ctc_t as weighted sum: ct=iαtihic_t = \sum_i \alpha_{ti} h_i
  4. Use ctc_t alongside sts_t to predict output

HOW it differs from vanilla seq2seq: Vanilla uses only the last encoder state hnh_n. Attention uses all h1,h2,,hnh_1, h_2, \ldots, h_n with learned weights.

Deriving Attention from First Principles

Step 1: The Alignment Function

WHY we need alignment: Before updating the decoder at step tt, we have the previous decoder state st1s_{t-1}. We want to know "which input positions are relevant now?" We measure relevance by a score function using st1s_{t-1}.

WHY use st1s_{t-1} not sts_t: In the standard Bahdanau ordering, the context ctc_t is needed to compute sts_t. So we can't use sts_t (it doesn't exist yet)—we align using the previous state st1s_{t-1}, then form ctc_t, then update to sts_t.

WHY this formula: We need a single scalar score. Concatenating/adding st1s_{t-1} and hih_i directly fails if dimensions differ. The tanh layer learns a nonlinear alignment space. The final dot product with vav_a reduces to a scalar.

Alternative (Multiplicative/Luong): eti=stTWahie_{ti} = s_t^T W_a h_i — simpler, used when ds=dhd_s = d_h (Luong applies it after computing sts_t).

Step 2: Attention Weights via Softmax

WHY softmax: Scores etie_{ti} are unbounded and don't sum to 1. We want a probability distribution over input positions.

WHY this step is crucial: αti[0,1]\alpha_{ti} \in [0,1] and iαti=1\sum_i \alpha_{ti} = 1. This makes attention interpretable: "41% focus on word 3, 28% on word 5, etc."

Step 3: Context Vector

WHY weighted sum: Each hih_i encodes information about position ii. The context ctc_t is a custom-built summary: high-α\alpha positions contribute more. This is a soft lookup (vs. hard selection).

Step 4: Decoder Update

The context vector ctc_t is fed into the decoder RNN alongside the previous hidden state and embedding:

where ff is RNN update (GRU/LSTM), gg is output projection (often softmax(W[st;ct])\text{softmax}(W[s_t; c_t])).

WHY include ctc_t twice: Once to update state (what information to store), once to generate output (what to emit). Empirically improves performance.

Worked Example 1: Translation Attention

Task: Translate "Je suis étudiant" → "I am a student"

Setup:

  • Encoder produces h1,h2,h3h_1, h_2, h_3 for "Je", "suis", "étudiant"
  • Decoder at t=1t=1 generates "I", at t=2t=2 generates "am", etc.

At t=2t=2 (generating "am"):

  • Previous decoder state s1s_1 (after emitting "I")
  • Compute scores: e21=vTtanh(Ws1+Uh1)e_{21} = v^T \tanh(W s_1 + U h_1), e22e_{22}, e23e_{23}
  • Say e21=0.3e_{21} = 0.3, e22=2.1e_{22} = 2.1, e23=0.5e_{23} = 0.5
  • Denominator: exp(0.3)+exp(2.1)+exp(0.5)=1.350+8.166+1.649=11.165\exp(0.3) + \exp(2.1) + \exp(0.5) = 1.350 + 8.166 + 1.649 = 11.165
  • Softmax: α21=exp(0.3)11.165=1.35011.165=0.12\alpha_{21} = \frac{\exp(0.3)}{11.165} = \frac{1.350}{11.165} = 0.12
  • α22=exp(2.1)11.165=8.16611.165=0.73\alpha_{22} = \frac{\exp(2.1)}{11.165} = \frac{8.166}{11.165} = 0.73, α23=exp(0.5)11.165=1.64911.165=0.15\alpha_{23} = \frac{\exp(0.5)}{11.165} = \frac{1.649}{11.165} = 0.15
  • Context: c2=0.12h1+0.73h2+0.15h3c_2 = 0.12\, h_1 + 0.73\, h_2 + 0.15\, h_373% focus on "suis"
  • WHY this makes sense: "am" translates "suis", so attention correctly identifies the source word

At t=4t=4 (generating "student"):

  • s3s_3 now carries context of "I am a"
  • Scores favor h3h_3 ("étudiant"): α430.85\alpha_{43} \approx 0.85
  • Context c4c_4 is mostly h3h_3
  • Decoder uses c4c_4 to generate "student"

WHY this works: Attention learned the alignment "student ↔ étudiant" from data, without explicit word-to-word labels.

Worked Example 2: Attention for Long Sequences

Problem: Translate a 50-word sentence. Fixed context vector loses details.

With Attention:

  • Encoder produces h1,,h50h_1, \ldots, h_{50}
  • At decoder step t=30t=30, attention might give:
    • α30,25=0.6\alpha_{30,25} = 0.6 (word 25 is relevant)
    • α30,26=0.3\alpha_{30,26} = 0.3 (word 26 is relevant)
    • α30,i0\alpha_{30,i} \approx 0 for i{25,26}i \notin \{25,26\}
  • WHY this scales: Information isn't squeezed through a bottleneck. Each decoder step gets a fresh, focused view of the input.

Computational cost: O(Tx×Ty)O(T_x \times T_y) attention scores. For Tx=50T_x=50, Ty=50T_y=50, that's 2500 scores—manageable. (Later: sparse attention for Tx=1000+T_x=1000+.)

Common Mistakes

Reality: Attention augments the encoder-decoder. The RNN encoder still processes the input sequentially to build hih_i (which capture context). Attention is a lookup mechanism over those representations. Without the RNN, hih_i would just be embeddings—no temporal context.

The fix: Think of attention as "which encoder states to use" not "how to encode."

Reality: Attention is correlation-based. High α\alpha means the model found hih_i useful for predicting yty_t, but it could be:

  • Syntactic agreement (gender/number)
  • Co-occurrence (idioms)
  • Spurious correlation (the model cheating)

The fix: Attention is interpretability, not causality. Always validate attention patterns against linguistic/domain knowledge.

Reality: If all scores etie_{ti} are similar, softmax gives uniform αti1/Tx\alpha_{ti} \approx 1/T_x (no focus). The model can learn to attend broadly or sharply depending on the task. For some tasks (e.g., summarization), diffuse attention is correct.

The fix: Examine attention entropy: H=iαtilogαtiH = -\sum_i \alpha_{ti} \log \alpha_{ti}. Low entropy = focused, high = diffuse. Both can be correct.

Visualizing Attention

Attention heatmap: Rows = decoder steps, columns = encoder steps, color = αti\alpha_{ti}.

  • Diagonal pattern → monotonic alignment (speech recognition, OCR)
  • Scattered pattern → reordering (English-Japanese translation)
  • Vertical bands → many-to-one (compound words)

Example: Translating "neural machine translation" → "traduction automatique neuronale" (French). Attention might show:

  • "traduction" attends to "translation" (word 3)
  • "automatique" attends to "machine" (word 2)
  • "neuronale" attends to "neural" (word 1)
  • Order reversed: English (1,2,3) → French (3,2,1)

Mathematical Properties

Property 1: Permutation Invariance of Encoder (Almost) If you permute encoder outputs hih_i, attention weights αti\alpha_{ti} permute identically. The context ctc_t is the same. Caveat: RNN encoders aren't permutation invariant (they process sequentially), but the attention mechanism itself is.

Property 2: Context Vector is Convex Combination ct=iαtihic_t = \sum_i \alpha_{ti} h_i with αti0\alpha_{ti} \geq 0, iαti=1\sum_i \alpha_{ti} = 1 means ctc_t lies in the convex hull of {hi}\{h_i\}. It's an interpolation, not extrapolation.

Property 3: Gradient Flow Every hih_i receives gradient from the loss at every decoder step tt (weighted by αti\alpha_{ti}). This mitigates vanishing gradients for long sequences—encoder position 1 still gets strong signal if it's attended to at step 50.

Connections to Other Concepts

To RNN and LSTM fundamentals: Attention addresses the long-term dependency problem from a different angle. LSTMs use gating to control information flow over time. Attention uses weighted aggregation over space (sequence positions).

To Encoder-decoder architecture: Attention modifies the decoder to accept a dynamic context vector ctc_t instead of a single fixed vector cc.

To Transformers and self-attention: Attention generalizes to self-attention (query=key=value from same sequence) and multi-head attention (multiple attention functions in parallel). The core "weighted sum over representations" is identical.

To Seq2seq models: Seq2seq + attention is the dominant architecture pre-Transformer. Attention was the breakthrough that made seq2seq viable for long sequences.

To Information bottleneck: Attention removes the bottleneck by giving the decoder access to the full encoder state history, not a compressed fixed vector.

Recall Explain to a 12-Year-Old

Imagine you're writing an essay about your summer vacation, and you have 20 pages of notes. A bad way: read all 20 pages once, close the notebook, then write the essay from memory. You'll forget stuff! A better way: keep the notebook open. When writing about the beach trip, look at the beach pages. When writing about the birthday party, look at the party pages. That's attention! The computer model keeps all its "notes" (the input) available. When it's writing each word of the output, it decides which notes to look at and how carefully to read them. The "attention weights" are like highlighter intensity—80% bright yellow on one note, 15% on another, 5% on the rest. Then it combines those highlighted notes to decide what word to write. This way, it never forgets, because it always has the notes right there to look at!

Connections

  • RNN and LSTM fundamentals
  • Encoder-decoder architecture
  • Seq2seq models
  • Transformers and self-attention
  • Information bottleneck
  • Gradient flow in deep networks
  • Neural machine translation

#flashcards/ai-ml

What problem does attention solve in sequence-to-sequence models? :: Attention solves the information bottleneck problem where a fixed-length context vector fails to capture long input sequences. It allows the decoder to selectively focus on relevant input positions at each decoding step.

What are the three main steps in computing attention?
1. Compute alignment scores etie_{ti} between previous decoder state st1s_{t-1} and each encoder state hih_i. 2. Apply softmax to get attention weights αti\alpha_{ti} that sum to 1. 3. Compute context vector ct=iαtihic_t = \sum_i \alpha_{ti} h_i as weighted sum of encoder states.
What is the formula for Bahdanau attention alignment score?
eti=vaTtanh(Wast1+Uahi)e_{ti} = v_a^T \tanh(W_a s_{t-1} + U_a h_i) where st1s_{t-1} is the previous decoder state, hih_i is encoder state, WaW_a, UaU_a are projection matrices, and vav_a is a learned weight vector.
Why does Bahdanau attention use st1s_{t-1} instead of sts_t for alignment?
Because the context vector ctc_t is needed to compute sts_t. Since sts_t doesn't exist yet, we align using the previous state st1s_{t-1}, then form ctc_t, then update to sts_t.
Why do we use softmax on alignment scores?
Softmax converts unbounded scores etie_{ti} into a probability distribution αti\alpha_{ti} where each weight is in [0,1][0,1] and they sum to 1. This makes attention interpretable as "percentage of focus" on each input position.
What is the context vector in attention?
The context vector ct=i=1Txαtihic_t = \sum_{i=1}^{T_x} \alpha_{ti} h_i is a weighted sum of all encoder hidden states, where weights αti\alpha_{ti} determine how much each position contributes. It's a dynamic, custom summary of the input for decoder step tt.
How does attention help with gradient flow?
Every encoder hidden state hih_i receives gradient from every decoder timestep tt (weighted by αti\alpha_{ti}). This provides strong gradient signal even to early encoder positions when they're attended to at late decoder steps, mitigating vanishing gradients.
What does a high attention weight αti\alpha_{ti} mean?
αti\alpha_{ti} indicates the model finds encoder position ii relevant for generating output at decoder step tt. It shows correlation, not causation—it could reflect translation alignment, syntactic agreement, or learned patterns.
Why include the context vector ctc_t both in RNN update and output projection?
Including ctc_t in the RNN update (st=f(st1,yt1,ct))(s_t = f(s_{t-1}, y_{t-1}, c_t)) lets it influence internal state. Including it in output (yt=g(st,ct))(y_t = g(s_t, c_t)) lets it directly inform generation. Empirically, both usages improve performance.
What does an attention heatmap diagonal pattern indicate?
A diagonal pattern (high αti\alpha_{ti} when iti \approx t) indicates monotonic alignment where input and output follow the same order, common in speech recognition and OCR tasks.

What is the computational complexity of attention for sequences of length TxT_x and TyT_y? :: O(Tx×Ty)O(T_x \times T_y) because we compute TxT_x scores for each of TyT_y decoder steps. For a 50-word input and 50-word output, that's 2,500 score computations per sample.

Concept Map

compresses input into

loses info for

solved by

uses all

scored against h_i by

scored by

Bahdanau additive

softmax normalizes

weighted sum of h_i

combined with s_t to

enables update to

Vanilla seq2seq

Fixed context vector

Long sequences bottleneck

Attention Mechanism

Encoder states h_i

Prev decoder state s_t-1

Alignment function

Alignment scores e_ti

Attention weights alpha_ti

Context vector c_t

Predict output

Decoder state s_t

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, yahan core problem samajhna zaroori hai. Purane seq2seq models mein poori input sentence ko ek single fixed vector mein squeeze kar dete the — jaise ek poori kitaab ko ek line mein yaad karne ki koshish karna. Chhoti sentences ke liye theek hai, par lambi sequences mein bahut information lost ho jaati thi, kyunki sab kuch ek hi vector mein compress ho raha hai. Yahi bottleneck problem hai. Attention mechanism isko solve karta hai — ye decoder ko allow karta hai ki har output word banate waqt woh input ke sirf relevant parts pe selectively focus kare, jaise kitaab khuli rakhkar exact page dekhna jahan se answer chahiye.

Ab isko step-by-step samjho. Jab decoder timestep tt pe naya word predict karna hota hai, toh pehle woh previous decoder state st1s_{t-1} ko har encoder hidden state hih_i ke saath compare karta hai — isse alignment score milta hai jo batata hai ki kaunsa input word abhi kitna relevant hai. Phir softmax lagakar in scores ko attention weights (αti\alpha_{ti}) mein convert karte hain jo 0 se 1 ke beech hote hain aur total sum 1 hota hai — yani ek probability distribution ban jaati hai (jaise "41% focus word 3 pe, 28% word 5 pe"). Finally, in weights ka use karke saare hih_i ka weighted sum nikaalte hain, jise context vector ctc_t kehte hain. Jo positions zyada relevant hain, unka contribution zyada hota hai — ye ek "soft" lookup hai.

Ye matter isliye karta hai kyunki attention ne machine translation, text summarization, aur baad mein Transformers jaise powerful models ka rasta khola. Iska sabse bada faayda ye hai ki ab model har output step ke liye ek dynamic, custom summary banata hai poore input ka, na ki ek fixed compressed vector pe depend karta hai. Aur bonus — attention weights interpretable hote hain, matlab tum literally dekh sakte ho ki model kis word pe dhyan de raha hai jab woh koi output nikaal raha hai. Yahi intuition aage chalke modern LLMs ki foundation banti hai, isliye ise achhe se pakadna zaroori hai.

Go deeper — visual, from zero

Test yourself — Sequence Models

Connections