softmax(Q·Kᵀ/√dₖ)·V. The first operation —
Q·Kᵀ — is a matrix multiplication that computes
every pairwise dot product between every query and every key, all at
once. This is the computational heart of the transformer, and this lesson
teaches you exactly how it works.
To multiply A (m×n) by B (n×p), the result C (m×p) has entry Cij = dot product of row i of A with column j of B:
Cij = Σₖ Aik · Bkj
The inner dimensions must match: (m×n) × (n×p) → (m×p). This is why K must be transposed — so its dimension matches Q's.
In attention, we have:
Q·Kᵀ has dimensions (seq_len × dk) × (dk × seq_len) = (seq_len × seq_len). Every entry (i,j) is the dot product between query i and key j:
That's it. One matrix multiplication computes the similarity between every word and every other word in the input. For a 2048-token context, that's 4,194,304 pairwise comparisons — in one operation.
Matrix multiplication also represents composition. If B transforms vector space U→V, and A transforms V→W, then A·B transforms U→W directly:
(A·B)·x = A·(B·x)
Apply B first, then A. The product A·B is a single matrix that does both. This is why stacking transformer layers works: each layer is a composition of transformations.
The full attention formula: softmax(Q·Kᵀ/√dₖ)·V
| Operation | What It Does | Lesson |
|---|---|---|
| Q·Kᵀ | Compute all pairwise similarities (matrix mult) | 0003 (this one) |
| /√dₖ | Scale to prevent vanishing gradients | 0013 |
| softmax(·) | Convert similarities to probabilities (rows sum to 1) | 0012 |
| ·V | Weighted average of value vectors by attention probabilities | 0013 |
Each piece has a mathematical reason for being there. None of it is arbitrary. By the end of this course, you'll understand all of them.
Q1: Q has shape (100 × 64) and K has shape (100 × 64). What is the shape of Q·Kᵀ?
A. (64 × 64) B. (100 × 100) C. (100 × 64) D. (64 × 100)Q2: Entry (3, 7) of Q·Kᵀ represents what?
A. The similarity between key 3 and query 7 B. The similarity between query 3 and key 7 C. The similarity between query 3 and value 7 D. The 7th component of query 3Q3 (Challenge): If context length doubles from 1024 to 2048, how does the size of the Q·Kᵀ matrix change?
A. It doubles (2×) B. It quadruples (4×) C. It stays the same D. It increases by 8×