mlprep
Hard25 min·2 rounds

Implement scaled dot-product attention from scratch

Written by the mlprep team · Updated

Interviewer Mode
Interviewer

Implement scaled dot-product attention in NumPy. Then extend it to multi-head attention. Walk me through the shapes at each step.

Ready to compare your reasoning?
Interviewer

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?

Ready to compare your reasoning?

The key takeaway unlocks after you reveal an expert answer.

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