Understanding Attention in Transformers
Attention is the core mechanism that makes transformers powerful. Let me explain it from scratch:
The Problem: Understanding Context
Traditional neural networks struggle with sequences (like sentences) because they don't naturally capture how words relate to each other. For example, in "The cat sat on the mat because it was comfortable," what does "it" refer to - the cat or the mat?
The Basic Idea of Attention
Attention lets a model "focus" on relevant parts of the input when producing each part of the output. It's like how you might re-read specific parts of a paragraph to understand a concept.
Self-Attention in Detail
Let's use a simple sentence: "The dog chased the cat"
-
For each word, we create three vectors:
- A Query vector (Q): "What am I looking for?"
- A Key vector (K): "What do I contain?"
- A Value vector (V): "What information do I hold?"
-
Computing Attention Scores:
For each word (like "cat"), we calculate how much it should "attend" to every word in the sentence:
- We compute the dot product between the Query of "cat" and the Key of each word
- This gives us raw attention scores
-
Scaling and Softmax:
- We divide these scores by the square root of the dimension size (for stability)
- Apply softmax to convert them to probabilities that sum to 1
-
Creating the Output:
- We take a weighted sum of all Value vectors, using the attention scores as weights
- This becomes the new representation for "cat" that captures its context
A Concrete Example
Imagine our word vectors have just 4 dimensions. For "The dog chased the cat":
- "Dog" might attend strongly to "chased" (showing who's doing the action)
- "Cat" might attend strongly to "chased" (showing what's being chased)
- "Chased" might attend to both "dog" and "cat" (capturing subject and object)
This creates a rich representation showing how words relate to each other, regardless of their position in the sentence.
Multi-Head Attention
Transformers actually use multiple "heads" of attention in parallel. Each head can focus on different relationships:
- One head might focus on subject-verb relationships
- Another on verb-object relationships
- A third on adjective-noun relationships
Would you like me to go deeper into any particular aspect of attention?