TOPICS
Search

Scaled Dot-Product Attention


Scaled dot-product attention maps a set of query vectors to weighted averages of value vectors. Each value has an associated key vector, and the weights for a query are obtained by applying the softmax function to its scaled dot products with the keys (Vaswani et al. 2017, 3Blue1Brown 2024).

Let Q and K be matrices with d>=1 columns whose rows are queries and keys, respectively. Assume there is at least one key. Let the rows of V be the corresponding values, in the same order as the keys. In matrix form,

 Attention(Q,K,V)=softmax((QK^T)/(sqrt(d)))V,

where the softmax function is applied to each row of QK^T/sqrt(d). Thus each output row is a convex combination of the rows of V. The factor 1/sqrt(d) keeps the variance of the scaled dot product equal to 1 when the components of the query and key are mutually independent with mean zero and unit variance (Vaswani et al. 2017).

In causal self-attention, query and key rows correspond to positions in the same sequence. For a query at position i, only keys at positions j<=i enter the softmax function. Equivalently, setting the scores for j>i to -infty before applying the softmax function assigns zero weight to those positions (Vaswani et al. 2017, 3Blue1Brown 2024). For example, if the first two scores for the second query are equal, its output is (v_1+v_2)/2, where v_1 and v_2 are the first two value rows.


See also

Dot Product, Softmax Function

Explore with Wolfram|Alpha

References

3Blue1Brown. "Attention in Transformers, Step-by-Step" Apr. 7, 2024. https://www.3blue1brown.com/lessons/attention/.Vaswani, A.; Shazeer, N.; Parmar, N.; Uszkoreit, J.; Jones, L.; Gomez, A. N.; Kaiser, L.; and Polosukhin, I. "Attention Is All You Need." In Proc. 31st International Conference on Neural Information Processing Systems (Ed. I. Guyon, U. von Luxburg, S. Bengio, H. M. Wallach, R. Fergus, S. V. N. Vishwanathan, and R. Garnett). Red Hook, NY: Curran Associates, pp. 5998-6008, 2017. https://proceedings.neurips.cc/paper/2017/hash/3f5ee243547dee91fbd053c1c4a845aa-Abstract.html.

Cite this as:

Weisstein, Eric W. "Scaled Dot-Product Attention." From MathWorld--A Wolfram Resource. https://mathworld.wolfram.com/ScaledDot-ProductAttention.html

Subject classifications