In scaled dot-product attention, why divide QK⊤ by dk, where Q and K are the query and key matrices and dk is the key dimension?

Sequence models and transformers, Attention
Level L3 Intermediate. Length Short. Nature Th+Mat Both.

What's being asked

Whether you can do a quick variance calculation and connect it to softmax saturation, where softmax gets stuck near a one-hot output.

Key idea

Take one query q and one key k. If their components are independent with mean 0 and variance 1, then q⋅k=∑i=1dkqiki has variance dk. Dividing by dk keeps the logits at unit variance, so softmax does not saturate and gradients do not vanish.

Steps

  1. Write Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤/dk)V, where V is the value matrix.
  2. Compute Var⁡(q⋅k)=dk under the independence assumption. Each term qiki has variance 1, and the variances of independent terms add.
  3. Explain that large logits push softmax towards a one-hot output, where its gradient is nearly zero.
  4. Conclude that the scaling keeps training stable as dk grows.

Common mistakes

How long your answer should be

About 1 minute; one line of variance and softmax saturation.

Read this

Previous in Sequence models and transformers: A single-layer LSTM has input size 128 and hidden size 256. How many trainable parameters does it have (one bias vector per gate), and how does the count compare with a GRU and a plain RNN of the same sizes? What changes if the LSTM is bidirectional?
Next in Sequence models and transformers: For a vanilla RNN ht=tanh⁡(Wht−1+Uxt+b) with loss L=∑tLt, how does backpropagation through time give ∂LT/∂hk for k<T, and why do gradients over long time spans vanish or explode?