ai/courses

AI Fundamentals/Lesson 5 of 8

Transformers Explained: How Attention Works, Step by Step

How every word looks at every other word, and why that architecture won.

Lesson
5 of 8
Time
30 min
Updated

TL;DR

The short answer

A transformer is a neural network that processes all the tokens of a text at once and lets each token look at every other token to work out what it means in context. That look-around step is called attention. In "the animal didn't cross the street because it was tired," attention is how "it" connects to "animal."

A transformer stacks dozens of layers, each with an attention step (tokens exchange information) and a feed-forward step (each token is processed on its own). Invented at Google in 2017, it's the architecture behind ChatGPT, Claude, Gemini, Llama and most modern AI for images, audio and video too.

The problem: meaning depends on context

After lesson 4, every token has an embedding, a list of numbers for its meaning. But one embedding per token isn't enough, because words change meaning with their neighbors. "Bank" in "river bank" and "bank account." "Apple" in "apple pie" and "Apple stock." And the classic:

The animal didn't cross the street because it was too tired.

The animal didn't cross the street because it was too wide.

One word changes at the end, and "it" switches from the animal to the street. To understand "it," a model must connect it to the right word, possibly far away, using knowledge about the world (animals get tired, streets are wide).

Before 2017, language models read text the way you'd read a telegram, one word at a time, passing a summary of everything so far to the next step. These recurrent networks had two big bugs: the summary faded over long texts, and the word-by-word design couldn't use the thousands of parallel cores in a GPU.

Fig. 1A recurrent network (top) passes a fading memory along the sentence. With attention (bottom), “it” connects directly to every other word, and the strongest link is to “animal.”

Attention: every word asks a question

Attention lets each token gather information from the other tokens directly, in one step, no matter how far apart they are. It works through three roles that every token plays at once. They have intimidating names, but they're like a matchmaking party:

  • Each token holds up a query: "Here's what I'm looking for." For "it," something like "I'm a pronoun; I need the noun I refer to."
  • Each token wears a key: "Here's what I am." For "animal": "I'm a noun, a living thing, the subject of this sentence."
  • Each token carries a value: "Here's the information I'll share if you pick me."

Every token compares its query with every other token's key and gets a match score. The scores are turned into percentages that add up to 100% (with the same softmax trick that turns scores into probabilities in lesson 7). Then each token takes a blend of everyone's values, weighted by those percentages. If "it" matches "animal" at 70%, its new embedding is mostly made of what "animal" had to share.

DemoClick any word to see how much attention it pays to the others. Switch the last word between “tired” and “wide” and watch where “it” looks. Illustrative weights, designed to show the idea.

The queries, keys and values aren't programmed. Each token computes them from its embedding by multiplying it with three weight matrices, and those weights are learned in training like every other knob. Nobody teaches the model grammar. It discovers that matching pronouns to nouns, verbs to subjects and adjectives to the things they describe lowers the loss, and the attention weights drift into those patterns.

attention.py
import numpy as np

def softmax(x):
    e = np.exp(x - x.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)

def attention(Q, K, V):
    scores = Q @ K.T / np.sqrt(K.shape[-1])   # how well each query matches each key
    weights = softmax(scores)                  # every row sums to 1
    return weights @ V, weights                # each token gets a blend of values

rng = np.random.default_rng(0)
x = rng.normal(size=(4, 8))       # 4 tokens, 8 numbers each (real models: thousands)
Wq, Wk, Wv = (rng.normal(size=(8, 8)) * 0.3 for _ in range(3))   # learned in a real model
out, w = attention(x @ Wq, x @ Wk, x @ Wv)
print(np.round(w, 2))             # row i: how much token i looks at each token
CodeThe core of attention in a few lines of numpy: compare queries with keys, softmax the scores, blend the values. With random weights the pattern means nothing; training is what makes it useful.

Many heads, many layers

A sentence has many relationships at once. "It" relates to "animal" (what it refers to), "tired" relates to "it" (what's tired), "didn't" relates to "cross" (what's negated). One attention pattern can't capture all of that, so each layer runs several attention operations side by side, called attention heads, each with its own queries, keys and values. Researchers who look inside trained models find heads that specialize: some track the previous word, some link pronouns, some follow quotes or brackets in code.

After attention comes the second half of each layer, the feed-forward network: a small two-layer network (lesson 2) applied to each token separately. If attention is the meeting where tokens share information, the feed-forward step is each token going back to its desk to think about what it heard. Research suggests much of a model's factual knowledge is stored in these feed-forward weights.

Then the whole thing repeats. A transformer is a stack of these layers, each refining every token's embedding a little more.

Fig. 2A transformer: tokens become embeddings with position information, then pass through many identical layers of attention and feed-forward steps. The last layer produces probabilities for the next token.
ModelYearLayersAttention heads per layer
Original Transformer (base)20176 + 6 (encoder and decoder)8
GPT-2 (largest)20194825
GPT-320209696
TableSizes published in the original papers. Most companies no longer publish the architecture of their flagship models.

How a transformer knows word order

Attention has a strange blind spot: it treats the text as a bag of tokens. Every token looks at every other one, and nothing in the matching says who came first. "Dog bites man" and "man bites dog" would look the same.

The fix is to mix position information into each token's embedding before the first layer, so that "dog at position 1" differs from "dog at position 3." The original paper used a pattern of waves of different frequencies; most modern models use a cleverer variant called rotary position embeddings. Either way, the model learns to use position like any other information.

One more rule matters for chatbots. A model that generates text is trained to predict the next token, so it must not peek at the future. In GPT-style models, each token can only attend to the tokens before it. This is called causal (or masked) attention, and it's why these models write strictly left to right.

Why transformers won

The 2017 paper, "Attention Is All You Need," was about machine translation. Its best model trained in three and a half days on eight GPUs and set new records. But the real breakthrough was that transformers fit the hardware: all tokens are processed at the same time, so training splits neatly across thousands of chips. That made it possible to scale models up enormously, and as lesson 6 explains, scale turned out to be most of the game.

The architecture also turned out to be general. A transformer doesn't care what its tokens are. Cut an image into small patches and treat each patch as a token, and you get a vision transformer (2020). Do the same with chunks of audio, video frames or molecules. DeepMind's AlphaFold 2, which predicted protein structures well enough to win a share of the 2024 Nobel Prize in Chemistry, is built around attention.

Exercise · about 5 minutes

Be an attention head

Take this sentence: "Sarah handed Maria the keys because she was leaving early."

  1. Who is "she"? Write down your answer and the words that made you decide.
  2. Now change the ending: "...because she had asked for them." Who is "she" now? Which word flipped it?
  3. Ask a chatbot the same two questions. Then ask it to explain which words it relied on.
  4. Draw the sentence with arrows from "she" to the words it should attend to most, thick for strong and thin for weak.

You just did what one attention head does, with the same clues: the other words, and knowledge about how the world works.

Quiz

  1. 1.What problem does attention solve?

  2. 2.In attention, what do queries and keys do?

  3. 3.Why does a transformer have many attention heads per layer?

  4. 4.Why does a transformer need position information added to its embeddings?

  5. 5.Which property did most to make transformers win over recurrent networks?

0 of 5 answered

Key takeaways

  • Meaning depends on context. Attention lets every token look at every other token to pick up that context.

  • Each token has a query (what it looks for), a key (what it is) and a value (what it shares). All three are learned.

  • Each layer has many attention heads plus a feed-forward step, and a transformer stacks dozens of layers.

  • Position information is added because attention alone ignores word order. Chat models attend only to earlier tokens.

  • Transformers won because they parallelize well. The cost: attention grows with the square of the text length.

Go deeper

AI Fundamentals: How Modern AI Actually Works

  1. 01How machines learn25 min
  2. 02Neural networks30 min
  3. 03Tokens20 min
  4. 04Embeddings25 min
  5. 05Attention and transformers30 min
  6. 06How LLMs are trained30 min
  7. 07How LLMs generate text25 min
  8. 08RAG, tools and agents30 min