Mental model
A decoder-only transformer refines token representations across stacked residual blocks: pre-norm RMSNorm stabilizes inputs, causal grouped-query self-attention with RoPE mixes context across past tokens without leaking future positions, and a gated SwiGLU feed-forward MLP transforms each position independently before handing residual tensors to the next layer.
Learning outcomes
- Derive scaled dot-product attention with causal masking and explain why the factor prevents softmax gradient saturation.
- Compare pre-norm RMSNorm and gated SwiGLU feed-forward blocks against original post-norm LayerNorm + ReLU transformers.
- Explain how Rotary Position Embeddings (RoPE) encode relative token offsets inside query-key dot products and how FlashAttention avoids HBM materialization.
- Calculate KV-cache bytes per token across Multi-Head Attention (MHA), Grouped-Query Attention (GQA), and Multi-Query Attention (MQA).
Theory
Inside layer , hidden states first pass through pre-normalization along a clean residual highway: , where Root Mean Square Normalization rescales vector magnitude using and learned gain , dropping LayerNorm's mean-centering step to cut kernel memory traffic while preserving stable gradient flow across deep stacks.
Next, linear projections produce Queries (), Keys (), and Values (). Before scoring compatibility, modern LLMs apply Rotary Position Embeddings (RoPE) to pairs of dimensions inside and . By rotating position by angle and position by , their inner product depends purely on relative offset :
Rotary Position Embedding (RoPE) Visualizer
θ_i = 10000^(-2(i-1)/d)⟨R_m q, R_n k⟩ depends ONLY on (m - n)Each head computes scaled dot-product causal attention:
Why divide by ? If components of and are independent zero-mean unit-variance variables, their dot product has variance . For , raw dot products swing by , pushing softmax weights toward hard saturation where Jacobian gradients vanish. Dividing by restores unit variance. Meanwhile, the additive causal mask for and for enforces autoregressive causality so token never attends to future positions.
Naive materialization of the attention matrix in GPU HBM incurs memory traffic. IO-aware FlashAttention (dao-flashattention-2022) tiles , , and blocks into fast on-chip SRAM and updates softmax normalization incrementally using online safe softmax statistics , computing exact attention without writing score tensors to HBM.
After residual addition (), a second pre-norm feeds the position-wise SwiGLU MLP:
Because SwiGLU introduces three projection matrices instead of two, architectures typically set inner width (rounded to tensor-core multiples such as 128) to match classic parameter budgets while improving training perplexity.
For autoregressive serving, MHA vs MQA vs GQA governs KV-cache footprint and decode bandwidth. With query heads, key/value heads (group ratio ), layers, head dimension , and bytes per element:
Standard MHA sets ; Multi-Query Attention (MQA) collapses ; Grouped-Query Attention (GQA) shares one KV pair across query heads (), retaining near-MHA expressive capacity while cutting KV-cache reads and VRAM by factor .
Worked quantitative example
Consider a 32-layer model (L = 32, d_model = 4,096, n_h = 32, d_h = 128) running in BF16 (b = 2 bytes) at context length N = 8,192 tokens:
- MHA (
n_kv = 32):512 KiB/tokenyields4.0 GiBper8ksequence. - GQA-8 (
n_kv = 8, g = 4):128 KiB/tokendrops per-sequence cache to1.0 GiB(4xmemory and decode bandwidth reduction). - MQA (
n_kv = 1, g = 32):16 KiB/tokenshrinks per-sequence cache to128 MiB(32xreduction). - Materialized vs Tiled Scores: Without FlashAttention SRAM tiling, storing BF16 scores for 32 heads at
N = 8,192in just one layer requires of transient HBM—more than the entire GQA KV cache across all 32 layers combined.
Attention KV-sharing architecture comparison
| Variant | Query : KV Ratio | KV Bytes / Token (32L, d_h=128, BF16) | Memory / HBM Bandwidth Reduction | Primary Architectural Trade-off |
|---|---|---|---|---|
| MHA | n_h : n_h (1:1) | 512 KiB | 1x (baseline) | Highest expressivity, severe KV VRAM & decode bottleneck |
GQA (g=4) | 32 : 8 (4:1) | 128 KiB | 4x smaller KV & bandwidth | Near-MHA quality with high concurrent batch headroom |
| MQA | 32 : 1 (32:1) | 16 KiB | 32x smaller KV & bandwidth | Maximum batching, slight quality drop on complex tasks |
Trade-offs
Adopting pre-norm RMSNorm, RoPE, SwiGLU, and GQA yields faster convergence, deeper training stability, and 4x–8x higher serving concurrency than post-norm absolute-positional MHA transformers. Yet every choice carries constraints: standard RoPE degrades beyond its pretraining context ceiling unless base frequency is rescaled (YaRN or NTK scaling), and GQA relies on fused attention kernels so broadcasting KV heads never materializes duplicate KV copies in HBM.
Meanwhile, quadratic prefill FLOPs remain unavoidable in dense causal attention even after FlashAttention shrinks HBM traffic to . Long-context workloads (128k+ tokens) still pair dense attention with prefix KV caching, context compaction, or hybrid sliding-window layers to bound Time To First Token.
Failure modes and misconceptions
- Assuming attention weights explain model reasoning faithfully. High attention scores show local routing inside one head and layer; residual bypasses and MLP key-value memories routinely route facts differently from attention heatmaps.
- Forgetting that FlashAttention still requires compute. FlashAttention removes HBM memory allocations via SRAM tiling, not the quadratic pairwise compute scaling over long prompts.
- Using
repeat_interleavenaively during GQA inference. ExpandingKandVtensors in HBM to matchn_hforfeits GQA's memory-bandwidth savings; production kernels index shared KV heads directly in SRAM. - Omitting
1/sqrt(d_k)scaling or FP32 softmax accumulation. Computing softmax in raw FP16/BF16 on unscaled logits triggers overflow,NaNactivations, or collapsed attention weights.
Decision scenario
An engineering team hosts an 8B assistant handling 16,384-token RAG prompts on 80 GB GPUs for 20+ concurrent users. Their legacy MHA checkpoint allocates 512 KiB/token for KV cache, requiring 8.0 GiB per user and crashing with OOM past 7 concurrent sessions even though weights occupy only 16 GB.
Migrate onto a GQA (n_kv = 8) + RoPE + SwiGLU backbone served with fused FlashAttention tiling. Per-user 16k KV footprint drops from 8.0 GiB to 2.0 GiB, raising safe concurrency past 25 sessions while keeping 16k prefill activations in SRAM without score-matrix OOMs. Verify long-range recall across 0%–100% prompt depth before rollout.
Implementation example
This PyTorch module implements pre-norm RMSNorm, grouped-query causal scaled dot-product attention with explicit 1/sqrt(d_k) scaling and upper-triangular -inf masking, and a SwiGLU residual MLP block.
pythonimport mathimport torchimport torch.nn as nnimport torch.nn.functional as Fclass CausalGQABlock(nn.Module):def __init__(self, d_model: int, n_heads: int, n_kv_heads: int, d_ff: int, eps: float = 1e-6) -> None:super().__init__()self.nh, self.nkv, self.hd, self.eps = n_heads, n_kv_heads, d_model // n_heads, epsself.g1, self.g2 = nn.Parameter(torch.ones(d_model)), nn.Parameter(torch.ones(d_model))self.wq = nn.Linear(d_model, self.nh * self.hd, bias=False)self.wk = nn.Linear(d_model, self.nkv * self.hd, bias=False)self.wv = nn.Linear(d_model, self.nkv * self.hd, bias=False)self.wo = nn.Linear(d_model, d_model, bias=False)self.w_gate = nn.Linear(d_model, d_ff, bias=False)self.w_up = nn.Linear(d_model, d_ff, bias=False)self.w_down = nn.Linear(d_ff, d_model, bias=False)def _rms(self, x: torch.Tensor, g: nn.Parameter) -> torch.Tensor:return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * gdef forward(self, x: torch.Tensor) -> torch.Tensor:b, t, _ = x.shapeh = self._rms(x, self.g1)q = self.wq(h).view(b, t, self.nh, self.hd).transpose(1, 2)k = self.wk(h).view(b, t, self.nkv, self.hd).transpose(1, 2).repeat_interleave(self.nh // self.nkv, dim=1)v = self.wv(h).view(b, t, self.nkv, self.hd).transpose(1, 2).repeat_interleave(self.nh // self.nkv, dim=1)scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.hd)mask = torch.triu(torch.full((t, t), float("-inf"), device=x.device), diagonal=1)attn = F.softmax((scores + mask).float(), dim=-1).to(q.dtype) @ vx = x + self.wo(attn.transpose(1, 2).contiguous().view(b, t, -1))h2 = self._rms(x, self.g2)return x + self.w_down(F.silu(self.w_gate(h2)) * self.w_up(h2))
Why does scaling dot products by 1/sqrt(d_k) prevent gradient vanishing, and how does GQA reduce KV-cache memory bandwidth without collapsing multi-head representation?