3.5.10Sequence Models

Bahdanau and Luong attention

3,535 words16 min readdifficulty · medium

What Are Bahdanau and Luong Attention?

Bahdanau attention (also called additive attention) and Luong attention (also called multiplicative attention) are two pionering mechanisms that allow neural sequence models to selectively focus on different parts of the input when generating each output token.

The fundamental difference: HOW they compute alignment scores between decoder and encoder states.

The Shared Framework

Both mechanisms follow this pattern:

  1. Alignment Scoring: Compute how relevant each encoder hidden state is to the current decoder state
  2. Attention Weights: Convert scores to a probability distribution (softmax)
  3. Context Vector: Weighted sum of encoder states using attention weights
  4. Output Generation: Use context vector (+ decoder state) to predict next token
Figure — Bahdanau and Luong attention

Bahdanau Attention (Additive/Concat)

Derivation from First Principles

Setup:

  • Encoder hidden states: h1,h2,,hT\mathbf{h}_1, \mathbf{h}_2, \ldots, \mathbf{h}_T (each Rdh\in \mathbb{R}^{d_h})
  • Decoder state at step tt: st1Rds\mathbf{s}_{t-1} \in \mathbb{R}^{d_s}
  • We need to generate output yty_t

Step 1: Alignment Score Function

WHY concatenate? We want to capture the interaction between decoder state and each encoder state. A simple dot product (Luong) assumes the spaces are already aligned; Bahdanau learns an alignment function.

eti=vaTtanh(Wast1+Uahi)e_{ti} = v_a^T \tanh(W_a \mathbf{s}_{t-1} + U_a \mathbf{h}_i)

WHERE:

  • WaRda×dsW_a \in \mathbb{R}^{d_a \times d_s} projects decoder state
  • UaRda×dhU_a \in \mathbb{R}^{d_a \times d_h} projects encoder state
  • vaRdav_a \in \mathbb{R}^{d_a} is the alignment weight vector
  • dad_a is the attention dimension (hyperparameter, often 128-512)

Why this form?

  1. Project both states into a common space (dad_a)
  2. tanh\tanh provides non-linearity (allows learning complex alignments)
  3. vaTv_a^T reduces to scalar score

This is a single-layer feedforward network with dad_a hidden units.

Step 2: Attention Weights

Convert scores to probability distribution (MUST sum to 1, all positive):

αti=exp(eti)j=1Texp(etj)\alpha_{ti} = \frac{\exp(e_{ti})}{\sum_{j=1}^{T} \exp(e_{tj})}

WHY softmax? Ensures iαti=1\sum_i \alpha_{ti} = 1 (proper probability distribution) and emphasizes high-scoring positions (exponential amplification).

Step 3: Context Vector

Weighted average of all encoder states:

ct=i=1Tαtihi\mathbf{c}_t = \sum_{i=1}^{T} \alpha_{ti} \mathbf{h}_i

This is the "summary" of input that's relevant for predicting yty_t.

Step 4: Decoder Update

Bahdanau concatenates context BEFORE the RNN step:

y~t1=[yt1;ct]\tilde{\mathbf{y}}_{t-1} = [\mathbf{y}_{t-1}; \mathbf{c}_t]

st=GRU(y~t1,st1)\mathbf{s}_t = \text{GRU}(\tilde{\mathbf{y}}_{t-1}, \mathbf{s}_{t-1})

p(yty<t,x)=softmax(Wost)p(y_t | y_{<t}, \mathbf{x}) = \text{softmax}(W_o \mathbf{s}_t)

Why concatenate before? This is input-feeding: the context influences the RNN state update itself, giving attention information more direct control over the hidden state evolution.

Luong Attention (Multiplicative)

Three Scoring Variants

Luong proposed three alignment functions:

1. Dot Product (simplest): score(st,hi)=stThi\text{score}(\mathbf{s}_t, \mathbf{h}_i) = \mathbf{s}_t^T \mathbf{h}_i

WHY this works: If decoder and encoder states are in the same semantic space, high similarity = high relevance. No parameters!

Limitation: Requires ds=dhd_s = d_h.

2. General/Bilinear (most common): score(st,hi)=stTWahi\text{score}(\mathbf{s}_t, \mathbf{h}_i) = \mathbf{s}_t^T W_a \mathbf{h}_i

WHERE WaRds×dhW_a \in \mathbb{R}^{d_s \times d_h} is a learned weight matrix.

WHY better? Learns to map encoder space to decoder space. Handles dsdhd_s \neq d_h. Still computationally cheap (single matrix multiply).

3. Concat (similar to Bahdanau): score(st,hi)=vaTtanh(Wa[st;hi])\text{score}(\mathbf{s}_t, \mathbf{h}_i) = v_a^T \tanh(W_a[\mathbf{s}_t; \mathbf{h}_i])

Complete Luong Attention (General)

Step 1: Decoder RNN First (KEY DIFFERENCE)

st=RNN(yt1,st1)\mathbf{s}_t = \text{RNN}(\mathbf{y}_{t-1}, \mathbf{s}_{t-1})

Compute decoder state WITHOUT attention first.

Step 2: Alignment Scores

eti=stTWahie_{ti} = \mathbf{s}_t^T W_a \mathbf{h}_i

Step 3: Attention Weights

αti=exp(eti)j=1Texp(etj)\alpha_{ti} = \frac{\exp(e_{ti})}{\sum_{j=1}^{T} \exp(e_{tj})}

Step 4: Context Vector

ct=i=1Tαtihi\mathbf{c}_t = \sum_{i=1}^{T} \alpha_{ti} \mathbf{h}_i

Step 5: Attentional Hidden State

The key innovation—combine decoder state and context:

s~t=tanh(Wc[st;ct])\tilde{\mathbf{s}}_t = \tanh(W_c[\mathbf{s}_t; \mathbf{c}_t])

WHERE WcRds×(ds+dh)W_c \in \mathbb{R}^{d_s \times (d_s + d_h)}.

WHY? This learned combination decides how much to rely on context vs. decoder state. tanh\tanh bounds the output, preventing explosion.

Step 6: Output

p(yty<t,x)=softmax(Wos~t)p(y_t | y_{<t}, \mathbf{x}) = \text{softmax}(W_o \tilde{\mathbf{s}}_t)

Side-by-Side Comparison

Aspect Bahdanau (Additive) Luong (Multiplicative)
When computed Before decoder RNN step After decoder RNN step
Uses decoder state st1\mathbf{s}_{t-1} (previous) st\mathbf{s}_t (current)
Score function vaTtanh(Was+Uah)v_a^T \tanh(W_a \mathbf{s} + U_a \mathbf{h}) sTWah\mathbf{s}^T W_a \mathbf{h} (general)
Complexity O(Tda(ds+dh))O(T \cdot d_a \cdot (d_s + d_h)) O(Tdsdh)O(T \cdot d_s \cdot d_h)
Parameters More (3 weight matrices) Fewer (1-2 weight matrices)
Input feeding Yes (context fed to RNN) No (context combined after)
Speed Slower Faster
Performance Slightly better on long sequences Competitive, often preferred

WHY the timing difference matters:

  • Bahdanau: Context influences hidden state evolution → more integrated reasoning
  • Luong: Cleaner separation, easier to interpret and implement

Local vs Global Attention (Luong Extension)

Luong also introduced local attention to reduce complexity:

Global attention: Attend to ALL encoder positions (what we've described so far).

  • Complexity: O(Td)O(T \cdot d) per decoder step
  • Problem: Expensive for long sequences

Local attention: Attend to a WINDOW around predicted position.

  1. Predict alignment position: pt=Ssigmoid(vpTtanh(Wpst))p_t = S \cdot \text{sigmoid}(v_p^T \tanh(W_p \mathbf{s}_t)) where SS is source length
  2. Define window: [ptD,pt+D][p_t - D, p_t + D] (e.g., D=10D=10)
  3. Compute attention only within window
  4. Apply Gaussian weighting: αti=softmax(eti)exp((ipt)22σ2)\alpha_{ti} = \text{softmax}(e_{ti}) \cdot \exp\left(-\frac{(i-p_t)^2}{2\sigma^2}\right)

Why Gaussian? Smoothly decay attention away from predicted center, preventing sharp cutoffs.

Result: Complexity drops from O(T)O(T) to O(D)O(D) per step, where DTD \ll T.

Implementation Considerations

Batching:

# Encoder states: (batch, seq_len, hidden_dim)
# Decoder state: (batch, hidden_dim)
 
# Broadcasting for efficient score computation:
decoder_expanded = decoder_state.unsqueeze(1)  # (batch, 1, hidden_dim)
scores = (decoder_expanded @ encoder_states.transpose(1,2)).squeeze(1)
# Result: (batch, seq_len)

Numerical stability: Use log_softmax + exp instead of raw softmax for large TT:

log_alpha = torch.log_softmax(scores, dim=1)
alpha = torch.exp(log_alpha)

Teacher forcing: During training, use ground-truth yt1y_{t-1} even if model predicted something else. This stabilizes early training but can cause exposure bias at test time.

Recall Explain to a 12-year-old

Imagine you're translating a sentence from English to Spanish, word by word. The old way was like reading the entire English sentence once, closing the book, and trying to remember everything while you write in Spanish. If the sentence was long, you'd forget important parts!

Attention is like being allowed to keep the English book open. When you're writing each Spanish word, you can look back at the English sentence and focus on the part that's most helpful right now.

Bahdanau is like looking at the book BEFORE you start thinking about the next Spanish word. You check the English, then think.

Luong is like thinking first about what Spanish word might come next, THEN checking the English book to make sure you're on track.

Both work great! Luong is a bit faster because it can pre-read parts of the English book, while Bahdanau reads it fresh each time.

The "attention weights" are like highlighting: you highlight the English words that matter most for the current Spanish word. Sometimes one word is highlighted bright (90% attention), sometimes it's spread across few words.

Connections

  • 3.5.1-Sequence-to-Sequence-Models: Both attention mechanisms extend seq2seq architecture
  • 3.5.9-AttentionMechanism-Overview: These are specific implementations of general attention
  • 3.5.11-Self-Attention-and-Transformers: Transformers evolved from these ideas, using self-attention
  • 3.5.8-Encoder-Decoder-Architecture: Attention bridges encoder and decoder
  • 2.4.7-Softmax-Function: Softmax converts scores to probability distribution
  • 3.3.5-Vanishing-and-Exploding-Gradients: Attention helps by providing shorter gradient paths
  • 4.2.3-Beam-Search: Attention weights guide beam search in decoding
  • 5.1.2-Word-Embeddings: Attention operates in embedding space

#flashcards/ai-ml

What is the key difference between Bahdanau and Luong attention timing? :: Bahdanau computes attention BEFORE the decoder RNN step (uses st1\mathbf{s}_{t-1}), while Luong computes attention AFTER the decoder RNN step (uses st\mathbf{s}_t).

What is the Bahdanau attention score function?
eti=vaTtanh(Wast1+Uahi)e_{ti} = v_a^T \tanh(W_a \mathbf{s}_{t-1} + U_a \mathbf{h}_i) — an additive/concat mechanism using a feedforward network with tanh nonlinearity.
What is the Luong general attention score function?
eti=stTWahie_{ti} = \mathbf{s}_t^T W_a \mathbf{h}_i — a bilinear/multiplicative mechanism that learns to map encoder space to decoder space.
What is input feeding in Bahdanau attention?
The context vector ct\mathbf{c}_t is concatenated with the input embedding and fed to the decoder RNN: st=RNN([yt1;ct],st1)\mathbf{s}_t = \text{RNN}([\mathbf{y}_{t-1}; \mathbf{c}_t], \mathbf{s}_{t-1}). This allows attention to directly influence hidden state evolution.
How does Luong attention combine context with decoder state?
It creates an attentional hidden state: s~t=tanh(Wc[st;ct])\tilde{\mathbf{s}}_t = \tanh(W_c[\mathbf{s}_t; \mathbf{c}_t]) which combines the decoder state and context vector through a learned projection.
What are the three Luong attention scoring variants?
1) Dot: stThi\mathbf{s}_t^T \mathbf{h}_i (no parameters, requires same dims), 2) General: stTWahi\mathbf{s}_t^T W_a \mathbf{h}_i (most common), 3) Concat: vaTtanh(Wa[st;hi])v_a^T \tanh(W_a[\mathbf{s}_t; \mathbf{h}_i]) (similar to Bahdanau).
Why is Luong attention typically faster than Bahdanau?
Luong can precompute WahiW_a \mathbf{h}_i for all encoder positions once, since it's independent of the decoder state. Bahdanau must compute the additive function separately for each encoder position at every decoder step.
What is the formula for attention weights from alignment scores?
αti=exp(eti)j=1Texp(etj)\alpha_{ti} = \frac{\exp(e_{ti})}{\sum_{j=1}^{T} \exp(e_{tj})} — softmax normalization to create a probability distribution that sums to 1.
What is the context vector formula in both mechanisms?
ct=i=1Tαtihi\mathbf{c}_t = \sum_{i=1}^{T} \alpha_{ti} \mathbf{h}_i — a weighted sum of all encoder hidden states using attention weights.
Why must padding positions be masked before computing attention?
Unmasked padding gets small but non-zero attention weights, wasting probability mass and corrupting the context vector with meaningless information. Masking with -\infty before softmax ensures padding positions get exactly 0 weight.
What is local attention (Luong extension)?
An optimization that attends to only a window [ptD,pt+D][p_t - D, p_t + D] around a predicted alignment position ptp_t, reducing complexity from O(T)O(T) to O(D)O(D) per decoder step.
What is the key architectural motivation for attention mechanisms?
To solve the fixed-length bottleneck problem in seq2seq models — instead of compressing the entire input into one vector, attention allows the decoder to dynamically access all encoder states.
How many weight matrices does Bahdanau attention require?
Three: WaRda×dsW_a \in \mathbb{R}^{d_a \times d_s} for decoder projection, UaRda×dhU_a \in \mathbb{R}^{d_a \times d_h} for encoder projection, and vaRdav_a \in \mathbb{R}^{d_a} for the alignment vector. Total parameters: da(ds+dh+1)d_a(d_s + d_h +1).
How many weight matrices does Luong general attention require?
Two: WaRds×dhW_a \in \mathbb{R}^{d_s \times d_h} for scoring (parameters: dsdhd_s \cdot d_h) and WcRds×(ds+dh)W_c \in \mathbb{R}^{d_s \times (d_s+d_h)} for combining context and decoder state (parameters: ds(ds+dh)d_s(d_s+d_h)).
Why does Bahdanau use tanh nonlinearity in the score function?
To allow the alignment function to learn complex, non-linear relationships between decoder and encoder states. Without nonlinearity, it would collapse to a simple linear transformation.

Concept Map

solved by

follows

step 1

step 2 softmax

step 3 weighted sum

step 4

type

type

computes scores via

computes scores via

differs in

differs in

Fixed-Length Bottleneck

Attention Mechanism

Shared Framework

Alignment Scoring

Attention Weights softmax

Context Vector

Output Generation

Bahdanau Additive

Luong Multiplicative

Feedforward Network tanh

Dot Product

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Chalo ek simple baat se shuru karte hain. Socho tumhe pura ek book padhkar uska sirf ek chhoti si line mein summary banana hai, aur phir usi ek line ke basis pe review likhna hai. Bahut saari important details toh gayab ho jayengi na? Yahi problem thi purane seq2seq models mein — woh pure input sequence ko ek fixed-size vector mein daba dete the, aur long sentences ke liye yeh "bottleneck" bahut information loss karta tha. Attention ka core idea yahi hai ki decoder ko pura book khula rakhne do — har output word banate waqt woh saare encoder states ko dekh sake aur dynamically decide kare ki abhi kaun sa part sabse relevant hai. Bilkul jaise review likhte waqt tum zaroorat ke hisaab se pages palat lo.

Ab Bahdanau aur Luong attention dono isi kaam ko karte hain, bas farak yeh hai ki alignment score kaise calculate karte hain. Bahdanau (additive attention) ek chhota feedforward network use karta hai — decoder state aur encoder state dono ko ek common space mein project karta hai, tanh se non-linearity add karta hai, phir score nikaalta hai. Iska fayda yeh hai ki model khud "seekh" leta hai ki alignment kaise karna hai. Luong (multiplicative) simple dot product use karta hai, jo maanke chalta hai ki spaces already aligned hain. Dono cases mein score nikalne ke baad softmax lagta hai (taaki weights probability ban jaayein aur sum 1 ho), phir un weights se encoder states ka weighted sum lete hain — yeh banta hai context vector, jo current word predict karne ke liye relevant summary hota hai.

Yeh samajhna kyun zaroori hai? Kyunki attention modern AI ki backbone hai — Google Translate se lekar ChatGPT tak, sab jagah yahi concept scale hua hai. Transformers, jo aaj sabse powerful models hain, seedhe isi attention idea ka advanced version hain. Toh agar tum yeh core intuition — "fixed bottleneck se bacho, dynamically focus karo" — aur alignment score ka basic maths samajh loge, toh tumhare paas poore modern deep learning ki foundation aa jayegi. Chhote se concept se badi cheezein banti hain, bas basics clear hone chahiye!

Go deeper — visual, from zero

Test yourself — Sequence Models

Connections