Why divide by √d_k: the experiment

Attention compares a query with each key by a dot product: multiply them entry by entry and add up. The longer the vectors, the bigger those sums can get. This experiment draws random vectors and shows why the paper divides the scores by √d_k before the softmax.

Seed 2017, 2000 trials

The dot products q · k

Dot products q · k of random vectors of dimension 64, unscaled and divided by √d_k A histogram: the unscaled dot products spread with a standard deviation of 7.8; divided by √d_k their spread is 0.98. 0 250 500 750 1000 −20 0 20 score trials
  • unscaled q · k
  • q · k / √d_k

Spread of q · k: 7.82 (√d_k = 8.00). Divided by √d_k: 0.98.

The softmax's largest weight, out of eight keys

The softmax's largest weight over eight keys, dimension 64, unscaled and scaled A histogram of the largest weight per trial: on average 87.1 % unscaled and 36.1 % scaled. 0 250 500 750 1000 0 % 20 % 40 % 60 % 80 % 100 % largest weight trials
  • unscaled q · k
  • q · k / √d_k

One key takes more than 90 % of the weight in 62.7 % of trials unscaled, in 0.1 % scaled.

What you are looking at

Each trial draws a query q and eight keys, every entry a random number around 0 with a spread of 1, the way the values inside a model start out. The left chart is the dot product of q with the first key, 2,000 times. Move the slider: with 4 entries the scores stay small, with 512 they reach 50 and beyond, because the sum of more products spreads further.

The right chart is what the softmax makes of eight such scores. Unscaled, big scores make one key win almost everything: the softmax becomes a hard choice, and in training its gradients become tiny, so the model learns slowly. Divided by √d_k, the scores keep the same spread at every size and the weights stay soft.

In the paper (3.2.1)

“We suspect that for large values of d_k, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients.”

Footnote 4 gives the reason in one line: if the entries of q and k are independent with mean 0 and variance 1, their dot product q · k = Σ q_i k_i has mean 0 and variance d_k. A variance of d_k is a spread (standard deviation) of √d_k, which is exactly what the left chart measures. The paper uses d_k = 64, so it divides by 8; our model uses d_k = 16 and divides by 4.

An unhandled error has occurred. Reload 🗙

Reconnecting…

Your connection to the Transformers and Attention Lab dropped, probably a Wi-Fi blip. Hold on while it reconnects.

The connection could not be restored. The page will reload in a few seconds.