PJ's Guide to Large Language Models

Chapter 2: Scaled Dot-Product Attention, KV Compression & FlashAttention

2.1 Variance Derivation of the 1/√dk Scaling Factor

For input activations X ∈ ℝS×d, a single attention head computes linear projections Q = XWQ, K = XWK, V = XWV ∈ ℝS×dk. Suppose entries of q, k ∈ ℝdk are independent zero-mean unit-variance random variables. Then the unscaled dot product has zero mean but variance proportional to head dimension dk:

PJ stretched horizontally across full context window on the windowsill
Fig 2.1 — Full Context Span
Var(qTk) = ∑i=1..dk Var(qiki) = dk

Ms. PJ demonstrating causal attention span across a sunny windowsill with zero gradient vanishing.

Var(qTk / √dk) = 1dk ∑i=1dk E[qi2] E[ki2] = 1
(2.1)

Without dividing by √dk, logits grow as O(√dk), pushing the softmax distribution p = softmax(z) into one-hot saturation where the Jacobian Jij = pi(δij − pj) collapses toward zero and backpropagated gradients vanish. Autoregressive causality is enforced by adding a strictly upper-triangular mask Mij = −∞ for j > i (0 otherwise).

2.2 MHA, MQA, GQA & Multi-Head Latent Attention (MLA)

During autoregressive decoding, previously computed keys and values are cached in GPU HBM. For nl layers, nkv KV heads, head dimension dh, sequence length S, batch size B, and precision b bytes/element (2 for BF16), the KV-cache footprint is:

BytesKV = 2 · B · nl · nkv · dh · S · b
(2.2)
Mechanism KV Heads (nkv) KV Cache Memory Architectural Trade-Off
MHA (Standard) nkv = nq 100% (Baseline) Maximum expressivity; severely HBM bandwidth-bound at long contexts and large batches.
MQA (Multi-Query) nkv = 1 1 / nq Dramatic decode speedup; noticeable quality degradation and training instability at scale.
GQA (Grouped-Query) 1 < nkv < nq (e.g., 8:1) nkv / nq (e.g., 12.5%) Industry standard (Llama-3, Qwen, Gemma): matches MHA perplexity at a fraction of KV traffic.
MLA (Latent Attention) Compressed latent ctKV ∈ ℝdc dc / (2nqdh) (~5–10%) DeepSeek-V2/V3: caches a low-rank latent vector and absorbs up-projection matrices into WQ and WO at inference!

2.3 Pre-LN Residual Stream, RMSNorm & SwiGLU

Modern decoder-only LLMs replace Post-LN with Pre-LN residual connections (xℓ+1 = xℓ + F(Norm(xℓ))), maintaining an unimpeded identity gradient highway ∂xL/∂xℓ = I + … across 100+ layers. Standard LayerNorm is simplified to RMSNorm (eliminating mean-centering overhead while preserving re-scaling invariance), and ReLU FFNs are replaced by gated SwiGLU blocks:

RMSNorm(x) = x√(d−1∑i xi2 + ε) ⊙ γ,     SwiGLU(x) = (SiLU(xW1) ⊙ xW3) W2
(2.3)

2.4 FlashAttention: IO-Aware SRAM Tiling & Online Softmax

Materializing the S×S attention matrix P = softmax(QKT/√dk) in slow GPU High-Bandwidth Memory (HBM, ~3.35 TB/s on H100) requires Θ(S2) HBM reads/writes. FlashAttention (Dao et al., 2022–2024) partitions Q, K, V into blocks that fit inside ultra-fast on-chip SRAM (~19 TB/s, ~20–50 MB), computing exact attention in a single fused kernel without ever writing S×S to HBM.

Because softmax normalization couples all columns across a row, FlashAttention maintains running row-wise maximum m(j) and partition sum ℓ(j) via the online softmax rescaling identity as each key/value tile j streams through SRAM:

mnew = max(mold, mtile),    ℓnew = emold−mnewℓold + emtile−mnewℓtile,    Onew = diag(ℓnew)−1(diag(ℓold)emold−mnewOold + emtile−mnewPtileVtile)
(2.4)
GPU HBM (80 GB) ~3.35 TB/s (Slow) Q, K, V (O(S·d)) NO S×S Matrix Written! Load Tiles Write Final O On-Chip SRAM (~20–50 MB, ~19 TB/s) Fused FlashAttention Kernel: 1. S_ij = Q_i K_j^T / sqrt(d_k) in Tensor Cores 2. Update running max (m) & sum (l) online 3. Rescale O_i in registers → O(S^2 d^2 / M) IO

Fig 2.2 — FlashAttention minimizes HBM traffic from O(S2) to O(S2d2M−1), enabling exact 128k–1M context training with linear memory.

Prof. PJ's Bench Note: Standard attention is like walking back to the pantry (HBM) after every single lick of peanut butter. FlashAttention brings the entire jar directly onto the couch cushion (SRAM) until the jar is mathematically empty.
« Previous: Ch. 1 — Tokenization & RoPE [ Table of Contents ] Next: Ch. 3 — Scaling Laws & 3D Parallel »