Lesson 19 of 23 · Transformer block
Turn comparisons into a blend.
Your win: calculate softmax probabilities from masked scores and use them to form a weighted sum of value vectors.
Softmax normalizes an entire score row
Numbers substituted: correct the supplied diagram
For masked scores \((0.7,1.1,0.2,-\infty)\):
The image lists \((0.26,0.41,0.33,0)\), but that vector is not the softmax of the displayed scores. This course uses the calculated values above.
The probabilities blend value vectors
Let \(\mathbf v_1=(1,0)\), \(\mathbf v_2=(0,2)\), \(\mathbf v_3=(1,1)\), and \(\mathbf v_4=(-1,1)\). Then for query 3:
Move the query and watch the distribution
| Key | Raw score | After mask | Softmax weight | Value |
|---|
Weighted output:
Code checkpoint · probabilities blend values
Softmax acts across the key axis. The following matrix multiplication replaces that key axis with the value feature axis.
Show softmax and weighted values
weights = F.softmax(scores.float(), dim=-1).to(dtype=q.dtype)
# weights: [B, H, T, T], each row sums to 1
context = weights @ v
# v: [B, H, T, Dh]
# context: [B, H, T, Dh]Trace it: Why does the final dimension of context equal Dh rather than T?
Retrieval check
What must the weights in one attention row sum to?
Practice before moving on
- Compute \(\operatorname{softmax}(0,0)\).
- Compute \(\operatorname{softmax}(\ln2,0)\).
- Why does adding the same constant to every finite score leave softmax unchanged?
- Use weights \((0.25,0.75)\) and values \((2,0)\), \((0,4)\) to calculate the output.
- Using \((0.323,0.482,0.196,0)\), verify the weights sum to approximately one. Explain the rounding discrepancy.
- If all attention weight is on \(\mathbf v_2\), what is the output?
Check solutions
- \((0.5,0.5)\).
- \((2/3,1/3)\), because \(e^{\ln2}=2\).
- The common factor \(e^c\) cancels between numerator and denominator.
- \(0.25(2,0)+0.75(0,4)=(0.5,3)\).
- The displayed sum is \(1.001\); the exact unrounded values sum to \(1\).
- Exactly \(\mathbf v_2\).
Primary source: Vaswani et al., Section 3.2.1.