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
and
be matrices with
columns whose rows are queries and keys, respectively.
Assume there is at least one key. Let the rows of
be the corresponding values, in the same order as the keys.
In matrix form,
where the softmax function is applied to each row of . Thus each output row is a convex
combination of the rows of
.
The factor
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 ,
only keys at positions
enter the softmax function.
Equivalently, setting the scores for
to
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
,
where
and
are the first two value rows.