Highlights

Contents

Part VII
07

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.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#Section 38One Line Runs Every Head

The attention formula:

Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V

Compare queries with keys, scale the scores, mask disallowed positions, and apply softmax across visible keys. The resulting weights blend values. Here dkd_k is query/key width and MM 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.

SCALED DOT-PRODUCT ATTENTION, ONE STAGE AT A TIME (T = 4, d_k = 4, √d_k = 2)1. S = QKᵀ0.240.590.300.310.541.150.590.700.370.831.420.890.581.081.161.22Thecatsatbec.2. ÷ √d_k0.120.300.150.150.270.580.300.350.180.410.710.450.290.540.580.613. + mask0.12−∞−∞−∞0.270.58−∞−∞0.180.410.71−∞0.290.540.580.614. softmax rows1.000.000.000.000.420.580.000.000.250.320.430.000.200.260.270.28→→→1.000.000.000.000.420.580.000.000.250.320.430.000.200.260.270.28×V1.00.00.01.00.50.50.20.8=5. output1.0000.0000.4240.5760.4670.5330.3890.611Wrow 0 can onlysee itself
Figure 1.51The whole computation on four tokens. Scores, scaling, masking, row-wise softmax, and the multiplication by V. Masked cells become exactly zero after softmax.

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.

ROW 2 OF W (“SAT” ASKING) IS ONE QUERY’S WEIGHTS, EXACTLY AS IN PART VI1.000.000.000.000.420.580.000.000.250.320.430.000.200.260.270.28Thecatsatbec.0.253The0.319cat0.428sat0.000bec.0.253 + 0.319 + 0.428 = 1
Figure 1.52One row of the weight grid is one token's attention, the same picture as Part VI. Every row sums to one.

#Section 40Why Divide by √d_k

Why divide by dk\sqrt{d_k}? 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.

DOT PRODUCTS OF RANDOM UNIT-VARIANCE VECTORS: SPREAD GROWS AS √d_kraw scored_k = 4, sd 2d_k = 64, sd 8d_k = 512, sd 22.6-40040score ÷ √d_kevery d_k: sd 1-404dividing by √d_k puts every head size on the same scale
Figure 1.53The spread of raw dot products grows with the head size (left). Dividing by the square root of the head size gives the same spread for every head size (right).

Large scores freeze softmax

Larger score differences concentrate softmax on one candidate, even when their ordering is unchanged.

SOFTMAX OF [1, 2, 3] × c: BIG SCORES TURN A PREFERENCE INTO A HARD CHOICEc = 10.0900.2450.665gradient 0.223c = 20.0160.1170.867gradient 0.115c = 55e-50.0070.993gradient 0.007c = 102e-95e-51.000gradient 4.5e-5saturated softmax: almost nothing left to learn from
Figure 1.54Softmax of [1, 2, 3] multiplied by growing factors. At c = 10 one token takes everything, and the gradient through the winning weight falls from 0.223 to 0.00005.

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:

softmax(s)i=esi∑jesj\text{softmax}(s)_i = \frac{e^{s_i}}{\sum_j e^{s_j}}

Read it: raise ee 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 ese^s 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:

softmax(s)i=esi−max⁡(s)∑jesj−max⁡(s)\text{softmax}(s)_i = \frac{e^{s_i - \max(s)}}{\sum_j e^{s_j - \max(s)}}

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.

THE OVERFLOW TRAP, AND THE SUBTRACT-THE-MAX FIXscores100010011002naive: esinfinfinfnaive: ÷ sumNaNNaNNaNs − max(s)−2−10es − max0.1350.3681.000÷ 1.5030.0900.2450.665e^1000 does not fitin any float typesame answer,every number small
Figure 1.55The overflow trap. Naively exponentiating large scores overflows to infinity and then to NaN. Subtracting the maximum first gives the same weights with every intermediate number small.

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, q⋅k=∥q∥ ∥k∥cos⁡θq \cdot k = \lVert q \rVert \, \lVert k \rVert \cos\theta: the length of qq, times the length of kk, times the cosine of the angle between them. Another way to see it: drop a perpendicular from the tip of kk onto the line of qq; the length of that shadow, times the length of qq, is the score. Point kk the same way as qq and the score is big. At right angles it is zero. Pointing apart, it goes negative. Making kk longer raises the score too.

WHAT A DOT PRODUCT MEASURES: LENGTH OF q × THE SHADOW OF k ON qqkcos 30° = 0.87aligned: large scoreqkcos 90° = 0.00right angle: zeroqkcos 140° = -0.77pointing apart: negative
Figure 1.56A dot product is the length of q times the shadow of k on q. Aligned vectors score high, perpendicular ones score zero, opposed ones score negative.

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.

THE OUTPUT IS ALWAYS A BLEND INSIDE THE VALUESv₁v₂v₃(0.6, 0.3, 0.1)(0.2, 0.2, 0.6)(0.34, 0.33, 0.33)weights are positiveand sum to 1, so theoutput can never leavethe shaded triangleattention can only mix, never invent
Figure 1.57Three value vectors form a triangle. Whatever the weights, the output (orange dots) lands inside it, because the weights are positive and sum to one.

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 −∞-\infty, 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 1/dk1/\sqrt{d_k}. 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.