Back to Tutorials
Deep Learning
Advanced

How Transformers Work: Attention, Step by Step

The idea behind every chatbot: each word decides which other words matter. Tap a word in a real sentence and watch where its attention goes.

12 minInteractive: drag, click and try things as you read


Every chatbot you’ve used runs on the same design: the transformer, introduced by Google researchers in 2017 in a paper called “Attention Is All You Need”. Its central idea is surprisingly simple. Every word looks at the other words and decides which ones matter to it. Here is that idea, working on a real sentence.

Words depend on other words#

Read this:

The trophy didn’t fit in the suitcase because it was too big.

What was too big? The trophy, obviously. Now change one word: “because it was too small”. Now “it” is the suitcase. You resolved that without noticing, by connecting “it” and “big” or “small” back to the right noun. A model has to do the same thing, for every word, in every sentence. The meaning of a word depends on the words around it.

Attention: every word asks a question#

A transformer handles this with attention. Each word gets three lists of numbers, which it learns during training:

  • a query: what it’s looking for (“which earlier word is the thing I describe?”),
  • a key: what it offers to words that are looking (“I’m an object that goes inside things”),
  • a value: the information it passes on to whoever attends to it.

Each word compares its query with every key it can see. A good match gets a high score. The scores go through softmax, the same function that turns scores into chances in our temperature explainer, so they become weights that add up to 100%. The word then takes a weighted mix of the values. That mix is how information flows from “trophy” into “big”.

Try it

Tap a word to see where its attention goes.

The
1%
trophy
87%
didn’t
1%
fit
1%
in
1%
the
1%
suitcase
3%
because
1%
it
1%
was
1%
too
1%
big
1%

“big” pays 87% of its attention to “trophy”.

One attention step, computed live. The queries and keys are hand-made, six named numbers each, so you can read them; a real model learns its own, with hundreds or thousands of numbers. The maths that turns them into weights is the real thing.

Start with “big”, which is selected: it pays most of its attention to “trophy”. Switch the ending to “too small”, and the last word now looks at “suitcase”. Same sentence, one different word, and the connections rewire themselves.

Predict first

Now tap “it”, with “Earlier words (chatbots)” selected. Where does its attention go?

Many heads, many layers#

One attention pattern can’t track everything a sentence needs, like who did what, which word a pronoun means, and what came just before. So transformers run several attention patterns side by side, called heads, each with its own queries and keys. Researchers studying trained models have found heads doing simple, recognisable jobs, such as always attending to the previous word.

Then they stack layers. Each layer’s attention works on what the layer below produced, so information can build up: early layers tend to handle nearby words and grammar, later ones longer-range meaning. In a real model, “it” would pick up what it refers to over several layers, not in one step like our toy.

Why transformers took over#

Before transformers, language models mostly read text the way you do: one word at a time, each step waiting for the last. That made them slow to train, and they struggled to connect words far apart.

Watch

One word at a time (older recurrent networks)

0 steps

Thetrophydidn’tfitinthesuitcasebecauseitwastoobig

Each word has to wait for the one before it to be processed.

All at once (a transformer layer)

0 steps

Thetrophydidn’tfitinthesuitcasebecauseitwastoobig

Every word is processed in the same step, side by side, which suits GPUs perfectly.

Attention connects every word to every other word in a single step, and all those comparisons can run at once on GPUs, the chips that do thousands of calculations in parallel. That made it practical to train on enormous amounts of text, which is what made today’s chatbots possible.

Predict first

A model reads a 1,000-token prompt, then one of 2,000 tokens. Roughly how much more attention work does the second take?

One more thing worth knowing: the all-at-once speed applies to reading. Writing is still one token at a time, because each new token needs the ones before it to exist.

The whole machine, end to end#

Put it together and this is what happens every time a chatbot writes a single token:

Step through

Step 1 of 6

Split the text into tokens

The model never sees letters or words, only tokens: common words, or pieces of rarer ones. Each token has an ID number.

Thetrophydidn’tfitinthesuitcasebecauseitwastoo
Six stages, simplified. The coloured strips stand in for real numbers.

See real attention#

You can look inside a real transformer in a few lines with Hugging Face’s transformers library and GPT-2, a small model that runs on a laptop:

from transformers import AutoModel, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModel.from_pretrained("gpt2", attn_implementation="eager")

text = "The trophy didn't fit in the suitcase because it was too big"
inputs = tokenizer(text, return_tensors="pt")
outputs = model(**inputs, output_attentions=True)

print(len(outputs.attentions))       # 12: one per layer
print(outputs.attentions[0].shape)   # (1, 12, tokens, tokens): 12 heads per layer

Each layer gives a grid like the one in the step-through figure, for each of its 12 heads. To explore them visually, the open-source bertviz library draws them for you. Real heads are messier than our toy, and that’s part of the fun.

What to remember

  • In attention, every token compares its query with other tokens’ keys, and takes a weighted mix of their values. The weights come from softmax.
  • Many heads run side by side and many layers stack up, so meaning builds from nearby words to the whole passage.
  • Transformers process all the tokens they read at once, which made training on huge amounts of text practical. Writing is still one token at a time.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.