A beginner's course · 9 modules

Transformers from scratch

The transformer is the design inside ChatGPT, Claude, Gemini and Llama. This course follows one sentence as it travels through a transformer, one step per module. You will poke at every part of it with sliders and buttons, and you only need to know multiplication.

Thenursegavethepatienthermedicinebecauseshehadafever→ who is "she"? By Module 5 you'll see how the model works it out.
1IdeaThe concept in plain words, with an everyday comparison.
2Try itA small working model you can change and watch.
3RememberFlip-cards for the key words.
4CheckTwo questions. Get both right to finish the module.
About 2 hours in totalNo coding needed (there's an optional Python exercise at the end)Progress saved in this browser
Module 1 · The goal

A very good guesser

What is a large language model actually doing when it answers you?

A language model does one thing: given some text, it predicts what comes next. It does not look up answers in a database. It produces a list of every word it knows, each with a probability, then picks one.

To write a whole answer, it adds the chosen word to the text and predicts again, over and over. Everything a chatbot does, from translating to writing code, comes from repeating that one step.

The transformer is the machine that makes those predictions good. The rest of the course opens it up.

Think of it likeYour phone's keyboard suggesting the next word, except it has read a large slice of the internet and can take a whole page of context into account, not just the last two words.
Try it · next-word predictor

Pick a prompt. The bars show how likely each next word is. Temperature controls how adventurous the pick is: low means "almost always take the top word", high spreads the chances out.

–chance of the top word
–chance of picking something else
Module 2 · Station 1

Chopping text into tokens

A computer can't read letters. How does a sentence become something it can work with?

First the text is cut into tokens: whole words, pieces of words, or punctuation marks. Each token has a fixed ID number from a vocabulary list.

Common words like "the" get one token. A rare word like "unvaccinated" is built from pieces such as "un" + "vacc" + "inated". That way a vocabulary of about 50,000 to 200,000 pieces can spell any word, even ones the model has never seen.

From here on, the model only sees a list of ID numbers.

Think of it likeLego. You don't need a special brick for every shape. A modest box of standard bricks can build almost anything.
Try it · a toy tokenizer

Type anything. Each coloured chip is one token, with its ID underneath. A dot (·) means the token starts with a space. Try made-up words, or long medical terms.

–words
–tokens
–tokens per word

This toy uses a small hand-made vocabulary and made-up IDs. Real tokenizers learn their pieces from huge amounts of text (a method called byte-pair encoding). As a rule of thumb, 100 English words come to about 130 tokens. Pricing and the "context window" of a model are counted in tokens.

Module 3 · Station 2

Words as points on a map

An ID number like 4,821 says nothing about meaning. How does the model know "nurse" and "doctor" are related?

Each token ID is swapped for a long list of numbers called an embedding (a vector). You can think of those numbers as coordinates that place the word on a map of meaning.

Nobody writes these numbers by hand. They are learned during training, and they settle so that words used in similar ways end up close together. Directions on the map come to mean something too, such as "male → female" or "country → its capital".

Real models use 768 to over 12,000 numbers per token. We'll squash it to 2 so you can see it.

Think of it likeA map of a city: clinics cluster together, markets cluster together. If you know where something sits, you know a lot about what it is.
Try it · a 2-D meaning map

Click any word to see its three nearest neighbours. Then try the word arithmetic: start at one word, move along a direction, and see where you land.

Module 4 · Station 3

Keeping track of word order

"Dog bites man" and "man bites dog" use the same words. How does the model tell them apart?

The attention step you'll meet next looks at all words at once, like a bag of words. On its own, it has no idea which word came first.

So before attention, each embedding gets a positional encoding added to it: another list of numbers that is different for position 1, position 2, position 3, and so on. The original transformer made these from sine waves of different speeds, so each position gets a unique pattern and neighbouring positions get similar patterns.

After this step, each vector carries two things: what the word is and where it sits.

Think of it likeNumbered seats in a waiting room. Same patients, but the seat number tells you who arrived first.
Try it · part 1 · the bag-of-words problem

Without position, both sentences contain the exact same set of tokens. Switch position on and see them become different.

Try it · part 2 · each position's fingerprint

Each column is one position (0 to 49), each row one of 16 numbers. Blue is positive, pink negative. Move the slider and look at the line underneath: positions close to the chosen one have similar fingerprints.

Module 5 · Station 4 · the big idea

Attention: who should I listen to?

In "the nurse gave the patient her medicine because she had a fever", who is "she"?

This is the idea that made transformers famous (the 2017 paper was titled Attention Is All You Need). For every word, the model asks: which other words in this text matter for understanding me?

Each word gives every other word an attention weight, a share of its focus that adds up to 100%. Then it updates its own vector by blending in information from the words it focuses on. After attention, the vector for "she" carries information from "patient", so it now means something closer to "the sick patient".

Older models read word by word and forgot the start of long sentences. Attention lets any word look directly at any other word, however far away.

Think of it likeA case meeting. When the team discusses one patient, everyone listens hardest to the people who know that patient: the attending nurse and the lab, not the whole hospital.
Try it · attention in context

Click any word to see where it puts its attention. Darker means more. Then switch the ending of the sentence and click "she" again.

These weights are hand-set to show the idea, not taken from a real model. In this demo every word can look both left and right, as in models like BERT. Chat models like GPT only let a word look at earlier words (Module 9).

Module 6 · Station 4, opened up

Query, Key and Value

How does a word decide how much attention to give each other word? With three small lists of numbers.

Each token's vector is turned into three new vectors by multiplying it with three learned tables of numbers:

  • Query: what am I looking for? ("she" is looking for a female person who could be sick.)
  • Key: what do I offer? (a label each word holds up: "patient" says "I'm a person, I'm sick".)
  • Value: what I pass on if you pick me (the actual information).

The score between two words is the dot product of one word's query with the other's key: multiply matching numbers and add them up. Matching directions give a big score. Scores are scaled down, turned into percentages with softmax, and used to blend the values.

Think of it likeA records office. You arrive with a request (query). Every folder has a label on its spine (key). You pull the folders whose labels best match your request and read what's inside them (value).
Attention = softmax( Q · KT ÷ √d ) × V
Try it · be the query for "she"

The query for "she" has two numbers. Move them and watch the scores, the weights and the blended output change. The keys and values stay fixed. Use the presets first.

WordKeyQ·K score÷ √2Weight (softmax)Value
Module 7 · Station 5

Many heads, many layers

One attention step is useful. What turns it into a model that can write an essay?

Multi-head attention. A transformer runs several attention steps side by side, each with its own query, key and value tables. These are called heads. During training each head drifts toward tracking a different kind of link: one follows grammar, one links pronouns to names, one simply looks at the previous word.

The block. Attention is wrapped with a few helpers into a transformer block. A feed-forward network lets each token "think" on its own about what it just gathered; much of the model's stored knowledge lives here. Residual connections add each step's input back to its output so nothing is lost, and normalisation keeps the numbers in a steady range.

The stack. Blocks are stacked: GPT-2 small has 12, GPT-3 has 96. Early layers pick up simple patterns, later layers more abstract meaning.

Think of it likeAn outbreak investigation team. The epidemiologist, the lab scientist and the field officer read the same reports but each notices different things (heads). Each review round refines the picture before the next round (layers).
Try it · part 1 · three heads, one sentence

Each row is a word, each column what it attends to. Switch heads and see the different patterns.

Try it · part 2 · walk through one block

Step through what happens to the vectors inside a single transformer block.

Module 8 · How it learns

Training: learning from surprise

All those tables of numbers start out random. How do they become useful?

Training is a guessing game played trillions of times. Take real text, hide the next token, let the model predict, then measure how surprised it was by the true answer. That surprise is the loss: if the model gave the right word a high probability, the loss is small.

Then every number in the model (its parameters or weights, 175 billion of them in GPT-3) is nudged a tiny bit in the direction that would have lowered the loss. This is gradient descent. The size of each nudge is the learning rate.

This first stage, called pre-training, gives a model that can continue any text. It is then fine-tuned on examples of good conversations and on human feedback to become a helpful assistant.

Think of it likeWalking down a foggy hillside to the valley floor. You can't see the valley, but you can feel which way the ground slopes under your feet, so you keep stepping downhill.
Try it · part 1 · measuring surprise

Prompt: "Wash your hands with soap and ___". The true next word is "water". How much probability did the model give it?

–loss = −ln(probability)
–what it means
Try it · part 2 · gradient descent on one weight

A real model has billions of weights; here there is one. The curve shows the loss for every value of that weight. Pick a learning rate and take steps downhill. There are two valleys. Can you reach the deeper one on the left?

0steps taken
–weight
–loss now
Module 9 · Station 6 · out comes text

Generating text, one token at a time

How does the stack of blocks turn into a full answer?

After the last block, the vector of the final token is turned into a probability for every token in the vocabulary (Module 1). One is picked, added to the text, and the whole thing runs again. This loop is called autoregressive generation.

Chat models use a causal mask: each token may only attend to tokens before it, never after. That matches the job of predicting the future from the past.

The model can attend to everything inside its context window (from a few thousand to over a million tokens today). It is trained to produce plausible text, not to check facts, which is why it can state wrong things confidently. People call this hallucination; always verify important claims.

Think of it likeWriting a sentence with your hand over everything to the right of your pen: you can reread what you've already written as often as you like, but you can't peek ahead.
Try it · generate a sentence

This toy model only remembers the last word, which is exactly what a transformer improves on: a real one would attend to the whole sentence. Press "Next token" and watch the loop. The grid on the right is the causal mask: row = the token doing the looking, filled square = allowed to look.

Three families of transformer

Encoder onlyReads in both directionsExample: BERT. Good at understanding and classifying text: search, sorting reports, spotting topics.
Decoder onlyReads left to right, writesExamples: GPT, Llama and most chat assistants. Uses the causal mask. This is the kind behind today's chatbots.
Encoder–decoderReads, then writesThe original 2017 design, and T5. One half reads the input, the other writes the output. Built for translation.
The whole journey

One sentence, start to finish

Glossary

Where to go next