Boss lesson · Unit 04
The math inside attention
Dot products, softmax and a weighted average, for three tokens
What you practise
- Similarity by dot product, scaling by √d, softmax weights, a weighted average of vectors: scaled dot-product attention computed for three tokens
Try a question from this lesson
Pick one
"The cat sat on the mat because it was tired." To work out what "it" refers to, which earlier word should a model look at most?
Correct answer
cat
Why
Mats do not get tired, so "it" is the cat. Attention is the mechanism that lets each word decide how much to look at every other word. The rest of this lesson computes it, number by number.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
All the scores at once
Stack the keys as the rows of a matrix K. Then one matrix-vector product scores every key against the query: each row dotted with q.
Here "cat" scores 4, "mat" scores 0 and "sat" scores 2. These are raw attention scores: not yet probabilities.
import numpy as np
q = np.array([1, 0, 1, 0]) # "it"
K = np.array([[2, 0, 2, 0], # cat
[0, 2, 0, 0], # mat
[1, 1, 1, 1]]) # sat
print(K @ q) # [4 0 2]Concept
Mixing the values
Each word also offers a value vector: the information it passes on when attended to.
The output of attention is the weighted average of the values, using the attention weights. Each weight multiplies its own row and the results are added, which is one more matrix product: w @ V.
import numpy as np
w = np.array([0.5, 0.25, 0.25])
V = np.array([[4, 0], # cat
[0, 4], # mat
[4, 4]]) # sat
print(w @ V) # [3. 2.]10 more exercises in the app
- 4× multiple choice
- 3× type the answer
- 1× fill the blanks
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.