AI Logic

Attention Mechanisms

Scaled Dot-Product Attention

Updated:

Structure of scaled dot-product attention. Left: how it is used inside multi-head attention (per-head linear layers, h heads, concatenation, linear layer). Right: its inside (matrix product of Q and K, division by the square root of d_k, optional mask, softmax, matrix product with V)

What is scaled dot-product attention

Scaled dot-product attention is a way of computing attention that builds weights for "where to look and how much" from dot products of queries and keys, and sums the values using those weights. It was proposed by Vaswani et al. in 2017 in the Transformer paper "Attention Is All You Need", and almost all of today's large language models use this computation.

The formula fits on one line (Eq. (1) of the paper).

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

The symbols mean the following.

  • QQ: queries (an n×dkn \times d_k matrix). nn vectors, each representing "what is being looked for".
  • KK: keys (an m×dkm \times d_k matrix). Labels describing "what information each position holds".
  • VV: values (an m×dvm \times d_v matrix). The content actually retrieved from each position.
  • dkd_k: the length of the query and key vectors. Dividing by dk\sqrt{d_k} is the "scaled" part.

Think of searching for a book in a library: the query is "a note describing what you want", the key is "the book's spine", and the value is "the book's contents". The more a note resembles a spine, the larger the weight, and the more of that book's contents is taken in. The weights are computed with the softmax function, so they sum to 1 for each query.

Computation steps

The right side of the figure at the top of the article shows the inside of scaled dot-product attention. The computation proceeds bottom-up as follows (in the same order as the left side of Figure 2 in the paper).

  1. Matrix multiplication: compute the dot products QK⊤QK^\top of QQ and KK. The result is an n×mn \times m matrix whose entry in row ii, column jj expresses "how similar the ii-th query is to the jj-th key".
  2. Scale: divide every value by dk\sqrt{d_k}.
  3. Mask (optional): set the values of positions that should not be seen to −∞-\infty.
    • In the Transformer decoder, this prevents each word from seeing the words after it (masking).
  4. Softmax: apply the softmax function row by row to get weights that sum to 1. Positions set to −∞-\infty get a weight of 0.
  5. Matrix multiplication: multiply the weight matrix by VV to get the weighted sum of values. The output is an n×dvn \times d_v matrix.

Let's check with small numbers. Take dk=4d_k = 4, one query q=(1,0,1,0)\boldsymbol{q} = (1, 0, 1, 0), and three key-value pairs.

Key kj\boldsymbol{k}_jDot product q⋅kj\boldsymbol{q} \cdot \boldsymbol{k}_jDivided by 4=2\sqrt{4} = 2Softmax weightValue vj\boldsymbol{v}_j
1(1,0,1,0)(1, 0, 1, 0)21.00.506(1,0)(1, 0)
2(0,1,0,1)(0, 1, 0, 1)00.00.186(0,1)(0, 1)
3(1,1,0,0)(1, 1, 0, 0)10.50.307(1,1)(1, 1)

The output is 0.506×(1,0)+0.186×(0,1)+0.307×(1,1)≈(0.814, 0.494)0.506 \times (1, 0) + 0.186 \times (0, 1) + 0.307 \times (1, 1) \approx (0.814,\ 0.494). The value of key 1, which closely resembles the query, contributes the most.

Why divide by √d_k

Dividing by dk\sqrt{d_k} prevents dot products from becoming too large for long vectors, which would make the slope of the softmax function almost 0.

The paper's explanation is as follows. If each component of q\boldsymbol{q} and k\boldsymbol{k} is an independent value with mean 0 and variance 1, the dot product q⋅k=∑i=1dkqiki\boldsymbol{q} \cdot \boldsymbol{k} = \sum_{i=1}^{d_k} q_i k_i has mean 0 and variance dkd_k. With the Transformer's dk=64d_k = 64, the standard deviation of the dot product is 64=8\sqrt{64} = 8.

When dot products spread out to around ±8, the softmax function puts almost all of the weight on the single largest one. For example, values of (8,0,−8)(8, 0, -8) give weights of about (0.9997,0.0003,0.0000)(0.9997, 0.0003, 0.0000). In this state, small changes to the values barely change the output, the gradients become small, and learning stalls. Dividing by dk\sqrt{d_k} brings the variance of the dot product back to 1, and the weights are spread more smoothly.

Scaling keeps the magnitude of the values entering the softmax function consistent regardless of the vector length dkd_k. Because training behavior changes little with dkd_k, the same formula can be used as is when changing the number of heads or the model size.

Comparison with other attention

There are two broad ways to assign attention weights (score functions). The paper compares scaled dot-product attention with both.

MethodScore computationSpeed and memoryCharacteristics
Additive attention (Bahdanau et al., 2015)A network with one hidden layer mixes q\boldsymbol{q} and k\boldsymbol{k}SlowStable even for large dkd_k
Dot-product attention (Luong et al., 2015)Dot product q⋅k\boldsymbol{q} \cdot \boldsymbol{k}Fast (matrix multiplications only)Values become too large for large dkd_k
Scaled dot-product attention (Vaswani et al., 2017)Dot product divided by dk\sqrt{d_k}Fast (matrix multiplications only)Keeps the speed of dot products while staying stable for large dkd_k

The theoretical complexity of additive and dot-product attention is similar, but dot products can be computed with highly optimized matrix multiplication code, so in practice they are much faster and more memory-efficient. On the other hand, the paper notes that while the two perform similarly for small dkd_k, unscaled dot-product attention loses to additive attention for large dkd_k. Scaled dot-product attention fixes this weakness with a single division.

How it is used inside multi-head attention

In real models, scaled dot-product attention is not used on its own but as a component of multi-head attention. The left side of the figure at the top of the article shows how it is used.

  1. Transform the input Q,K,VQ, K, V into short vectors with separate linear layers for each head.
  2. Compute scaled dot-product attention for each head.
  3. Concatenate the outputs of the hh heads and pass them through a linear layer.

The Transformer paper uses dmodel=512d_{\text{model}} = 512, h=8h = 8 heads, and dk=dv=512/8=64d_k = d_v = 512 / 8 = 64 per head. It is called by different names depending on where Q,K,VQ, K, V come from.

  • Self-attention: Q,K,VQ, K, V are all produced from the same sequence. It captures relationships between words within a sentence.
  • Cross-attention: QQ comes from the decoder side, and KK and VV from the encoder output. In translation, it decides where in the input sentence to look when producing each target word.

Computational cost and implementation notes

Scaled dot-product attention has a limitation: it becomes heavy as sequences get longer.

The weight matrix QK⊤QK^\top is n×mn \times m, so in self-attention (n=mn = m), compute and memory grow with the square of the sequence length nn. Doubling the sequence length quadruples the weight matrix. For long documents and high-resolution images, this becomes the bottleneck.

The following remedies have been proposed.

  • Reorganize the computation: FlashAttention splits the weight matrix into small tiles and computes them inside the GPU's fast memory without changing the result, reducing memory reads and writes.
  • Narrow the range attended: sparse attention and Longformer restrict the keys each position looks at to a subset.
  • Approximate the formula: methods such as linear attention approximate the softmax function in another form so that the cost is linear in nn.

Masks also need care in implementations. If every position in a row is set to −∞-\infty, the denominator of the softmax function becomes 0 and the output becomes NaN (not a number). If rows consisting only of padding can occur, check how the mask is built.

PyTorch example

Show code
python
import math
import torch
import torch.nn.functional as F


def scaled_dot_product_attention(q, k, v, mask=None):
    """q: [..., n, d_k], k: [..., m, d_k], v: [..., m, d_v]
    mask: boolean [..., n, m]. Positions that are True are hidden"""
    d_k = q.size(-1)
    scores = q @ k.transpose(-2, -1) / math.sqrt(d_k)  # 1-2. matrix multiplication and scaling [..., n, m]
    if mask is not None:
        scores = scores.masked_fill(mask, float("-inf"))  # 3. mask
    weights = torch.softmax(scores, dim=-1)              # 4. each row sums to 1
    return weights @ v, weights                          # 5. sum V with the weights [..., n, d_v]


# The example from the table in the text (d_k = 4, one query, three key-value pairs)
q = torch.tensor([[1.0, 0.0, 1.0, 0.0]])
k = torch.tensor([[1.0, 0.0, 1.0, 0.0],
                  [0.0, 1.0, 0.0, 1.0],
                  [1.0, 1.0, 0.0, 0.0]])
v = torch.tensor([[1.0, 0.0],
                  [0.0, 1.0],
                  [1.0, 1.0]])
out, w = scaled_dot_product_attention(q, k, v)
print(w)    # weights are about [0.506, 0.186, 0.307]
print(out)  # output is about [0.814, 0.494]

# Decoder self-attention: hide positions after each token (batch 2, 8 heads, length 10, d_k = 64)
x = torch.randn(2, 8, 10, 64)
causal = torch.triu(torch.ones(10, 10, dtype=torch.bool), diagonal=1)
out, _ = scaled_dot_product_attention(x, x, x, mask=causal)
print(out.shape)  # torch.Size([2, 8, 10, 64])

# Built-in function in PyTorch 2.0+ (automatically selects fast implementations such as FlashAttention)
out2 = F.scaled_dot_product_attention(x, x, x, is_causal=True)
print(torch.allclose(out, out2, atol=1e-5))  # same computation, so this should be True

FAQ

Q. Why divide by the square root? Can't we divide by d_k?
A.

The variance of the dot product is d_k, so dividing by its standard deviation √d_k brings the variance back to exactly 1. Dividing by d_k makes the values too small, so the weights are spread almost evenly across all positions and it becomes hard to distinguish where to look.

Q. Where do Q, K, and V come from?
A.

They are produced by multiplying the input vectors by separate linear layers (learned weight matrices). In self-attention all three come from the same sequence; in cross-attention only the queries come from a different sequence (the decoder side).

Q. When is a mask used?
A.

There are two main uses. One is in text-generation models, to hide words further ahead that have not been generated yet. The other is to hide padding positions added to equalize lengths. In both cases, values are set to −∞ before the softmax function so that their weights become 0.

References

  1. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  2. D. Bahdanau, K. Cho, and Y. Bengio, "Neural Machine Translation by Jointly Learning to Align and Translate," ICLR, 2015.
  3. M.-T. Luong, H. Pham, and C. D. Manning, "Effective Approaches to Attention-based Neural Machine Translation," EMNLP, 2015.
  4. T. Dao, D. Y. Fu, S. Ermon, A. Rudra, and C. Ré, "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness," NeurIPS, 2022.
  5. PyTorch Documentation, "torch.nn.functional.scaled_dot_product_attention."