AI & prompting

Attention Mechanism Explained: Queries, Keys and Values

An attention mechanism lets each token in a sequence build its new representation as a weighted average of the other tokens, with the weights computed from how well its query matches their keys. In a Transformer this is the formula Attention(Q, K, V) = softmax(QK^T / √d_k) V, applied in parallel by many heads in every layer.

That one line is the core of every current large language model. The rest of this article unpacks it with numbers small enough to check by hand.

The problem attention solved

Before attention, neural translation models read a sentence into a single fixed-length vector and generated the translation from that vector alone. Bahdanau, Cho and Bengio called this "a bottleneck" in their 2014 paper: long sentences had to be squeezed into the same number of values as short ones. Their fix let the decoder "search" softly over all the encoded source words at each step and take a weighted mix of the relevant ones.

In 2017, Vaswani et al. took the idea further in Attention Is All You Need: the Transformer drops recurrence entirely and builds the whole model from attention plus small feed-forward layers. Because every position can be processed at once instead of one word after another, training parallelises far better.

Queries, keys and values

Each token starts as a vector (its embedding plus position information). In every attention layer the model multiplies that vector by three learned weight matrices to get three new vectors:

  • Query (Q): what this token is looking for.
  • Key (K): what this token offers, used to decide whether it matches someone's query.
  • Value (V): the information this token passes on if it is attended to.

The analogy is a soft lookup table. A normal dictionary returns the one value whose key matches exactly. Attention compares the query with every key, turns the match scores into weights that sum to 1, and returns a blend of all the values.

The formula, step by step

  1. Score. Take the dot product of the query with each key. A larger dot product means a better match.
  2. Scale. Divide by √d_k, the square root of the key length. The paper's reason: for large d_k the dot products grow large, "pushing the softmax function into regions where it has extremely small gradients", which makes training stall.
  3. Softmax. Turn the scores into weights between 0 and 1 that add up to 1.
  4. Mix. Multiply each value vector by its weight and add them up. The result is the token's output from this attention layer.

Done for all tokens at once, these steps are the matrix formula: QK^T computes every query-key score in one multiplication, and multiplying the softmaxed score matrix by V does all the mixing.

A worked example you can check

Take a three-token sequence, "The cat sat", with tiny 2-dimensional vectors (the original Transformer used 64 per head). Suppose the query for the token being updated is q = [1, 0], and the keys and values are:

TokenKeyValueq · k÷ √2Softmax weight
The[0, 1][1, 0]00.0000.198
cat[1, 0][0, 1]10.7070.401
sat[1, 1][1, 1]10.7070.401

The softmax step: e^0 = 1 and e^0.707 ≈ 2.028, so the weights are 1 / 5.056 ≈ 0.198 and 2.028 / 5.056 ≈ 0.401. The output is the weighted sum of values:

0.198 × [1, 0] + 0.401 × [0, 1] + 0.401 × [1, 1] = [0.599, 0.802]

"cat" and "sat" matched the query, so their values dominate the result; "The" still contributes about 20%, because softmax never gives exactly zero. In a trained model, the weight matrices that produce Q, K and V are learned so that useful matches score high: for example, a pronoun's query can learn to line up with the key of the noun it refers to.

Multi-head attention

One set of weights can only express one kind of match at a time. The Transformer runs several attention operations in parallel, each with its own Q, K and V projections, and concatenates their outputs. The original paper used 8 heads with d_k = d_v = 64 each, which together make up the model width of 512. Different heads can track different relationships, for example one following syntax and another following nearby tokens, and the layer combines them with one more learned matrix.

Self-attention, cross-attention and masking

The original Transformer uses attention in three places:

  • Encoder self-attention: every input token attends to every other input token.
  • Decoder self-attention: every output token attends only to itself and earlier output tokens.
  • Encoder-decoder (cross) attention: the decoder's queries attend to the encoder's keys and values, so each output position can look at the whole input.

The "only earlier tokens" rule is enforced by a mask. Before the softmax, the scores for future positions are set to −∞, which the paper describes as "masking out (setting to −∞) all values in the input of the softmax which correspond to illegal connections". e^−∞ is 0, so those positions get zero weight. GPT-style chat models are decoder-only: every layer uses this masked self-attention, which is why they generate text strictly left to right.

Where word order comes from

Attention on its own ignores order: shuffle the tokens and each one gets the same weighted mix. The Transformer therefore adds position information to each token's vector before the first layer. The 2017 paper used sine and cosine waves of different frequencies. Many newer models use other schemes, but the purpose is the same.

Why long prompts are expensive

Every token's query is compared with every token's key, so a sequence of n tokens produces an n × n score matrix in every head of every layer. The paper lists the cost of a self-attention layer as O(n²·d). Doubling the prompt length roughly quadruples the attention work. This quadratic growth is a large part of why context windows are limited and why long prompts cost more time and money. Since text is counted in tokens rather than words, how many tokens a word takes decides what n actually is for your input.

During generation, models avoid recomputing old keys and values by storing them (the KV cache). Each new token then needs only its own query compared against the cached keys, but the cache itself grows with every token in the context and takes up GPU memory.

How attention relates to embeddings

Embeddings give each token a starting vector; attention is what makes those vectors context-dependent. After a few layers, the vector for "bank" in "river bank" and in "bank account" are different, because each mixed in information from different neighbours. If you want the starting point of that process, see what embeddings are.

Frequently asked questions

What is the difference between attention and self-attention?
In self-attention the queries, keys and values all come from the same sequence, so each token looks at the other tokens of its own text. In cross-attention (encoder-decoder attention) the queries come from one sequence and the keys and values from another, for example a translation decoder looking at the encoded source sentence.
Why is it called 'attention'?
Because the weights decide how much each output position draws on each input position, which resembles focusing on some words and ignoring others. It is ordinary arithmetic, a weighted average with learned weights, not a model of human attention.
Does attention mean the model understands which words matter?
Attention weights show which positions a head mixed information from, but they are not a reliable explanation of why the model produced an answer. Models have many heads and layers, and the same information can flow through several routes.
Who invented the attention mechanism?
Attention for neural networks was introduced for machine translation by Bahdanau, Cho and Bengio in 2014, to remove the bottleneck of compressing a whole sentence into one fixed-length vector. The 2017 paper Attention Is All You Need built the Transformer entirely from attention, without recurrence.

Sources