Intermediate · about 25 minutes

The transformer

How a chatbot links words, stores facts and writes its answer word by word, and why long documents cost more and can be read less reliably.

TopicHow models work

Helpful to read first, if the subject is new to you: Words as numbers, an Intermediate module.

Where it came from

Every major chat assistant is built on a design called the transformer, so its strengths and weaknesses are shared by every chatbot a lawyer is likely to use. The transformer is a way of arranging a neural network, which is a program that learns its own settings, called weights, from examples. Researchers, most of them at Google, introduced it in 2017 in a paper titled “Attention Is All You Need”, as a better and faster way to build systems for machine translation, the task of turning text in one language into another.

Translation systems before the transformer used recurrent networks, a design that reads a sentence one word at a time, each step waiting for the one before to finish. The transformer looks at every word of a passage at once, which lets graphics processing units (GPUs), chips built to run many sums side by side, do the work in parallel and train a model in much less time.

Text entering a transformer is first cut into tokens, each a word or a piece of a word, and each token is given a vector, a list of numbers the model can calculate with. The vectors then pass up through a stack of identical blocks, and each block runs two layers in turn, an attention layer and then a feed-forward layer, where a layer is one round of calculation applied to every token’s vector. The model turns what comes out of the top of the stack into a prediction of the next token.

1

Cut the text into tokens

The prompt “The appeal was dismissed by the” becomes six tokens.

Theappealwasdismissedbythe
2

Give each token a list of numbers

Each token is swapped for its row in the embedding table, a list of thousands of numbers. The list then travels through every later step as a running total, which researchers call the residual stream, and each step adds its result to the list while keeping what is already there.

Theappealwasdismissedbythe

Steps 3 and 4 together form one block, which the model repeats 96 times in GPT-3 and 126 times in Llama 3 405B.

3

Attention: gather context

Each token draws information from itself and the tokens before it, weighing each one by how relevant it looks. Here the last token, “the”, draws most on “dismissed” and “appeal”, shown by the longer bars and darker shading.

Theappealwasdismissedbythe
4

Feed-forward: add stored knowledge

Each token’s list then passes, on its own, through a small network that appears to hold many of the facts the model learned, and the result is added to the list.

Theappealwasdismissedbythe
5

Score every possible next token

The final list for the last token is compared with every token in the vocabulary, which runs to 100,000 or more in current models, and each one receives a score.

court2.0tribunal1.0judge0.1and a score for every other token
6

Turn the scores into percentages

Softmax turns the scores into percentages that add up to 100, and the model picks the next token from them.

court65.9%tribunal24.2%judge9.9%
How a chat model predicts the next token, step by step, for the prompt “The appeal was dismissed by the”. All the numbers are illustrative, and the bars show how much the last word draws on each earlier word. The final steps score three candidate next words, “court”, “tribunal” and “judge”, and turn the scores into percentages shared among those three for simplicity.

Attention

Attention is the step in which each token gathers information from itself and the tokens before it, which lets a model work out how a word depends on something said earlier. In “The tribunal dismissed the appeal because it was filed out of time”, a reader knows that “it” means the appeal, and attention is the part of a model that can make the same link. The same step is how a model can connect a defined term in a long contract to the clause that defines it, or a proviso to the clause it qualifies.

Attention links words by a kind of matching, in which each token asks a question and each earlier token, like the asking token itself, advertises what it holds. The asking token then takes in information from each of them, taking more from a token whose advertisement answers the question well and less from one whose advertisement answers it poorly. In the tribunal sentence, the question asked by “it” can match the advertisement of “appeal” closely, so “it” takes in information from “appeal” and later layers can treat the two words as linked.

Each token’s question, advertisement and information are three lists of numbers, called its query, key and value, which the model works out from the token’s vector using three grids of weights learned in training. The model compares the current token’s query with its own key and the key of each earlier token, which gives a relevance score for each one, and converts the scores into percentages that add up to 100. Each token then receives a blend of the compared tokens’ values in matching proportions.

The query of “it” is compared with the key of each word up to and including itself The tribunal dismissed the appeal because it match score share after softmax −0.6 2% 1.2 12% 0.3 5% −0.9 1% 3.0 70% 0.2 4% 0.6 6% added to the vector for “it”: mostly from “appeal” values blended by share
Attention for the word “it”, with illustrative labels and figures, in which its query is compared with the key of every word up to and including itself, the scores become percentages, and the words’ values are blended in those percentages.
Try it: one attention head, illustrative percentages

The word “it” draws on itself and on the words before it in these proportions.

The2.9%
tribunal11.9%
dismissed4.4%
the2.9%
appeal72.0%
because2.9%
it2.9%
Choose a word to see how strongly it draws on itself and on each earlier word. The percentages are chosen for illustration, since a real model runs many attention operations side by side, called heads, each with its own pattern, so a single set of real figures would describe only one head.

The step that turns scores into percentages is called the softmax, and it keeps every share above zero, makes the shares add up to 100 per cent and gives a higher score a larger share. The softmax gives the top score a much larger share when the scores are far apart and similar shares when they are close together, so a word with one clear match focuses its attention there while a word with several plausible matches spreads it among them.

A single attention operation follows one pattern of matching, so each layer runs many of them side by side, called heads, each with its own grids of weights for queries, keys and values. One head might track the word just before, while another might link pronouns to the nouns they stand for. Large models run dozens of heads in every attention layer, 96 in the case of GPT-3, OpenAI’s 2020 model in the line that led to ChatGPT, and each head learns its own pattern in training.

A common picture of attention is a room of delegates, in which each delegate holds up a question card, wears a badge describing their expertise and keeps a briefing folder under one arm. Each delegate compares their question card with every badge in the room and takes a mix of the folders, weighted towards the badges that best answer the question. The picture is only a guide, since the cards and badges in a real model are lists of numbers produced by learned weights, without meanings a person assigned, and researchers have not yet named what many heads do. A chat model also limits each delegate to itself and the delegates before it, since the model is built to predict each word from the words that precede it.

Watch: attention as a room of delegates
head 3head 2head 1the query of “the” is compared with each keyThekey[1.2…]?[0.4,…]?[0.4,…]4%appealkey[−0.7…]?[1.3,…]?[1.3,…]22%waskey[0.3…]?[−0.2,…]?[−0.2,…]5%dismissedkey[2.1…]?[0.9,…]?[0.9,…]33%bykey[0.8…]?[−1.1,…]?[−1.1,…]16%thekey[−1.4…]?[0.6,…]20%blendeach delegate may consult itself and the delegates to its left

Each token in the prompt “The appeal was dismissed by the” is a delegate in the room.

Press Play to watch the delegates picture of attention unfold scene by scene for the last word of the prompt, with illustrative shares, or step through it with Back and Next.
  1. Each token in the prompt “The appeal was dismissed by the” is a delegate in the room.
  2. Each delegate holds a question card standing for its query, wears a badge standing for its key, which describes what the delegate offers, and keeps a briefing folder standing for its value, worked out from its list of numbers.
  3. The last delegate, “the”, compares its question card with every badge in the room up to and including its own.
  4. The words “dismissed” and “appeal” have the highest match scores, and softmax turns the scores into shares that add up to 100 per cent, giving those two words the largest shares.
  5. The delegate takes a blend of the folders, weighted by the shares, and adds the blend to its own list of numbers, keeping what was there before.
  6. Every delegate does the same at the same moment, and in a chat model each one may consult only itself and the delegates before it.
  7. A layer runs many such rooms side by side, called attention heads, and each head learns its own way of matching questions to badges.
  8. In a real model the cards and badges are lists of numbers produced by learned weights, without labels a person wrote, and researchers have yet to name what many heads do.

Feed-forward layers and stored facts

The feed-forward layer is a small network of its own, which each token’s vector passes through separately after attention, and its name comes from the numbers flowing straight through it in one direction. Research suggests that much of what a model knows about the world, such as which city a landmark is in, is stored in the feed-forward layers, which therefore come up when a lawyer asks whether a fact, or a person’s data, can be found inside a model and removed.

Inside the feed-forward layer, a first stage widens the token’s list of numbers to about four times its length, and each new number works like a detector, its size showing how strongly one pattern is present in the token’s list. An activation function, a simple rule applied to each number, then keeps the detectors whose pattern is present and quiets the rest, and a second stage narrows the list back to its original length, adding what the active detectors contribute. The feed-forward layers hold roughly two thirds of the weights in a standard transformer, which led researchers to ask what so many weights do.

One study described each feed-forward layer as a memory with keys and values, using those words in a different sense from attention. Each detector acts as a key that recognises a pattern in the input, and its contribution in the second stage acts as a value that pushes the prediction towards the words likely to follow that pattern. Researchers went further in 2022 with a technique called Rank-One Model Editing, or ROME, which changes one fact by adjusting the weights of a single feed-forward layer. In one example, they found a feed-forward layer partway up the stack where a model appeared to hold the link between the Eiffel Tower and Paris, and edited that layer’s weights so that the model placed the tower in Rome.

The idea that each fact sits in one place is contested, since later work found that the layer where a fact appeared to sit was often not the best layer to edit, which would be odd if the fact lived in that layer alone. Knowledge appears to be spread across many weights that also serve other facts, so an edit made to change one association can disturb others. Repeated editing also wears a model down: a study that edited a model with one fact after another found that it gradually forgot earlier edits and lost some of its ability at other tasks, before failing abruptly. A fact in a model is therefore unlike a record in a database, which can be found and deleted. Lawyers meet the editing research when a person asks a business to correct or erase personal data that its model has learned, since the business may be unable to point to where the data sit or to show that an edit removed them.

Watch: a feed-forward block recalls a fact
other layers hold overlapping pieces of many factslist for “Tower”about four times wider: one detector per number“Eiffel Tower” detector“landmark” detectorParisParisa place nameRomeedited weights+added to thelist for “Tower”next word after “city of”ParisRomeother facts may shift

After attention, the list for one token, here “Tower” in the prompt “The Eiffel Tower is in the city of”, enters the feed-forward layer on its own.

Press Play to watch a feed-forward layer, with illustrative detectors and labels, recall a fact, have it edited and show why edits are uncertain, or step through it with Back and Next.
  1. After attention, the list for one token, here “Tower” in the prompt “The Eiffel Tower is in the city of”, enters the feed-forward layer on its own.
  2. The first stage widens the list to about four times its length, and each new number works like a detector, its size showing how strongly one pattern is present in the list.
  3. The activation function keeps the detectors whose pattern is present and quiets the rest, so only a few light up, including one that responds to “Eiffel Tower”.
  4. Researchers liken each detector to a key and its contribution in the second stage to a value, in a different sense from attention, and the value of the “Eiffel Tower” detector pushes towards “Paris”.
  5. The second stage narrows the result back to the original length and adds it to the list for “Tower”. The next word is predicted from the list at the last position, so later attention layers pass the information on to the last word, “of”, and the final step favours “Paris”.
  6. In 2022, researchers changed the Eiffel Tower association by editing one feed-forward layer’s weights, so the model answered “Rome”, using a technique called ROME, short for Rank-One Model Editing.
  7. Later research suggests that facts are spread across many detectors and layers that also serve other facts, so an edit to one association can disturb others and is hard to verify.

Depth, order and the running total

Each token’s vector travels up through every block in the stack, and each block adds its output to the vector without overwriting what is already there. The running vector that every block reads from and adds to is called the residual stream, and it works like a running total. A fair picture is a file passed down a line of specialists, each adding notes without erasing earlier ones, although the notes are numbers added into the same list, so one note can overlap with another or cancel it out. The overlapping notes help explain why what a model knows is hard to trace to a single place inside it.

Word order changes meaning, since a sentence in which the landlord sues the tenant uses the same words as one in which the tenant sues the landlord. Attention on its own does not register word order, since the match between two tokens depends on what each one contains, wherever the two sit in the text, so each token’s place is marked separately. Chat models can work out some of the order even without those marks, probably because a token that sees only the tokens before it can gauge roughly how far into the text it sits from the number of tokens it can see.

The 2017 transformer added a fixed pattern of numbers to each token’s vector to mark its place in the text. Recent models whose weights are published, such as Meta’s Llama 3, use a method called rotary position embedding, or RoPE, which adjusts each query and key according to the token’s place in the text so that the match between two tokens reflects how far apart they are. The method inside a closed commercial chatbot, whose weights are kept private, is known only where its maker has disclosed it.

Predicting the next token

At the top of the stack, the model converts the final vector at the last position into a score for every token in its vocabulary, the fixed list of tokens it knows, and a softmax turns those scores into probabilities. The model then picks a token, adds it to the end of the text and runs the whole stack again to choose the next one, a loop called autoregressive generation because each token the model writes is fed back in as input. Every word of a chatbot’s answer, a case name or a citation included, is built from tokens chosen one at a time by that loop. How the model picks from the probabilities, and why a citation assembled token by token can be invented, is explained in Sampling, hallucination and memorisation, an Intermediate module.

Watch: writing an answer one token at a time
TheappealwasdismissedbythecourtofappealKV cache: a key and a value kept for each token6 tokens cachedmodelevery layer, run once per new tokencourt66%tribunal24%judge10%appendedrun again for the next tokenmemory grows with every token,and each new token is checked against all of it

The model reads the prompt “The appeal was dismissed by the” and works out a key and a value for every token in every layer, which it stores in the KV cache.

Press Play to watch a model write the end of a sentence one token at a time, keeping the keys and values of earlier tokens in a store called the KV cache so that it need not work them out again, with illustrative percentages shared among three candidate words.
  1. The model reads the prompt “The appeal was dismissed by the” and works out a key and a value for every token in every layer, which it stores in the KV cache.
  2. At the last position it scores every token in the vocabulary and picks one, here “court”.
  3. The chosen token is appended, and the model runs again for the new token alone, since the earlier tokens’ keys and values are already waiting in the cache. The new token’s query is compared with every key in the cache, and its own key and value are added for the tokens still to come.
  4. The loop repeats, adding “of” and then “appeal”, one token per run, which is why answers appear word by word.
  5. The cache grows with every token, and each new token is compared with all the earlier ones, so long conversations cost more memory and more work for each token written.

The 2017 transformer had two halves, built for translation: an encoder that read the source sentence in full, and a decoder that wrote the translation one token at a time, drawing on the encoder’s reading of the source and on the part of the translation already written. Chat models keep only the decoder, which suits open-ended writing and became the basis of today’s chat assistants. Google’s BERT model kept only the encoder, reading a whole passage in both directions, which suits tasks such as sorting documents into categories or finding the answer to a question within a passage. A tool that sorts or searches a firm’s documents may therefore run on a different kind of transformer from the chatbot that drafts its letters.

The context window is the maximum number of tokens a model can take in at once, covering the prompt, any documents, the conversation so far and the answer. The window sets the limit on how much of a long agreement, or of a bundle of documents, a tool can read in one pass. Windows have grown quickly, from 2,048 tokens in GPT-3 in 2020 to around one million in leading commercial models in 2026, which is roughly 750,000 English words on the common estimate of three quarters of a word for each token.

Long context is expensive, since in the standard design every token is compared with itself and every earlier token. Doubling the length of a prompt gives twice as many tokens, each compared with about twice as many others, so the attention work needed to read it roughly quadruples. The software that runs a model also saves the keys and values already worked out for earlier tokens in a store called the key-value cache, or KV cache, so that they need not be worked out again for each new token. The KV cache grows with every token in the conversation, so a long conversation costs more memory as well as more work for each token written.

4 tokens: 10 comparisons The appeal was lost The appeal was lost 8 tokens: 36 comparisons Each row is one token comparing itself with the tokens before it. Doubling the length roughly quadruples the shaded cells.
Each token compared with itself and every earlier token, giving 10 comparisons for 4 tokens and 36 for 8, so doubling the length roughly quadruples the work.

Models may not read every part of a long input equally well, since a 2023 study found that the models it tested used information best when it appeared at the beginning or end of a long input, and worse when it sat in the middle.

Check your understanding

  1. Question 1 In an attention layer, what part does a token’s query play?

    Choose one answer to question 1
    Show the answer

    Answer: It is compared with its own key and earlier tokens’ keys to decide how much of each value to collect. The token’s query is compared with its own key and the keys of earlier tokens, the softmax turns the resulting scores into percentages, and the percentages decide how much of each token’s value it receives.

  2. Question 2 Why does doubling the length of a prompt roughly quadruple the attention work?

    Choose one answer to question 2
    Show the answer

    Answer: Each token is compared with itself and every earlier token, so comparisons grow with the length squared. Twice as many tokens means twice as many queries, each compared with about twice as many keys, which gives roughly four times the comparisons.

  3. Question 3 What does the editing research suggest about removing a fact from a model?

    Choose one answer to question 3
    Show the answer

    Answer: Edits can change an association, but knowledge is spread widely and side effects are hard to rule out. Editing methods such as ROME show that associations can be changed, while later work shows that locating knowledge is unreliable and side effects are hard to rule out.

Sources

  1. Regulation (EU) 2016/679 (the General Data Protection Regulation), Articles 16 and 1727 April 2016 · checked 29 October 2026
  2. UK GDPR, Article 16, right to rectification (legislation.gov.uk, latest available version)27 April 2016 · checked 29 October 2026
  3. UK GDPR, Article 17, right to erasure (legislation.gov.uk, latest available version)27 April 2016 · checked 29 October 2026
  4. European Data Protection Board, Opinion 28/2024 on certain data protection aspects related to the processing of personal data in the context of AI models17 December 2024 · checked 29 October 2026
  5. Landgericht München I, press release 11/2025 on GEMA v OpenAI, 42 O 14139/24 (in German)11 November 2025 · checked 29 October 2026
  6. Vaswani and others, Attention Is All You Need2017 · checked 29 October 2026
  7. Vaswani and others, Attention is All you Need, Advances in Neural Information Processing Systems 30 (NIPS 2017)2017 · checked 29 October 2026
  8. NIPS 2017, Long Beach Convention Center, 4 to 9 December 2017 (conference page)December 2017 · checked 29 October 2026
  9. Brown and others, Language Models are Few-Shot Learners2020 · checked 29 October 2026
  10. Meta, The Llama 3 Herd of Models2024 · checked 29 October 2026
  11. Geva and others, Transformer Feed-Forward Layers Are Key-Value Memories2021 · checked 29 October 2026
  12. Meng and others, Locating and Editing Factual Associations in GPT2022 · checked 29 October 2026
  13. Meng, Bau, Andonian and Belinkov, Rank-One Model Editing (ROME) project page, on the Eiffel Tower edit2022 · checked 29 October 2026
  14. Hase and others, Does Localization Inform Editing? Surprising Differences in Causality-Based Localization vs. Knowledge Editing in Language Models2023 · checked 29 October 2026
  15. Gupta, Rao and Anumanchipalli, Model Editing at Scale leads to Gradual and Catastrophic Forgetting2024 · checked 29 October 2026
  16. Su and others, RoFormer: Enhanced Transformer with Rotary Position Embedding2021 · checked 29 October 2026
  17. Haviv and others, Transformer Language Models without Positional Encodings Still Learn Positional Information2022 · checked 29 October 2026
  18. Devlin and others, BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding2018 · checked 29 October 2026
  19. Liu and others, Lost in the Middle: How Language Models Use Long Contexts2023 · checked 29 October 2026
  20. Anthropic, Context windows (Claude API documentation): models with a 1M-token context windowchecked 29 October 2026
  21. Google Cloud, Long context (Gemini documentation): a 1-million-token context window as standardchecked 29 October 2026
  22. OpenAI, Key concepts (API documentation), on tokens: about 0.75 words per token in Englishchecked 29 October 2026

Your progress

Switched on, it keeps a short record of the modules you open and the quizzes you finish in this browser’s own storage, and the record stays on this device.

This module is general information, checked against the sources above on 29 October 2026. It is not legal advice, and the law it describes may have changed since then. Read the disclaimer.