Attention visualization and limitations
6.3.4· AI-ML › Interpretability & Explainability
Overview
Attention visualization wo process hai jisme transformer models ke attention weights ko inspect karte hain taaki yeh samjha ja sake ki prediction karte waqt model kaun se input tokens par focus karta hai. Yeh intuitive lagta hai—"chalo dekhte hain model kya dekhta hai"—lekin explanation tool ke roop mein attention visualization ki kaafi significant limitations hain jo har practitioner ko samajhni chahiye.
Ise aise samjho jaise kisi ko padhte hue dekh rahe ho: woh jahan zyada der tak aankhein tikaayen, shayad woh unhe important lagta hoga. Lekin sirf isliye ki unhone ek word dekha, iska matlab yeh nahi ki usi wajah se unka conclusion aya.
Core Concepts
Attention weights woh matrix hai jahan represent karta hai ki position position ko kitna attend karta hai.
KYU softmax? Yeh scores ko ek probability distribution mein normalize karta hai: saare weights sum karke 1 hote hain, jisse inhe "importance scores" ki tarah interpret kiya ja sakta hai.
KYA matlab hai ka? Yeh token ki information ka woh fraction hai jo is layer par token ki representation mein flow karta hai.
KAISE extract karein? Apne model mein attention compute karne ke baad, se multiply karne se pehle softmax output ko simply save kar lo.
Attention ko First Principles se Derive Karna
Chaliye samjhte hain ki attention yeh form kyun leta hai:
- Goal: Multiple input tokens se information combine karna, learned importance weights ke saath
- Similarity scoring: Query vector aur key vector ke liye, dot product ke zariye similarity compute karo:
- Dot product kyun? Yeh alignment measure karta hai: high hota hai jab vectors ek hi direction mein point karte hain
- High dimensions mein, raw dot products ke saath badhte hain, isliye hum scale karte hain:
- Normalization: Scores ko softmax use karke probabilities mein convert karo:
- Softmax kyun? Ensure karta hai ki weights positive hain aur sum karke 1 hote hain (valid probability distribution)
- Weighted combination: Output hai —har value vector apne attention score se weighted
Yeh humein upar wala formula deta hai. Koi magic nahi, bas learned similarity → normalized weights → weighted average.
jahan
Har head ka apna attention matrix hota hai. Visualization typically yeh dikhata hai:
- Per-head heatmaps: har head ke liye
- Averaged attention:
- Max attention: (kaun sa head sabse zyada attend karta hai)
Visualization Methods
Input: "The cat sat on the mat" → Agla word predict karo
Visualization: 7×7 heatmap jahan cell dikhata hai ki token token ko kitna attend karta hai.
Interpretation attempt: Agar "mat" strongly "on" aur "the" ko attend karta hai, toh hum soch sakte hain ki model prepositional context use kar raha hai.
Code structure:
import matplotlib.pyplot as plt
import numpy as np
# attention_weights shape: [seq_len, seq_len]
attention = model.get_attention_weights(input_ids, layer=6, head=3)
plt.imshow(attention, cmap='viridis')
plt.xlabel('Key position')
plt.ylabel('Query position')Yeh step kyun? Heatmap raw matrix dikhata hai, jisse patterns visually obvious ho jaate hain.
Task: BERT ke saath Sentiment classification
Approach: Layer 8 ke saare 12 heads ko side-by-side visualize karo
Observation:
- Head 2: Punctuation ko attend karta hai (exclamation marks, question marks)
- Head 7: Negation words ko attend karta hai ("not", "never")
- Head 10: Dispersed attention (uninformative)
Interpretation: Alag-alag heads alag-alag linguistic features mein specialize karte hain.
Critical question: Lekin kya yeh patterns prediction ko cause karte hain? (Spoiler: Zaroori nahi)
Yeh step kyun? Heads ki comparison specialization reveal karti hai, lekin causality ko hume alag se test karna hoga.
Problem: Single-layer attention poore model mein information flow nahi dikhata.
Solution: Attention rollout layers mein cumulative attention compute karta hai:
Derivation: Information layer se layer mein flow karti hai. Agar layer 1 token se tak information move karta hai, aur layer 2 se tak, toh effectively , ke through ko influence karta hai.
Matrix multiplication is transitive flow ko capture karta hai: product mein entry saare intermediate tokens par sum karta hai.
Yeh step kyun? Deep information flow capture karta hai, sirf local attention nahi.
Limitation: Assume karta hai ki attention hi information ka ek maatra pathway hai (aisa nahi hai—residual connections aur MLPs bhi matter karte hain).
Fundamental Limitations
Galat intuition: Agar kisi token ko high attention weight milta hai, toh woh prediction ke liye important hona chahiye.
Kyun sahi lagta hai: Attention ka literally matlab hai "dhyan dena"—zyada attention ka matlab zyada influence hona chahiye, hai na?
Haqeeqat: Attention weights directly causal importance reveal nahi karte. Jain & Wallace (2019) aur Serano & Smith (2019) ki research ne dikhaya:
- Adversarial examples: Tum bilkul alag attention distributions dhundh sakte ho jo same output produce karte hain
- Attention is not explanation: Token par high attention ka matlab yeh nahi ki use ablate karne se prediction change hogi
- Value vectors matter karte hain: High attention weight ke bawajood, agar value vector downstream layers ke null space mein hai, toh woh kuch contribute nahi karta
Mathematical fix:
True importance ke liye gradient ya ablation impact measure karna padta hai, sirf attention weights nahi.
Yeh kyun hota hai: Attention ek deep network mein sirf ek operation hai. Value vectors LayerNorm, residual additions, aur MLPs se guzarte hain jo unke contribution ko amplify ya nullify kar sakte hain.
Galat approach: Saare attention heads ko average karo aur result interpret karo.
Kyun sahi lagta hai: Averaging noise smooth out karta hai aur ek "consensus" view deta hai.
Haqeeqat: Heads ho sakte hain:
- Redundant: Multiple heads same pattern seekh rahe hain (wasteful lekin harmless)
- Antagonistic: Kuch heads confounders ko attend karte hain, kuch true signal ko—averaging inhe mix kar deta hai
- Specialized: Ek head task ki saari information carry karta hai; averaging use dilute kar deta hai
Fix: Individually heads ko gradient-based attribution ke saath analyze karo taaki pata chale kaunse heads actually classification layer use karta hai.
Attention flow: Attention weights ke through forward-pass information routing
Gradient flow: Backward-pass credit assignment jo dikhata hai kaun se inputs loss ko affect karte hain
Attention correlation dikhata hai, gradients causation dikhate hain.
Token aur output ke liye:
- Attention: "Model ne ko kitna dekha?"
- Gradient : " ko change karne se loss kitna change hota hai?"
Yeh disagree kar sakte hain! Ek token ko high attention mil sakta hai lekin near-zero gradient ho sakta hai (examine kiya gaya lekin use nahi kiya), ya low attention ho lekin high gradient ho (doosre tokens ke through indirect influence).
Practical Visualization Guidelines
layers ke liye attention matrices ke saath:
Identity kyun add karein? Residual connections ka matlab hai ki har layer attention padhta bhi hai aur raw input pass through bhi karta hai. add karna residual stream ko model karta hai.
Normalization: Probability interpretation maintain karne ke liye har product ke baad row-normalize karo:
Yeh step kyun? Normalization ke bina, values multiplication ke through geometrically explode ho jaati hain.
Kab use karein: Jab aapko input se output tak end-to-end attribution ki parwah ho, sirf local patterns ki nahi.
Gradient information incorporate karne ke liye:
Derivation: Chain rule se, attention weight ka output par influence hai:
Term output ka attention weight w.r.t. gradient hai—yeh us attention connection ke liye prediction ki sensitivity measure karta hai.
(forward importance) ko is gradient (backward sensitivity) se multiply karna akele attention se behtar attribution score deta hai.
Yeh step kyun? "Model ne kya dekha" (attention) aur "output ke liye kya matter kiya" (gradient) dono ko combine karta hai.
When to Trust Attention Visualization
Trust karo: ✓ Exploratory analysis: "Model kaun se patterns seekhta hai?" ✓ Debugging: "Kya model padding tokens ko attend kar raha hai?" (bug indicator) ✓ Linguistic analysis: "Kya heads syntactic structures capture karte hain?"
Trust mat karo: ✗ Causal explanations: "Is token ne prediction cause ki" ✗ Model debugging: "Model fail hua kyunki usne X ko attend nahi kiya" ✗ Fairness audits: "Model discriminate karta hai kyunki attention pattern Y hai"
Gold standard: Attention visualization ko combine karo:
- Ablation studies ke saath: Tokens remove karo aur output change measure karo
- Gradient-based attribution ke saath: Integrated Gradients, Attention×Gradient
- Probing ke saath: Representations par classifiers train karo taaki test ho sake kya information encoded hai
Recall Ek 12-saal ke bacche ko explain karo
Socho tum ek multiple-choice test de rahe ho, aur tum apne notes dekh sakte ho (input tokens). Attention visualization aise hai jaise track karo ki teri aankhein page par kahan jaati hain—apne notes ke kaun se hisse tum sabse dhyan se padhte ho.
Ab yahan trick hai: sirf isliye ki tumne kuch dekha, iska matlab yeh nahi ki usne answer karne mein madad ki! Shayad tumne galat section padha, ya tumhe answer pehle se yaad tha. Tumhane kahan dekha yeh track karna hamein tumhari strategy ke baare mein kuch batata hai, lekin yeh prove nahi karta ki kyun tumne question sahi ya galat kiya.
Yahi limitation hai: attention maps dikhate hain AI ne kya "dekha," lekin kya actually uske decision ka cause bana yeh nahi. Woh pata karne ke liye, humein experiments karne padte hain—jaise notes ke hisse cover karke dekhna ki answer change hota hai ya nahi (yahi ablation testing hai).
Connections
- Transformer Architecture - Jahan se attention aata hai
- Integrated Gradients - Based attribution alternative
- Attention Mechanisms - Mathematical foundation
- SHAP for Deep Learning - Model-agnostic explanation method
- Layer-wise Relevance Propagation - Ek aur gradient-based approach
- Probing Classifiers - Test karna ki representations kya encode karti hain
- BertViz Tool - Practical visualization library
- Adversarial Attention - Attention distribution robustness
#flashcards/ai-ml
Transformer mein attention weights kya hote hain? :: Matrix jahan represent karta hai ki position position ko kitna attend karta hai—token ki information ka woh fraction jo token ki representation mein flow karta hai.