KatInterview

Efficient Transformer Inference: Fused Attention, Caching, Rotary Positions

Machine LearningModel answer
MediumModel answerMachine Learningtransformersflashattentionkv-cache

Last updated

Explain how IO-aware attention kernels, cached keys and values, and rotary position encoding each remove a different bottleneck in transformer training and decoding.

Making Transformers Fast and Scalable

Large language models depend on a handful of engineering and architectural tricks to be practical at long context lengths. Walk through the three techniques below and explain what bottleneck each one removes.

1. IO-aware exact attention (FlashAttention)

Standard softmax attention builds an N×N score matrix. Explain how FlashAttention avoids the quadratic memory cost without changing the result. Your answer should cover the roles of tiling and recomputation, and say what does and does not change in compute and memory traffic.

2. Key-Value cache

During autoregressive generation, tokens are produced one at a time. Explain why re-running the full sequence at each step is wasteful, what exactly is stored in the KV cache, and how the cache changes the cost of attention at inference time.

3. Rotary positional embeddings (RoPE)

RoPE rotates query and key vectors instead of adding an absolute position vector. Explain how this encodes relative position, and discuss how well it handles sequences longer than those seen in training.

Wrap-up

Finish by describing how the three techniques fit together in a real serving pipeline (prompt processing and token-by-token decoding), and how they jointly improve efficiency and scalability.

Hints

Hint 1

For attention, ask where the time actually goes on a GPU: arithmetic, or moving the N×N matrices between slow high-bandwidth memory and fast on-chip memory? Think about how softmax can be computed block by block using a running maximum and running sum.

Hint 2

For the cache, consider which quantities from earlier tokens change when a new token is appended under causal masking, and which do not. Then write the memory per token as a product of layers, KV heads, head dimension, and bytes per element.

Hint 3

For rotary encoding, work out what happens to the dot product of two rotated 2D vectors, and be careful about the claim on long sequences: separate 'depends only on relative offset' from 'extrapolates for free'.