Scaled Dot-Product Attention
Matching scores must become a useful blend. Scale and normalization control how they compete. Follow the attention operation, the reason for scaling, and the numerical rules that keep softmax stable.
#Section 38One Line Runs Every Head
The attention formula:
Compare queries with keys, scale the scores, mask disallowed positions, and apply softmax across visible keys. The resulting weights blend values. Here is query/key width and is the mask.
Scaled dot-product attention comes from the 2017 Attention Is All You Need paper. Dot products turn all comparisons into matrix multiplications, which fit GPU execution better than evaluating a separate small network for each pair.
#Section 39The stages of attention
Follow the figure from queries and keys to a blended output.
Scores compare each query with every key. One row contains a position's comparisons; one column belongs to a key.
Scaling adjusts score magnitude for head width.
Masking hides comparisons the model must not use, such as future positions in a causal decoder.
Normalization applies softmax to each row. Visible keys share a total weight of one; masked keys receive zero.
Blending averages values with those weights. Repeat the operation independently for each head.
Each head uses its own queries, keys, and values. The operation is shared, while its learned projections differ.
Every row is Part VI again
The matrix form evaluates many queries together. Each row is the single-query matching and blending process from Part VI.
#Section 40Why Divide by √d_k
Why divide by ? This is one of the most common interview questions about Transformers, and the answer is a two-line argument about spread.
Variance measures squared deviation from a mean; its square root is standard deviation. Under independent zero-mean, unit-variance components, wider dot products have greater spread because they add more terms.
Dividing by the square root of head width normalizes that spread under these assumptions. It prevents width alone from making scores excessively large.
Large scores freeze softmax
Larger score differences concentrate softmax on one candidate, even when their ordering is unchanged.
The gradient measures how a change affects the result. Near a saturated softmax, small score changes barely affect its weights, weakening that gradient route. Scaling limits this effect when wide vectors increase score magnitude.
#Section 41Softmax, Carefully
Softmax turns any list of scores into weights that are positive and sum to one:
Read it: raise to each score, then divide each result by the total of all of them. Raising to a power makes everything positive, and dividing by the total makes the results add up to one. Larger scores get disproportionately larger weights, because grows fast: a score 1 higher gets 2.718 times the weight.
Exponentiating large scores can overflow. An invalid division can then yield NaN, or "not a number", which contaminates later computation.
The fix is to subtract the largest score from all of them first:
Subtracting the largest score scales every exponential equally, so the normalization cancels the change. The largest exponential becomes one and the others cannot exceed it.
Every serious implementation, including PyTorch's torch.softmax, does this subtraction for you. You need to know it because you will write it yourself in kernels, in loss functions, and in interviews, and because Unit II's FlashAttention is built on a clever extension of it.
#Section 42What the Scores and the Output Mean
A dot product is alignment times size
What does a dot product actually measure? Geometrically, : the length of , times the length of , times the cosine of the angle between them. Another way to see it: drop a perpendicular from the tip of onto the line of ; the length of that shadow, times the length of , is the score. Point the same way as and the score is big. At right angles it is zero. Pointing apart, it goes negative. Making longer raises the score too.
So an attention score is "how much do they point the same way" times "how big are they". It is the cosine similarity of Section 12 with the lengths left in. The lengths matter: a key with a large norm gets attention from many queries, which is one way models create "attention sink" tokens (Part IX).
The output never leaves the values
Because softmax weights are all positive and sum to one, the output of attention is a convex combination of the value vectors: a weighted average. Geometrically, the output always lies inside the shape whose corners are the values. With three values, it lies inside their triangle, whatever the scores are.
For fixed values, normalized attention is a blend inside their convex hull. Attention's projections and input-dependent weights still transform features. The MLP adds a separate nonlinear transformation at each position.
Sharp edges of the attention formula
A fully masked row produces NaN. If masking hides every key from some query, its whole row of scores is , and softmax computes zero divided by zero. The result is NaN, and it spreads everywhere. Make sure every query can see at least one key, usually itself.
Mask constants need a dtype policy. Large negative constants can overflow when cast. Use the backend's supported masking convention, and handle fully masked rows explicitly; a finite minimum does not make their uniform softmax meaningful.
Near-uniform weights at the start are normal. At initialization the scores are small and similar, so softmax gives every visible token roughly the same weight. Training breaks the ties.
Attention dropout must be off at evaluation. Use evaluation mode and set explicit functional dropout arguments to zero. model.eval() alone does not change an argument supplied directly to SDPA.
Not every model uses . Some use a different scale or learn one. A trained model expects the scale it was trained with, so never change it on a pretrained model.