What is the full mathematical formula for scaled dot-product attention?
Last updated
Scaled dot-product attention is Attention(Q, K, V) = softmax(QKᵀ / √d_k + M) V. It scores every query against every key, scales the scores, optionally adds a mask M, turns each row into a probability distribution, and returns a weighted average of the values.
Inputs and shapes:
Q = XW_Q(n × d_k),K = XW_K(m × d_k),V = XW_V(m × d_v).QKᵀis n × m: entry (i, j) is how strongly query i matches key j.The output is n × d_v: one mixed value vector per query.
Why divide by
√d_k:If the components of q and k are roughly independent with unit variance,
q·khas variance d_k. Large logits saturate the softmax into near one-hot outputs with vanishing gradients.Scaling brings the variance back to about 1.
Softmax is applied row-wise (over keys):
softmax(s)_j = exp(s_j) / Σ_k exp(s_k), so each query's weights are non-negative and sum to 1.Mask
M(optional): Additive: 0 where attention is allowed, −∞ where it is blocked (causal or padding). This happens before the softmax.Multi-head extension:
head_i = Attention(QW_i^Q, KW_i^K, VW_i^V).MultiHead = Concat(head_1..head_h) W_O, typically with d_k = d_model / h.
Cost: O(n·m·d) time and O(n·m) memory for the score matrix, which is quadratic in sequence length for self-attention.
- https://www.sundeepteki.org/advice/the-transformer-revolution-the-ultimate-guide-for-ai-interviews
- https://www.geeksforgeeks.org/nlp/multi-head-attention-mechanism/
- https://apxml.com/courses/foundations-transformers-architecture/chapter-2-attention-mechanism-core-concepts/practice-implementing-attention