← Questions

Scaled dot-product attention from scratch

0
MetaCodingLast asked Sep 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Sep 2025. It tests attention, transformers and numpy.

Write the forward pass of single-head scaled dot-product attention by hand, from the formula. The code doesn't need to run, but the shapes must be right.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • attention(Q, K, V, mask=None) -> O
    • Q has shape (Tq, d), K has shape (Tk, d), V has shape (Tk, dv).
    • mask is optional, shape (Tq, Tk). mask[i][j] == 0 means query i may not attend to key j.
    • O has shape (Tq, dv).
  • The steps: scores S = Q Kᵀ / sqrt(d). Masked scores become -inf. Take a softmax over each row of S to get weights A. Then O = A V.

Example

Q = [[1, 0]]
K = [[1, 0], [0, 1]]
V = [[1, 2], [3, 4]]

attention(Q, K, V)                  ->  [[1.660477, 2.660477]]
    # scores [1, 0] / sqrt(2) = [0.7071, 0]; softmax = [0.6698, 0.3302]
attention(Q, K, V, mask=[[1, 0]])   ->  [[1.0, 2.0]]       # only key 0 is visible
attention([[0, 0]], [[5, -3], [2, 8]], [[10, 0], [0, 10]])  ->  [[5.0, 5.0]]   # equal scores, equal weights

Constraints

  • Pure Python lists or NumPy are both fine. Say which one you use.
  • d and dv are at least 1.

Clarifying questions

  • Is the mask boolean or additive (0 and -inf)? Does 1 mean "keep" or "block"?
  • What should a fully masked row produce: zeros, a uniform distribution, or an error?
  • Is a batch dimension needed, or several heads?
  • Is this for training (gradients) or inference only?

What a strong answer covers

  • Correct shapes at every step, written down: (Tq, d) x (d, Tk) -> (Tq, Tk), then (Tq, Tk) x (Tk, dv) -> (Tq, dv).
  • Why the scores are divided by sqrt(d): without it, large d pushes the softmax into saturation.
  • A numerically stable softmax: subtract each row's maximum before exp. Masked entries are set to -inf so they get weight 0.
  • Edge cases: a fully masked row (avoid 0 / 0 and NaN), very large scores, shape mismatches between K and V.
  • Cost: O(Tq · Tk · d + Tq · Tk · dv) time, O(Tq · Tk) memory for the scores.

Follow-ups

  • Extend it to multi-head attention with projection matrices Wq, Wk, Wv, Wo.
  • Add a causal mask for decoder self-attention.
  • The sequence is 100,000 tokens long and Tq · Tk does not fit in memory. How do you compute attention in blocks (the idea behind FlashAttention)?
  • Write the backward pass for the softmax.

Where it's asked

  • Meta · AI-enabled coding · Last asked Sep 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

attention · transformers · numpy · machine learning

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding