Implement Multi-Head Attention: Head Splitting, Scaled Dot-Product and Masking
Company: Meta
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Onsite
Implement multi-head attention, the core layer of a transformer. Given query, key and value inputs and the layer's projection weights, project the inputs, split them into `num_heads` heads, apply scaled dot-product attention in every head independently, concatenate the heads, and apply the output projection.
The reported prompt names only multi-head attention, so the framework, the masking requirements and whether the layer is used for self-attention or cross-attention are open: settle them with the interviewer first. Unless told otherwise, assume NumPy and this interface:
```python
def multi_head_attention(query, key, value, w_q, w_k, w_v, w_o, num_heads, mask=None):
"""
query: (batch, len_q, d_model)
key: (batch, len_k, d_model)
value: (batch, len_k, d_model)
w_q, w_k, w_v, w_o: (d_model, d_model) projection matrices, applied as x @ w
num_heads: d_model is divisible by num_heads
mask: optional boolean array broadcastable to (batch, num_heads, len_q, len_k);
True means the query position may attend to the key position
returns: (batch, len_q, d_model)
"""
```
```hint Track the shapes
Write the shape of every intermediate array next to the line that produces it; most bugs in this layer are a reshape or transpose that silently mixes heads with sequence positions.
```
```hint Where the mask acts
Decide which array the mask must modify, and at which step, so that a blocked position ends up with exactly zero attention weight.
```
### Clarifying Questions
- NumPy or PyTorch? May a built-in attention function be called, or must the computation be written out?
- Is the layer used only for self-attention, or also for cross-attention with different query and key lengths?
- Which masks are needed: padding, causal, or both? What should a query row whose keys are all masked return?
- Are biases, dropout on the attention weights, or returning the attention weights required?
- Is this for training on full sequences, or for step-by-step decoding?
### What a Strong Answer Covers
- Correct projections, and a head split and merge that keep each head's features together
- Scaled dot-product attention with the right scaling factor and a numerically stable softmax over the key axis
- Masking applied before the softmax, including the fully masked row
- Shape bookkeeping for batch, heads, query length and key length, including cross-attention
- Time and memory cost in sequence length, and a test against a simple reference implementation
### Follow-up Questions
- How do you add a causal mask, and how would you verify that no position attends to a later one?
- During autoregressive decoding, what would you cache between steps, and how does the cost per generated token change?
- Memory grows with the square of the sequence length. Where does that come from, and how do memory-efficient attention kernels avoid it?
- How would you change the layer so that several query heads share one key/value head, and why would you want to?
Overview: A machine learning coding question that asks for a multi-head attention layer: project queries, keys and values, split them into heads, apply scaled dot-product attention with an optional mask, merge the heads and apply the output projection. It tests tensor shape handling, masking and numerical stability.