Transformers and attention — the architecture behind LLMs
**Scaled dot-product attention (Vaswani et al. 2017):**
Attn(Q,K,V) = softmax(QKᵀ / √d_k) V
Q (queries) and K (keys) are projected from hidden states; V (values) is also projected. √d_k scaling prevents softmax saturation as dimensionality grows.
**Multi-head attention (MHA):** h parallel attention heads on dim d_model/h each. Concat and project back to d_model. Allows heads to specialize on different relational patterns. **GQA (Grouped-Query Attention, Ainslie et al. 2023)** and **MQA** share K,V across groups of heads — reduce KV cache memory ~4-8× at small quality cost; standard in Llama 3, Claude, Mistral.
**Decoder-only transformer block:** RMSNorm (or LayerNorm) → self-attention (causal mask) → residual → RMSNorm → MLP (SwiGLU or GELU) → residual. Stacked N times.
**Positional encoding:** • **Sinusoidal** (original) — fixed; limited extrapolation. • **Learned absolute** — positions 0..max_len. • **RoPE** (Rotary PE, Su et al. 2021) — rotates Q,K in 2D planes by position. Used by Llama, Mistral, most modern LLMs. Extendable via NTK/YaRN/LongRoPE. • **ALiBi** — linear distance bias on attention scores.
**KV cache:** during autoregressive generation, cache computed K,V tensors for past tokens. Memory scales O(L × d × layers) per request — the dominant memory cost for long context. Paged attention (vLLM, Kwon et al. 2023), KV quantization (Int4/Int8), and context-parallel serving are active areas.
**FlashAttention (Dao et al. 2022, v2 2023, v3 2024):** IO-aware attention that tiles computation to fit in SRAM, avoiding materialization of the N×N attention matrix. 2-4× speedup and enables long context. Standard in production training/inference stacks.
**Encoder-decoder** transformers (T5, BART) remain strong for translation/summarization; decoder-only dominates general chat/coding.