Attention Mechanisms
When reading a complex sentence like The trophy didn’t fit into the brown suitcase because it was too big, understanding what the pronoun it refers to requires linking it directly back to trophy.
Before the Transformer, sequence models processed text strictly one word at a time from left to right. Every past word had to be compressed into a single, fixed-size hidden vector passed step-by-step along the chain:
- The Parallelization Barrier: Because step could not begin until step finished, GPUs could not process tokens in parallel across a sequence during training.
- The Information Bottleneck: Forcing an entire document of thousands of words through a single fixed-width vector caused early details to fade or get overwritten long before later tokens needed them.
Attention eliminates sequential passing entirely. Instead of funneling history through a single state vector, attention treats every token in the context window as an addressable entry in a parallel key-value database. Every token simultaneously broadcasts three vectors:
- Query (): Encodes what specific context or grammatical partner the token is looking for.
- Key (): Advertises the syntactic and semantic features the token contains.
- Value (): Holds the actual information payload contributed once selected.
By taking dot products between Queries and Keys across all token pairs simultaneously, any token can directly retrieve information from any earlier token in a single parallel matrix operation—regardless of how far apart they sit in the text.
Scaled Dot-Product Attention
The fundamental building block of the Transformer is Scaled Dot-Product Attention (Vaswani et al. 2017). Given packed matrices of Queries , Keys , and Values , it computes contextualized representations as a weighted sum of values:
Mathematical Definitions & Tensor Shapes
Each symbol in the governing equation plays a distinct geometric and computational role:
| Symbol | Tensor Shape | Geometric & Computational Role |
|---|---|---|
| Input Token Matrix: Sequence of input tokens, where each row is the continuous embedding vector for token . | ||
| Learned Projection Weights: Linear parameter matrices projecting token states from into per-head Query, Key, and Value subspaces (). | ||
| Query Matrix (Search Requests): Row encodes what contextual features token is actively looking for across the sequence. | ||
| Key Matrix (Index Descriptors): Row acts as the searchable address advertising what syntactic or semantic attributes token contains. | ||
| Value Matrix (Content Payload): Row holds the information payload contributed by token once addressed. | ||
| Scaled Compatibility Scores: All-pairs dot-product matrix normalized by to maintain unit variance () and prevent softmax gradient saturation. | ||
| Autoregressive Causal Mask: Upper-triangular mask with for past/present tokens () and for future tokens (). | ||
| Normalized Attention Matrix: Row-stochastic probability matrix () with future positions () zeroed out. | ||
| Contextualized Head Output: Weighted combination of Value rows , followed by multi-head fusion via . |
Matrix Contraction & Context Aggregation Geometry (T = 3, dk = 2)
Forward Pass Walkthrough
To trace the arithmetic mechanics, let us calculate the forward pass for an autoregressive sequence of 3 tokens () with a head dimension of :
- :
The - :
cat - :
sat
1. Projecting Queries, Keys, and Values
Each token embedding is projected into Query, Key, and Value coordinate matrices :
2. Computing Attention Scores
We compute the pairwise dot product , where entry represents the compatibility between query and key :
3. Temperature Scaling
Dividing by normalizes score variance to , preventing extreme values that cause softmax gradients to saturate:
The Mathematical Intuition for Scaling:
If components of and are independent random variables with zero mean and unit variance, their dot product has mean and variance .
When is large (e.g., ), dot products grow to large magnitudes (), pushing into flat saturation regions where gradients vanish (). Dividing by normalizes the variance back to .
4. Causal Masking
In an autoregressive decoder, token is strictly forbidden from looking into future tokens (). We enforce this by setting the upper triangle of the score matrix to ():
5. Softmax Normalization
Applying row-wise normalizes scores into a valid probability distribution ():
- Row 1 (
The): Attends solely to itself (). - Row 2 (
cat): Distributes attention betweenThe() andcat(). - Row 3 (
sat): Synthesizes context acrossThe(),cat(), andsat().
6. Value Aggregation
Multiplying attention weights by the Value matrix produces the contextual output :
Token 3 (sat) has synthesized information from The (24%), cat (24%), and itself (52%), producing the contextual vector representation .
Interactive Attention Simulator
Test the mechanics interactively below. Drag the temperature slider to see how variance scaling influences the sharpness of the probability distribution, or toggle causal masking to compare decoder vs. encoder attention:
Scaled Dot-Product Attention Simulator
Step through how raw dot products transform into probability distributions, and adjust temperature scaling (√dk) and causal masking.
| The | cat | sat |
|---|
| The | cat | sat |
|---|
| The | cat | sat |
|---|
GPU Memory & Hardware Efficiency
The KV-Cache Bottleneck
During prefill (processing the initial prompt), tokens are known upfront and can be processed in parallel, saturating the GPU’s tensor computing cores.
However, during autoregressive token generation, the model produces one token at a time. Recomputing past token keys and values from scratch on every step would scale compute quadratically (). Instead, modern LLMs maintain a KV-Cache in GPU High-Bandwidth Memory (HBM):
For a 70B parameter model (80 layers, 64 heads, ) running at FP16 precision:
- At context length : per user.
- At context length : per user.
When generating each new token, the GPU must stream this entire cache from off-chip HBM into on-chip SRAM just to compute dot products against a single new Query vector. The model is not limited by compute (TFLOPs), but by memory bandwidth (TB/s).
MHA vs. GQA vs. MQA
To break this memory-bandwidth wall without sacrificing the expressivity of multiple Query perspectives, modern Transformers share Key and Value heads across groups of Queries:
KV-Cache Sharing Topology: MHA vs. GQA vs. MQA (h = 8 Query Heads)
By grouping Query heads over shared Key-Value heads, Grouped-Query Attention (GQA) cuts KV-cache capacity and memory-bandwidth pressure by to while matching standard Multi-Head Attention perplexity.
FlashAttention & SRAM Tiling
Standard naive attention implementations materialize the intermediate attention matrix in GPU global memory (HBM). For long sequences (), reading and writing this quadratic matrix to HBM introduces severe I/O latency.
FlashAttention avoids materializing the full matrix entirely:
- Tiling: Loads small blocks of into high-speed on-chip SRAM ( per streaming multiprocessor).
- Online Softmax: Computes softmax normalizers incrementally across tiles using running maximums and sums.
- IO-Awareness: Eliminates quadratic HBM roundtrips, reducing memory operations from to and accelerating attention by to .