Transformer Attention: Math, Caching, Precision, and Masking Trade-offs
Machine LearningModel answerLast updated
Walk through scaled dot-product attention, KV-cache memory and complexity, mixed-precision training with loss scaling vs BF16, and masked vs cross-attention design choices.
Transformer Internals: A Conceptual Deep Dive
You are asked to explain the core machinery of the Transformer architecture and connect each design decision to the performance, memory, and stability properties it produces. Treat this as a whiteboard conversation: derive results rather than reciting formulas, attach concrete numbers where they matter, and for every mechanism name the failure mode it exists to prevent.
1. Scaled Dot-Product Attention
Write the definition of scaled dot-product attention, Attention(Q, K, V) = softmax(QKᵀ / √d_k) V. Derive why the 1/√d_k factor matters for softmax gradient stability, assuming query and key components are independent with zero mean and unit variance. Describe what happens to the attention distribution and its gradients if the factor is dropped and d_k is large (e.g., 128).
2. KV-Caching
For autoregressive inference, describe the memory consumed by the key/value cache given sequence length N, L layers, H heads, and model width d_model. Show how caching changes the cost of producing the next token from quadratic to linear in context length, and explain the difference between prefill and decode phases.
3. Training Precision
Explain why modern LLM pretraining uses lower-precision formats (FP16/BF16) alongside higher-precision state. What does the loss scaler do in FP16 training, and why has BF16 largely replaced FP16 on current accelerators? Mention the failure modes each choice guards against.
4. Masked Self-Attention vs. Cross-Attention
Compare causal (masked) self-attention in a decoder-only model against cross-attention in an encoder-decoder model. Discuss how each constrains information flow and in what task regimes you would pick one architecture over the other.
Hints
Hint 1
Compute the variance of the dot product q·k under unit-variance assumptions — the scaling factor falls straight out of that calculation.
Hint 2
The KV cache size is 2 × L × N × d_model × bytes-per-element; note that head count cancels unless K/V heads are shared (GQA/MQA).
Hint 3
Loss scaling exists because small FP16 gradients underflow; BF16 avoids the problem entirely because its exponent range matches FP32.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Transformer Internals: A Strong Answer
The goal is to show derivations, numbers, and the failure each mechanism prevents — not just recall.
1. Scaled Dot-Product Attention
For Q ∈ R^{N×d_k}, K ∈ R^{M×d_k}, V ∈ R^{M×d_v}:
Attention(Q, K, V) = softmax(QKᵀ / √d_k) V
Every row of the softmax is a distribution over the M keys, and each output is a convex combination of value rows.
Deriving the scaling. Assume each q_i, k_i is independent, mean 0, variance 1. Then q·k = Σ q_i k_i, with E[q_i k_i] = 0 and Var(q_i k_i) = E[q_i²]E[k_i²] = 1. Summing d_k independent terms gives Var(q·k) = d_k, i.e. standard deviation √d_k. Dividing by √d_k pins the logit variance at 1 regardless of head width.
Without the scaling. At d_k = 128 logits have std ≈ 11, so gaps of 20–30 are common. The softmax saturates toward one-hot, its entropy collapses, and — critically — the softmax Jacobian diag(p) − ppᵀ goes to zero when p is one-hot. Gradients through the attention weights vanish, attention locks onto a single token early, and training stalls. The scaling keeps logits in the softmax's responsive regime at initialization; it is not a guarantee throughout training, which is the motivation for QK-normalization in some modern models.
2. KV-Caching
Memory. Per layer you store one K and one V per token across all heads. With d_head = d_model / H, the heads jointly hold d_model values each for K and V, so:
KV bytes = 2 × L × N × d_model × bytes_per_elem × batch
Head count H cancels — it only re-enters when K/V heads are shared (GQA/MQA), where you replace H with H_kv. With H=32, H_kv=8, the cache shrinks 4×.
Worked example (L=32, d_model=4096, FP16): per token 2 × 32 × 4096 × 2B = 512 KB. A 4K-token sequence ≈ 2 GB; a batch of 32 ≈ 64 GB — dwarfing the ~13 GB of weights. At long context the cache, not the parameters, caps batch size.
Complexity. Without caching, generating token t reruns the whole prefix: attention is O(t² d) per layer, so generating N tokens costs O(N³ d). With a cache, the new token's projections cost O(d²) and its single query attends over t cached keys at O(t·d) — linear per token, O(N² d) total. You trade memory for compute since cached K/V are never recomputed.
Prefill vs decode. Prefill processes the prompt in parallel with quadratic attention; it is compute-bound and sets time-to-first-token. Decode emits one token per step, re-reading all weights and the full cache from HBM each step; it is memory-bandwidth-bound and sets time-per-output-token. GQA/MQA, FP8/INT8 KV quantization, and paged allocation all target this bandwidth bottleneck.
3. Mixed Precision and Loss Scaling
16-bit formats halve memory and bandwidth and hit tensor-core throughput several times that of FP32. The standard recipe keeps sensitive pieces wide: an FP32 master copy of weights, FP32 optimizer states (tiny updates added to large weights would round away in 16 bits), FP32 accumulation inside matmuls, and FP32 softmax, norms, and loss.
Formats. FP16 has 5 exponent / 10 mantissa bits, max ~65504, min normal ~6.1e-5. BF16 has 8 exponent / 7 mantissa bits, matching FP32's range (~3.4e38). FP32 has 8 exponent / 23 mantissa bits.
Loss scaler (FP16). Many gradients fall below ~6e-8 and flush to zero. Scale the loss by S (e.g. 2¹⁶) so gradients land in range, backpropagate, then unscale in FP32 before the optimizer step. Adapt dynamically: on inf/NaN, skip the step and halve S; after a few thousand clean steps, double it.
Why BF16 won. Same exponent range as FP32 means no underflow or overflow at 65504 — no scaler, no skipped steps. The smaller mantissa (~3 significant digits vs ~3.3) adds acceptable noise for SGD, especially with FP32 accumulation and master weights. It ships natively on TPUs and A100/H100-class GPUs, making it the default. FP8 training re-introduces per-tensor scaling for the same range reasons.
4. Masked Self-Attention vs Cross-Attention
Masked (causal) self-attention, decoder-only. Q, K, V all come from one sequence; a lower-triangular mask sets future logits to −∞ so token i sees only ≤ i. This allows the next-token objective to be evaluated at every position in parallel and keeps KV-caching trivial. Prompt and output share one stream.
Cross-attention, encoder-decoder. Queries come from the decoder, keys/values from the encoder output. The encoder attends bidirectionally over the source, so each source token sees full context; its K/V are computed once and reused at every decode step.
Choosing. Decoder-only suits open-ended generation, chat, in-context learning, and very large scale — one architecture, one objective, the most mature tooling. Encoder-decoder suits tasks where input and output are clearly distinct and the input is long relative to the output: translation, summarization, speech recognition, structured transduction (T5-style), and multimodal conditioning where an image/audio encoder feeds the decoder through cross-attention. Bidirectional encoding often buys quality per FLOP, and the encoder can be sized independently of the decoder.
Common mistakes: forgetting that H cancels in the KV formula; claiming caching makes attention O(N) total rather than per generated token; saying BF16 is "more precise" than FP16 (it is not — it has more range, less mantissa); and asserting loss scaling is needed for BF16.