3.5.10 · HinglishSequence Models

Bahdanau and Luong attention

3,458 words16 min readRead in English

3.5.10 · AI-ML › Sequence Models

Bahdanau aur Luong Attention kya hain?

Bahdanau attention (jise additive attention bhi kehte hain) aur Luong attention (jise multiplicative attention bhi kehte hain) — yeh do pioneering mechanisms hain jo neural sequence models ko allow karte hain ki woh har output token generate karte waqt input ke alag-alag parts par selectively focus karein.

Fundamental difference: YEH ki woh decoder aur encoder states ke beech alignment scores KAISE compute karte hain.

Shared Framework

Dono mechanisms is pattern ko follow karte hain:

  1. Alignment Scoring: Compute karo ki har encoder hidden state current decoder state ke liye kitni relevant hai
  2. Attention Weights: Scores ko ek probability distribution mein convert karo (softmax)
  3. Context Vector: Attention weights use karke encoder states ka weighted sum
  4. Output Generation: Agla token predict karne ke liye context vector (+ decoder state) use karo
Figure — Bahdanau and Luong attention

Bahdanau Attention (Additive/Concat)

First Principles se Derivation

Setup:

  • Encoder hidden states: (har ek )
  • Step par decoder state:
  • Humein output generate karna hai

Step 1: Alignment Score Function

Concatenate kyun? Hum decoder state aur har encoder state ke beech interaction capture karna chahte hain. Simple dot product (Luong) assume karta hai ki spaces already aligned hain; Bahdanau ek alignment function seekhta hai.

JAHAN:

  • decoder state ko project karta hai
  • encoder state ko project karta hai
  • alignment weight vector hai
  • attention dimension hai (hyperparameter, aksar 128-512)

Yeh form kyun?

  1. Dono states ko ek common space mein project karo ()
  2. non-linearity provide karta hai (complex alignments seekhne deta hai)
  3. scalar score tak reduce karta hai

Yeh hidden units wala ek single-layer feedforward network hai.

Step 2: Attention Weights

Scores ko probability distribution mein convert karo (ZAROORI hai ki sum 1 ho, sab positive):

Softmax kyun? Ensure karta hai ki (proper probability distribution) aur high-scoring positions ko emphasize karta hai (exponential amplification).

Step 3: Context Vector

Saare encoder states ka weighted average:

Yeh input ka "summary" hai jo predict karne ke liye relevant hai.

Step 4: Decoder Update

Bahdanau RNN step se PEHLE context concatenate karta hai:

Pehle concatenate kyun karte hain? Yeh input-feeding hai: context RNN state update ko directly influence karta hai, jisse attention information ka hidden state evolution par zyada direct control hota hai.

Luong Attention (Multiplicative)

Teen Scoring Variants

Luong ne teen alignment functions propose kiye:

1. Dot Product (sabse simple):

Yeh kyun kaam karta hai: Agar decoder aur encoder states same semantic space mein hain, toh high similarity = high relevance. Koi parameters nahi!

Limitation: zaroori hai.

2. General/Bilinear (sabse common):

JAHAN ek learned weight matrix hai.

Yeh better kyun hai? Encoder space ko decoder space mein map karna seekhta hai. ko handle karta hai. Phir bhi computationally sasta hai (single matrix multiply).

3. Concat (Bahdanau se milta-julta):

Complete Luong Attention (General)

Step 1: Pehle Decoder RNN (KEY DIFFERENCE)

Pehle attention ke bina decoder state compute karo.

Step 2: Alignment Scores

Step 3: Attention Weights

Step 4: Context Vector

Step 5: Attentional Hidden State

Key innovation — decoder state aur context ko combine karo:

JAHAN .

Kyun? Yeh learned combination decide karta hai ki context par kitna rely karna hai versus decoder state par. output ko bound karta hai, explosion rokta hai.

Step 6: Output

Side-by-Side Comparison

Aspect Bahdanau (Additive) Luong (Multiplicative)
Kab compute hoti hai Decoder RNN step se pehle Decoder RNN step ke baad
Decoder state use karta hai (previous) (current)
Score function (general)
Complexity
Parameters Zyada (3 weight matrices) Kam (1-2 weight matrices)
Input feeding Haan (context RNN ko fed hoti hai) Nahi (context baad mein combine hoti hai)
Speed Slow Fast
Performance Lambe sequences par thoda better Competitive, aksar preferred

Timing ka difference kyun matter karta hai:

  • Bahdanau: Context hidden state evolution ko influence karta hai → zyada integrated reasoning
  • Luong: Cleaner separation, interpret aur implement karna asaan

Local vs Global Attention (Luong Extension)

Luong ne complexity kam karne ke liye local attention bhi introduce ki:

Global attention: SAARE encoder positions ko attend karo (ab tak hum yahi describe kar rahe the).

  • Complexity: per decoder step
  • Problem: Lambe sequences ke liye expensive

Local attention: Predicted position ke aaspaas ek WINDOW ko attend karo.

  1. Alignment position predict karo: jahan source length hai
  2. Window define karo: (e.g., )
  3. Sirf window ke andar attention compute karo
  4. Gaussian weighting apply karo:

Gaussian kyun? Predicted center se door attention smoothly decay karo, sharp cutoffs rokne ke liye.

Result: Complexity se per step tak girti hai, jahan .

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: Bade ke liye raw softmax ki jagah log_softmax + exp use karo:

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

Teacher forcing: Training ke dauran, model kuch aur predict kare tab bhi ground-truth use karo. Yeh early training stabilize karta hai lekin test time par exposure bias cause kar sakta hai.

Recall 12 saal ke bachche ko samjhao

Imagine karo tum English se Spanish mein ek sentence translate kar rahe ho, word by word. Purana tarika yeh tha: poori English sentence ek baar padho, kitaab band karo, aur phir sab yaad rakhne ki koshish karte hue Spanish likhna shuru karo. Agar sentence lamba ho, toh zaroori parts bhool jaoge!

Attention matlab hai ki English kitaab khuli rakhne ki permission milna. Har Spanish word likhte waqt, tum English sentence par nazar daal sakte ho aur us part par focus kar sakte ho jo abhi sabse helpful hai.

Bahdanau matlab hai kitaab dekhna PEHLE, phir agla Spanish word ke baare mein sochna. Pehle English check karo, phir socho.

Luong matlab hai pehle sochna ki agla Spanish word kya ho sakta hai, PHIR English kitaab check karo ki sahi track par ho.

Dono bahut acche kaam karte hain! Luong thoda faster hai kyunki woh English kitaab ke kuch hisson ko pehle se padh sakta hai, jabki Bahdanau har baar fresh padhta hai.

"Attention weights" highlighting jaisi hain: tum English words ko highlight karte ho jo current Spanish word ke liye sabse zyada matter karte hain. Kabhi ek word bright highlight hota hai (90% attention), kabhi kuch words par spread hota hai.

Connections

  • 3.5.1-Sequence-to-Sequence-Models: Dono attention mechanisms seq2seq architecture extend karte hain
  • 3.5.9-AttentionMechanism-Overview: Yeh general attention ke specific implementations hain
  • 3.5.11-Self-Attention-and-Transformers: Transformers inhi ideas se evolve hue, self-attention use karke
  • 3.5.8-Encoder-Decoder-Architecture: Attention encoder aur decoder ko bridge karta hai
  • 2.4.7-Softmax-Function: Softmax scores ko probability distribution mein convert karta hai
  • 3.3.5-Vanishing-and-Exploding-Gradients: Attention shorter gradient paths provide karke help karta hai
  • 4.2.3-Beam-Search: Attention weights decoding mein beam search guide karte hain
  • 5.1.2-Word-Embeddings: Attention embedding space mein operate karta hai

#flashcards/ai-ml

Bahdanau aur Luong attention timing ka key difference kya hai? :: Bahdanau attention decoder RNN step se PEHLE compute karta hai (uses ), jabki Luong attention decoder RNN step ke BAAD compute karta hai (uses ).

Bahdanau attention score function kya hai?
— ek additive/concat mechanism jo tanh nonlinearity wale feedforward network use karta hai.
Luong general attention score function kya hai?
— ek bilinear/multiplicative mechanism jo encoder space ko decoder space mein map karna seekhta hai.
Bahdanau attention mein input feeding kya hai?
Context vector ko input embedding ke saath concatenate karke decoder RNN ko feed kiya jaata hai: . Isse attention hidden state evolution ko directly influence kar sakti hai.
Luong attention context ko decoder state ke saath kaise combine karta hai?
Yeh ek attentional hidden state banata hai: jo decoder state aur context vector ko ek learned projection ke through combine karta hai.
Teen Luong attention scoring variants kya hain?
1) Dot: (koi parameters nahi, same dims zaroori), 2) General: (sabse common), 3) Concat: (Bahdanau se milta-julta).
Luong attention typically Bahdanau se faster kyun hota hai?
Luong ko saare encoder positions ke liye ek baar precompute kar sakta hai, kyunki yeh decoder state se independent hai. Bahdanau ko har decoder step par har encoder position ke liye additive function alag se compute karna padta hai.
Alignment scores se attention weights ka formula kya hai?
— softmax normalization se ek probability distribution banta hai jo sum 1 hoti hai.
Dono mechanisms mein context vector ka formula kya hai?
— attention weights use karke saare encoder hidden states ka weighted sum.
Attention compute karne se pehle padding positions ko kyun mask karna zaroori hai?
Unmasked padding ko small but non-zero attention weights milte hain, probability mass waste hoti hai aur context vector meaningless information se corrupt hoti hai. Softmax se pehle se mask karne se padding positions ko exactly 0 weight milta hai.
Local attention (Luong extension) kya hai?
Ek optimization jo predicted alignment position ke aaspaas sirf ek window ko attend karta hai, complexity se per decoder step tak kam kar deta hai.
Attention mechanisms ka key architectural motivation kya hai?
Seq2seq models mein fixed-length bottleneck problem solve karna — poore input ko ek vector mein compress karne ki jagah, attention decoder ko dynamically saare encoder states access karne deta hai.
Bahdanau attention mein kitni weight matrices hoti hain?
Teen: decoder projection ke liye, encoder projection ke liye, aur alignment vector ke liye. Total parameters: .
Luong general attention mein kitni weight matrices hoti hain?
Do: scoring ke liye (parameters: ) aur context aur decoder state combine karne ke liye (parameters: ).
Bahdanau score function mein tanh nonlinearity kyun use hoti hai?
Alignment function ko decoder aur encoder states ke beech complex, non-linear relationships seekhne dene ke liye. Nonlinearity ke bina yeh simple linear transformation tak collapse ho jaata.

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