Attention visualization and limitations
Overview
Attention visualization is the process of inspecting attention weights from transformer models to understand which input tokens the model focuses on when making predictions. While intuitively appealing—"let's see what the model looks at"—attention visualization has significant limitations as an explanation tool that every practitioner must understand.
Think of it like watching someone read: where their eyes linger might tell you what they find important. But just because they looked at a word doesn't mean it caused their conclusion.
Core Concepts
The attention weights are the matrix where represents how much position attends to position .
WHY softmax? It normalizes scores into a probability distribution: all weights sum to 1, making them interpretable as "importance scores."
WHAT does mean? It's the fraction of information from token that flows into the representation of token at this layer.
HOW to extract? After computing attention in your model, simply save the softmax output before multiplying with .
Deriving Attention from First Principles
Let's build up why attention takes this form:
- Goal: Combine information from multiple input tokens, with learned importance weights
- Similarity scoring: For query vector and key vector , compute similarity via dot product:
- Why dot product? It measures alignment: high when vectors point in the same direction
- In high dimensions, raw dot products grow with , so we scale:
- Normalization: Convert scores to probabilities using softmax:
- Why softmax? Ensures weights are positive and sum to 1 (valid probability distribution)
- Weighted combination: Output is —each value vector weighted by its attention score
This gives us the formula above. No magic, just learned similarity → normalized weights → weighted average.
where
Each head has its own attention matrix . Visualization typically shows:
- Per-head heatmaps: for each head
- Averaged attention:
- Max attention: (which head attends most)
Visualization Methods
Input: "The cat sat on the mat" → Predict next word
Visualization: 7×7 heatmap where cell shows how much token attends to token .
Interpretation attempt: If "mat" attends strongly to "on" and "the", we might think the model is using prepositional context.
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')Why this step? The heatmap shows the raw matrix, making patterns visually obvious.
Task: Sentiment classification with BERT
Approach: Visualize all 12 heads in layer 8 side-by-side
Observation:
- Head 2: Attends to punctuation (exclamation marks, question marks)
- Head 7: Attends to negation words ("not", "never")
- Head 10: Dispersed attention (uninformative)
Interpretation: Different heads specialize in different linguistic features.
Critical question: But do these patterns cause the prediction? (Spoiler: Not necessarily)
Why this step? Comparing heads reveals specialization, but we must test causality separately.
Problem: Single-layer attention doesn't show information flow through the entire model.
Solution: Attention rollout computes cumulative attention across layers:
Derivation: Information flows from layer to layer. If layer1 moves information from token to , and layer 2 moves from to , then effectively influences through .
Matrix multiplication captures this transitive flow: entry in the product sums over all intermediate tokens .
Why this step? Captures deep information flow, not just local attention.
Limitation: Assumes attention is the only information pathway (it's not—residual connections and MLPs matter too).
Fundamental Limitations
The wrong intuition: If a token gets high attention weight, it must be important for the prediction.
Why it feels right: Attention literally means "paying attention to"—more attention should mean more influence, right?
The reality: Attention weights don't directly reveal causal importance. Research by Jain & Wallace (2019) and Serano & Smith (2019) showed:
- Adversarial examples: You can find completely different attention distributions that produce the same output
- Attention is not explanation: High attention on token doesn't mean ablating it would change the prediction
- Value vectors matter: Even with high attention weight , if value vector is in the null space of downstream layers, it contributes nothing
Mathematical fix:
True importance requires measuring gradient or ablation impact, not just attention weights.
Why this happens: Attention is only one operation in a deep network. The value vectors pass through LayerNorm, residual additions, and MLPs that can amplify or nullify their contribution.
The wrong approach: Average all attention heads and interpret the result.
Why it feels right: Averaging smooths out noise and gives a "consensus" view.
The reality: Heads can be:
- Redundant: Multiple heads learning the same pattern (wasteful but harmless)
- Antagonistic: Some heads attend to confounders, others to true signal—averaging mixes them
- Specialized: One head carries all information for a task; averaging dilutes it
The fix: Analyze heads individually with gradient-based attribution to identify which heads are actually used by the classification layer.
Attention flow: Forward-pass information routing through attention weights
Gradient flow: Backward-pass credit assignment showing which inputs affect the loss
Attention shows correlation, gradients show causation.
For token and output :
- Attention: "How much did the model look at ?"
- Gradient : "How much does changing change the loss?"
These can disagree! A token might receive high attention but have near-zero gradient (it was examined but not used), or low attention but high gradient (indirect influence through other tokens).
Practical Visualization Guidelines
For layers with attention matrices :
Why add identity ? Residual connections mean each layer both reads attention and passes through raw input. Adding models the residual stream.
Normalization: Row-normalize after each product to maintain probability interpretation:
Why this step? Without normalization, values explode geometrically through multiplication.
When to use: When you care about end-to-end attribution from input to output, not just local patterns.
To incorporate gradient information:
Derivation: By chain rule, the influence of attention weight on output is:
The term is the gradient of the output w.r.t. the attention weight—it measures sensitivity of the prediction to that attention connection.
Multiplying (forward importance) by this gradient (backward sensitivity) gives a better attribution score than attention alone.
Why this step? Combines "what the model looked at" (attention) with "what mattered for the output" (gradient).
When to Trust Attention Visualization
Trust it for: ✓ Exploratory analysis: "What patterns does the model learn?" ✓ Debugging: "Is the model attending to padding tokens?" (bug indicator) ✓ Linguistic analysis: "Do heads capture syntactic structures?"
Don't trust it for: ✗ Causal explanations: "This token caused the prediction" ✗ Model debugging: "The model failed because it didn't attend to X" ✗ Fairness audits: "The model discriminates because of attention pattern Y"
Gold standard: Combine attention visualization with:
- Ablation studies: Remove tokens and measure output change
- Gradient-based attribution: Integrated Gradients, Attention×Gradient
- Probing: Train classifiers on representations to test what information is encoded
Recall Explain to a 12-year-old
Imagine you're taking a multiple-choice test, and you can look at your notes (the input tokens). Attention visualization is like tracking where your eyes move on the page—which parts of your notes you read most carefully.
Now here's the catch: just because you looked at something doesn't mean it helped you answer! Maybe you read the wrong section, or you already knew the answer from memory. Watching where you looked tells us something about your strategy, but it doesn't prove why you got the question right or wrong.
That's the limitation: attention maps show what the AI "looked at," but not what actually caused its decision. To find that out, we need to do experiments—like covering up parts of the notes and seeing if the answer changes (that's ablation testing).
Connections
- Transformer Architecture - Where attention comes from
- Integrated Gradients -based attribution alternative
- Attention Mechanisms - Mathematical foundation
- SHAP for Deep Learning - Model-agnostic explanation method
- Layer-wise Relevance Propagation - Another gradient-based approach
- Probing Classifiers - Testing what representations encode
- BertViz Tool - Practical visualization library
- Adversarial Attention - Attention distribution robustness
#flashcards/ai-ml
What are attention weights in a transformer? :: The matrix where represents how much position attends to position —the fraction of information from token flowing into token 's representation.
Why do we divide by in scaled dot-product attention?
What is attention rollout and why use it?
What's the key limitation: "high attention = high importance"?
How does Attention×Gradient improve attribution?
Why is averaging multi-head attention dangerous?
What should you use attention visualization for?
What is the mathematical formula for multi-head attention output?
Why do value vectors matter for attention interpretation?
What is the difference between attention flow and gradient flow?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Attention visualization ka matlab hai transformer models ke attention weights ko dekhna—yeh samajhne ke liye ki model kis input token par focus kar raha hai jab prediction bana raha hai. Sochiye jaise ap exam de rahe ho aur apki notes par nazar ghoom rahi hai—attention map yeh track karta hai ki apne kaun se parts ko carefully padha.
Lekin yahan ek bada catch hai: sirf dekhne se yeh prove nahi hota ki woh chez aapke answer ka reason thi. Ho sakta hai apne galat section padha, ya aapko already yad tha. Yahi attention visualization ki limitation hai—yeh "association" dikhata hai (model ne kya dekha), par "causation" nahi (kya actual decision ko affect kiya). Jaise agar token "cat" par high attention hai, toh zaruri nahi ki "cat" hatane se output badal jayega.
Is problem ko solve karne ke liye hum gradient-based methods use karte hain jaise Integrated Gradients ya Attention×Gradient. Gradients yeh bate hain