Scaled Dot-Product and Multi-Head Attention

Summary

An attention function maps “a query and a set of key-value pairs to an output”: a weighted sum of the values, with weights given by a compatibility function between the query and each key (Vaswani et al., Sec. 3.2). The Transformer uses scaled dot-product attention, , where the factor keeps the softmax out of its saturated, vanishing-gradient regime. Multi-head attention runs such functions in parallel on learned low-dimensional projections and concatenates the results, so that different heads can attend to different positions and representation subspaces at the same total cost. Read statistically, an attention head is a Nadaraya-Watson kernel smoother with a learned, asymmetric exponential kernel.

Overview

Before 2017, attention was an add-on to recurrent encoder-decoder models: the decoder’s hidden state queried the encoder’s hidden states. Vaswani et al. make attention the only mechanism that moves information between positions. Three properties motivate the choice (Sec. 4, Table 1):

  • Path length. A self-attention layer connects any two positions in sequential operations; a recurrent layer needs and a convolution with kernel width needs stacked layers. Short paths make long-range dependencies easier to learn.
  • Parallelism. All positions are processed at once, with sequential operations per layer compared with for recurrence.
  • Cost. Per-layer complexity is compared with for recurrence, so self-attention is cheaper whenever sequence length is smaller than representation dimension . The quadratic term in is the price, and the reason later work restricts attention to neighborhoods of size (complexity , path length ).

Main Content

Scaled dot-product attention ^def-sdpa

Let hold queries, keys and values, one per row. Then (Eq. 1)

with the softmax applied row-wise. Row of the output is with weights

The paper contrasts this with additive attention, which scores compatibility with a one-hidden-layer feed-forward network. The two have similar theoretical complexity, but dot-product attention “is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code” (Sec. 3.2.1).

Why divide by

Assume the components of and are independent with mean and variance . Then

(footnote 4). Unscaled logits therefore have standard deviation ; for large they push the softmax “into regions where it has extremely small gradients”. Dividing by restores unit variance regardless of head dimension. The paper cites the observation that additive attention outperforms unscaled dot-product attention for large , and introduces the scaling “to counteract this effect”.

Multi-head attention ^def-mha

With heads and learned projections , , and ,

The base model uses and . “Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality” (Sec. 3.2.2).

The motivation is that a single softmax-weighted average blurs: “Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.” The same averaging is why the Background section describes attention as having “reduced effective resolution”.

The three uses of attention in the Transformer ^def-three-uses

(Sec. 3.2.3)

  1. Encoder self-attention. , , all come from the previous encoder layer; every position attends to every position.
  2. Encoder-decoder (cross) attention. Queries come from the previous decoder layer; keys and values come from the encoder output, so each decoder position attends over the whole input.
  3. Masked decoder self-attention. Each position may attend only to positions up to and including itself. This is implemented “by masking out (setting to ) all values in the input of the softmax which correspond to illegal connections”, which preserves the autoregressive property used in Autoregressive Language Modeling and Pretraining.

Ablation evidence

Table 3 of the paper varies heads at constant compute on English-to-German (newstest2013 dev). Rows (A): () gives 24.9 BLEU, gives 25.5, and give 25.8, () falls back to 25.4: “single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.” Rows (B): reducing to 16 or 32 with other settings fixed lowers BLEU to 25.1 and 25.4, which the authors read as evidence “that determining compatibility is not easy and that a more sophisticated compatibility function than dot product may be beneficial.” Kaplan et al. later find that, at fixed non-embedding parameter count, language-model loss varies only a few percent across head counts (Neural Scaling Laws).

Attention as kernel smoothing (interpretive, not from the paper)

Write . A head’s output is

which is the Nadaraya-Watson kernel regression estimator with “inputs” , “responses” and evaluation point . If queries and keys have fixed norms, and is a Gaussian RBF kernel with squared bandwidth . Differences from classical smoothing are instructive:

  • The kernel acts in a learned feature space ( and ), and because it is not symmetric.
  • The “responses” are learned too.
  • Compare the Gaussian Process Regression posterior mean : also a linear smoother, but its weights involve the inverse Gram matrix, can be negative and need not sum to one. Attention weights are a convex combination, so an attention output always lies in the convex hull of the values. The RKHS view in Kernel Quadrature and Kernel Means (weighted sums of kernel evaluations as embeddings of measures) is the closest formal relative: row of the attention matrix is a probability measure over positions and the output is the mean of under that measure.
  • Multi-head attention is then an additive model over smoothers, each with its own metric.

Examples

Hand computation. Take , one query , three keys , , and scalar values .

  • Dot products: . Scaled by : .
  • Softmax: , , so weights are .
  • Output: .

Now suppose the same geometry occurred with and logits eight times larger ( standard deviations instead of one). Without scaling the logits give weights : the second key is effectively invisible and its gradient is near zero. This is the saturation that the factor prevents.

Code sketch (NumPy).

import numpy as np
 
def softmax(z, axis=-1):
    z = z - z.max(axis=axis, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=axis, keepdims=True)
 
def attention(Q, K, V, causal=False):
    d_k = Q.shape[-1]
    scores = Q @ K.swapaxes(-1, -2) / np.sqrt(d_k)       # (n_q, n_k)
    if causal:                                            # illegal connections -> -inf
        n_q, n_k = scores.shape[-2:]
        scores = np.where(np.tril(np.ones((n_q, n_k), bool)), scores, -np.inf)
    return softmax(scores) @ V
 
def multi_head(X, WQ, WK, WV, WO, causal=False):
    # WQ, WK, WV: lists of h projection matrices; WO: (h*d_v, d_model)
    heads = [attention(X @ q, X @ k, X @ v, causal) for q, k, v in zip(WQ, WK, WV)]
    return np.concatenate(heads, axis=-1) @ WO

With causal=True row of the weight matrix is supported on positions , which makes the layer a learned, content-dependent distributed-lag operator; contrast the fixed geometric or Weibull lag weights in Carryover (Adstock) Functional Forms.

Connections

See Also