Linear algebra for LLMsPart 5: Attention, one operation at a time
Softmax
7 min
Scores in, weights out
Raise to each score, then divide by the total. Every weight comes out positive, and they add up to 1.
Write
Step 1: exponentiate
, , . Bigger scores grow much faster: a gap of 1 in score becomes a factor of .
Step 2: divide by the total
The total is . The weights keep the order of the scores, and the biggest score gets most of the weight.
Write
Adding a constant changes nothing
The factor cancels. So gives the same weights as . Code uses this: it subtracts the largest score first, so never has to be computed (it would overflow to infinity).
Write
Temperature
. Dividing by a small stretches the gaps, so the top score takes nearly everything; a large shrinks them toward a uniform spread. Dividing attention scores by is a temperature of .
Write
means exactly zero weight
, so that entry gets no weight, and the others are normalized among themselves. This is how the causal mask works.
On a matrix: one softmax per row
weights = scores.softmax(dim=-1) # each row sums to 1For attention scores (one row per query, one column per key), each query gets its own distribution over the keys.
✏️ Your turn
Softmax by hand
Use . Write the three weights.
Work it out on paper, then go to the next card to check.
Answer
Exponentiate to , total 5, divide.
Softmax at the output too
In a transformer
The model’s last layer produces a score (a logit) for every token in the vocabulary; turns them into next-token probabilities. The temperature setting when you sample from an LLM is this .
📌 Recap
Softmax in one card
- : positive, sums to 1, keeps the order.
- Shift-invariant, so subtract the max for safety.
- Temperature: .
- A score of gets weight exactly 0.
Write