The formula divides the scores by d. Here's why, with numbers.
Predict
Query and key entries have variance 1, and d = 64. About what's the standard deviation of a raw dot product?
rng = np.random.default_rng(0)for d in [4, 64, 256]: q = rng.normal(size=(1000, d)) k = rng.normal(size=(1000, d)) # 1,000 dot products s = (q * k).sum(axis=-1) print(d, s.std().round(1), (s / np.sqrt(d)).std().round(2))
4 2.0 1.064 8.0 1.01256 16.1 1.01
Each line is a head size d, then the standard deviation of 1,000 raw scores, then the same after dividing by d. The raw spread grows with d. The divided spread stays near 1.
The standard deviation of the scores
d = 4, raw
2
d = 64, raw
8
d = 256, raw
16
any d, ÷ √d
1
Here is why. Say the entries of q and k are independent, with mean 0 and variance 1. Then q⋅k=∑i=1dqiki adds up d terms that each have variance 1.
So the score has variance d, and standard deviation d. At d=256 that's 16. Dividing by d brings the spread back to about 1 at any head size.
In the editor, s holds 1,000 dot products at d=100. Fill in raw, their standard deviation, and scaled, the same after dividing by d.
Pick an answer above to see the rest
Instructions
1
Fill in raw: the standard deviation of the 1,000 dot products in s.
2
Fill in scaled: the same, after dividing every score by the square root of d.