One query scores every key, then blends the values
Here's one lookup in NumPy: one query, three keys.
import numpy as npdef softmax(s, axis=-1): e = np.exp(s) return e / e.sum(axis=axis, keepdims=True)keys = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])values = np.array([10.0, 20.0, 30.0])query = np.array([1.0, 2.0])scores = np.array([key @ query for key in keys])weights = softmax(scores)print(scores)print(weights.round(2))print((weights * values).sum().round(1))
Predict
Query [1, 2] against keys [1, 0], [0, 1] and [1, 1]. Which key gets the biggest weight?
Pick one to see what it prints.
One query, three keys. Each key's score is its dot product with the query, and a bigger score means a better match. A softmax turns the scores into weights that are positive and sum to 1. The output is the values, averaged with those weights.
Query [1, 2]:
Key
Score
Weight
Value
[1, 0]
1
0.09
10
[0, 1]
2
0.24
20
[1, 1]
3
0.67
30
The output blends the values: 0.09·10 + 0.24·20 + 0.67·30 = 25.8.
A Python dict needs an exact key match, and it returns one value. Attention scores every key against the query and returns a blend, weighted toward the best matches.
Nothing is ever picked, only weighted. That's why the whole thing is differentiable: a small change to a score makes a small change to the output.
This softmax is the plain formula. It breaks on huge scores, and Part 4 fixes it.
In symbols, the output for position i is:
outi=j∑softmaxj(dqi⋅kj)vj
Read it from the inside out:
qi⋅kj is query i dotted with key j.
d is the length of each query and key vector. Part 2 explains the division by d.
softmaxj runs over j: one query's scores against every key.
The sum blends the values vj with those weights.
The loop over the keys is fine for three of them. In the editor, do it the NumPy way. keys is (3, 2) and query is (2,), so one @ scores every key at once, as in the NumPy lesson's grades, and one more @ blends the values. query is [0, 3] there, a new query against the same three keys. The keys [0, 1] and [1, 1] tie, so expect them to share most of the weight.
Pick an answer above to see the rest
Instructions
1
Fill in scores with one @: each key dotted with query, one number per key.
2
Fill in weights with softmax, then out with one more @: the values blended with those weights.