4.1.2 · HinglishTransformer Architecture

Self-attention mechanism in detail

3,322 words15 min readRead in English

4.1.2 · AI-ML › Transformer Architecture

Overview

Self-attention woh core operation hai jo sequence mein har position ko baaki sabhi positions par attend karne deta hai, relevance ke basis par ek weighted representation compute karta hai. RNNs ke unlike jo sequentially process karte hain, self-attention parallel processing aur long-range dependencies enable karta hai bina vanishing gradient problem ke.

Figure — Self-attention mechanism in detail

Core Concepts

First Principles se Derivation

Step 1: Teen Matrices Kyun?

Problem: Hume compute karna hai ki har word kितना relevant hai har doosre word ke liye. Lekin raw embeddings directly use karne mein issues hain:

  1. Embeddings meaning encode karti hain, "relevance" nahi
  2. Hum apples ko oranges se compare kar rahe honge (position 1 ka role vs position 5 ka role)

Solution: Teen specialized representations banao:

Step 2: Attention Scores Compute Karna

Step 3: Scaling Factor

Step 4: Softmax Normalization

Step 5: Weighted Aggregation

Complete Formula Derivation

Worked Examples

Common Mistakes

Active Recall Questions

Recall Self-attention ko ek 12-saal ke bachche ko explain karo

Socho tum ek mystery story padh rahe ho, aur tumhare saamne "he" word aata hai. "He" kaun hai? Tumhe answer dhundhhne ke liye pehle ke sentences mein wapas dekhna hoga—shayad yeh detective hai, ya shayad suspect.

Self-attention computer ka yahi karna ka tarika hai! Jab computer "he" padhta hai, toh yeh sabhi previous words ko dekhta hai aur poochhta hai: "Mujhe 'he' samajhne ke liye in mein se har word par kitna dhyan dena chahiye?"

Yeh har word ko ek score deta hai (jaise 0% se 100% tak). Agar "detective" recently mention hua tha aur context mein sense banta hai, toh use 80% jaisa high score milta hai. Agar "suspect" mention hua tha lekin utna fit nahi baith raha, toh use 20% milta hai. Phir yeh sabhi words ke meanings ko unke scores ke basis par combine karta hai—80% "detective" ki meaning + 20% "suspect" ki meaning—"he" samajhne ke liye.

Cool part? Yeh EVERY word ke liye karta hai! Har word har doosre word ko dekhta hai aur decide karta hai ki use kitna attend karna hai. Isliye ise self-attention kehte hain—sentence khud apne aap par attention de raha hai.

Computer lakhs sentences practice karke seekhta hai ki in words ko kaise score karna hai, jab tak yeh har word ko samajhne ke liye kaun se words matter karte hain yeh samajhne mein really good nahi ho jaata.

Connections

  • Transformer Architecture Overview - self-attention core building block hai
  • Multi-Head Attention - multiple self-attention operations parallel mein chalana
  • Positional Encoding - self-attention ko order information provide karta hai
  • Attention Mechanism Basics - encoder-decoder attention (self-attention se alag)
  • Computational Complexity - bottleneck self-attention se aata hai
  • Gradient Flow - self-attention RNNs se better gradient flow enable karta hai

#flashcards/ai-ml

Self-attention kya hai aur yeh encoder-decoder attention se kaise alag hai? :: Self-attention tab hota hai jab ek sequence khud par attend karta hai—har position same sequence mein sabhi doosre positions ko dekh sakta hai. Encoder-decoder attention ke unlike jahan queries decoder se aur keys/values encoder se aate hain, self-attention mein Q, K, V teeno same input sequence X se alag-alag learned projections ke through aate hain.

Teen separate matrices W^Q, W^K, W^V kyun chahiye seedha embeddings use karne ki jagah?
Teen projections specialized representations create karte hain: W^Q seekhta hai kaunse aspects search karne hain, W^K seekhta hai matching ke liye kaunse aspects offer karne hain, W^V seekhta hai kaunsa content retrieve karna hai. Yeh model ko similarity aur relevance ke task-specific notions seekhne deta hai, sirf raw embedding similarity use karne ki jagah.
Derive karo ki hum attention scores ko 1/sqrt(d_k) se kyun scale karte hain
Assume karo Q aur K entries mean 0, variance 1 ke saath random hain. Dot product q·k, d_k terms sum karta hai, har ek variance 1 ke saath, toh Var(q·k) = d_k. Standard deviation sqrt(d_k) ke roop mein badhti hai. Scaling ke bina, bada d_k bahut bade scores create karta hai → softmax almost one-hot ban jaata hai → gradients vanish ho jaate hain. sqrt(d_k) se divide karne par unit variance normalize hoti hai, softmax ko responsive region mein rakhta hai.
Self-attention ki computational complexity kya hai aur yeh kahan se aati hai?
O(n²d) jahan n sequence length hai aur d model dimension hai. n² sabhi pairwise attention scores compute karne se aata hai (har position har position par attend karta hai), ek n×n attention matrix chahiye hoti hai. Yeh long sequences ke liye main bottleneck hai.
Self-attention positional encodings ke bina word order kyun nahi seekh sakta?
Self-attention permutation-invariant hai: formula Attention(Q,K,V) = softmax(QK^T/sqrt(d_k))V positions ko ek set ki tarah treat karta hai. Agar tum inputs shuffle karo, outputs sirf correspondingly shuffle ho jaate hain. Embeddings mein positional encodings add kiye bina, "dog bites man" aur "man bites dog" identical representations produce karenge (reordering tak).

Formula softmax(QK^T/sqrt(d_k))V mein, explain karo ki har matrix multiplication kya compute karta hai :: QK^T (n×d_k)(d_k×n) = (n×n) sabhi-pairs ke similarity scores deta hai—har query har key ke against. Softmax rows ko probability distributions mein normalize karta hai. Result (n×n) times V (n×d_v) = (n×d_v) weighted aggregation perform karta hai—har output position sabhi value vectors ka ek weighted sum hai, weights attention scores se aate hain.

Jab d_k bada ho aur hum scale nahi karte, toh self-attention mein gradients ka kya hota hai?
Bade d_k ke liye, dot products bade ho jaate hain (std sqrt(d_k) ke roop mein badhta hai). Softmax ke bade inputs nearly one-hot outputs create karte hain (jaise [0.01, 0.98, 0.01]). Softmax ke through backpropagating karte waqt, near-zero probabilities wale positions ke near-zero gradients hote hain → model un positions par attention adjust karna nahi seekh sakta → vanishing gradient problem.
Self-attention us long-range dependency problem ko kaise solve karta hai jisse RNNs struggle karte hain?
RNNs sequentially process karte hain, isliye position 1 ki information position 100 tak pahunchne ke liye sabhi intermediate states se guzarni hoti hai (potential degradation ke 100 steps). Self-attention directly har position ko doosre se ek step mein connect karta hai—position 100, position 1 par direct gradient path ke saath attend kar sakta hai, sequential bottleneck aur vanishing gradients se bachta hai.

Concept Map

projected by WQ

projected by WK

projected by WV

dot product

dot product

scaled by sqrt dk

softmax

weighted sum of

enables

Input embeddings X

Query - what to search

Key - what can offer

Value - actual content

Scores QK^T

Scaled scores

Attention weights

Output representation

Parallel processing and long range deps