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
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.
Score, softmax, blend
The formula, with shapes
Worked case: T=2, $d_{\text{head}}$=4
Attention in numpy, and the std check
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
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.
Bytewise
All courses