Lesson 5 of 12 · 2 min
Self-Attention Mechanism
Core innovation. Lets each word "look at" all other words to understand context.
Step-by-step:
- For each word, create 3 vectors from embedding: Query (Q), Key (K), Value (V)
- Compute attention score:
score(Q, K) = Q · Kᵀ / √d_k - Apply softmax to get attention weights (sum to 1)
- Weighted sum of Values:
attention = softmax(QKᵀ/√d_k) × V
Analogy: Query = what I’m looking for. Key = what each word offers. Value = the actual content.
Sentence: "The bank by the river is flooded" • "bank" attends strongly to "river" and "flooded" • Self-attention disambiguates: bank = geographical, not financial
Worked Example — Self-Attention (Simplified, 2D vectors)
Sentence: 'cat sat'. Each word has embedding: cat=[1,0], sat=[0,1]
Q = K = V = embeddings (simplified, no learned projection)
Attention(cat→cat): score = [1,0]·[1,0] / √2 = 1/1.41 = 0.71
Attention(cat→sat): score = [1,0]·[0,1] / √2 = 0/1.41 = 0
Softmax([0.71, 0]): [e^0.71/(e^0.71+e^0), e^0/(e^0.71+e^0)] = [2.03/3.03, 1/3.03] = [0.67, 0.33]
Output for 'cat' = 0.67×[1,0] + 0.33×[0,1] = [0.67, 0.33]
← cat's representation now contains 67% itself + 33% sat's context
This is how attention lets each word 'look at' other words to understand context.
Why divide by √d_k?
Prevents dot products from becoming very large in high dimensions — which would cause softmax to saturate (near-zero gradients).
