Lesson 6 of 96 min
Queries, keys, values and heads
Each token makes a query, a key and a value; a share comes from a query's dot product with each key, divided and put through softmax, and the shares blend the values.
After this lesson you can compute attention weights by hand for a tiny example.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Write attention in one line
Stack the queries, keys and values in rows. The blend is softmax(Q @ K.T / sqrt(d_k)) @ V, where d_k is how many numbers are in each key. Softmax runs across the keys so each query gets a row of shares. Attention Is All You Need
import torch
q_seal = torch.tensor([2., 0., 1., 0.])
k = torch.tensor([[1., 0., 2., 0.], [0., 2., 0., 1.],
[0., 1., 0., 2.], [1., 1., 0., 0.]])
v = torch.tensor([[2., 1., 0., 0.], [0., 0., 2., 1.],
[0., 1., 1., 0.], [1., 0., 0., 2.]])
scores = q_seal @ k.T
shares = (scores / k.size(-1)**0.5).softmax(dim=-1)
print(scores, shares, shares @ v, sep="\n")tensor([4., 0., 0., 2.]) tensor([0.6103, 0.0826, 0.0826, 0.2245]) tensor([1.4451, 0.6929, 0.2478, 0.5316])
Read the trained matrices
In layer 7 of Qwen3-0.6B-Base, 16 query heads of 128 numbers take in 1,024 numbers and produce 2,048. PyTorch stores linear weights as [outputs, inputs], so q_proj.weight is [2048, 1024]. The tiny model stores Wq the other way around so it can write x @ Wq. Qwen configuration · PyTorch Linear
from transformers import AutoConfig
name = "Qwen/Qwen3-0.6B-Base"
revision = "da87bfb608c14b7cf20ba1ce41287e8de496c0cd"
config = AutoConfig.from_pretrained(name, revision=revision)
width = config.hidden_size
query_width = config.num_attention_heads * config.head_dim
kv_width = config.num_key_value_heads * config.head_dim
print("q_proj", (query_width, width))
print("k_proj, v_proj", (kv_width, width))
print("o_proj", (width, query_width))q_proj (2048, 1024) k_proj, v_proj (1024, 1024) o_proj (1024, 2048)
See why scaling helps
When query and key components are independent with variance one and mean zero, a dot product’s typical size grows with the square root of its length. Scaling by that amount keeps scores from spreading out. With very spread-out scores, softmax can give almost everything to one key, where its gradients get small. Attention Is All You Need
import torch
torch.manual_seed(7)
for width in (4, 128):
q = torch.randn(4096, width)
k = torch.randn_like(q)
raw = (q * k).sum(dim=-1)
print(width, round(raw.std().item(), 1), round((raw / width**0.5).std().item(), 1))4 2.0 1.0 128 11.3 1.0
Join the heads
Each query head produces its own blend. Join the 16 blends end to end and o_proj maps those 2,048 numbers back to 1,024 per token. A small output layer shows the same change of shape. Attention Is All You Need, section 3.2.2
import torch
head1 = torch.tensor([[1.4451, 0.6929, 0.2478, 0.5316]])
head2 = torch.tensor([[0.4, 0.1, -0.2, 0.8]])
joined = torch.cat((head1, head2), dim=-1)
output = torch.nn.Linear(8, 4, bias=False)(joined)
print(joined.shape, output.shape)torch.Size([1, 8]) torch.Size([1, 4])
Share keys and values across heads
Qwen’s 16 query heads use eight sets of keys and values. Each pair of query heads shares one set. That halves the key and value entries stored per token compared with giving every query head its own set. Each query head still gets its own shares and blend. Qwen model configuration · PyTorch scaled dot-product attention
# Two heads share one key/value head. Their queries look in different directions.
import torch
from torch.nn import functional as F
queries = torch.tensor([[[[3., 0.]], [[0., 3.]]]])
keys = torch.tensor([[[[1., 0.], [0., 1.]]]])
values = torch.tensor([[[[1.], [0.]]]])
print(F.scaled_dot_product_attention(queries, keys, values, enable_gqa=True).flatten())tensor([0.8930, 0.1070])
Keep the future out
In causal self-attention, a token sees itself and the tokens before it. With is_causal=True, the first query in the example below can use only the first value. The second query has the same scores but can use both values, so it gets their average. PyTorch scaled dot-product attention
import torch
from torch.nn import functional as F
q = k = torch.zeros(2, 2)
v = torch.tensor([[2.], [6.]])
print(F.scaled_dot_product_attention(q, k, v, is_causal=True).flatten())tensor([2., 4.])
Run on Python 3.13, PyTorch 2.15.0, Transformers 5.24.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The dot product
You rate two movies [1, 2]. A friend rates them [2, -2]. What is your dot product?
2 of 3
In the tiny model, the query of "seal" matches Penguins' key best. What does "seal" take in?
3 of 3
In a tiny model whose keys have four numbers, "swim" sees two tokens: "Seals", key [1, 0, 2, 0], and itself, key [0, 2, 0, 1]. Its query is [2, 0, 0, 0]. What share does it give "Seals"?
The ideas in this lesson
- Query and key
- Each token makes a query, what it looks for, and a key, what it has to offer: its vector times two learned matrices.
- Scaled dot-product attention
- A query's dot product with each key, divided by the square root of the key's size, softmax, then the values blended.
- Heads
- Several sets of query, key and value matrices side by side, each scoring its own way; their blends are joined.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Queries, keys and values
Here's a problem. "Seal" looks for the words it needs. It compares itself with each word before it. But the word most like "seal" is "seal" itself. So how does it find "penguin"?
A tiny model
Does it skip itself?
Does it compare something else?
Hold on to your guess. Let's work it out by hand, in a tiny made-up model.
Four tokens: "Penguins fear the seal." Each token is a vector of just four numbers. Here, "Penguins" is the word that tells "seal" which seal it is.
A vector matches itself
In attention, each token gives every token before it, and itself, a share of its attention. Then it takes in a blend. Suppose "seal" scored each token with the token's own vector. Take the dot product: multiply the matching numbers, and add them up. Against Penguins: one. Fear: one. "The": two. And against itself: four, the biggest. Skip itself, and "the" still beats "Penguins". So comparing vectors finds words like "seal". Not the words "seal" needs.
A query and a key
So each token makes two new vectors from its own. Each one is its vector times a matrix the model learned.
A query: what it's looking for. A key: what it has to offer.
So a query is like a question, and a key is like a label. Seal's query is two, zero, one, zero.
Query times key
Which key will match seal's query best? Guess, then work it out.
Penguins' key is one, zero, two, zero. Against seal's query: two times one, plus one times two.
Four. Fear's key and the key of "the": zero. Its own key: two.
These are the scores.
Divide first
Each token makes a query and a key, and a score is the query's dot product with a key. Softmax, from Deep Learning, turns the scores into shares that add up to one. But first, each score is divided. Why? Keys with more numbers give bigger scores. Here's a real model. Its keys have a hundred and twenty-eight numbers. It reads "The penguin swam away from the seal." With the scores divided, "seal" gives "penguin" a little more than half.
Now watch it without the dividing.
Softmax gives "penguin" everything, and every other token zero. No blend is left. So each score is divided by the square root of how many numbers a key has.
Then softmax
Back in the tiny model, each key has four numbers. The square root of four is two, so divide by two.
The scores become two, zero, zero, one.
Then softmax turns the scores into shares.
The picture does the math.
Which token gets the biggest share?
Penguins gets more than half.
Fear and "the" get less than a tenth each.
Seal itself gets a little over a fifth.
The values
Shares of what?
Each token makes a third vector, with a third matrix: its value. That's what it passes on.
The blend is every value times its share, added up. Most of it comes from Penguins' value.
Why a third vector? Because what makes a token easy to find isn't always what it should pass on. So Penguins' key and Penguins' value are different numbers.
Not a lookup
So the query found Penguins' key. Does it just get Penguins' value, like looking up a word in a list? A lookup would give two, one, zero, zero.
Attention gives the blend. Every value is in it, and Penguins' most of all.
Heads
Each token makes a query, a key and a value, each from its own matrix. One set of matrices scores one way. So a model runs several sets side by side. They're called heads. In head two, seal's query finds "fear", with about two thirds of its share. Each head's blend is joined to the others'. Then one more matrix turns them back into one vector. The real model has sixteen heads in each of its twenty-eight layers, and each head looks for something different.
In code
Now in real code. Here are the tiny model's queries, keys and values, as three PyTorch arrays. Seal's shares: its query times every key, divided by two, then softmax. What will it print?
The same shares we worked out by hand. The blend is the shares times the values.
Then PyTorch's own call does it all at once, and a check says the numbers match.
In PyTorch, most models calculate attention with this same call.
Three ideas
So each token makes a query, a key and a value. A score is a query times a key, divided, then softmax. The shares blend the values. And heads do it several ways at once.
The lab
That's the end of this unit. In the lab, you use these three lessons to write attention by hand. Then you check it against PyTorch's own.
A query, the keys, a blend
Attention matches a query with every key, then mixes the values. Now try it on this lesson's page, and take the quiz. Work out a row in head two.
You use this lesson in Lab 2: Attention, written by hand, which comes next.
Facts last checked on .
