KatInterview

Multi-Head Attention Forward Pass, Built from Primitives

Machine LearningModel answer
MediumModel answerMachine Learningtransformersattentionnumpy

Last updated

Implement the forward pass of a multi-head attention layer using only basic tensor operations, handling projections, head splitting, scaled dot-product attention, and masking.

Multi-Head Attention Forward Pass, Built from Primitives

Transformers sit at the core of modern NLP and vision models, and multi-head attention is their defining operation. Your task is to implement its forward pass from scratch — no calls to nn.MultiheadAttention, F.scaled_dot_product_attention, or any other attention utility.

Setup

You receive an input tensor x of shape (batch, seq_len, d_model). Assume self-attention unless you decide to support cross-attention as an extension. The layer has four learned weight matrices — for queries, keys, values, and the output projection — each of shape (d_model, d_model). The number of heads num_heads divides d_model evenly, giving a per-head dimension d_head = d_model // num_heads.

An optional mask argument controls which positions may attend to which. You get to decide (and must state) the convention you use.

Only the forward pass is in scope: no parameter initialization scheme, no optimizer, no backward pass.

What to implement

Write a function (or class with a forward method) with roughly this signature:

def multi_head_attention_forward(
    x,          # (batch, seq_len, d_model)
    W_q, W_k, W_v, W_o,  # each (d_model, d_model)
    mask=None,  # shape and semantics of your choosing
    num_heads=8,
):
    ...

Walk through each step, annotating the shape of every intermediate tensor. After writing the implementation, argue for its correctness — either by comparing it against a naive per-head loop, checking that a known-trivial input produces an expected output, or both.

Clarifying questions worth asking before you start

Good candidates surface these before writing a line of code:

  • NumPy or framework tensors (PyTorch/JAX)? The answer changes whether you use @, einsum, or matmul.
  • Self-attention or cross-attention? For cross-attention, keys and values come from a second sequence.
  • What mask format? Causal (lower-triangular), padding (per-sequence lengths), or a general boolean tensor? Does True mean "this position is allowed" or "this position is blocked"?
  • Bias terms on the projections? Dropout on the attention weights?
  • Should the function also return the attention weight tensor alongside the output?

You do not need to handle all variants — pick a reasonable subset, state your assumptions, and note what would change to support the rest.

Hints

Hint 1

Start by figuring out shapes. Write down (batch, seq_len, d_model) → (batch, num_heads, seq_len, d_head) and confirm every reshape and transpose produces that. Getting this wrong is the most common source of silent bugs.

Hint 2

For numerical stability, subtract the row-wise maximum from the scores before exponentiating. The result of softmax is identical in exact arithmetic, but you avoid overflow when scores are large.

Hint 3

Apply the mask before softmax by filling blocked positions with a very large negative number (e.g. -1e9), so they become effectively zero after exponentiation. A causal mask is a lower-triangular boolean matrix; a padding mask broadcasts across the head and key-position dimensions.