Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

ML coding · Deep learning layers

Scaled dot-product attention with a causal mask

Medium · Target 20 minutes · Python and NumPy

Given queries Q (n × d), keys K (m × d) and values V (m × dv), return softmax(QKᵀ/√d)V as an n × dv matrix, with the softmax over each row. If causal is true (then n = m), query i may only attend to keys j ≤ i.

Examples

Input Q = [[1, 0]], K = [[1, 0], [0, 1]], V = [[10, 0], [0, 10]], causal = False

Output [[6.6976, 3.3024]]

The query is closer to the first key, so the output leans towards the first value.

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

Output [[1, 2], [2.3395, 3.3395]]

Causal: the first query sees only the first key, so its output is exactly V[0].

Input Q = [[0, 0]], K = [[1, 1], [2, 2], [3, 3]], V = [[1], [2], [3]], causal = False

Output [[2]]

A zero query scores every key equally: the output is the mean of V.

Constraints

  • 1 ≤ n, m ≤ 256, 1 ≤ d, d_v ≤ 128
  • If causal, n = m
  • Checked to a relative tolerance of 10⁻⁹

Hints

Hint 1

Scores are Q @ K.T, shape (n, m), divided by √d where d is the key width.

Hint 2

For the mask, set scores above the diagonal to −∞ before the softmax. np.tril builds the mask.

Hint 3

Shift each row by its maximum before exponentiating. With a causal mask every row keeps its diagonal, so no row is all −∞.

Where candidates go wrong

  • Masking with 0 instead of −∞. A zero score still gets weight e⁰ = 1.
  • Scaling by d instead of √d, or by the value width d_v.
  • Taking the softmax over axis 0, so that each key's weights sum to 1 instead of each query's.
  • Masking after the softmax and not renormalising.
Console⌘/Ctrl + Enter runs

Python runs in your browser with NumPy. The first run downloads the runtime, which takes a few seconds.


Why interviewers ask it

Since transformers took over, this has become the most asked deep learning implementation question. A complete answer has the scaling, a stable softmax and a correct mask, and the candidate can say why each is there.

The theory behind it is in the lesson Attention, normalisation and convolution from scratch.


Keep going