AttentionIsAllYouNeed:TransformerArchitecturefromScratch
Line-by-line PyTorch reproduction of scaled dot-product attention, multi-head projection matrices, and sinusoidal positional embeddings.
Self-Attention Mechanism Visualizer
Explore how transformer tokens calculate pairwise relevance to resolve context and coreference.
Coreference Intuition: When evaluating “it”, the model computes high dot-product similarity with “animal” (85%), dynamically pulling information from the correct referent without requiring recurrent sequential steps.
Start Here: Beginner Primer & Intuition
No heavy equations required — grasp the core mechanics in plain English first.Quick TL;DR: Understand how the core engine of modern generative AI (ChatGPT, Claude, Gemini) works by allowing every word to connect directly and simultaneously to every other word.
Why the Old Approach Broke Down
Before the Transformer, older AI models (RNNs & LSTMs) processed sentences like an old cassette tape: one word at a time from left to right. This was agonizingly slow on GPUs, and models often forgot earlier sentences by the time they reached the end.
The Elegant Engineering Fix
Self-Attention looks at the entire sentence simultaneously in a single parallel GPU pass. For every token, it computes attention scores determining which other tokens provide the most important context.
The Library Catalog System (Query, Key, Value)
Think of self-attention as searching in a library: your Query (Q) is what you're looking for, the Key (K) is the label on book spines, and the Value (V) is the actual content inside. When Query matches Key, the library hands you the Value.
Parallel Processing
Because there are no step-by-step loops, thousands of GPU cores process long documents concurrently.
Multi-Head Attention
Instead of a single attention score, the model uses multiple 'heads' (e.g. 8 or 32) so different heads can track grammar, subject-verb connections, or pronouns at the same time.
Positional Encodings
Because self-attention reads all words at once, it adds mathematical sine and cosine wave signals to track word positions in the sequence.
Abstract & Theoretical Context
Mathematical Formulations & Variables
1. Scaled Dot-Product Attention:
Attention(Q, K, V) = softmax( (Q * K^T) / sqrt(d_k) ) * V
- Q in R^(B x N x d_k) : Query matrix
- K in R^(B x N x d_k) : Key matrix
- V in R^(B x N x d_v) : Value matrix
- d_k : Dimensionality of keys (scaling by sqrt(d_k) prevents large values from pushing softmax into regions with vanishing gradients)
2. Multi-Head Attention:
MultiHead(Q, K, V) = Concat(head_1, ..., head_h) * W^O
where head_i = Attention(Q * W_i^Q, K * W_i^K, V * W_i^V)
- W_i^Q in R^(d_model x d_k)
- W_i^K in R^(d_model x d_k)
- W_i^V in R^(d_model x d_v)
- W^O in R^(h*d_v x d_model)
3. Sinusoidal Positional Encoding:
PE_(pos, 2i) = sin(pos / 10000^(2i / d_model))
PE_(pos, 2i+1) = cos(pos / 10000^(2i / d_model))
- Enables the model to learn relative position relationships via trigonometric identity:
PE_(pos + k) can be represented as a linear function of PE_(pos).PyTorch Implementation Code
Step-by-Step Reproduction Guide
Key Insights & Operator Insights
- Scaling Factor sqrt(d_k): Without scaling, for large d_k dot products grow large in magnitude, pushing softmax into extreme regions with tiny gradients.
- Parallel Training: Unlike RNNs which require seq_len sequential GPU calls, Transformers compute all token representations simultaneously in parallel.
- Multi-head projections allow the model to attend to information from different representation subspaces at different positions simultaneously.
- Causal Masking: Prevents leftward information flow in decoder layers during autoregressive token generation.
NVIDIA RTX 3060 (8GB VRAM), T4, or Apple M-Series Silicon