Multi-head attention with a KV cache and grouped-query attention
I was asked this
No reports yet. Sign in to say where you were asked it.
An AI/ML design interview question asked in Amazon's system design round, last asked Jan 2026. It tests transformers, attention and kv cache.
Implement the attention layer of a decoder-only transformer from scratch, in three steps that build on each other. Use NumPy or PyTorch tensors, but no built-in attention module. Attention is causal: each token attends only to itself and earlier tokens. The input is a batch of hidden states x of shape (batch, seq_len, d_model), and the layer owns its query, key, value and output projections.
Part 1: multi-head attention
Unless you agree on a different interface with the interviewer, assume:
-
MultiHeadAttention(d_model: int, n_heads: int)withhead_dim = d_model // n_heads. -
forward(x) -> Tensor— returns(batch, seq_len, d_model).
Project x to queries, keys and values, split them into heads, compute scaled dot-product attention with a causal mask, merge the heads and apply the output projection.
Part 2: a key-value cache
Extend the layer so generation does not recompute keys and values of tokens it has already seen:
-
forward(x, cache=None) -> (Tensor, cache)— the first call (prefill) gets the whole prompt; each later call gets only the new token and attends to every earlier token through the cache.
The causal mask and any position encoding must use each token's position in the full sequence, not its index in the current call. Test that cached decoding gives the same outputs as one full uncached forward pass.
Part 3: grouped-query attention with the cache
The layer now has n_heads query heads but only n_kv_heads key/value heads, where n_kv_heads divides n_heads; each group of n_heads // n_kv_heads query heads shares one key/value head. Implement the forward pass, cache included.
Clarifying questions
- NumPy or PyTorch? May I use
einsumand broadcasting freely? - Are the projections part of the layer, or are queries, keys and values passed in already projected?
- Do all sequences in the batch have the same length, or is a padding mask needed?
- Is the cache preallocated to a maximum length, or can it grow by concatenation?
- Is position encoding (for example rotary embeddings) applied inside this layer?
What a strong answer covers
- The shape of every intermediate tensor written down, with a consistent axis order and no reshape that mixes the head axis with the time axis.
- Scaling by
sqrt(head_dim), a causal mask that still works when there are fewer queries than keys, and a numerically stable softmax. - What the cache stores (
(batch, n_kv_heads, seq, head_dim)for keys and values), how much it saves per token, and how much memory it costs; under grouped-query attention it shrinks byn_heads / n_kv_heads. - The query-to-key/value head mapping done by reshaping or broadcasting, without copying keys and values per query head.
- Checks: cached matches uncached;
n_kv_heads == n_headsreproduces multi-head attention andn_kv_heads == 1is multi-query attention. - Compute and memory cost in sequence length and model width, and why decoding is limited by memory bandwidth.
Follow-ups
- Support a batch whose prompts have different lengths, at prefill and while decoding.
- With rotary position embeddings, do you cache keys before or after the rotation, and why?
- Bound cache memory for very long conversations, for example with a sliding window. What does that do to the mask?
- Why does grouped-query attention speed up decoding much more than prefill?
Where it's asked
- Amazon · System design · Last asked Jan 202655 min · Design discussion
What it tests
transformers · attention · kv cache
No official answer yet. Draw yours on the right; publish it and it shows under Community.
Nothing published yet. Publish your canvas and it shows here for others to open and remix.
