Module 8 — Self Attention
Self-Attention is the core building block of the Transformer architecture. It allows every token in a sequence to attend to every other token, enabling the model to capture long-range dependencies and contextual relationships efficiently.
The attention mechanism transforms the input embeddings into Query (Q), Key (K), and Value (V) vectors before computing attention scores.
Topics
- Query
- Key
- Value
- Attention Score
- Scaling
- Attention Matrix
- Attention Output
1. Input Embedding
The input to Self-Attention is the embedding matrix.
Formula
where
- = Sequence length
- = Embedding dimension
2. Query (Q)
Each token is projected into a Query vector.
Formula
where
Output Shape
3. Key (K)
Each token is projected into a Key vector.
Formula
where
Output Shape
4. Value (V)
Each token is projected into a Value vector.
Formula
where
Output Shape
5. Attention Score
Each Query is compared with every Key using a dot product.
Formula
Element-wise
Output Shape
6. Scaling
Large dot-product values can make the Softmax function unstable. The scores are therefore scaled by the square root of the key dimension.
Formula
where
- = Dimension of each key vector
7. Softmax Attention Matrix
Softmax converts the scaled scores into attention probabilities.
Formula
Each row of the attention matrix satisfies
Output Shape
8. Attention Output
The attention matrix is multiplied by the Value matrix.
Formula
Expanded Formula
Output Shape
9. Complete Self-Attention Formula
The complete Scaled Dot-Product Attention mechanism is
This is the fundamental equation of the Transformer architecture.
10. Matrix Dimensions
Suppose
- Sequence Length =
- Embedding Dimension =
- Key Dimension =
Then
Input
Query
Key
Value
Attention Matrix
Output
11. Why Self-Attention Matters
Self-Attention enables each token to gather information from all other tokens in the sequence.
It is the foundation of
- Transformer
- BERT
- GPT
- T5
- ViT
- LLaMA
- Gemma
- Qwen
- Mistral
- DeepSeek
- Phi
- Modern Large Language Models (LLMs)
Summary
| Concept | Formula |
|---|---|
| Query | |
| Key |