KatInterview

Build a Causal Multi-Head Attention Layer from Scratch

Machine LearningModel answer
EasyModel answerMachine Learningtransformersattentionpytorch

Last updated

Write a multi-head self-attention module with Q/K/V projections, scaled scores, and a causal mask so each token sees only itself and earlier tokens, then explain how it works.

Task

Build a self-attention layer for a decoder-style Transformer, written in PyTorch (NumPy is also acceptable). The layer must split its work across several heads and must be causal: the output at position i may depend only on input positions 0..i.

Interface

class MultiHeadAttention:
    def __init__(self, d_model, n_heads):
        # Create the layers needed for Q, K, V and the final output projection
        ...

    def forward(self, x):
        # x: (batch_size, seq_len, d_model)
        # returns: (batch_size, seq_len, d_model)
        ...

What the layer must do

  1. Project. Map x through three separate d_model -> d_model linear layers to obtain queries, keys and values.
  2. Split into heads. Divide each projected tensor into n_heads chunks of size d_k = d_model // n_heads, so that each head works on its own slice.
  3. Score. For every head compute softmax(Q Kᵀ / sqrt(d_k) + mask) V.
  4. Mask the future. Before the softmax, block every score where the key position is later than the query position, using -inf (or a very large negative value). Position i may attend to positions j <= i, which is the lower-triangular region including the diagonal.
  5. Merge. Concatenate the head outputs and apply a final d_model -> d_model linear projection.

Example

With x of shape (1, 3, 8) and n_heads = 2, each head has d_k = 4. Token 0 can only see itself, token 1 can see tokens 0 and 1, and token 2 can see tokens 0, 1 and 2. The output has shape (1, 3, 8).

Constraints

  • d_model is divisible by n_heads.
  • The output shape equals the input shape.

What to cover in your answer

  • Working code.
  • Why the scores are divided by sqrt(d_k).
  • How you verify that the layer is really causal.
  • Time and memory complexity, and the edge cases you would guard against.
  • Briefly, how you would extend the layer for padded batches and for fast autoregressive inference.

Hints

Hint 1

After projecting, reshape (B, T, d_model) into (B, T, n_heads, d_k) and swap the two middle axes, so the head dimension behaves like an extra batch dimension for the matrix multiplications.

Hint 2

The score matrix per head is T x T. The positions to block are the ones strictly above the diagonal, so torch.triu(..., diagonal=1) gives the boolean mask to pass to masked_fill. The diagonal itself must stay visible.

Hint 3

To prove causality, change only the last token of the input and check that the outputs at all earlier positions are unchanged. Also check that every attention row sums to 1 and has zeros above the diagonal.