# What Are Queries, Keys and Values?

> How queries, keys and values let each word in a transformer find and weigh the other words, explained simply for your AI interview.

**In short:** Queries, keys and values are three vectors a transformer (the neural network design behind modern language models) builds from each token. The query is what a token looks for, the key is what it offers to be matched on, and the value is what it passes on when matched.

AI and LLM interview question Q044, Transformer architecture. Intermediate, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-are-queries-keys-and-values

## Say it in 30 seconds

Every token in a transformer becomes three vectors: a query, a key and a value. The query says what this word is looking for, and the key says what each word offers to be matched on. I take a dot product of the query with every key, turn those scores into weights with softmax, and blend the values by those weights. The three are learned in training, so their roles come from the data.

## Say it in 2 minutes

A transformer turns each token, a word or part of a word, into a list of numbers. From that list, each token makes three new lists, one for each job: a query, a key and a value. Each one is the token's list multiplied by a matrix of weights that the model learned during training. Attention then runs on those three lists.

Take a bank's dispute note: the customer disputed the card charge, and the bank refunded it after review. To work out what it means, the word it sends out a query and compares it with the key of every word in the note. The key of the charge matches best, so the charge's value gets the biggest share of the blend. That is the idea behind how a model links it to the charge, shown here with made-up numbers.

This is a soft lookup: every value gets some weight, and the output blends all of them. The paper's model runs several sets of the three side by side, called heads.

The roles are learned, so I say that plainly. Nobody wrote down what each vector means. Training sets the numbers, and the results show whether they work. Q045 and Q046 cover the scaling and the heads.

## What are queries, keys and values, in plain words?

A transformer turns each word, or token, into a list of numbers. From that list, each token makes three new lists, one for each job: a query, a key and a value. Think of a records clerk at an insurer. A request slip says what she needs, the labels on the files say what each file is about, and the file contents are what she hands over once a label matches.

Now the real case. A bank's dispute assistant reads this note: "The customer disputed the card charge. The bank refunded it after review." It has to work out that it means the charge. The word it sends out a query asking what it refers to. Every word in the note offers a key, and each value is passed on in proportion to how well its key matches.

- **Token:** A piece of text the model reads, often a whole word or part of one.
- **Query:** What this token is looking for, built from its vector.
- **Key:** What this token offers to be matched on, built from its vector.
- **Value:** The content this token passes on when its key is picked.
- **Attention weight:** A share, from 0 to 1, of how much one token listens to another.

## How do queries, keys and values work together?

For one token, the layer runs four steps. Every token runs the same steps in each layer, so a whole sentence is handled in one pass through that layer.

1. **Make the three vectors:** Multiply the token's vector by three weight matrices the model learned. That gives a query, a key and a value.
2. **Score each key:** Take the dot product of the query with every key. A dot product is one number that is larger when the two lists point the same way.
3. **Turn scores into weights:** Softmax makes the scores positive and scales them so they add up to 1. A higher score gets a bigger share.
4. **Blend the values:** Multiply each value by its weight and add them up. That blend is the token's new vector.

*Diagram, How one token builds its new vector: One token's vector goes through three learned matrices. Softmax turns the scores into weights, and the values are blended by those weights.*
1. The token's vector goes into the query matrix.
2. The same vector goes into the key matrix.
3. And into the value matrix.
4. The query is dotted with each key.
5. Each key gives its own score to that query.
6. Softmax turns the scores into shares that add up to 1.
7. The shares weight the values, which are added together.
8. Each value is multiplied by its share and passed in.

> "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors." (Vaswani et al., Attention Is All You Need (2017))

The paper multiplies each token's vector by different, learned matrices to make the three, so nobody sets their roles by hand. Every token keeps some share of the blend, and a strong match takes the biggest share.

The paper also scales the dot products to counteract their growth with key size. The authors suspect that very large dot products leave the softmax learning very little, which slows training. That is the subject of Q045.

The paper's model runs several sets of the three at once, called heads, and combines their outputs (Q046). The paper says multi-head attention lets the model jointly attend to information from different representation subspaces at different positions.

## What does one lookup look like with numbers?

Back to the dispute note. The word it sends out a query, and each word in the note offers a key. The picture shows the matching step for that one word.

*Diagram, The word it finds its noun: A simplified picture of one attention step for the word it. The charge's key matches best, so its value gets the largest share. The weights are made up.*
1. The query for it is compared with the customer's key.
2. It is also compared with the charge's key, a strong match.
3. And with the bank's key, a weaker match.
4. The strongest match earns the biggest weight.
5. The charge's value is blended in, so it reads as the charge.

Here is the same step in a few lines of Python, with made-up numbers.

```python
import math

# Made-up 2-number vectors for three words in the note (a real model uses far longer vectors).
keys = {"customer": [0.2, 0.9], "charge": [0.9, 0.3], "bank": [0.4, 0.5]}
values = {"customer": [1.0, 0.0], "charge": [0.0, 1.0], "bank": [0.5, 0.5]}
query = [1.0, 0.2]  # built from the word "it"

# Score = query dot key: a bigger number means a better match.
scores = {w: sum(q * k for q, k in zip(query, key)) for w, key in keys.items()}

# Softmax turns the scores into weights that are all positive and add up to 1.
total = sum(math.exp(s) for s in scores.values())
weights = {w: math.exp(s) / total for w, s in scores.items()}

# The output is a weighted blend of the values.
out = [sum(weights[w] * values[w][i] for w in keys) for i in range(2)]

for w in keys:
    print(f"{w:<9} score {scores[w]:.2f}  weight {weights[w]:.2f}")
print(f"blend     {out[0]:.2f} {out[1]:.2f}")
```

Output:

```text
customer  score 0.38  weight 0.26
charge    score 0.96  weight 0.46
bank      score 0.50  weight 0.29
blend     0.40 0.60
```

The charge's key takes the biggest weight, so the blend leans toward the charge's value. Real models do this with much longer vectors and several sets at once, but the steps stay the same.

## Where do the three come from in self-attention and cross-attention?

The three always come from some sequence. Two cases come up often.

- **Self-attention: One sequence, one source.** The queries, keys and values all come from the same tokens, such as the previous layer's output. Every token can look at every other token in that sequence.
- **Cross-attention: Two sequences.** The queries come from one sequence, such as the text being written. The keys and values come from another, such as the source text. In the paper's translation model, the decoder (the part that writes the output) asks, and the encoder (the part that reads the input) answers.

The paper uses both kinds. Its encoder uses self-attention, so each token reads the whole input. Its decoder uses encoder-decoder attention, which reads the encoder's output. The decoder's own self-attention only looks at positions up to and including the current one, so it cannot read words it has yet to write.

### How would you check that attention links the right words?

A dispute assistant keeps linking it to the bank instead of the charge. One example proves little, so you test the pattern across real cases.

1. **Collect real cases:** Pull around 200 dispute notes where the team has already marked the right noun for each pronoun. Remove names and card numbers first.
2. **Read the top links and sort the misses:** For each pronoun, find the word with the largest weight and record whether it is the right noun. Group the wrong links by type, such as charges, people or dates. A pattern in the misses points to the fix.
3. **Test the final answer:** A link can look right and still lead to a wrong answer. Measure the final answers on the same cases before and after any change.

> **Tip:** Treat a high weight as a clue, and check final answers on real cases.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Each token makes a query, a key and a value by multiplying its vector with three learned matrices.
- [ ] The query is scored against every key with a dot product, then softmax turns the scores into weights.
- [ ] The output is a weighted blend of the values, so attention is a soft lookup.
- [ ] Self-attention takes all three from one sequence; cross-attention takes queries from one and keys and values from another.
- [ ] Keys and values are split so a token can be matched on one thing and pass on another.
- [ ] The roles are learned, and I check them by results.

**Common traps**

- Trap: "The key and the value are the same vector." Better: They come from the same token but are separate projections, so the match and the content can differ.
- Trap: "Each vector has a fixed meaning, like noun or verb." Better: The roles are learned. Nobody labels them, and the results show whether they work.
- Trap: "Attention picks the one best record and returns it." Better: It is a soft lookup. Every value gets a weight, and the output is the blend.

## Can you spot the right description?

**Spot the error:** Your dispute assistant's design doc describes its attention step. Which sentence is correct?

A. The values are compared with the query, and the keys are blended into the output.
B. The query is compared with each key, softmax turns those scores into weights, and the values are blended.
C. Softmax keeps the raw scores, so the largest key wins outright and the rest are ignored.
D. Each token has one shared vector that serves as its query, key and value at once.

**Answer:** B. Queries are scored against keys. Softmax gives every key a share, so no single winner takes all. The output blends the values. Learned matrices make three separate vectors from each token.

**Quick check:** Your loan-letter translator uses cross-attention. In that setup, where do the keys and values come from?

A. The same tokens as the queries
B. A different sequence, such as an encoder's output
C. A fixed table of word meanings that never changes
D. Only the last token in the prompt

**Answer:** B. In cross-attention the queries come from one sequence and the keys and values come from another. In the paper's translation model, that other sequence is the encoder's output.

## Can you answer these from memory?

**Flash cards**

- **What is a query?** What this token looks for. Built from its vector by a learned matrix.
- **What is a key?** What this token offers to be matched on. Each query is scored against it.
- **What is a value?** The content passed on, blended by the weights when its key matches.
- **How is a score made?** A dot product of one query with one key. Bigger means a closer match.
- **What does softmax do?** Turns the scores into positive weights that add up to 1.
- **Self vs cross-attention?** Self: all three from one sequence. Cross: queries from one, keys and values from another.

## Likely follow-up questions

- Q043 What is self-attention? https://designervenkat.online/interview/ai/what-is-self-attention
- Q045 Why scale attention scores by √d_k? https://designervenkat.online/interview/ai/why-scale-attention-scores-by-square-root-of-d-k
- Q046 What is multi-head attention? https://designervenkat.online/interview/ai/what-is-multi-head-attention
- Q047 What is positional encoding, and why is it needed? https://designervenkat.online/interview/ai/what-is-positional-encoding
- Q050 What is causal (masked) attention? https://designervenkat.online/interview/ai/what-is-causal-masked-attention
- Q051 What is cross-attention? https://designervenkat.online/interview/ai/what-is-cross-attention

## Learn it in depth

- [Attention Mechanisms](https://designervenkat.online/learn/machine-learning/attention-mechanisms)
- [Self-Attention](https://designervenkat.online/learn/machine-learning/self-attention)
