Put the queries in the rows of Q, and the keys and values in the rows of K and V. Then the whole layer is two matrix products and a softmax:
Attention(Q,K,V)=softmax(dQK⊤)V
K⊤ is K with rows and columns swapped, so each key becomes a column. One product scores every query against every key. The second blends the values.
Interviewers care more about the shapes than the formula, because the shapes are where code breaks. With Tq queries, Tk keys, head size d and value size dv:
Tensor
Shape
What it is
q
(..., T_q, d)
one query per position
k
(..., T_k, d)
one key per position
v
(..., T_k, d_v)
one value per key
q @ k.swapaxes(-1, -2)
(..., T_q, T_k)
every query scored against every key
softmax(scores, axis=-1)
(..., T_q, T_k)
each row sums to 1
weights @ v
(..., T_q, d_v)
one blended value per query
The ... is whatever leading axes you have, usually batch and heads.