Dot Products, Softmax & Attention Math
The last lesson gave you the containers: vectors, matrices, and the shape rule that decides when two matrices can multiply. This lesson is about the arithmetic inside the multiplication. One small operation, the dot product, does nearly all of the work, and one small function, softmax, turns the raw numbers it produces into usable weights.
The destination is the attention equation, softmax(QKᵀ / √d) · V. Read cold, it is dense with notation. Read after this lesson, it is three moves in sequence, each of which you will have done by hand: score pairs of vectors with dot products, turn each row of scores into weights with softmax, and spend the weights on weighted sums.
The dot product
Take two vectors of the same length. Multiply them position by position, add the products, and the single number that comes out is the dot product, written a · b. For a = [1, 3, −2, 0] and b = [2, 1, 1, 4], that is 1·2 + 3·1 + (−2)·1 + 0·4 = 2 + 3 − 2 + 0 = 3.
The number is worth reading, not only computing. A dot product is large and positive when the two vectors are large in the same positions with matching signs, near zero when their patterns have little to do with each other, and negative when they disagree. Two dimensions make this visible: u = [1, 2] against v = [2, 1], which points in a similar direction, gives 4; against w = [−2, 1], which points at a right angle, gives exactly 0; against z = [−1, −2], which points the opposite way, gives −5.
That behavior is the first reading: the dot product is the field's standard similarity score. It costs one multiply and one add per position, and the result ranks how well two patterns line up.
The second reading treats one of the vectors as weights on the other. Dot the weights [0.7, 0.2, 0.1] with the values [10, 20, 30] and you get 0.7·10 + 0.2·20 + 0.1·30 = 14: mostly the first value, with a little of the other two blended in. The arithmetic is identical; the question has changed, from how alike two patterns are to what proportions to mix a set of numbers in. Attention uses both readings at once, so keep both.
Matrix multiplication is this operation on a grid. In the [m, k] × [k, n] → [m, n] rule, every one of the m · n output cells is a single dot product: row i of the left matrix against column j of the right. The cost rule falls out of the grid: each cell is a k-length dot product at about 2k operations, and m · n cells at 2k each is the 2 · m · k · n FLOPs you already have.
Softmax
The two readings want to work together: score a set of candidates with dot products, then blend the candidates using the scores as proportions. Raw scores are the wrong shape for that. They can be negative, and they sum to whatever they happen to sum to, so “how much of each” is not yet a meaningful question. Blending needs positive weights that sum to 1.
Softmax is the standard converter. Exponentiate every score, then divide each exponential by the sum of all of them. The exponential eˣ is positive whatever the sign of x and only grows as x does, so every weight comes out positive and in the same order as the scores; the division makes the weights sum to exactly 1.
On the scores [2, 1, 0]: the exponentials are e² = 7.389, e¹ = 2.718, e⁰ = 1.000, their sum is 11.107, and dividing gives the weights 0.665, 0.245, and 0.090. Two thirds of the weight to the leader, a quarter to the runner-up, the scraps to the tail, and the three together make 1.000: a probability distribution over the candidates.
Because the exponential does the work, softmax responds to the gaps between scores, and it rewards a lead disproportionately. Double every gap, [4, 2, 0] in place of [2, 1, 0], and the leading weight climbs from 0.665 to 0.867 while the tail collapses from 0.090 to 0.016. Wider gaps in, more peaked weights out; shrink the gaps toward zero and the weights flatten toward an even split.
The exponential is also where a careless implementation dies. eˣ grows fast enough that e⁸⁹ overflows a 32-bit float, whose ceiling is about 3.4 × 10³⁸, and e¹² is already past the 65,504 ceiling of FP16, one of the two-byte formats from memory and throughput arithmetic's precision table. Scores in the teens are not exotic, so this is an overflow real systems would actually hit.
The fix rides on a symmetry you can check in one line. Subtract the same constant c from every score, and every exponential picks up the same factor e⁻ᶜ, which cancels between numerator and denominator: softmax sees only the gaps. So implementations subtract the maximum score from every score before exponentiating. The biggest exponent becomes e⁰ = 1, overflow is impossible, and a far-behind score that underflows to a weight of zero was headed there anyway.
The attention equation
You can now read the equation whole: Attention(Q, K, V) = softmax(QKᵀ / √d) · V. Attention is how a model lets the tokens of an input inform one another, and Q, K, and V are three matrices handed to the computation; what the letters stand for, and where the matrices come from inside a model, is covered in understanding one token. Here they are inputs with shapes: for an input seq tokens long and a working width d, each of the three is [seq, d], one row per token. In Llama 3.1 8B, each of the attention computations inside the model runs at d = 128.
Start inside the parentheses. The superscript ᵀ flips a matrix so that rows become columns, the transpose: K's [seq, d] becomes [d, seq]. The shapes now chain, [seq, d] × [d, seq] → [seq, seq], and the grid reading says what every cell is: cell (i, j) of QKᵀ is row i of Q dotted with row j of K. The product is a table of similarity scores, every row of Q against every row of K.
The division by √d exists because dot products grow with dimension. Each score is a sum of d products, and under the standard assumption, components independent with mean 0 and variance 1, that sum has variance d, so a typical magnitude near √d. At d = 128 a typical score sits near √128 ≈ 11.3, and softmax on an 11-point gap saturates: softmax([11.3, 0]) ≈ [0.99999, 0.00001], essentially all of the weight on one entry. Dividing by √d pulls typical scores back to order 1, where softmax([1, 0]) ≈ [0.73, 0.27] keeps a difference visible without letting it swamp the row.
Attention Is All You Need, the 2017 paper the equation comes from, introduces the scale with exactly this variance argument. Its stated worry is training, since a saturated softmax has almost no gradient to learn from, but the saturation itself is just as real when you only run the model.
Softmax then applies to each row of the scaled table, turning each token's scores into a distribution over all seq positions, and the final multiplication spends those weights. The shapes chain again, [seq, seq] × [seq, d] → [seq, d], and each output row is a weighted sum of the rows of V, in the proportions its weight row holds. That is the 0.7·10 + 0.2·20 + 0.1·30 arithmetic from the top of the lesson, run d columns wide. Attention leaves with the shape it entered, [seq, d] in and [seq, d] out, every row now a mixture of rows of V.
One napkin observation before leaving the equation. The score table is [seq, seq]: its size depends on nothing but the input length, and the cost rule prices QKᵀ at 2 · d · seq² FLOPs, so doubling the input quadruples both the table and the work to fill it. That square is why attention over long inputs is an engineering subject of its own; attention optimization is spent on computing this table efficiently.
The equation, read whole: score every pair of rows with dot products, weigh each row's scores with softmax, and mix the rows of V in those proportions. The next lesson picks up the thread softmax left hanging: rows that sum to 1 are probability distributions, and probability, sampling, and the statistics that make a measured number trustworthy are where the toolkit goes next.