Attention as Soft Lookup: Queries, Keys and Values
Attention explained as a soft dictionary lookup: queries are scored against keys, the scores become weights with a softmax, and the output is a weighted average of the values. Measure why scores are divided by the square root of the key size, compute self-attention and a causal mask by hand, and check the result against PyTorch.
Contentsand lesson path
On this page
- Why it matters
- From a dictionary lookup to a soft lookup
- Scaled dot-product attention
- Self-attention and the causal mask
- Check your understanding
- Apply it
- Review prompt
Lessons of Transformer Architecture
- Attention as Soft Lookup: Queries, Keys and Values Concept · 20 min
- Lab: Build Multi-Head Causal Self-Attention from Scratch Lab · 30 min
- Anatomy of a Transformer Block and the Three Model Families Concept · 25 min
- Tokens In, Tokens Out: Tokenizers, Decoding Controls and the KV Cache Concept · 25 min
- Lab: Fine-Tune a Pretrained Encoder for Classification Lab · 30 min
- Check: Inside the Transformer Knowledge check · 8 questions
What you will learn
- Implement scaled dot-product and multi-head self-attention with causal masking in PyTorch and verify output shapes and masking behaviour.
Prerequisites: Deep Learning Fundamentals
01. Why it matters
Every transformer, from a sentence classifier to a large language model, is built around one operation: attention. It lets each position in a sequence build its new representation from the other positions, weighting each one by how relevant it is. In the lesson on why recurrence hit a wall you met attention as an add-on that let a decoder look back at encoder states. Transformers keep only the attention and drop the recurrence, so every position can look at every other position in one step, and all positions are computed in parallel.
This lesson builds attention from the smallest possible example up to the form used in real models, with PyTorch code you can run on a laptop. The next lesson, the multi-head attention lab, turns it into a reusable module. You need Python 3.12 and PyTorch 2; the CPU build is enough.
02. From a dictionary lookup to a soft lookup
A Python dictionary does a hard lookup: you give it a key, it finds the one entry with exactly that key and returns its value. Attention does a soft lookup with three kinds of vectors. A query describes what you are looking for. Each entry has a key, which describes what it offers, and a value, which is what it returns. Instead of requiring an exact match, attention scores the query against every key with a dot product, turns the scores into positive weights that sum to 1 with a softmax, and returns the weighted average of all the values.
"""A dictionary lookup, then the same lookup done softly with dot products."""
import torch
names = ["cat", "dog", "car"]
keys = torch.tensor([[1.0, 0.0], [0.8, 0.6], [0.0, 1.0]]) # one key per entry
values = torch.tensor([[10.0, 0.0], [0.0, 10.0], [5.0, 5.0]]) # what each returns
print("hard lookup of 'dog':", values[names.index("dog")].tolist())
queries = torch.tensor([[3.0, 0.0], [2.0, 2.0], [0.0, 0.0]])
for query in queries:
scores = keys @ query # how well the query matches each key
weights = torch.softmax(scores, dim=0) # positive, and they sum to 1
output = weights @ values # weighted average of the values
print(f"query {query.tolist()}: scores {[round(s, 2) for s in scores.tolist()]}")
print(f" weights {[round(w, 3) for w in weights.tolist()]} "
f"-> output {[round(o, 2) for o in output.tolist()]}")python soft_lookup.pyhard lookup of 'dog': [0.0, 10.0]
query [3.0, 0.0]: scores [3.0, 2.4, 0.0]
weights [0.626, 0.343, 0.031] -> output [6.41, 3.59]
query [2.0, 2.0]: scores [2.0, 2.8, 2.0]
weights [0.237, 0.527, 0.237] -> output [3.55, 6.45]
query [0.0, 0.0]: scores [0.0, 0.0, 0.0]
weights [0.333, 0.333, 0.333] -> output [5.0, 5.0]The first query points in the same direction as the "cat" key, so "cat" gets the largest weight (0.626), "dog", whose key is similar, gets a fair share, and "car" almost nothing; the output is mostly the "cat" value with some "dog" mixed in. The second query matches "dog" best. The zero query scores every key the same, so the weights are equal and the output is the plain average of the three values. Two properties matter for what follows. The output is always a blend of values, never something outside them. And every step is differentiable, so a network can learn what its queries, keys and values should be, which a hard lookup would not allow.
03. Scaled dot-product attention
With many queries at once, stack them as the rows of a matrix Q, the keys as rows of K and the values as rows of V. Then all scores are one matrix product, and scaled dot-product attention is
Attention(Q, K, V) = softmax(Q Kᵀ / √d_k) V
where d_k is the length of each query and key vector, and the softmax runs along each row, so each query gets its own weights. Why divide by √d_k? A dot product adds up d_k products. If the entries are random with variance 1, the sum has variance d_k, so its typical size grows like √d_k. The script measures this, then shows what large scores do to the softmax.
"""Why scores are divided by sqrt(d_k): dot products grow with the dimension."""
import torch
torch.manual_seed(0)
for d in (4, 64, 256):
q, k = torch.randn(10_000, d), torch.randn(10_000, d) # unit-variance entries
dots = (q * k).sum(-1)
print(f"d_k={d:3d}: std of q.k {dots.std():5.1f} (sqrt(d_k) = {d ** 0.5:4.1f}), "
f"after scaling {(dots / d ** 0.5).std():.2f}")
d = 256
q, k = torch.randn(d), torch.randn(8, d) # one query, eight keys
for name, scores in (("unscaled", k @ q), ("scaled ", k @ q / d ** 0.5)):
w = torch.softmax(scores, dim=0)
grad = w * (1 - w) # d(weight)/d(own score) for each key
print(f"{name}: largest weight {w.max():.3f}, "
f"largest softmax slope {grad.max():.4f}")python scaling.pyd_k= 4: std of q.k 2.0 (sqrt(d_k) = 2.0), after scaling 1.00
d_k= 64: std of q.k 8.0 (sqrt(d_k) = 8.0), after scaling 1.00
d_k=256: std of q.k 16.1 (sqrt(d_k) = 16.0), after scaling 1.01
unscaled: largest weight 1.000, largest softmax slope 0.0000
scaled : largest weight 0.584, largest softmax slope 0.2429The standard deviation of the dot products is 2, 8 and 16 for d_k = 4, 64 and 256, exactly √d_k, and dividing by √d_k brings it back to about 1. Without the scaling, eight keys at d_k = 256 give one weight of 1.000 and the others almost 0: the softmax has saturated and behaves like a hard lookup. That hurts learning. The slope of a softmax weight with respect to its own score is w(1 − w), which is 0 when w is 0 or 1, so the gradient that would teach the queries and keys almost vanishes. With scaling, the largest weight is 0.584 and the slope is a healthy 0.24.
04. Self-attention and the causal mask
In self-attention, the queries, keys and values all come from the same sequence. Each token embedding x is multiplied by three learned matrices, W_q, W_k and W_v, to give its query, key and value. The score matrix then has one row per query position and one column per key position, so row i says how token i mixes the values of all tokens into its output.
Why three separate projections rather than scoring the embeddings against each other directly? Because a token often needs to look for something different from what it is. A verb may need to find its subject, which does not look like a verb. Scoring x @ x.T compares each token with itself as well as with the others, and a vector usually matches itself best. The script checks this, and then applies a causal mask, which a model that predicts the next token needs: position i may only use positions 0 to i, never later ones, or it could read the answer it is meant to predict. The mask sets the forbidden scores to −∞ before the softmax, so their weights become exactly 0. masked_fill writes where its mask is True, so the script fills where allowed is False.
"""Self-attention for one 4-token sequence, without and with a causal mask."""
import torch
import torch.nn.functional as F
torch.manual_seed(0)
T, d_model, d_k = 4, 8, 8
x = torch.randn(T, d_model) # one embedding per token
W_q, W_k, W_v = (torch.randn(d_model, d_k) / d_model ** 0.5 for _ in range(3))
raw = torch.softmax(x @ x.T / d_k ** 0.5, dim=-1) # compare embeddings directly
print("x @ x.T: each row's largest weight is on column", raw.argmax(-1).tolist())
q, k, v = x @ W_q, x @ W_k, x @ W_v # queries, keys and values: (T, d_k) each
scores = q @ k.T / d_k ** 0.5 # (T, T): row i = how query i matches every key
weights = torch.softmax(scores, dim=-1)
print("with projections, largest weight per row on column", weights.argmax(-1).tolist())
allowed = torch.tril(torch.ones(T, T, dtype=torch.bool)) # True on and below diagonal
causal = torch.softmax(scores.masked_fill(~allowed, float("-inf")), dim=-1)
print("causal weights (row = query position, column = key position):")
for row in causal:
print(" ", " ".join(f"{w:.2f}" for w in row.tolist()))
out = causal @ v
ref = F.scaled_dot_product_attention(q[None], k[None], v[None], is_causal=True)[0]
print("output shape", tuple(out.shape), "| matches F.scaled_dot_product_attention:",
torch.allclose(out, ref, atol=1e-6))python self_attention.pyx @ x.T: each row's largest weight is on column [0, 1, 2, 3]
with projections, largest weight per row on column [2, 3, 3, 2]
causal weights (row = query position, column = key position):
1.00 0.00 0.00 0.00
0.40 0.60 0.00 0.00
0.38 0.59 0.04 0.00
0.09 0.13 0.68 0.10
output shape (4, 8) | matches F.scaled_dot_product_attention: TrueWith raw embeddings, every token gives its largest weight to itself. With the projections, even random ones, the largest weights move to other positions: what a token asks for and what it offers are now separate, and training shapes both. In the causal weights, everything above the diagonal is 0. The first token can only attend to itself, so its row is 1.00 followed by zeros. Row 3 builds its output mostly from token 2 (0.68). Each row still sums to 1.
The last line compares the hand-written version with torch.nn.functional.scaled_dot_product_attention, which does the same computation with is_causal=True. In real code, prefer the built-in function: on GPUs it dispatches to fused kernels such as FlashAttention that never store the full score matrix. That matters because the score matrix has T × T entries: doubling the sequence length makes it four times larger. A padding mask works the same way as the causal mask: in a batch of sequences padded to equal length, it hides the pad positions as keys so that no token attends to them.
05. Check your understanding
06. Apply it
Start the practice project, a small decoder-only transformer:
- Write
attention(q, k, v, causal)for tensors of shape (batch, T, d_k), using the formula from this lesson and a boolean causal mask. - Test it against
F.scaled_dot_product_attentionfor T = 1, 5 and 64, with and without the mask. - Print the weight matrix for one short sequence and check by eye that the masked entries are zero and every row sums to 1.
07. Review prompt
Without looking back, explain the roles of queries, keys and values; write the formula for scaled dot-product attention and say along which axis the softmax runs; explain why the scores are divided by √d_k and what goes wrong without it; describe what a row of the weight matrix means; and explain how a causal mask is applied and why a next-token model needs it.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.