Attention Mechanisms

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:

  1. The Parallelization Barrier: Because step could not begin until step finished, GPUs could not process tokens in parallel across a sequence during training.
  2. 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:

SymbolTensor ShapeGeometric & 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)

Queries Q(3 × 2)1.00.00.01.01.01.0×Keys KT(2 × 3)1.00.01.00.01.01.0softmax÷√2 + MaskAttention Map A(3 × 3 Causal)1.00000.330.6700.240.240.52×Values V(3 × 2)2.00.00.04.01.02.0=Output O(3 × 2)2.000.000.672.671.002.00
Figure 1 (Highlighted Row 3): Query token 3 (, highlighted in carmine) computes dot products with all three Keys, producing causal attention weights that blend the three Value rows into output .

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 between The () and cat ().
  • Row 3 (sat): Synthesizes context across The (), cat (), and sat ().

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.

1.41
Phase 1: Dot ProductS = Q · KTPhase 2: ScaleS / √dkPhase 3: Causal Maskj > i → −∞Phase 4: Softmax & AVRow Σ Aij= 1.0Query "sat" Attention Weights:The 24%cat 24%sat 52%Output o₃ = [1.000, 2.000]
1. Scores (S = Q·KT) 3 × 3
Thecatsat
2. Scaled & Masked S/√dk + M
Thecatsat
3. Softmax (A) Row Σ = 1
Thecatsat
Phase 1 (Dot Product Sweep): Each token's Query vector computes inner products against all Key vectors to measure directional alignment. Phase 1 / 4
Phase:

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)

1. Multi-Head (MHA)8 Q ↔ 8 KV (1× Cache)100% HBM Bandwidth2. Grouped-Query (GQA)8 Q ↔ 2 KV (4× Smaller)KV 1KV 2LLaMA 3 / Mistral / Qwen3. Multi-Query (MQA)8 Q ↔ 1 KV (8× Smaller)Global KV 1Minimum HBM Footprint
Figure 2 (KV-Cache Sharing): Grouping Query heads into shared Key-Value groups (GQA, highlighted in carmine) reduces GPU HBM KV-cache memory bandwidth by while preserving multi-head relational capacity.

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:

  1. Tiling: Loads small blocks of into high-speed on-chip SRAM ( per streaming multiprocessor).
  2. Online Softmax: Computes softmax normalizers incrementally across tiles using running maximums and sums.
  3. IO-Awareness: Eliminates quadratic HBM roundtrips, reducing memory operations from to and accelerating attention by to .

Key Papers & References