Multi-Head and Grouped-Query Attention
🧠 What is multi-head attention? Multi-head attention runs several small attentions side by side instead of one big one. Each head has its own query, key and value projections, so it can match tokens on a different kind of similarity, and the heads' outputs are joined and mixed by one output projection. Grouped-query attention keeps all the query heads but lets groups of them share one key and value head, which shrinks the memory a model needs at inference.
Waymo asked a senior machine learning engineer to write a runnable transformer encoder whose middle step is this
module, x -> qkv -> MHA, and then asked why the scores are divided by sqrt(d_k) and what the complexity is
(the question).
The Prompt
The math is the same as single-head attention; what is graded is the reshaping. A candidate who gets the transposes right without trial and error shows they know what every axis means.
"Implement multi-head causal self-attention as a PyTorch module:
(B, T, D)in,(B, T, D)out, withn_headsheads. Then change it to grouped-query attention."
Clarifying Questions
You: Can I assume D is divisible by the number of heads, so each head has size d_head = D / H?
Interviewer: Yes. Assert it.
You: Biases, dropout, a padding mask?
Interviewer: No biases and no dropout. Causal mask only.
You: For grouped-query attention, n_kv_heads divides n_heads, and query head i uses key/value head
i // (n_heads / n_kv_heads)?
Interviewer: Yes, consecutive query heads share a group.
You: Can I call F.scaled_dot_product_attention?
Interviewer: Not in the module. Use it, or nn.MultiheadAttention, to test.
What You'll Build
causal_attention(q, k, v) -> (..., T, d_head): scaled dot-product attention with a causal mask over any leading batch axes.MultiHeadAttention(d_model, n_heads):forward(x)maps(B, T, D)to(B, T, D).GroupedQueryAttention(d_model, n_heads, n_kv_heads): the same interface;n_kv_heads = 1is multi-query attention andn_kv_heads = n_headsis plain multi-head.