Basis Lab

Answers · How models work

Why do we divide the attention scores by the square root of the key dimension?

In shortThe square root of the key dimension is the typical size of an unscaled attention score, so dividing by it stops softmax from becoming a hard pick-one.

The square root of the key dimension is the standard deviation of an unscaled attention score, so dividing by it holds the spread of the scores at one however wide the head happens to be. It is a derived number, not a tuning knob: it falls out of the variance of a dot product between independent vectors. Any other constant would fail at some head width, and the failure is not cosmetic, because softmax converts a change of scale into a change of sharpness.

Where the spread comes from

Fix one head with key dimension dkd_k, and suppose the components of a query qq and a key kk are independent random variables with mean zero and variance one. That is roughly what a fresh initialisation gives, and roughly what normalisation maintains. A single attention score is their dot product, a sum of dkd_k products:

q⋅k=∑i=1dkqikiq \cdot k = \sum_{i=1}^{d_k} q_i k_i

Each term qikiq_i k_i is a product of two independent mean-zero variables, so its mean is 0⋅0=00 \cdot 0 = 0 and the whole score is centred. For the variance of one term, independence lets the expectation of the product of squares factorise, so E[qi2ki2]=E[qi2] E[ki2]=1⋅1=1\mathbb{E}[q_i^2 k_i^2] = \mathbb{E}[q_i^2]\,\mathbb{E}[k_i^2] = 1 \cdot 1 = 1. Every term therefore contributes exactly one unit of variance. The terms are independent of one another, and independent variances add, so dkd_k of them give a variance of dkd_k.

FIG 1The variance of one attention score
the dimension of the query and key vectors inside one head
variance, the average squared distance from the mean
standard deviation, the square root of the variance, measured in score units
Each of the terms adds one unit of variance, and the variance of a sum of independent terms is the sum of the variances. The standard deviation, which is in the same units as the score itself, grows like the square root of the width.

Read the numbers off the formula. With dk=16d_k = 16 a typical score sits about 44 from zero, at the dk=64d_k = 64 of the original transformer about 88, and at dk=256d_k = 256 about 1616. Dividing each score by dk\sqrt{d_k} brings all three of those back to 11. That is the whole content of the denominator: it restores a fixed unit of spread to a quantity whose spread was drifting with the width of the head.

What a score of 8 does to softmax

Softmax sees only differences between scores, and it turns a difference Δ\Delta into a ratio of weights of eΔe^{\Delta}. Multiply every score by a constant cc and every difference becomes cΔc\Delta, so every ratio is raised to the power cc: the distribution sharpens. This is exactly a temperature. With raw scores of spread 88, take five of them, 1212, 88, 44, 00, −4-4, and exponentiate: e12=162754e^{12} = 162754, e8=2981e^{8} = 2981, e4=54.6e^{4} = 54.6, e0=1e^{0} = 1, e−4=0.018e^{-4} = 0.018, summing to 165791165791. The top weight is 162754/165791=0.98162754/165791 = 0.98. The second token is only four raw points behind, and gets 2981/165791=0.0182981/165791 = 0.018, a factor of e4=54.6e^{4} = 54.6 smaller.

FIG 2The same five scores, before and after dividing by 8
stepraw scoreweight unscaledscaled scoreweight scaledwhat happened
1120.981.50.43Top token. Unscaled it takes 98 per cent of the attention.
280.01810.26Four raw points behind, yet 55 times smaller in weight.
340.00030.50.16Still a plausible match, effectively erased.
406e-0600.1Neutral.
5-41e-07-0.50.06A poor match, downweighted in both columns.
5 steps
The ordering never changes; only the sharpness does. Scaling makes a near-argmax into a graded mixture.

Divide by 88 instead and the scores become 1.51.5, 11, 0.50.5, 00, −0.5-0.5, with exponentials 4.484.48, 2.722.72, 1.651.65, 11, 0.610.61 summing to 10.4610.46. The weights are 0.430.43, 0.260.26, 0.160.16, 0.100.10, 0.060.06. The top two are now 0.43/0.26=1.650.43/0.26 = 1.65 apart, which is e0.5e^{0.5}, exactly as it must be, since the gap shrank from 44 to 0.50.5. The information in the second and third tokens survives.

Why a smaller number is not enough

The natural guess is that the division is a general trick for keeping numbers small, so any constant that brings the magnitudes down would serve, or that 88 was found by experiment. Suppose you fixed the divisor at 88 regardless of width. At dk=256d_k = 256 the raw spread is 1616, so a gap of one standard deviation becomes 22 after dividing, and the weight ratio is e2=7.39e^{2} = 7.39. At dk=16d_k = 16 the raw spread is 44, the same standard-deviation gap becomes 0.50.5, and the ratio is e0.5=1.65e^{0.5} = 1.65. The head is saturated at one width and washed out at another, and the constant that was correct at dk=64d_k = 64 is wrong at both. Dividing by dk\sqrt{d_k} gives a gap of exactly 11 in both cases and a ratio of e=2.72e = 2.72. The scale factor has to track the width because the standard deviation does; no single number does that.

The damage from getting it wrong is not confined to ugly weights. The derivative of softmax output aia_i with respect to input sjs_j is a product of probabilities, so it is largest when the weights are moderate and collapses when they are extreme. On the diagonal the derivative is ai(1−ai)a_i(1-a_i): at the scaled top weight of 0.430.43 that is 0.43×0.57=0.250.43 \times 0.57 = 0.25, while at the unscaled 0.980.98 it is 0.98×0.02=0.020.98 \times 0.02 = 0.02. Off the diagonal it is −aiaj-a_i a_j, so the gradient reaching the third token's score is −0.43×0.16=−0.068-0.43 \times 0.16 = -0.068 when scaled against −0.98×0.0003=−0.0003-0.98 \times 0.0003 = -0.0003 when not, roughly two hundred times smaller. Almost no signal reaches the projections, and the head cannot learn to attend differently because the confidence has switched off the mechanism by which it would learn.

FIG 3Why a saturated softmax stops learning
off the diagonal this is minus the product of two probabilities, tiny unless both are moderate
on the diagonal, largest at a_i = 1/2 and tending to zero at both 0 and 1
Every partial derivative is a product involving the output probabilities, so it collapses at both ends of the range and peaks in the middle.

What the derivation assumes

The argument needed two things: that query and key components are roughly independent, and that they have roughly unit variance. Neither is exactly true in a trained network. Learned projections introduce correlations between components, and the actual variance depends on where the block sits and how it is normalised. If the components have variance σ2\sigma^2 rather than 11, the score variance becomes dkσ4d_k \sigma^4 and the correct divisor is σ2dk\sigma^2\sqrt{d_k}, so a fixed dk\sqrt{d_k} under-corrects as the variance drifts upward with depth. That is why the placement of layer normalisation changes how stable training is, and why variants that normalise queries and keys directly before the dot product exist at all: both are repairs to the assumption rather than to the algebra. The constant is worth knowing precisely because its assumptions are visible; when they fail, the constant is the part you adjust.

Dividing by dk\sqrt{d_k} leaves the score distribution with unit spread whatever the head width, which keeps softmax graded, which keeps gradients alive. A wide head without it does not attend badly so much as commit to an answer before it has learned anything.

Worth keeping

  • The variance of an unscaled attention score is the key dimension, so its standard deviation is the square root of that dimension.
  • Softmax is exponential in score gaps, so multiplying all scores by a constant raises every weight ratio to that constant and changes sharpness without changing order.
  • When one softmax weight approaches 1, every partial derivative is a product of probabilities and collapses, so an unscaled head stops receiving gradient.

Where this goes next

This question is one step of The Mathematics of Attention, a course that works through its subject from the beginning. The page that teaches this part of it is The Scaling Factor, and it reads the whole way through whether or not you have an account.

What an account changes is the practice: problems standing under every idea, marked with a reason rather than a tick, in a copy of the course that is yours.

Read that pageThe whole course

Other questions people ask about this

  1. What do multiple attention heads actually give you that one big head doesn't?Several heads let a model track several relationships at once, each in its own lower-dimensional subspace, instead of squeezing every relationship into one weighted average that destroys information.
  2. Why does attention use softmax instead of just dividing each score by the sum of all the scores?Dividing by the sum can give negative weights and fails when scores cancel; exponentiating first makes weights positive and turns score gaps into ratios.
  3. How does masking actually make attention causal?The mask is applied to the scores before they become weights, so forbidden positions end up with exactly zero weight and the rest are renormalised automatically.
  4. Why does attention need positional encoding if it already looks at the whole sequence at once?Attention treats tokens as an unordered set, so position has to be added to the vectors; otherwise a sentence and its anagram get the same representations.
  5. Why does the model get stuck repeating the same sentence over and over?The model is not stuck in a memory loop: once it has written a phrase, that phrase is in its context and makes writing it again more likely, so a decoder that always picks the top word cannot leave.
  6. Why does diffusion add Gaussian noise instead of any random corruption?Diffusion adds Gaussian noise because Gaussian errors combine exactly: each step keeps the spread fixed and gives a closed-form noisy picture at any later step, which makes the reverse step learnable.

Read alongside