|
|
2.1 Variance Derivation of the 1/√dk Scaling FactorFor 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: |
Ms. PJ demonstrating causal attention span across a sunny windowsill with zero gradient vanishing. |
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).
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:
| 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! |
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:
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:
Fig 2.2 — FlashAttention minimizes HBM traffic from O(S2) to O(S2d2M−1), enabling exact 128k–1M context training with linear memory.
| « Previous: Ch. 1 — Tokenization & RoPE | [ Table of Contents ] | Next: Ch. 3 — Scaling Laws & 3D Parallel » |