KatInterview

Transformer Attention: Math, Caching, Precision, and Masking Trade-offs

Machine LearningModel answer
HardModel answerMachine Learningtransformersattentionkv-cache

Last 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.