The Idea of Attention
When you translate a long sentence, you do not look at all words equally. For each word you write, you look at the most relevant source words. Attention lets a neural network do the same: for each position it decides how much to focus on every other position.
Query, Key and Value
| Part | Role | Library analogy |
|---|---|---|
| Query (Q) | What am I looking for? | Your search question |
| Key (K) | What do I contain? | The label on each book |
| Value (V) | The actual information | The content of the book |
The model compares the query with all keys to get scores, turns the scores into weights with softmax, and then returns the weighted sum of the values.
Attention from Scratch
When Q, K and V all come from the same sequence, we call it self-attention. Every word looks at every other word in the same sentence.
Multi-Head Attention in Keras
Multi-head attention runs several attention operations in parallel. Each head can focus on a different kind of relation, such as grammar or meaning.
Why Attention is Better than RNNs
- Looks at all positions at once, so long-range links are easy
- Can be computed in parallel, so it trains much faster on GPUs
- Scales to very large datasets and models
Conclusion
Attention lets the model focus on what matters. It is the core building block of Transformers, which power modern language models.

