Implement scaled dot-product attention from scratch
Written by the mlprep team · Updated
Implement scaled dot-product attention in NumPy. Then extend it to multi-head attention. Walk me through the shapes at each step.
Single-head attention#
import numpy as np
def softmax(x, axis=-1):
x = x - x.max(axis=axis, keepdims=True)
exp_x = np.exp(x)
return exp_x / exp_x.sum(axis=axis, keepdims=True)
def attention(Q, K, V, mask=None):
"""
Q: (seq_len, d_k)
K: (seq_len, d_k)
V: (seq_len, d_v)
Returns: (seq_len, d_v)
"""
d_k = Q.shape[-1]
# Attention scores: (seq_len, seq_len)
scores = Q @ K.T / np.sqrt(d_k)
# Optional mask (for causal/decoder attention)
if mask is not None:
scores = np.where(mask, scores, -1e9)
weights = softmax(scores, axis=-1) # (seq_len, seq_len)
return weights @ V # (seq_len, d_v)Why divide by sqrt(d_k)?#
The dot product Q @ K.T grows in magnitude with d_k. If each element of Q and K is drawn from N(0,1), then q · k = Σ q_i * k_i has variance d_k. Without scaling, the scores have std sqrt(d_k), pushing softmax into saturation (near-zero gradients). Dividing by sqrt(d_k) normalizes the variance back to 1.
Causal mask (for autoregressive decoding)#
In decoder self-attention, position i should only attend to positions ≤ i:
def causal_mask(seq_len):
# True where attention is allowed
return np.tril(np.ones((seq_len, seq_len), dtype=bool))Multi-head attention#
def multi_head_attention(X, W_q, W_k, W_v, W_o, num_heads):
"""
X: (seq_len, d_model)
W_q: (d_model, d_model)
W_k: (d_model, d_model)
W_v: (d_model, d_model)
W_o: (d_model, d_model)
"""
seq_len, d_model = X.shape
d_k = d_model // num_heads
# Project to Q, K, V
Q = X @ W_q # (seq_len, d_model)
K = X @ W_k
V = X @ W_v
# Split into heads: (num_heads, seq_len, d_k)
Q = Q.reshape(seq_len, num_heads, d_k).transpose(1, 0, 2)
K = K.reshape(seq_len, num_heads, d_k).transpose(1, 0, 2)
V = V.reshape(seq_len, num_heads, d_k).transpose(1, 0, 2)
# Attention per head: (num_heads, seq_len, d_k)
d_k_scale = np.sqrt(d_k)
scores = Q @ K.transpose(0, 2, 1) / d_k_scale # (num_heads, seq_len, seq_len)
weights = softmax(scores, axis=-1)
head_out = weights @ V # (num_heads, seq_len, d_k)
# Concatenate heads: (seq_len, d_model)
head_out = head_out.transpose(1, 0, 2).reshape(seq_len, d_model)
# Final projection
return head_out @ W_o # (seq_len, d_model)Shape walkthrough for d_model=512, num_heads=8, seq_len=10#
X: (10, 512)
Q, K, V: (10, 512) after projection
After split: (8, 10, 64) — 8 heads, each d_k=64
scores: (8, 10, 10) — each head attends over full sequence
weights: (8, 10, 10) — softmax over last dim
head_out: (8, 10, 64)
After concat: (10, 512)
After W_o: (10, 512)
Why multiple heads?#
Each head operates on a d_k = d_model / num_heads subspace of the representation. Different heads can learn to attend to different relationship types simultaneously — one head might track syntactic dependencies, another coreference, another positional proximity. A single large attention over all of d_model can only learn one weighted average of values at a time. Multi-head gives you num_heads parallel attention patterns for the same compute cost.
Interview red flags#
- Forgetting the 1/√d_k scaling, or being unable to explain that it keeps dot products from saturating the softmax.
- Applying softmax over the wrong axis; it must normalize over the key dimension for each query.
- Losing track of shapes when splitting into heads, for example reshaping without the transpose that groups dimensions by head.
- Mentioning causal masking but adding the mask after the softmax instead of setting masked logits to a large negative value (−∞ or −1e9) before it.
You implement attention with X @ W_q as a single matrix multiply. In PyTorch's actual nn.MultiheadAttention, the Q, K, V projections are sometimes fused into one matrix. How would you implement that, and why might it be faster?
Fused QKV projection#
Instead of three separate projections X @ W_q, X @ W_k, X @ W_v, concatenate the weight matrices and split the output:
def multi_head_attention_fused(X, W_qkv, W_o, num_heads):
"""
W_qkv: (d_model, 3 * d_model) — fused Q, K, V weights
"""
seq_len, d_model = X.shape
d_k = d_model // num_heads
# One matmul instead of three
QKV = X @ W_qkv # (seq_len, 3 * d_model)
Q, K, V = np.split(QKV, 3, axis=-1) # each (seq_len, d_model)
# Split into heads
def split_heads(x):
return x.reshape(seq_len, num_heads, d_k).transpose(1, 0, 2)
Q, K, V = split_heads(Q), split_heads(K), split_heads(V)
scores = Q @ K.transpose(0, 2, 1) / np.sqrt(d_k)
weights = softmax(scores, axis=-1)
out = weights @ V
out = out.transpose(1, 0, 2).reshape(seq_len, d_model)
return out @ W_oWhy faster?#
Matrix multiplication efficiency depends on arithmetic intensity — the ratio of FLOPs to memory reads. Modern GPUs have massive compute throughput but relatively slow memory bandwidth. Three matmuls of shape (10, 512) @ (512, 512) require loading three separate weight matrices from memory. One matmul of shape (10, 512) @ (512, 1536) loads one contiguous weight matrix — better cache utilization and fewer kernel launch overheads.
The gain is more significant for long sequences where the weight load dominates. For very long sequences where the (seq_len, seq_len) attention matrix dominates (like FlashAttention's use case), fusing QKV is a smaller win relative to the attention computation itself.
PyTorch uses fused QKV in nn.MultiheadAttention when batch_first=True and can dispatch to cuBLAS kernels that handle large contiguous matmuls more efficiently.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Attention = softmax(QK^T / sqrt(d_k)) @ V. The sqrt(d_k) scaling prevents dot products from growing large enough to saturate softmax. Multi-head splits the representation into num_heads subspaces, runs attention independently in each, then concatenates — this lets different heads learn different relationship patterns. Shapes: after splitting, each head sees (num_heads, seq_len, d_k) where d_k = d_model / num_heads. Fused QKV projection merges three matmuls into one for better GPU utilization.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- FlashAttention is described as "IO-aware" attention — what memory bottleneck is it solving, and how does tiling help?
- How would you modify this implementation to support cross-attention (Q from one sequence, K and V from another), as used in encoder-decoder transformers?
- Implement positional encoding in NumPy — both the original sinusoidal version and RoPE (rotary position embeddings).
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
Implement softmax and cross-entropy loss from scratch
Implement k-nearest neighbors with efficient distance computation
Implement gradient descent for linear regression from scratch
Explain attention mechanisms beyond transformers — types and trade-offs