Multi-Head Attention Forward Pass, Built from Primitives
Machine LearningModel answerLast 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, ormatmul. - 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
Truemean "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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Multi-head attention projects the input into queries, keys, and values; splits each into num_heads sub-spaces; computes scaled dot-product attention independently in each sub-space; concatenates the results; and projects back to d_model. Every step has a predictable shape, so annotating shapes as you go is both good practice and a built-in sanity check.
Clarifications and assumptions
- Using NumPy for portability (swap
np.matmul/@fortorch.matmulin PyTorch with no structural changes). - Self-attention: Q, K, V all come from
x. - Mask convention: a boolean array where
Truemarks positions that should be blocked (i.e. set to −∞ before softmax). A causal mask and a padding mask both fit this convention. - No bias terms, no dropout — easy to add but they don't change the architecture.
- The function returns both the output and the attention weights.
Step-by-step with shapes
import numpy as np
def multi_head_attention_forward(x, W_q, W_k, W_v, W_o, mask=None, num_heads=8):
"""
x: (batch, seq_len, d_model)
W_q/k/v/o: (d_model, d_model)
mask: (batch, 1, seq_len, seq_len) or broadcastable; True = block
returns: out (batch, seq_len, d_model), attn (batch, num_heads, seq_len, seq_len)
"""
batch, seq_len, d_model = x.shape
assert d_model % num_heads == 0
d_head = d_model // num_heads
# 1. Linear projections — (batch, seq_len, d_model)
Q = x @ W_q # (batch, seq, d_model)
K = x @ W_k
V = x @ W_v
# 2. Split into heads — (batch, num_heads, seq_len, d_head)
def split_heads(t):
# reshape then transpose so heads are contiguous in memory
t = t.reshape(batch, seq_len, num_heads, d_head)
return t.transpose(0, 2, 1, 3) # (batch, heads, seq, d_head)
Q, K, V = split_heads(Q), split_heads(K), split_heads(V)
# 3. Scaled dot-product attention
scale = np.sqrt(d_head)
# scores: (batch, heads, seq_len, seq_len)
scores = Q @ K.transpose(0, 1, 3, 2) / scale
# 4. Apply mask before softmax
if mask is not None:
scores = np.where(mask, -1e9, scores)
# 5. Numerically stable softmax over the key dimension
scores -= scores.max(axis=-1, keepdims=True) # subtract row max
exp_scores = np.exp(scores)
attn = exp_scores / exp_scores.sum(axis=-1, keepdims=True) # (batch, heads, seq, seq)
# 6. Weighted sum of values — (batch, heads, seq_len, d_head)
context = attn @ V
# 7. Merge heads — (batch, seq_len, d_model)
context = context.transpose(0, 2, 1, 3).reshape(batch, seq_len, d_model)
# 8. Output projection
out = context @ W_o # (batch, seq_len, d_model)
return out, attn
Why scale by √d_head?
Q and K are each roughly unit-variance random vectors of length d_head. Their dot product has variance d_head, so its standard deviation is √d_head. Without scaling, large d_head values push scores into the saturating region of softmax, collapsing gradients toward zero. Dividing by √d_head restores unit variance.
Mask semantics
A causal mask prevents position i from attending to position j > i:
def causal_mask(seq_len):
# True where we want to block (upper triangle, excluding diagonal)
return np.triu(np.ones((1, 1, seq_len, seq_len), dtype=bool), k=1)
A padding mask blocks attention to pad tokens. If valid is a boolean array of shape (batch, seq_len) marking real tokens, the key-side mask is ~valid[:, None, None, :] (broadcast across heads and query positions).
Correctness check: compare against a naive per-head loop
def naive_mha(x, W_q, W_k, W_v, W_o, num_heads=8):
batch, seq_len, d_model = x.shape
d_head = d_model // num_heads
heads = []
for h in range(num_heads):
Wq_h = W_q[:, h*d_head:(h+1)*d_head]
Wk_h = W_k[:, h*d_head:(h+1)*d_head]
Wv_h = W_v[:, h*d_head:(h+1)*d_head]
q = x @ Wq_h # (batch, seq, d_head)
k = x @ Wk_h
v = x @ Wv_h
s = q @ k.transpose(0, 2, 1) / np.sqrt(d_head)
s -= s.max(axis=-1, keepdims=True)
a = np.exp(s) / np.exp(s).sum(axis=-1, keepdims=True)
heads.append(a @ v)
concat = np.concatenate(heads, axis=-1) # (batch, seq, d_model)
return concat @ W_o
# Verify
rng = np.random.default_rng(0)
B, S, D, H = 2, 6, 16, 4
x_t = rng.standard_normal((B, S, D))
Wq, Wk, Wv, Wo = [rng.standard_normal((D, D)) for _ in range(4)]
out1, _ = multi_head_attention_forward(x_t, Wq, Wk, Wv, Wo, num_heads=H)
out2 = naive_mha(x_t, Wq, Wk, Wv, Wo, num_heads=H)
assert np.allclose(out1, out2, atol=1e-6), "Outputs diverge!"
Complexity and memory
- Time: O(batch · heads · seq² · d_head) = O(batch · seq² · d_model). The quadratic term in
seq_lenis the classic bottleneck of vanilla attention. - Memory: the score tensor is
(batch, heads, seq, seq)— atseq=2048,batch=32,heads=8that is ~4 GB in float32, which is why sparse and linear-attention variants exist.
Common mistakes
- Transposing the wrong axes when splitting heads, producing incorrect dot products with no shape error.
- Forgetting to subtract the row maximum before softmax, causing
nanfor long or high-dimensional sequences. - Applying a padding mask on the query side instead of the key side, which blocks the wrong positions.
- Skipping the output projection and returning the raw concatenation.