Skip to main content

Implement single-head scaled dot-product self-attention in NumPy for one sequence. For example, an input of 4 tokens with 8 features each should return 4 output vectors, and each row of the attention weights should sum to 1.

Coding rounds · Intermediate 3

Short answer

Project the input into queries, keys and values. Scores are Q @ K.T divided by the square root of the key size. Apply softmax to each row to get weights, then multiply the weights by V. With a causal mask, set future positions to a large negative number before the softmax. Cost is O(n squared d).

Deeper answer

Clarify the shapes first: X is n by d for one sequence, or batch by n by d. The three projection matrices map d to d_k.

The steps: Q = X @ Wq, K = X @ Wk, V = X @ Wv. Then scores = Q @ K.T / np.sqrt(d_k), an n by n matrix where row i holds how much token i attends to each token. Apply a stable softmax along the last axis to get the weights, and the output is weights @ V. For a causal mask, set the scores above the diagonal to -1e9 before the softmax, so those weights become 0.

The scaling matters: without it, dot products grow with d_k, the softmax saturates, and gradients get very small. Time is O(n squared d) and memory is O(n squared). Test that each row of weights sums to 1 and that, with the causal mask, the first token attends only to itself. Interviewers watch for softmax on the wrong axis, a missing scale, and a mask applied after the softmax.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Transformers

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.