✖

Transformer and attention: how a model knows what a word refers to

The transformer is a type of neural network on which ChatGPT and most of today’s language models are built. At its heart is attention, the attention mechanism. The whole idea fits into one sentence: every word looks at the words before it (and at itself), works out how much they matter to it, and takes a weighted average of them. You know a weighted average from school: an exam counts for more than classwork, so it moves the final mark more. In this way a word soaks up a bit of meaning from the words that matter to it, and only then carries on calculating with that.

A language model chops text into tokens, pieces of words, and replaces each token with a vector, a list of numbers like (1, 1), only much longer, which captures its meaning (the first part of the series How artificial intelligence computes). The vectors then pass through a neural network, a huge amount of multiplying and adding (the second part). From here on we will simplify tokens to whole words.

Who was slow?

Read these two sentences:

  • The dog didn’t catch the cat because it was too slow.
  • The dog didn’t catch the cat because it was too fast.

In the first sentence it was the dog that was slow, in the second the cat that was fast. The word “it” could stand for either animal, and grammar does not help: “it” fits the dog and the cat equally well. Meaning decides: whoever fails to catch up is slow, and whoever gets away is fast. You see this without thinking. But the model sees only vectors, and it has to work out somehow that “slow” belongs to the dog. Moreover, at the start the vector of the word “slow” is always the same: it knows nothing about its sentence.

This is where attention comes in. The word “slow” looks at all the words before it and at itself, and gives each of them a weight: how much that word interests it. The weights add up to one, so they produce a weighted average.

The sentence The dog didn’t catch the cat because it was too slow, and below it the same sentence ending with the word fast. From the last word (in orange) arcs with arrowheads lead to all the words, the larger the weight, the thicker the arc. For slow the thickest red arc leads to dog with a weight of 0.50, for fast to cat with a weight of 0.52. The other weights are small, in grey The sentence The dog didn’t catch the cat because it was too slow, and below it the same sentence ending with the word fast. From the last word (in orange) arcs with arrowheads lead to all the words, the larger the weight, the thicker the arc. For slow the thickest red arc leads to dog with a weight of 0.50, for fast to cat with a weight of 0.52. The other weights are small, in grey

The weights in the picture are made up, they only show the principle. A real model calculates such weights for every word in the text, and nobody sets them for it: it finds them out itself while guessing the next word in billions of sentences. How does it do that?

Query, key and value

Each word’s vector gives rise to three new ones:

  • a query: what I am looking for. The word “slow” asks roughly “who here is slow?”,
  • a key: what I offer. The other words use the key to tell whether it matches them. The key of “dog” says roughly “I am an animal”,
  • a value: what I hand over when somebody takes an interest in me.

It is like searching in a library. The query is what you type into the search engine, the keys are the labels on the books, and the value is the content of the book you finally take away. But you do not take home a single book, rather a bit of each, depending on how well its label matched the query.

The dog’s key, incidentally, knows nothing about the chase after the cat: context from the sentence gets into the vectors only gradually, layer by layer.

Where do these three vectors come from? The word’s vector x→ is multiplied by three weight matrices, just like in a layer of the network from the second part:

q→=WQ⋅x→k→=WK⋅x→v→=WV⋅x→

The matrices WQ, WK and WV are the same for all the words, and the model finds their numbers during learning.

How well a key matches a query is measured by the scalar product (dot product): we multiply the corresponding components and add up. The more the two vectors point in the same direction, the larger the number. The cosine similarity from the first part is built on the same idea. But why not compare the word vectors directly? Because “slow” does not resemble “dog” at all: it is a property, not an animal. It looks for something other than what it is itself, and that is exactly what the query and key allow.

By hand on three words

From the sentence we keep only the three words that matter: dog, cat, slow. The vectors will have just two components, and we will choose the numbers so that they come out nicely. In a real model they would be produced by learned matrices and would have hundreds of components. The query of the word “slow” will be q→=(1,1) and the keys

k→dog=(1,1)k→cat=(1,−1)k→slow=(0,1)

Even “slow” itself has a key, because it also looks at itself.

Step 1: scores. We take the scalar product of the query with each key:

q→⋅k→dog=1⋅1+1⋅1=2q→⋅k→cat=1⋅1+1⋅(−1)=0q→⋅k→slow=1⋅0+1⋅1=1

Step 2: softmax. From the scores we make weights that are positive and add up to one. For that we have the softmax function from part four: it raises the number e ≈ 2.718 to the power of each score and divides the results by their sum. We have already calculated the scores 2, 1 and 0 there, so we know that for the dog we get

e2e2+e0+e1=7.397.39+1+2.72≈0.67

The others turn out similarly:

word dog cat slow
score 2 0 1
weight 0.67 0.09 0.24

Step 3: weighted sum of the values. We choose the values so that they are easy to read: each word has a one in its own place, v→dog=(1,0,0), v→cat=(0,1,0) and v→slow=(0,0,1). From the result we can then read off directly how much “slow” took from which word. Real values are not so transparent, they carry the meaning of the word. Now we multiply each value by its weight and add everything up:

0.67⋅(1,0,0)+0.09⋅(0,1,0)+0.24⋅(0,0,1)=(0.67,0.09,0.24)

Diagram of the calculation. At the top, in orange, the query of the word slow, q = (1, 1). Below it three rows: dog (red) with the key (1, 1) and the score 2, cat (blue) with the key (1, −1) and the score 0, slow (green) with the key (0, 1) and the score 1. The scores lead into an orange rectangle, softmax, from which the weights 0.67, 0.09 and 0.24 emerge as horizontal bars. Each weight is multiplied by the value (1, 0, 0), (0, 1, 0) and (0, 0, 1), and the sum gives, in red, the new vector of the word slow (0.67, 0.09, 0.24) Diagram of the calculation. At the top, in orange, the query of the word slow, q = (1, 1). Below it three rows: dog (red) with the key (1, 1) and the score 2, cat (blue) with the key (1, −1) and the score 0, slow (green) with the key (0, 1) and the score 1. The scores lead into an orange rectangle, softmax, from which the weights 0.67, 0.09 and 0.24 emerge as horizontal bars. Each weight is multiplied by the value (1, 0, 0), (0, 1, 0) and (0, 0, 1), and the sum gives, in red, the new vector of the word slow (0.67, 0.09, 0.24)

The new vector of the word “slow” is 67% dog, 24% the original “slow” (its own key matches the query a little) and only 9% cat. The word “fast” would ask differently, say with the query (1, −1), and the cat would get the highest score: 1 · 1 + (−1) · (−1) = 2.

One more detail for the curious: real models divide the scores by the square root of the number of components of the query, d, before the softmax. The scalar product adds up d products, and the sum of d random products typically grows like d; without the division, softmax would give almost all the weight to a single word, just like at a low temperature. In GPT-3 the query in one head has 128 components, so the scores are divided by 128≈11.3. In our two-component example we skipped this.

All at once: the attention formula

If you do not like matrices, you can skip this section. If you are only after the formula, the attention mechanism is written as

softmax(Q⋅KTd)⋅V,

where Q, K and V are matrices whose rows hold the queries, keys and values of all the words in the text. The product Q · KT merely means that we take the scalar product of every row of Q with every row of K, that is, every query by every key. The transpose KT (rows swapped with columns) is just a trick for writing this as a single matrix multiplication. Softmax is then applied in each row separately, and multiplying by the matrix V produces the weighted sums. Out comes exactly our calculation, only for all the words at once, and because it is matrix multiplication, graphics cards handle it in a flash.

Heads, layers and word order

A single word needs to ask about several things at once: what it belongs to, who is doing what, what tense it is in. The model therefore runs several attentions in parallel, each with its own matrices, and calls them heads (multi-head attention). GPT-3 had 96 of them in each layer. The result of the attention is added to the word’s original vector (in a real model, unlike in our example, all the vectors have the same number of components), so the word carries forward both its own information and what it has gathered from the others. After it comes an ordinary network from the second part, and together they form one layer. GPT-3 had 96 such layers stacked on top of each other, and each builds on what the ones below added. After the last layer, the network calculates from the vector of the last token a score for every token in the vocabulary, and softmax turns these into probabilities of the next token (the first and fourth part).

One thing escapes attention: a weighted sum does not care in what order the words stand. That is why, at the start, a vector that encodes its position in the sentence is added to each word’s vector, otherwise the model could not tell “the car overtook the bicycle” from “the bicycle overtook the car”.

Why twice the text costs four times as much in attention

Attention has its price, though. Scores are calculated for pairs of words, and a text of n words has n · n = n2 of them, in every head and every layer. If we double the text, both the number of words that ask and the number of words they ask about double. In a grid where the row belongs to the word that asks and the column to the word it asks about, there are therefore four times as many cells:

Two square grids. On the left 6 by 6 cells labelled 6 tokens and 36 cells, on the right 12 by 12 cells labelled 12 tokens and 144 cells. In both the diagonal and everything below it is shaded red, that is, the scores the model really calculates: 21 cells out of 36 on the left, 78 out of 144 on the right Two square grids. On the left 6 by 6 cells labelled 6 tokens and 36 cells, on the right 12 by 12 cells labelled 12 tokens and 144 cells. In both the diagonal and everything below it is shaded red, that is, the scores the model really calculates: 21 cells out of 36 on the left, 78 out of 144 on the right

length of text number of scores n2
1,000 tokens 1,000,000
2,000 tokens 4,000,000
10,000 tokens 100,000,000

Language models such as GPT, which write text, look only backwards, though: the words that come after a given word do not exist yet, the model has yet to write them. Each word therefore sees only itself and the words before it, so in the grid the diagonal and the lower half stay shaded, and only about half of the scores remain. But twice the text still means four times the work.

The factor of four applies only to attention itself. The work on matrix multiplication in the rest of the network merely doubles when the text doubles, because each word passes through it on its own. For short texts attention therefore does not cost much, but for long ones it starts to dominate. And texts keep getting longer: GPT-3 from 2020 handled 2,048 tokens at a time, GPT-4.1, which OpenAI introduced in April 2025, up to a million. For a million tokens the grid has a trillion cells, and even half of that is half a trillion scores in a single head of a single layer. No wonder developers look for ways to save part of the work.

Where the transformer came from

The transformer was introduced by eight researchers, mostly from Google, in the paper Attention Is All You Need (Vaswani et al., 2017). It was originally meant for machine translation from English into German and French. The title of the paper was a message: earlier networks read text word by word, whereas the transformer gets by with attention, and so it can process all the words of a text it already has at once. New words, though, it still writes one at a time, as the first part showed.

A year later, in 2018, OpenAI built its first GPT model on it. The abbreviation stands for Generative Pre-trained Transformer, a transformer that is generative (it creates text) and trained in advance. So the T in ChatGPT stands for transformer.

Attention helps the model find what a word refers to, but it does not guarantee that what it finally writes is true. Why a model sometimes confidently makes things up is explained in the part on AI hallucinations.

Chapters: How ChatGPT and artificial intelligence work: the maths inside, Neural network: what it is and how it computes, Gradient descent: how a neural network learns, Softmax: how numbers become probabilities and what temperature is, Transformer and attention: how a model knows what a word refers to, AI hallucination: why artificial intelligence confidently writes falsehoods