All courses

Scaled dot-product attention

Compute softmax(QKᵀ/√d_head)V with shapes T×d_head → T×T → T×d_head. Explain why dividing by √d_head keeps the softmax from saturating.

Builds on: Queries, keys and values, Softmax, logits and the log-sum-exp trick, Variance of sums and dot products of random vectors

▶ Watch this lesson Start the whole course

What the animation says

From a grid of scores to one vector

Each position has a query, a key, and a value. Score every query against every key, and you get a grid. With T positions, that's a T by T grid of raw scores. Any real number, large or small. But each position needs one thing: a new vector, built from the other positions' values. The recipe runs three steps per row: score, softmax, blend. Plus one odd detail: divide by the square root of the head size. Let's run it on a tiny case and see why.

Score, softmax, blend: T = 2

Two positions, four entries each. Query one scores four against key one, zero against key two. Query two scores zero and two. Divide everything by root four, which is two. Softmax each row. Row one becomes point eight eight one and point one one nine, summing to one. Blend: row one's output is mostly value one, with a little of value two. Now skip the division. Row one keeps scores four and zero. What happens to its weights?

Why divide by √d_head

Row one jumps to ninety-eight versus two. Same vectors, much sharper. Why does dimension matter? A dot product adds one term per entry. More entries, wider spread. With random entries of variance one, the spread grows like the square root of the dimension. At sixty-four dimensions, raw scores spread about eight. Two scores can differ by sixteen. E to the minus sixteen is one in ten million. The row goes one-hot; training stalls. Dividing cancels that growth. At sixty-four dimensions, what's the divisor? Tap it.

The whole thing as shapes and code

Eight. Now the whole thing as shapes. Q, K and V each have T rows and head-size columns. Query times key transposed gives T by T: one score for every pair. This line also divides by root head size. The next two lines are a stable softmax along each row, giving the attention pattern A. The last line blends: A times V brings us back to T rows of head-size width. Here T is five and head size sixty-four. Tap the shape of the output.

From match scores to a new vector

From $Q$ and $K$ you can score how well each position's query matches every key. That gives a $T\times T$ grid of raw scores, and each score can be any real number, large or small. What each position actually needs is **one new vector** built from the other positions' values. How do we turn the score grid into that vector? And why does the standard recipe divide the scores by $\sqrt{d_{head}}$ before the softmax?

Score, softmax, blend

Each position (one row) does three steps: 1. Score its query against every key. 2. Softmax those scores into weights that sum to 1. 3. Output the weighted average of the value vectors. Dividing by $\sqrt{d_{head}}$ is a volume knob. Dot products of vectors with more entries add up more terms, so they spread out more. Without the division, softmax puts almost all weight on one position, a hard switch instead of an adjustable blend.

The formula, with shapes

$$\text{Attn}=\text{softmax}\!\left(\tfrac{QK^\top}{\sqrt{d_{head}}}\right)V$$ - $Q,K,V\in\mathbb{R}^{T\times d_{head}}$, with rows $q_t$, $k_s$, $v_s$ - $QK^\top\in\mathbb{R}^{T\times T}$, where entry $(t,s)=q_t\cdot k_s$ - Softmax is applied to each row, giving the attention pattern $A\in\mathbb{R}^{T\times T}$ with rows summing to 1 - $AV\in\mathbb{R}^{T\times d_{head}}$, where row $t=\sum_s A_{ts}v_s$ If the entries of $q,k$ are independent with mean 0 and variance 1, then $q\cdot k$ has std $\sqrt{d_{head}}$. Dividing brings the std back to 1. (Language models also add a mask that blocks attention to later positions; that comes later.)

Worked case: T=2, $d_{\text{head}}$=4

$q_1=[2,0,2,0]$, $q_2=[0,1,0,1]$, $k_1=[1,0,1,0]$, $k_2=[0,1,0,1]$. **Scores** $QK^\top=\begin{bmatrix}4&0\\0&2\end{bmatrix}$. Divide by $\sqrt4=2$: $\begin{bmatrix}2&0\\0&1\end{bmatrix}$. **Row softmax** $A=\begin{bmatrix}.881&.119\\.269&.731\end{bmatrix}$. **Blend** with $v_1=[1,0,0,1]$, $v_2=[0,1,0,1]$: row 1 is $[.881,.119,0,1]$, row 2 is $[.269,.731,0,1]$. Unscaled, row 1 would be $[.982,.018]$, much sharper.

Attention in numpy, and the std check

With $d_{head}=64$, raw scores have std ≈ 8. Two keys' scores can easily differ by 16, and $e^{-16}\approx10^{-7}$, so the row becomes nearly one-hot (saturating). Then nudging a score barely moves the weights, and training gets almost no signal about which positions to prefer. After scaling, the std is ≈ 1 and the weights stay soft.
import numpy as np
def attention(Q, K, V):
    S = Q @ K.T / np.sqrt(Q.shape[1])       # [T, T] scaled scores
    S = S - S.max(axis=1, keepdims=True)   # stable softmax
    A = np.exp(S); A /= A.sum(axis=1, keepdims=True)
    return A @ V                            # [T, d_head]
rng = np.random.default_rng(0)
T, dh = 5, 64
Q, K, V = (rng.standard_normal((T, dh)) for _ in range(3))
print(attention(Q, K, V).shape)             # (5, 64)
print((Q @ K.T).std(), (Q @ K.T / 8).std()) # ~8 vs ~1

Remember this

Attention is $\text{softmax}(QK^\top/\sqrt{d_{head}})V$, with shapes $T\times d_{head}\to T\times T\to T\times d_{head}$. Each row is a weighted average of value vectors. The $\sqrt{d_{head}}$ cancels the $\sqrt{d_{head}}$ growth in dot-product spread, so the softmax stays soft and adjustable instead of saturating into one-hot.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.