How Self-Attention Works
What Is Self-Attention?
Each word attends to the whole sentence
Query
"cat"
Attends Most To
"cat"
Top Weight
22%
"cat" attends most to itself (22%). In self-attention, each word in a sentence computes how relevant every other word is to its own meaning — including itself.
Step 1 of 6: What Is Self-Attention?
Each word attends to the whole sentence
Query
"cat"
Attends Most To
"cat"
Top Weight
22%
"cat" attends most to itself (22%). In self-attention, each word in a sentence computes how relevant every other word is to its own meaning — including itself.
Step 2 of 6: Query, Key, Value
Projecting input into Q, K, V matrices
Projection
Query
Input Shape
6 × 3
Query Shape
6 × 3
The Query matrix is computed by multiplying the input embeddings by W_Q. Each row becomes a query vector — it asks "what am I looking for?"
Step 3 of 6: Q·K Dot Product
Computing similarity between queries and keys
Query
"cat"
Highest Score
0.63
Best Match
"cat"
Score("cat", "cat") = 0.63 is the highest. The attention score is the dot product Q·K — multiply each dimension pairwise and sum. Higher scores mean the query and key are more aligned.
Step 4 of 6: Attention Score
Scale, softmax, and attention weights
Query
"cat"
1/√d_k
0.58
Top Weight
21.5%
Attends To
"cat"
Raw Q·K scores are divided by √d_k = 1.73 to prevent large values from pushing softmax into extremes. Then softmax converts scores into a probability distribution — "cat" puts 21.5% of its attention on "cat".
Step 5 of 6: Causal Self-Attention
Masking future tokens in decoders
Query
"sat"
Visible Tokens
6
Top Weight
24.2%
In bidirectional self-attention, "sat" attends to all 6 tokens equally. This is used in encoders (like BERT) where the full context is available. Compare with causal masking to see the difference.
Step 6 of 6: Full Pipeline
End-to-end attention in one view
Query
"cat"
Attends to
"cat"
Output
[0.14, 0.17, 0.45]
This is the full attention pipeline for "cat": embed → project to Q,K,V → compute Q·K scores → scale by 1/√3 → softmax → weighted sum of V vectors. The output [0.14, 0.17, 0.45] is a context-aware representation that blends information from all words, weighted by relevance.