Lesson 3.2: Self-attention: queries, keys and values
Build self-attention from queries, keys and values. See why scores are scaled by the square root of the key size, then train it to solve a lookup task.
By the end of this lesson you will be able to explain attention as a soft lookup, build it from three matrices by hand and then in a full layer with its gradients, say why the scores are divided by the square root of the key size, show that attention without positions cannot see order, and train a model that uses it. You will show that hand-set matrices solve the lookup task of Lesson 3.1 on 2,000 examples (100% with a score scale of 8, 98.6% with a scale of 1), that the spread of a dot product grows as the square root of the vector length (2.0, 4.01, 8.03 and 15.97 for lengths 4, 16, 64 and 256), that analytic gradients agree with numerical ones to eight digits, that a one-head layer with 2,112 numbers reaches a validation loss of 1.0061 on the toy language, and that the same layer learns the lookup task to 100% accuracy with 94.7% of its weight on the right pair. You need Python and NumPy, and helpers.py from Lesson 3.1.
Lesson 3.1 ended with a requirement: weights over earlier tokens that are computed from the content, passed through a masked softmax. This lesson builds that. The mechanism is called self-attention: "attention" because each position decides how much to attend to each other position, and "self" because the tokens attend to other tokens in the same sequence. It is the most important idea in the course, and it is short. We will build it three ways: first by hand, with matrices we set ourselves, so that every number can be read; then as a full layer with its gradients; then trained.
A soft lookup table
Think of a dictionary. You hold a query, a key you want to find. The dictionary holds keys, each attached to a value. A lookup compares your query to every key, finds the matching one and returns its value. A normal dictionary does this with an exact match, and returns one value or nothing.
Attention does the same thing softly. Every position produces three vectors from its own vector:
a query, what this position is looking for,
a key, what this position offers to be found by,
a value, what this position hands over if it is chosen.
Position t compares its query with the key of every position, using a dot product, which is large when the two vectors point the same way. That gives one score per position. A softmax turns the scores into weights that sum to one. The result for position t is the weighted sum of all the values. If one key matches the query much better than the rest, nearly all the weight goes to it and the output is almost exactly its value: a lookup. If several match, the output blends them. Because every step is a smooth function, training can adjust it.
The three vectors come from the same input by three different matrices. Why three? Because "what I am looking for", "what I advertise" and "what I give" are different things. In a sentence, a verb may look for a subject (query), advertise that it is a verb (key) and pass on its tense (value). One vector could not play all three roles.
Attention by hand
Before training anything, let us build attention for the lookup task with matrices we choose, so that nothing is hidden. Each token becomes 24 numbers. A pair token has a one in the slot of its key (slots 0 to 7) and a one in the slot of its value (slots 8 to 15). The query token has a one in the slot of the key it asks about (slots 16 to 23). Then:
the query matrix reads the queried-key slots and multiplies by a scale,
the key matrix reads the key slots,
the value matrix reads the value slots.
python
import numpy as np
from helpers import softmax
def makelookup(n, rng):
X = np.zeros((n, 5), dtype=int); y = np.zeros(n, dtype=int)
for i in range(n):
keys = rng.permutation(8)[:4]
vals = rng.integers(0, 8, 4)
q = rng.integers(0, 4)
X[i, :4] = keys 8 + vals
X[i, 4] = 64 + keys[q]
y[i] = vals[q]
return X, y
def tovectors(tokens):
"""24 numbers per token: slot 0-7 the key, 8-15 the value, 16-23 the queried key."""
X = np.zeros((5, 24))
for i, t in enumerate(tokens[:4]):
key, val = divmod(t, 8)
X[i, key] = 1
X[i, 8 + val] = 1
X[4, 16 + tokens[4] - 64] = 1
return X
def attend(tokens, scale):
X = tovectors(tokens)
Wq = np.zeros((24, 8)); Wq[16:24] = np.eye(8) scale # the query asks about the queried key
Wk = np.zeros((24, 8)); Wk[0:8] = np.eye(8) # a pair advertises its key
Wv = np.zeros((24, 8)); Wv[8:16] = np.eye(8) # a pair hands over its value
Q, K, V = X @ Wq, X @ Wk, X @ Wv
S = Q @ K.T
S = np.where(np.triu(np.ones((5, 5), dtype=bool), 1), -np.inf, S) # causal mask
A = softmax(S)
return S, A, A @ V
X, y = makelookup(3, np.random.defaultrng(0))
S, A, O = attend(X[0], scale=8)
print(X[0], y[0])
print(S[4]) # scores of the query position against positions 0..4
print(np.round(A[4], 4)) # attention weights of the query position
print(np.round(O[4], 3)) # the value it reads out
for scale in (1, 8):
X, y = makelookup(2000, np.random.defaultrng(999))
hits = sum(attend(x, scale)[2][4].argmax() == t for x, t in zip(X, y))
print(scale, hits / 2000, np.round(attend(X[0], scale)[1][4].max(), 4))
The first line printed is the example: pairs 17, 38, 29, 55, query 67, answer 5. The scores of the query position against positions 0 to 4 are [0, 0, 8, 0, 0]: the pair at position 2 has key 3, which is what the query asks about, so its score is 8, and the others score 0. The softmax turns this into weights of [0.0003, 0.0003, 0.9987, 0.0003, 0.0003]. The output is 0.999 in slot 5 and zero elsewhere: the value 5. Nothing was trained, and attention found the right pair.
The last lines run it on 2,000 new examples. With a score scale of 8, it is right every time (1.0). With a scale of 1, the weight on the right pair is only 0.4046, since a score of 1 against 0 gives e against 1 for each of the other four, and the answer is right in 98.6% of cases. It still wins most of the time, but a few blended values outvote it. The scale controls how sharp the lookup is, which is the point of the next section.
The recipe
For a sequence of T vectors, collected as a matrix X with one row per token, self-attention is:
1. Project. Q = X Wq, K = X Wk and V = X Wv. Each is T rows by dk columns.
2. Score. S = Q Kᵀ divided by the square root of dk. This is a T by T matrix: row t, column s is how much position t wants position s.
3. Mask. Set S[t, s] to minus infinity for s greater than t, so that no position reads the future. Lesson 3.3 explains why this is essential.
4. Weigh. A = softmax of S, applied to each row. Each row of A sums to one.
5. Mix. The output is A V: for each position, the weighted sum of the value vectors.
That is the whole mechanism. The matrix A is the lower-triangular weight matrix from Lesson 3.1, now computed from the content in place of being fixed.
Why divide by the square root of dk
Step 2 divides by the square root of dk, and it deserves a reason. If the entries of a query and a key are independent with spread 1, their dot product is a sum of dk products, each with spread 1. The sum has spread equal to the square root of dk. So the scores grow as vectors get longer. A softmax of large scores is almost a hard choice: one weight near one and the rest near zero. That is a problem for training. Where a softmax output is nearly one-hot, its gradient is nearly zero (the softmax derivative contains the factor A times 1 minus A), and learning stalls.
Dividing by the square root of dk brings the spread back to about 1, whatever the vector length. We can measure it:
python
import numpy as np
from helpers import softmax
rng = np.random.defaultrng(0)
for dk in (4, 16, 64, 256):
q = rng.standardnormal((20000, dk))
k = rng.standardnormal((20000, dk))
spread = (q k).sum(axis=1).std() # spread of one dot product
Q = rng.standardnormal((5000, dk))
K = rng.standardnormal((5000, 8, dk)) # eight random keys per query
S = np.einsum("nd,nkd->nk", Q, K)
raw = softmax(S).max(axis=1).mean() # biggest weight, no scaling
scaled = softmax(S / np.sqrt(dk)).max(axis=1).mean() # biggest weight, divided by sqrt(dk)
print(dk, round(spread, 2), round(np.sqrt(dk), 2), round(raw, 3), round(scaled, 3))
The columns are the vector length, the measured spread of a dot product, the square root of the length, the average largest weight from a softmax over 8 random keys without scaling and with it.
Length dk · Spread of a dot product · Largest weight, unscaled · Largest weight, scaled4 · 2.00 · 0.531 · 0.346
16 · 4.01 · 0.744 · 0.356
64 · 8.03 · 0.877 · 0.360
256 · 15.97 · 0.940 · 0.362
The scaled weights hover near 0.35, whatever the length. The unscaled ones drift toward 1, the saturation that stalls training. The model can still learn sharp attention, by making its scores larger on purpose, as the hand-built example did with a scale of 8. The division only decides where it starts.
The full layer
Here is the layer as code. Save it as attention.py. It handles a batch of sequences and any number of heads h; this lesson uses one, and Lesson 3.3 uses more. The backward pass is written by hand, as in Lesson 1.4.
python
# attention.py
import numpy as np
from helpers import softmax
def init(V, d, seed=0, scale=0.1):
rng = np.random.defaultrng(seed)
n = lambda shape: rng.standardnormal(shape) scale
return dict(E=n(V, d), Wq=n(d, d), Wk=n(d, d), Wv=n(d, d), Wo=n(d, d), U=n(d, V))
def forward(p, x, h, P, causal=True):
"""x: token ids (B, T). h: number of heads. P: position vectors (>= T, d)."""
B, T = x.shape
d = p["E"].shape[1]
dh = d // h
H0 = p["E"][x] + P[:T] # (B, T, d)
split = lambda Z: Z.reshape(B, T, h, dh).transpose(0, 2, 1, 3) # (B, h, T, dh)
Q, K, Vv = split(H0 @ p["Wq"]), split(H0 @ p["Wk"]), split(H0 @ p["Wv"])
S = np.einsum("bhtd,bhsd->bhts", Q, K) / np.sqrt(dh) # (B, h, T, T) scores
if causal:
S = np.where(np.triu(np.ones((T, T), dtype=bool), 1), -1e9, S)
A = softmax(S) # weights; each row sums to 1
O = np.einsum("bhts,bhsd->bhtd", A, Vv) # weighted sums of values
Oc = O.transpose(0, 2, 1, 3).reshape(B, T, d) # glue the heads together
H1 = H0 + Oc @ p["Wo"] # residual connection
logits = H1 @ p["U"]
return logits, dict(x=x, H0=H0, Q=Q, K=K, V=Vv, A=A, Oc=Oc, H1=H1, h=h, dh=dh)
def backward(p, c, dlogits):
B, T, d = c["H0"].shape
h, dh = c["h"], c["dh"]
g = {}
g["U"] = np.einsum("btd,btv->dv", c["H1"], dlogits)
dH1 = dlogits @ p["U"].T
g["Wo"] = np.einsum("btd,bte->de", c["Oc"], dH1)
dO = (dH1 @ p["Wo"].T).reshape(B, T, h, dh).transpose(0, 2, 1, 3)
dA = np.einsum("bhtd,bhsd->bhts", dO, c["V"])
dV = np.einsum("bhts,bhtd->bhsd", c["A"], dO)
dS = c["A"] (dA - (dA c["A"]).sum(-1, keepdims=True)) / np.sqrt(dh) # softmax backward
dQ = np.einsum("bhts,bhsd->bhtd", dS, c["K"])
dK = np.einsum("bhts,bhtd->bhsd", dS, c["Q"])
merge = lambda Z: Z.transpose(0, 2, 1, 3).reshape(B, T, d)
dQ, dK, dV = merge(dQ), merge(dK), merge(dV)
g["Wq"] = np.einsum("btd,bte->de", c["H0"], dQ)
g["Wk"] = np.einsum("btd,bte->de", c["H0"], dK)
g["Wv"] = np.einsum("btd,bte->de", c["H0"], dV)
dH0 = dH1 + dQ @ p["Wq"].T + dK @ p["Wk"].T + dV @ p["Wv"].T
g["E"] = np.zeroslike(p["E"])
np.add.at(g["E"], c["x"], dH0)
return g
def crossentropy(logits, y):
P = softmax(logits)
B, T = y.shape
return -np.log(P[np.arange(B)[:, None], np.arange(T)[None, :], y]).mean(), P
def lossandgrads(p, x, y, h, P, causal=True):
logits, c = forward(p, x, h, P, causal)
loss, probs = crossentropy(logits, y)
dlogits = probs.copy()
B, T = y.shape
dlogits[np.arange(B)[:, None], np.arange(T)[None, :], y] -= 1
dlogits /= B T
return loss, backward(p, c, dlogits)
Four points on the code.
The shapes. x is a batch of token ids, (B, T). After the embedding and positions, H0 has shape (B, T, d). Splitting into heads reshapes it to (B, h, T, dh), where dh is d divided by h. The scores S have shape (B, h, T, T): a T by T matrix for every example and every head.
The mask. np.triu(np.ones((T, T)), 1) marks the entries above the diagonal, which are the future. They get minus 1e9, which the softmax turns into zero weight. (We use a large negative number in place of minus infinity, because it avoids NaN in the backward pass if a whole row were ever masked.)
The residual connection. H1 = H0 + Oc @ Wo adds the attention output to the input, not replacing it. The current token's own vector therefore reaches the output untouched, and attention only adds what it gathered from the other positions. Lesson 4.1 treats residual connections properly.
The backward pass. It follows the forward pass in reverse. The only new step is the gradient of the softmax: dS = A (dA - (dA A).sum(-1, keepdims=True)), which is the standard formula for the derivative of a softmax applied to a row. Everything else is matrix products and reshapes.
Checking the gradients
Hand-written backward passes are easy to get wrong, so we check them as we did in Lesson 1.4: compare each analytic gradient with a numerical one, from a small change in one entry.
python
import numpy as np
from helpers import
from attention import
T, d, h = 8, 16, 2
p = init(V, d, seed=1, scale=0.3)
P = sinusoidal(T, d)
x, y = getbatch(trainids, 4, T, np.random.defaultrng(5))
loss, g = lossandgrads(p, x, y, h, P)
for name, idx in [("Wq", (3, 5)), ("Wk", (2, 7)), ("Wv", (9, 1)), ("Wo", (4, 4)), ("U", (6, 20)), ("E", (5, 3))]:
eps, w = 1e-5, p[name]
old = w[idx]
w[idx] = old + eps; lp, = lossandgrads(p, x, y, h, P)
w[idx] = old - eps; lm, = lossandgrads(p, x, y, h, P)
w[idx] = old
print(name, round(g[name][idx], 8), round((lp - lm) / (2 eps), 8))
Each line gives the analytic gradient and the numerical estimate for one entry of one matrix:
Wq 0.00048173 0.00048173
Wk 0.00426571 0.00426571
Wv -0.13015014 -0.13015014
Wo -0.02585231 -0.02585231
U 0.05558035 0.05558035
E 0.03634887 0.03634887
They agree to eight digits for all six matrices, including the query, key and value matrices, whose gradients pass through the softmax. The code can be trusted.
What attention cannot see: order
There is a gap. Attention treats its inputs as a set. Swap two tokens, and the outputs for those two tokens swap in the same way. Nothing in a query, a key or a value says where a token sits. We can check this: give the layer six random tokens and the same six in shuffled order, with no position information and no mask, and compare.
python
import numpy as np
from helpers import
from attention import
rng = np.random.defaultrng(1)
p = init(V, 16, seed=1, scale=0.3)
x = rng.integers(0, V, (1, 6)) # six random tokens
perm = rng.permutation(6) # a shuffled order
nopos = np.zeros((16, 16)) # no position information
a, = forward(p, x, 1, nopos, causal=False)
b, = forward(p, x[:, perm], 1, nopos, causal=False)
print(np.allclose(a[:, perm], b)) # True: shuffle the inputs, the outputs shuffle the same way
The output is True: shuffling the inputs just shuffles the outputs. This property is called permutation equivariance. It is useful for some tasks and wrong for language, where "the dog chased the cat" differs from "the cat chased the dog". The fix is the one from Lesson 2.3: add a position vector to each token vector before attention. We use the sinusoidal vectors from there. With the mask on, the model also gets some position information for free, since position t can see exactly t plus one tokens, but explicit positions help, as the results below show.
Training on the toy language
Now we train a one-head layer on the toy language with a window of 16 and 16-dimensional vectors, and compare it with the earlier models.
python
import numpy as np
from helpers import
from attention import
T, d = 16, 16
def train(h, P, steps=3000, lr=0.01, seed=0):
p = init(V, d, seed=seed)
opt = Adam(p, lr)
rng = np.random.defaultrng(seed)
for step in range(steps):
x, y = getbatch(trainids, 32, T, rng)
loss, g = lossandgrads(p, x, y, h, P)
opt.step(g)
if step in (0, 100, 500, 1000, 2000, 2999):
print(step, round(loss, 4))
return p
def validation(p, h, P):
x, y = getbatch(valids, 400, T, np.random.defaultrng(123))
logits, cache = forward(p, x, h, P)
return crossentropy(logits, y)[0], cache
P = sinusoidal(T, d)
p = train(1, P)
loss, cache = validation(p, 1, P)
print("validation loss", round(loss, 4), " parameters", sum(w.size for w in p.values()))
A = cache["A"][:, 0] # (400, T, T): weights of the single head
print("average weight by distance back:",
[round(float(np.mean([A[:, t, t - o].mean() for t in range(8, T)])), 2) for o in range(6)])
nopos = np.zeros((T, d))
p0 = train(1, nopos)
print("without positions", round(validation(p0, 1, nopos)[0], 4))
The loss falls from 3.5261 at the start to 0.997 on the training batches, and the validation loss is 1.0061. The model has 2,112 numbers: an embedding table of 544, four 16-by-16 matrices (1,024) and an output matrix of 544.
Model · Validation lossPlain running mean · 1.331
Bigram · 1.1615
Learned weight per distance · 1.0095
One attention head · 1.0061
Trigram table · 0.992
Best possible · 0.988
The gain over fixed weights is small, and that is the honest result. The toy language has no long-range structure: the last two or three tokens carry everything useful, and fixed weights already capture that. Attention matches them and costs more. It is no better on this language because there is nothing better to find.
The code also prints the average weight that the head gives to each distance back: [0.81, 0.03, 0.06, 0.06, 0.01, 0.01]. The head puts 81% of its weight on the current token, and a few per cent on the three before it. Because the current token already reaches the output through the residual connection, the head's job is small: a light correction from the previous tokens.
The last lines train the same model without positions. Its validation loss is 1.0501 instead of 1.0061. The model still works, because the mask gives it a trace of position, but explicit position vectors are worth about 0.044 in loss.
Training on the lookup task
The lookup task is where attention earns its place. We train the same layer with a larger dimension (32) and a gentler learning rate (0.003), on batches of freshly made examples. Only the last position has a target.
python
import numpy as np
from helpers import
from attention import
def makelookup(n, rng):
X = np.zeros((n, 5), dtype=int); y = np.zeros(n, dtype=int); where = np.zeros(n, dtype=int)
for i in range(n):
keys = rng.permutation(8)[:4]
vals = rng.integers(0, 8, 4)
q = rng.integers(0, 4)
X[i, :4] = keys 8 + vals
X[i, 4] = 64 + keys[q]
y[i], where[i] = vals[q], q
return X, y, where
d, T = 32, 5
P = sinusoidal(T, d)
p = init(72, d, seed=0, scale=0.3)
opt = Adam(p, 0.003)
rng = np.random.defaultrng(0)
for step in range(4000):
x, y, = makelookup(64, rng)
logits, cache = forward(p, x, 1, P)
probs = softmax(logits[:, -1, :]) # only the last position has a target
dlogits = np.zeroslike(logits)
dz = probs.copy(); dz[np.arange(64), y] -= 1
dlogits[:, -1, :] = dz / 64
opt.step(backward(p, cache, dlogits))
if step in (0, 500, 1000, 3999):
print(step, round(-np.log(probs[np.arange(64), y]).mean(), 3), (probs.argmax(1) == y).mean())
x, y, where = makelookup(2000, np.random.defaultrng(999))
logits, cache = forward(p, x, 1, P)
print("accuracy", (softmax(logits[:, -1, :]).argmax(1) == y).mean())
w = cache["A"][:, 0, -1, :] # weights of the query position
print("weight on the matching pair", round(w[np.arange(2000), where].mean(), 3))
The loss falls from 6.611 to 0.002 within 500 steps, and the accuracy on 2,000 new examples is 1.0: all correct. The weight that the query position puts on the matching pair is 0.947 on average. The model has learned, from examples alone, the thing we set by hand: queries that point at matching keys, keys that advertise their key, values that carry their value.
This closes the gap that 3.1 left. Fixed weights, whether equal or learned, reach 42%. Attention reaches 100%, because it chooses where to look from the content.
What one attention layer costs
Attention is powerful and not cheap. Four quantities set its cost for a layer with model width d, a sequence of T tokens and h heads.
Parameters: four matrices of d by d (query, key, value and output): 4 times d squared.
Score matrices: one T by T matrix per head, h times T squared numbers per sequence.
Attention arithmetic: the scores and the weighted sums take about 2 times T squared times d multiply-adds.
Projection arithmetic: the four projections take about 4 times T times d squared multiply-adds.
The ratio of the attention arithmetic to the projection arithmetic is T divided by 2d. For short sequences the projections dominate. When T is greater than twice the width, the T-squared part takes over, and that is the cost Lesson 3.4 examines.
Key takeaways
Self-attention is a soft lookup. Each position makes a query, a key and a value. Scores are query-key dot products, a softmax turns them into weights, and the output is the weighted sum of the values.
The weights are the lower-triangular matrix of Lesson 3.1, now computed from the content. Three matrices, Wq, Wk and Wv, produce the three vectors, and a fourth, Wo, projects the result back.
Divide the scores by the square root of dk. A dot product of two random vectors of length dk has a spread of the square root of dk (2.0, 4.01, 8.03 and 15.97 for 4, 16, 64 and 256). Without scaling, the largest softmax weight rises from 0.53 to 0.94 and gradients vanish.
Attention is permutation equivariant: shuffle the inputs and the outputs shuffle the same way. Position vectors added to the token vectors supply the order. Removing them cost 0.044 in validation loss (1.0501 against 1.0061).
The mask sets the scores of the future to a large negative number so that their weights are zero. The residual connection keeps the token's own vector in the output.
The hand-written backward pass matches numerical gradients to eight digits.
On the toy language, one head with 2,112 numbers reaches 1.0061, close to the trigram (0.992) and the best possible (0.988), but barely better than fixed weights (1.0095). The language has no long-range structure to exploit.
On the lookup task, fixed weights score 42% and attention scores 100%, with 94.7% of its weight on the right pair.
The cost: 4 d squared parameters, h T squared score numbers, and attention arithmetic that exceeds the projections once T is greater than 2 d.
Common mistakes
Forgetting the square root. Without it, the scores grow with the vector length and the softmax saturates. Training slows or stalls.
Applying softmax over the wrong axis. The softmax must run over the keys, the last axis of the score matrix, so that each row sums to one.
Masking after the softmax. Setting weights to zero after the softmax leaves rows that no longer sum to one. Mask the scores first.
Leaving out positions. Without them the layer cannot tell the order of its inputs, except through the mask.
Mixing up the three matrices. Query and key must have the same length, because they are multiplied. The value can differ, and its length sets the length of the output.
Trusting a backward pass without a check. Always compare with numerical gradients before training.
Expecting a gain on every task. Attention helps where the useful token's position varies. On a language with fixed structure it matches simpler models.
Check yourself
1. In your own words, what do the query, key and value of a token do?
The query says what the token is looking for, the key says what it offers to be found by, and the value is what it passes on if another token attends to it.
2. Two random vectors of length 100 have independent entries with spread 1. About what is the spread of their dot product?
The square root of 100, which is 10.
3. Why does a softmax with very large scores make training slow?
The softmax output is nearly one-hot, and its gradient, which contains the factor of a weight times one minus that weight, is nearly zero. Little error signal reaches the earlier layers.
4. A layer has width d = 64 and uses a sequence of 512 tokens. Is the attention arithmetic larger or smaller than the projection arithmetic, and by what factor?
The ratio is T over 2d = 512 ÷ 128 = 4, so it is four times larger.
5. How many parameters do the four attention matrices have for d = 768?
4 × 768² = 4 × 589,824 = 2,359,296.
6. What does the residual connection do in the layer?
It adds the attention output to the input vector, so the token's own vector still reaches the output, and attention only adds what it gathered from other positions.
Try this
Set aside two hours. You need Python, NumPy, helpers.py and attention.py.
1. Run the hand-built lookup. Change the scale to 2, 4 and 16 and print the weight on the right pair and the accuracy for each. Where does it stop improving?
2. Run the scaling experiment, then change it to use 32 random keys in place of 8. How do the unscaled and scaled largest weights change?
3. Run the gradient check with a different seed and with h = 4. Do the gradients still agree?
4. Train the language model with d = 32 and with d = 8. How does the validation loss change, and how many parameters does each have?
5. Change the mask so that each position can also see one future token. Train, and see what happens to the validation loss. (Lesson 3.3 explains what you will see.)
6. Train the lookup task with five pairs and a window of six tokens. Does 100% still hold? What weight does the query put on the right pair?
7. Print the attention weights of the trained lookup model for one example. Does the query attend to the right position? What does position 4 attend to besides?
A good result is a hand-built attention that solves the lookup, a gradient check that agrees to eight digits, a language model at about 1.006 and a lookup model at 100%. The next lesson explains the mask properly, and shows what a model does when it is left out. It then uses several heads at once.
Read more
Ashish Vaswani and colleagues, "Attention Is All You Need" (2017), defines scaled dot-product attention and gives the reason for dividing by the square root of the key size. Jay Alammar's "The Illustrated Transformer" shows the same steps with pictures. Andrej Karpathy's lecture "Let's build GPT: from scratch, in code, spelled out" builds a single head step by step. Nelson Elhage and colleagues, "A Mathematical Framework for Transformer Circuits" (2021), describes what attention heads compute, with queries, keys and values as separate operations.
Tags: Build an LLM Self-attention Queries and keys Backpropagation Transformer