Home / Learn / AI, explained simply

Transformers and attention explained: how AI reads a whole sentence

New to this? Read from the top. Already know the basics? Jump to Going deeper for intermediate and advanced detail.

Attention: the word it looks at every other word in the sentence; the thickest line goes to cable, showing which word it attends to most
Beginner

Almost every well-known AI language model, including ChatGPT, Claude and Gemini, is built on one neural network design: the transformer. It was introduced by a team at Google in a 2017 paper called Attention Is All You Need. Its key idea, attention, lets every word in a passage look directly at every other word to work out what it means in context. This guide explains how that works, step by step, without assuming any maths beyond multiplying and adding.

Step 1: text becomes tokens, tokens become vectors

The model first splits text into tokens: whole words, parts of words or punctuation. Each token is then swapped for an embedding, a long list of numbers (a vector) that captures something of its meaning. Words used in similar ways end up with similar vectors. Because attention on its own takes no notice of word order, information about each token's position is mixed in as well.

Step 2: the problem attention solves

Take "The breaker protects the cable because it trips first" and "The breaker protects the cable because it would overheat". In the first, "it" is the breaker; in the second, it's the cable. The meaning of "it" depends on other words, sometimes far away. Older designs read text one word at a time, passing a summary along, and tended to lose track over long passages. Attention lets the model, for each word, weigh up every other word at once and pull in information from the ones that matter.

Step 3: queries, keys and values

For every token, the model makes three new vectors by multiplying its embedding by three sets of learned weights:

  • a query: "what am I looking for?"
  • a key: "what do I contain?"
  • a value: "what will I pass on if you pick me?"

Think of searching a parts catalogue. Your query is what you need; each part's key is its description; the value is the part itself. For each token, the model compares its query with every token's key to get a score (bigger means a better match), turns the scores into weights that add up to 1 using a function called softmax, then takes a weighted blend of all the values. The token's new vector is that blend: its meaning, updated with context.

Attention(Q, K, V) = softmax(Q KT ÷ √dk) V

That's the formula from the 2017 paper. The √dk (the square root of the vector length) keeps the scores from growing too large in long vectors.

Attention you can run

Here is one query attending over three tokens, with tiny two-number vectors so you can follow every step. Plain Python, no libraries:

# Scaled dot-product attention for one query over three keys
import math

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

query = [1.0, 0.0]
keys = [[1.0, 0.0], [0.0, 1.0], [0.7, 0.7]]
values = [[10.0, 0.0], [0.0, 10.0], [5.0, 5.0]]

d = len(query)
scores = [sum(q * k for q, k in zip(query, key)) / math.sqrt(d) for key in keys]
weights = softmax(scores)
output = [sum(w * v[i] for w, v in zip(weights, values)) for i in range(2)]

print("scores ", [round(s, 3) for s in scores])
print("weights", [round(w, 3) for w in weights])
print("output ", [round(o, 2) for o in output])

The real output:

scores  [0.707, 0.0, 0.495]
weights [0.434, 0.214, 0.351]
output  [6.1, 3.9]

The query matches the first key best, so the first token gets the largest weight (43%) and the output leans towards its value. Nothing is ignored completely, though: the result is a blend. In a real model the vectors have hundreds or thousands of numbers, and the weights that make queries, keys and values are learned during training, so the model itself discovers what's worth paying attention to.

Step 4: many heads, many layers

Multi-head attention runs several attention calculations side by side, each with its own learned weights. One head might track which noun a pronoun refers to, another nearby words, another sentence structure, although in practice what each head does is rarely that tidy. The results are combined and passed through a small ordinary neural network (a "feed-forward" layer) for each token.

That attention-plus-feed-forward pair is one layer, and a transformer stacks many of them. The original 2017 model used 6 layers of 8 heads in each half; today's large models use many more. Early layers tend to capture grammar and nearby words; later ones more abstract meaning.

Step 5: predicting the next token

Chat models are "decoder-only" transformers trained to do one thing: predict the next token. When generating, each token may only attend to the ones before it, never ahead (this is called a causal mask). The final layer gives a probability for every token in the vocabulary, one is picked (see temperature and sampling), it's added to the text, and the whole process repeats for the next token. A long answer is hundreds of these steps, one token at a time.

Why long inputs cost more

Every token attends to every token before it, so the work grows with the square of the length: 1,000 tokens means about a million comparisons, and doubling to 2,000 makes it roughly four times as many. That's one reason context windows have limits, and why providers charge per token. Models save time while generating by caching the keys and values of earlier tokens (the "KV cache") rather than working them out again for every new token.

What this means when you use AI

  • The model sees your whole prompt at once, so clear structure and putting the important instruction where it can't be missed both help. See how to write better prompts.
  • It works in tokens, not letters, which is why models can stumble on spelling and counting letters.
  • It predicts likely text, rather than looking facts up, so it can sound sure and still be wrong.
Intermediate and advanced

Going deeper

Self-attention versus cross-attention

In self-attention the queries, keys and values all come from the same text. The original transformer was built for translation and also used cross-attention, where the decoder's queries look at keys and values from the encoder's reading of the source sentence. Decoder-only chat models use self-attention only; encoder-only models such as BERT read the whole text in both directions and are used for search and classification rather than generation.

Residual connections and normalisation

Each layer adds its output to its input rather than replacing it (a residual connection), and normalises the numbers so they stay in a sensible range. Without both, stacks of dozens of layers would be almost impossible to train.

Position information

The 2017 paper added fixed sine and cosine patterns to the embeddings to mark position. Many current models use rotary position embeddings (RoPE), which rotate the query and key vectors by an angle that depends on position, so attention scores naturally depend on how far apart two tokens are.

Taming the quadratic cost

Because full attention grows with the square of the length, long-context models rely on engineering such as FlashAttention (which reorganises the calculation to use GPU memory efficiently without changing the result), grouped-query attention (several query heads share one set of keys and values, shrinking the KV cache), and in some designs attention limited to a sliding window of recent tokens.

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.