The formula
One equation carries the entire transformer, and everything else in the architecture is arranged around it.
- : the queries, one row per position: what each position is looking for.
- : the keys, one row per position: what each position offers.
- : the values, one row per position: what each position actually contributes.
- : the width of a single query or key vector.
Read it right to left
is every query dotted with every key, producing an table of raw compatibility scores.
Dividing by rescales those scores, for a reason that has its own part below.
Softmax turns each row of that table into weights that are positive and sum to one, so every position distributes exactly one unit of attention across all positions.
Multiplying by takes, for each position, a weighted average of every value in the sequence.
The output is the same shape as the input: one vector per position, each now a blend of the whole sequence.
Why the square root is there
The dot product of two independent random vectors of width , each component with unit variance, has variance .
So the scores grow in size as the head gets wider, and softmax on large inputs saturates: one weight approaches 1 and the rest approach 0.
A saturated softmax has almost no gradient, which stops the layer learning at all.
Dividing by puts the variance back to one whatever the width, which keeps the softmax in the range where it has a usable gradient.
The mask
- : a matrix that is zero where attention is allowed and negative infinity where it is not.
Negative infinity, not zero: it goes in before the softmax, so the exponential sends it to exactly zero afterwards.
In a decoder this is upper-triangular, which is what stops position reading anything after it.
One pass, in order
- Project the input three times to get queries, keys and values.
- Multiply queries by transposed keys to get the score table.
- Divide every score by the square root of the head width.
- Add the mask, then softmax each row.
- Multiply those weights by the values.
What it costs
The score table is , so doubling the sequence length quadruples both.
Everything from FlashAttention to sliding-window attention exists to attack one or other of those two terms.