Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 10. Inside the transformer
  4. 10.1

Lesson 10.1 · 1 of 7 · 7 min read · Reviewed 24 Nov 2026

Queries, keys and values

By the end, you can

  • Compute an attention output from queries, keys and values for a few tokens.
  • Explain why the scores are divided by the square root of the key size.

Lesson 2.3 described attentionAttention: The mechanism that lets each token weigh every other token in the context when building its representation. as each tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. asking “which of you matter for understanding me?”. This lesson opens the box and shows the arithmetic. It needs only dot products and the softmax from lesson 9.2.

Three roles for every token

In each attention layer, every token’s vector x is multiplied by three learned weight matrices:

Vector Made by Plays the role of
Query q x times W_Q What this token is looking for
Key k x times W_K What this token offers, used for matching
Value v x times W_V What this token passes on if it is chosen

A library is a fair picture: your query is the search, each book’s key is its catalogue entry, and the value is the book’s content. The difference is that attention never picks just one book. It takes a little from every book, in proportion to how well the catalogue entry matched.

The recipe

For one token:

  1. Score every token: dot product of this token’s query with each key.
  2. Scale each score by dividing by the square root of the key length, sqrt(d_k).
  3. Softmax the scores into weights that are positive and sum to 1.
  4. Mix: the output is the sum of each value vector times its weight.
attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V

A worked example

Three tokens, vectors of length 2 (real models use 64 or 128 per head). We compute the output for sat, whose query is [1, 0].

Token Key q . k / sqrt(2) Weight Value
the [0, 1] 0 0.00 0.14 [1, 0]
cat [2, 0] 2 1.41 0.58 [0, 1]
sat [1, 1] 1 0.71 0.28 [0.5, 0.5]

Output = 0.14 x [1, 0] + 0.58 x [0, 1] + 0.28 x [0.5, 0.5] = [0.28, 0.72]. The new vector for sat is now mostly made of cat’s value: the verb has picked up information about its subject. Every token does the same at the same time, which is why it is all one matrix multiply on a GPU.

Why divide by sqrt(d_k)?

Dot products of long vectors get large. With 128 numbers per vector, raw scores can easily be in the tens, and softmax of big numbers puts almost all the weight on one token. That makes the gradients tiny and training slow. Dividing by sqrt(d_k) keeps the scores in a range where softmax still spreads weight and learning still works.

The causal mask

A model that writes text left to right must not peek at tokens it hasn’t written yet. In a decoder, scores for later positions are set to minus infinity before the softmax, so their weights become exactly 0. the can attend only to itself; sat can attend to all three. Lesson 10.4 compares this with encoders, which attend both ways.

Common mistakes

  • ThinkingExtended thinking: A mode in which the model reasons step by step in thinking blocks before giving its final answer. Q, K and V are three different inputs. In self-attention they are three views of the same tokens.
  • Reading the weights as fixed. They are computed fresh for every token, every layer and every prompt.
  • Forgetting that weights sum to 1. Attention redistributes focus. A token can’t attend strongly to everything at once.

Key points

  • Each token's vector is multiplied by three learned matrices to make a query (what it is looking for), a key (what it offers) and a value (what it passes on).
  • A token's attention scores are its query dotted with every key, divided by the square root of the key size, then turned into weights with softmax.
  • The output is the weighted average of the value vectors, so it is a blend of the tokens it attended to.
  • In a decoder, a causal mask stops each token attending to tokens after it.
Hands-on labRuns in the Playground

Compute attention for three tokens

Turn queries, keys and values into attention weights and an output vector, with and without scaling and masking.

You will have: A function attend(token) that reproduces the lesson's weights and output, plus scaled, unscaled and causal runs.

Steps

  1. Read the query, key and value vectors for the, cat and sat.
  2. Add the scaling by sqrt(d_k) and the causal mask inside attend.
  3. Fill in the output: the weighted sum of the value vectors.
  4. Run it and compare with the lesson table.
  5. Turn scaling off and see the weight on cat rise; turn the mask on for the first token.

Done when

  • Weights print as the 0.14, cat 0.58, sat 0.28.
  • The output is [0.28, 0.72].
  • With the causal mask, the first token puts all its weight on itself.

Open in the Playground No API key needed.

Starter code (Python)
import math

TOKENS = ["the", "cat", "sat"]
Q = {"the": [0, 1], "cat": [1, 1], "sat": [1, 0]}
K = {"the": [0, 1], "cat": [2, 0], "sat": [1, 1]}
V = {"the": [1, 0], "cat": [0, 1], "sat": [0.5, 0.5]}

def dot(a, b):
    return sum(x * y for x, y in zip(a, b))

def softmax(scores):
    m = max(scores)
    exps = [math.exp(s - m) for s in scores]
    total = sum(exps)
    return [e / total for e in exps]

def attend(token, causal=False, scale=True):
    i = TOKENS.index(token)
    q = Q[token]
    scores = []
    for j, other in enumerate(TOKENS):
        s = dot(q, K[other])
        # TODO: if scale, divide s by sqrt(len(q)).
        # TODO: if causal and j > i, set s to float("-inf") so a decoder can't look ahead.
        scores.append(s)
    weights = softmax(scores)
    # TODO: the output is the weighted sum of the VALUE vectors: for each dimension d,
    #       sum weights[j] * V[TOKENS[j]][d].
    out = [0.0, 0.0]
    return weights, out

weights, out = attend("sat")
print("weights:", " ".join(f"{t} {w:.2f}" for t, w in zip(TOKENS, weights)))
print("output:", [round(x, 2) for x in out])

w_noscale, _ = attend("sat", scale=False)
print("without sqrt(d_k), weight on cat:", round(w_noscale[1], 2))

w_first, out_first = attend("the", causal=True)
print("causal, first token weights:", [round(w, 2) for w in w_first])
Show a solution
import math

TOKENS = ["the", "cat", "sat"]
Q = {"the": [0, 1], "cat": [1, 1], "sat": [1, 0]}
K = {"the": [0, 1], "cat": [2, 0], "sat": [1, 1]}
V = {"the": [1, 0], "cat": [0, 1], "sat": [0.5, 0.5]}

def dot(a, b):
    return sum(x * y for x, y in zip(a, b))

def softmax(scores):
    m = max(scores)
    exps = [math.exp(s - m) for s in scores]
    total = sum(exps)
    return [e / total for e in exps]

def attend(token, causal=False, scale=True):
    i = TOKENS.index(token)
    q = Q[token]
    scores = []
    for j, other in enumerate(TOKENS):
        s = dot(q, K[other])
        if scale:
            s = s / math.sqrt(len(q))
        if causal and j > i:
            s = float("-inf")          # a decoder can't look ahead
        scores.append(s)
    weights = softmax(scores)
    out = [sum(w * V[t][d] for w, t in zip(weights, TOKENS)) for d in range(2)]
    return weights, out

weights, out = attend("sat")
print("weights:", " ".join(f"{t} {w:.2f}" for t, w in zip(TOKENS, weights)))
print("output:", [round(x, 2) for x in out])

w_noscale, _ = attend("sat", scale=False)
print("without sqrt(d_k), weight on cat:", round(w_noscale[1], 2))

w_first, out_first = attend("the", causal=True)
print("causal, first token weights:", [round(w, 2) for w in w_first])
Quick checkIn self-attention, where do the queries, keys and values for a sentence come from?
How sure are you?
Pick an answer and how sure you are