Types of Attention Mechanisms
A comprehensive taxonomy of attention: multi-head, multi-query, grouped-query, linear attention, sparse attention, sliding window, flash attention, and cross-attention — with complexity analysis and use cases for each.
Prerequisites
Table of Contents
- Learning Objectives
- Notation
- Core Intuition
- Multi-Head Attention (MHA)
- Multi-Query Attention (MQA)
- Grouped-Query Attention (GQA)
- Sliding Window Attention
- Sparse Attention Patterns
- Linear Attention
- Cross-Attention
- FlashAttention (IO-Aware)
- Comparison Table
- Common Pitfalls
- Summary
- Exercises
Learning Objectives
- Distinguish MHA, MQA, and GQA and derive their KV-cache sizes.
- Derive sliding window attention and compute its effective receptive field.
- Explain how linear attention avoids the quadratic bottleneck.
- Understand FlashAttention's IO-aware tiling strategy.
- Choose the appropriate attention variant for a given constraint (memory, latency, context length).
Notation
- — number of attention heads
- — number of KV groups (for GQA)
- — window size (sliding window)
- — sequence length
- — dimension per head
Core Intuition
Standard multi-head attention is powerful but has two bottlenecks: (1) memory for the attention matrix, and (2) large KV-cache at inference. Different attention variants trade off expressiveness for efficiency, each targeting a specific bottleneck.
Types of Attention Masks
Multi-Head Attention (MHA)
Each head has independent Q, K, V projections:
KV-cache size per token: values (2 for K and V, across all layers).
Used in: Original Transformer, BERT, GPT-2, GPT-3.
Multi-Query Attention (MQA)
Key idea: All heads share a single set of K, V projections; only Q is per-head.
KV-cache reduction: smaller (only 1 K/V head instead of ).
Tradeoff: Slight quality loss (~1% on benchmarks) for massive inference speedup. KV-cache for : MHA needs 1 GB, MQA needs 32 MB.
Used in: PaLM, Falcon, StarCoder.
Grouped-Query Attention (GQA)
Key idea: Group heads into groups. Each group shares K, V.
where maps head to its group.
Interpolation:
- : full MHA (every head has its own K, V)
- : MQA (all heads share one K, V)
- : GQA (balanced tradeoff)
KV-cache size: per token. For : reduction vs MHA.
Used in: LLaMA-2 (70B), Mistral, Gemma.
Sliding Window Attention
Each token attends only to the nearest tokens:
Complexity: instead of — linear in for fixed .
Effective receptive field: After layers of window size , a token can "see" up to positions away (information propagates through the residual stream).
Used in: Mistral (window with full attention every few layers), Longformer.
Sparse Attention Patterns
Fixed patterns (predefined sparsity):
- Strided: Attend to every -th position → .
- Block-sparse: Divide into blocks, attend within block + selected global tokens.
- BigBird: Combination of random, window, and global tokens.
Learned patterns:
- Routing Transformer: Cluster tokens via k-means, attend within clusters.
- Reformer: LSH-based grouping of similar tokens.
Complexity: Generally or .
Linear Attention
Replace softmax with a kernel decomposition:
Standard:
Linear:
where is a feature map (e.g., ).
Key insight: Compute once (), then query in each. Total: — linear in .
Tradeoff: Expressiveness is reduced; performance gap vs softmax attention, especially for long-range dependencies.
Used in: Linear Transformer, RWKV, RetNet.
Cross-Attention
Queries from one sequence, keys/values from another:
Use cases:
- Encoder-decoder models (T5, BART)
- Text-conditioned image generation (Stable Diffusion)
- Retrieval-augmented generation (retrieved docs as keys/values)
FlashAttention (IO-Aware)
FlashAttention computes exact attention but reorders computation to minimize GPU memory reads/writes:
Problem: Standard attention materializes the attention matrix in HBM (slow GPU memory).
Solution: Tile the computation into blocks that fit in SRAM (fast on-chip memory):
- Load blocks of Q, K, V from HBM to SRAM.
- Compute local attention for each block (with online softmax normalization).
- Write output back to HBM.
Result: FLOPs (same) but HBM memory (vs ). Enables 2–4x speedup and much longer sequences.
Used in: Nearly all modern LLM training and inference.
Comparison Table
- MHA: Full expressiveness, compute, KV per token per layer
- MQA: Shared K/V, compute, KV per token per layer
- GQA: Grouped K/V, compute, KV per token per layer
- Sliding Window: compute, KV per token
- Linear: compute, state per layer
- Flash: compute, memory (IO-optimal)
Common Pitfalls
Pitfall 1. Assuming linear attention is always better for long sequences. While asymptotically better, it often underperforms softmax attention on standard benchmarks due to reduced expressiveness.
Pitfall 2. Using MQA without quality validation. For smaller models, the quality drop from shared K/V can be significant. GQA with – is often a better tradeoff.
Pitfall 3. Confusing algorithmic complexity with wall-clock time. FlashAttention has the same FLOP count but is much faster due to better memory access patterns.
Summary
- MHA: Maximum expressiveness, baseline cost.
- MQA/GQA: Reduce KV-cache for efficient inference.
- Sliding window: Linear complexity with bounded context.
- Linear attention: Replace softmax with kernel tricks for .
- FlashAttention: IO-optimal implementation of exact attention.
- Choose based on your bottleneck: training memory → Flash; inference KV → GQA; context length → sparse/linear.
Exercises
Exercise 1. Compute the KV-cache size (in GB) for MHA vs GQA () for a model with .
Exercise 2. Derive the effective receptive field after layers of sliding window attention with .
Exercise 3. Show that linear attention with (identity) is equivalent to a linear layer.
Exercise 4. Prove that GQA with is identical to MHA and with is identical to MQA.
Exercise 5. Explain why FlashAttention uses HBM memory despite computing the exact attention.