Core

Scaled dot-product attention & the √d_k

Dividing query–key scores by the square root of their dimension keeps softmax usable as attention width grows.

Updated

1

Concept

Self-attention begins with a simple compatibility measure: the dot product between a query and a key. If two vectors point in similar directions, their dot product tends to be positive and large. If they are poorly aligned, it is smaller or negative. For a query matrix QQ and key matrix KK, all pairwise scores appear in QKQK^\top. But the raw score scale changes when the vector dimension changes.

Write one score as

s=qk=i=1dkqiki.s = q \cdot k = \sum_{i=1}^{d_k} q_i k_i.

For an intuition used in the original Transformer paper, suppose components are independent, have mean zero, and variance one. Each product qikiq_i k_i then has variance near one. Adding dkd_k such terms gives Var(s)dk\operatorname{Var}(s) \approx d_k, so the score’s standard deviation grows like dk\sqrt{d_k}. A 256-dimensional head therefore produces wider raw score variation than a 16-dimensional head even when the component statistics are otherwise comparable.

Attention sends each row of scores through softmax. Softmax exponentiates its inputs, so scale matters dramatically. Scores [0.2,0.1,0][0.2,0.1,0] produce a fairly distributed result. Scores [20,10,0][20,10,0] produce an almost winner-take-all result. The ranking is identical, yet the second distribution behaves as if the model were extremely certain. When probabilities approach zero or one, many useful gradients become small, which can make learning brittle.

Scaled dot-product attention corrects this dimension effect:

Attention(Q,K,V)=softmax(QKdk)V.\operatorname{Attention}(Q,K,V) = \operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V.

Dividing by dk\sqrt{d_k} approximately normalizes the score standard deviation under the assumptions above. It does not force exact variance one in a trained network, and it does not normalize each query or key vector. Learned projections, normalization layers, correlations, and real activations violate the tidy independence story. The scaling is still a robust design choice because it removes the most obvious growth with dimension.

The divisor can also be viewed as a fixed temperature. Softmax temperature is usually written softmax(s/T)\operatorname{softmax}(s/T). Here T=dkT=\sqrt{d_k}. A larger temperature flattens a distribution; a smaller one sharpens it. In attention the scale is tied to head dimension rather than exposed as a decoding control. A model can still learn sharper or flatter patterns by changing query and key norms.

Numerical stability adds another layer. Practical softmax implementations subtract the row maximum before exponentiating:

softmax(s)i=exp(simaxjsj)kexp(skmaxjsj).\operatorname{softmax}(s)_i = \frac{\exp(s_i-\max_j s_j)}{\sum_k \exp(s_k-\max_j s_j)}.

Subtracting a constant does not change the ratio of probabilities, but it prevents a large positive score from overflowing the exponential. This technique solves numerical overflow; it does not solve saturation caused by score gaps. The dk\sqrt{d_k} scaling addresses the latter source at initialization and during early training.

Consider scores from one query against three keys. If the raw dot products are [8,4,0][8,4,0] and dk=64d_k=64, scaling produces [1,0.5,0][1,0.5,0]. Softmax can assign meaningful mass to all three, allowing gradients to adjust each relationship. Without scaling, the first key would dominate much more strongly before the model had evidence that it deserved such certainty.

The lesson is broader than memorizing a denominator. Whenever a sum collects many roughly independent contributions, its typical magnitude often grows with the number of terms. Passing that sum into a sensitive nonlinearity can change behavior merely because width changed. The Transformer compensates with a scale derived from variance, keeping the routing mechanism in a trainable regime.

2

Explain it like I am five

Suppose judges score a performance by adding marks from many independent categories. A show evaluated on 64 categories naturally accumulates larger positive and negative totals than one evaluated on four, even if quality per category is unchanged. Sending those raw totals into a winner-take-all rule would make the larger scorecard look absurdly certain. Dividing by the square root of the category count restores a comparable scale before the final vote.

3

Teach it back

Derive why dot-product variance grows with key dimension and explain what dividing by square root of d_k does to softmax.

Minimum: 80 characters and 15 words. Your text stays only in this browser.

Saved only on this device.

Show a model answer

If query and key components are roughly independent with zero mean and unit variance, each product contributes variance near one. Summing d_k products gives variance near d_k, so the standard deviation grows as square root of d_k. Dividing scores by that standard deviation keeps their typical magnitude roughly stable, preventing softmax from saturating solely because the head dimension increased.

4

Check your understanding

1. Why scale dot products by 1/sqrt(d_k)?
Answer and explanation

To keep score magnitude roughly stable across head widths — The dot product's variance grows with dimension under common initialization assumptions; scaling prevents dimension alone from making softmax overly sharp.

2. What is the immediate risk of very large score differences before softmax?
Answer and explanation

A saturated, nearly one-hot distribution with small gradients — Large logit gaps push softmax probabilities toward zero and one, where many derivatives become very small.

Complete the teach-back and answer the quiz correctly to finish this lesson.

Sources

  1. Ashish Vaswani et al. (2017). Attention Is All You Need.