KatInterview

Build Multi-Head Attention in PyTorch Without Library Helpers

Machine LearningModel answer
MediumModel answerMachine Learningattentiontransformerspytorch

Last updated

Write a multi-head attention module from raw tensor ops: projections, head reshaping, scaled scores, masking, softmax, and output merge, plus cost and testing discussion.

You are asked to write, from scratch, a layer that performs multi-head attention. Treat it as a live coding exercise followed by a discussion.

The task

The layer takes three batched inputs:

  • query with shape (batch, len_q, d_model)
  • key with shape (batch, len_k, d_model)
  • value with shape (batch, len_k, d_model)

It must:

  1. Apply a learned linear projection to each of the three inputs.
  2. Split each projection into num_heads heads.
  3. Compute scaled dot-product attention separately in every head.
  4. Join the heads back together and pass the result through a final learned linear projection.
  5. Accept an optional mask that stops certain query/key pairs from interacting.

Rules

  • Use NumPy or PyTorch. Matrix multiplication, reshape, transpose, softmax and linear layers are fine.
  • Library attention modules (torch.nn.MultiheadAttention, torch.nn.functional.scaled_dot_product_attention) are off limits.
  • You may assume d_model is divisible by num_heads.

What to be ready to discuss

  • Should the same code serve self-attention and cross-attention (where len_q and len_k differ)?
  • Which masks do you need (padding, causal, or both), and what convention does the boolean mask follow?
  • Should the layer support attention dropout or return the attention weights?
  • How would you check correctness, including gradients and behavior in half precision?
  • How do time and memory scale with sequence length, model width and head count?

Hints

Hint 1

Project first with full-width `d_model x d_model` matrices, then reshape to `(batch, len, num_heads, d_head)` and transpose to `(batch, num_heads, len, d_head)` so one batched matmul handles all heads.

Hint 2

Scores have shape `(batch, heads, len_q, len_k)`. Divide by `sqrt(d_head)`, fill blocked positions with a large negative number (or `-inf`) before softmax, and softmax over the last (key) axis.

Hint 3

Think about edge cases: a query row where every key is masked yields NaN with `-inf`; half precision can overflow with large negative constants; and the merge step needs `contiguous()` or `reshape` after transposing back.