How a model guesses the next word

One example, start to finish. The model reads four tokens and has to fill the gap:

wheredidthecat?
Our corpus: the only text in the whole course. Module 1 cleans and tokenizes it, module 6 trains on it, module 7 tests the trained model on it.
Where did the cat sat?
The cat sat on the  mat.
the Dog  sat on the mat .
WHERE did the dog sat ?

Tiny sizes, so every number fits on screen: 10 tokens in the vocabulary, 3 numbers per token, one attention head. Every number is computed in code. Read the modules in order.

The big picture
The big picture: from text to the next token, and the two loops “Where did the cat sat?” text 1 tokens → IDs where 9 did 3 the 8 cat 2 ? 2 vectors X 4 × 3 word rows + position rows 3 question, name tag, message Q K V Q K V 4 attention: cat looks back → cat's new row h 5 chances for every token sat (after training) 6 Training compare with “sat” → loss → which way → nudge the tables repeat many times 7 Inference tables frozen → pick “sat” → append it → run again Real models: same steps, far bigger tables, many attention heads, and dozens of stacked blocks (3–4).
Part A · The forward pass: from text to a guess (used by training and inference)
Part B · Training: the weights change
Part C · Inference: the weights are frozen

The modules

1

From text to tokens

Clean the raw text, chop it into tokens, and give every distinct token an ID number.

Hover or tap a token to see it light up everywhere it appears. Tap empty space to reset.

1Our corpus: four messy sentences
Our corpus as typed, then cleaned our corpus, as typed (4 sentences) W h e r e d i d t h e c a t s a t ? T h e c a t s a t o n t h e · m a t . t h e D o g · s a t o n t h e m a t · . W H E R E d i d t h e d o g s a t · ? lower-case one space between words no space before ? or . cleaned w h e r e d i d t h e c a t s a t ? t h e c a t s a t o n t h e m a t . t h e d o g s a t o n t h e m a t . w h e r e d i d t h e d o g s a t ? fixed by cleaning

This tiny text is the only data in the whole course. Module 6 trains on it and module 7 tests on it. Cleaning first makes “The”, “the” and “WHERE”/“where” the same.

Also called normalisation.

2Chop it into tokens
The clean text is chopped into tokens w h e r e d i d t h e c a t s a t ? cut at every space, and before each punctuation mark where did the cat sat ? 6 tokens · “?” is a token too the whole corpus as tokens where did the cat sat ? the cat sat on the mat . the dog sat on the mat . where did the dog sat ?

A token is one piece the model reads. Here a token is a word or a punctuation mark.

Also called tokenization. This toy one splits by words.

3Give every distinct token an ID
Every distinct token gets an ID number ID token times it appears in our text 0 . × 2 1 ? × 2 2 cat × 2 3 did × 2 4 dog × 2 5 mat × 2 6 on × 2 7 sat × 4 8 the × 6 9 where × 2 10 distinct tokens, sorted A→Z (marks first). The ID is only a place in this list. No meaning yet.

Collect each different token once. That list is the vocabulary: 10 tokens here.

Vocabulary size V = 10.

4Our sentence as ID numbers
Our sentence becomes a list of ID numbers where did the cat sat ? 9 3 8 2 7 1 what the model sees [9, 3, 8, 2] its answer 7

From now on the model never sees letters, only these numbers.

Token IDs, length 4: [9, 3, 8, 2] → target 7.

5One sentence, five questions
One sentence gives five practice questions seen the right next token 1 where did 2 where did the 3 where did the cat 4 where did the cat sat 5 where did the cat sat ? ← question 4 is the one we follow

Every token in the text is a “guess what comes next” question. We follow question 4.

This is next-token prediction.

6Real models: pieces of words
Real models split words into pieces (byte-pair encoding) start: every letter is a piece w h e r e d i d t h e c a t s a t merge 1: h + e → he most common pair (8×) w he r e d i d t he c a t s a t merge 2: a + t → at most common pair (8×) w he r e d i d t he c at s at merge 3: t + he → the most common pair (6×) w he r e d i d the c at s at merge 4: s + at → sat most common pair (4×) w he r e d i d the c at sat Keep merging until the list is big enough: real models use 50,000 to 200,000 pieces. A brand-new word can always be spelled from pieces.

Splitting isn't a fixed rule like “every 4 letters”. It is learned from text: start from single letters (or bytes), merge the most frequent neighbouring pair into a new token, and repeat until the vocabulary reaches a chosen size. The four merges above are exactly that, run on our corpus.

Merges computed on our four sentences. Method: byte-pair encoding (BPE). The learned merge list is the tokenizer.

7One word, more than one token
One word can be more than one token a real tokenizer, trained on lots of English playing play ing 2 tokens singing sing ing 2 tokens played play ed 2 tokens “play” and “ing” show up together in many words, so each piece earned its own token. our four sentences, after the 4 merges in step 6 cat c at 2 tokens mat m at 2 tokens where w he r e 4 tokens sat sat 1 token

Pieces that often appear together earn their own token, so a word can be one token or several. “playing” becomes “play” + “ing”.

These are sub-word tokens. Each piece gets its own ID, just like the words in step 4.

Training doesn't care what a token is Whole words or word pieces, the model always does the same job: guess the ID of the next token. The loss in module 6 is the same too: −log p(the true next token), also called cross-entropy.

Caveat: the formula is identical, but loss numbers from different tokenizers aren't directly comparable, because they count different units. A word split into 3 pieces is 3 predictions; as one whole-word token it is 1. So “average loss per token” measures something different for each tokenizer. To compare, divide the total loss over the same text by its number of characters or bytes (e.g. bits per byte).

Our text is now numbers: “where did the cat” → [9, 3, 8, 2], and the right answer “sat” is 7. The sentence isn't perfect English. That's fine: a model learns whatever text it's fed.
2

From tokens to vectors

Each ID picks a row of numbers from a table, and a second table adds where the word sits.

Hover or tap a word or a row to follow it from ID to E to X. Tap empty space to reset.

blue frame: learned weights (training changes them)green frame: numbers worked out for this sentence
1Each ID picks a row of numbers
Each ID picks one row of the embedding table E E 10 × 3 0.1 0.2 −0.2 −0.5 −0.3 −0.6 0.1 0.8 −0.3 −0.4 0.3 0.2 0.1 −0.6 0.1 0.4 −0.8 −0.3 −1.1 −0.8 −1.1 −0.1 −0.8 0.2 0.1 −0.1 −1.5 −0.3 0.1 0.1 0 . 1 ? 2 cat 3 did 4 dog 5 mat 6 on 7 sat 8 the 9 where ID word vectors 4 × 3 −0.3 0.1 0.1 −0.4 0.3 0.2 0.1 −0.1 −1.5 0.1 0.8 −0.3 where did the cat Random at first. Training reshapes these numbers.

A table called E has one row of 3 numbers for every token in the vocabulary. Our four IDs pick four rows.

E is the embedding table (10 × 3). A row is the token's embedding vector.

2The same lookup, as a multiplication
Picking a row is the same as multiplying a one-hot row by E “where” as a row of zeros with one 1 0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 1 9 1 × 10 × E 10 × 3 = −0.3 0.1 0.1 row 9 of E Every 0 wipes out its row; the single 1 keeps row 9.

A row of zeros with a single 1, times E, gives exactly one row of E. Same answer, matrix style.

one-hot vector · E = embedding.

3Add where each word sits
Add a position row so the model knows the order word 4 × 3 where −0.3 0.1 0.1 did −0.4 0.3 0.2 the 0.1 −0.1 −1.5 cat 0.1 0.8 −0.3 position P rows 0–3 −0.9 −0.3 −0.6 −0.5 0.6 −0.5 0.1 0.5 −0.4 −0.1 0.1 0.1 X 4 × 3 −1.2 −0.2 −0.5 −0.9 0.9 −0.3 0.2 0.4 −1.9 0.0 0.9 −0.2 + = P has one row per place in a sentence (0 to 6). Place 0 always adds the same row, place 1 another… Why bother? Without P, “cat did the where” would give the very same rows, just shuffled. With P, “cat” at place 0 would be [−0.8, 0.5, −0.9], not [0.0, 0.9, −0.2].

A second table, P, adds a row for each position. Now the same word in a different place looks different.

X = E[ids] + P[0:4]. P holds learned positional embeddings.

Four words are now four rows of numbers: X, 4 × 3. Each row = the word's own numbers + its position's numbers.
3

Query, key, value

Every word makes a question, a name tag and a message by multiplying with three matrices.

Hover or tap a word to follow its row. Tap empty space to reset.

blue frame: learned weights (training changes them)green frame: numbers worked out for this sentence
1The idea, with readable numbers
Hand-made example: question, name tag, message Two readable slots, made up by hand: cat asks (query): time? 1.0 question? 0.5 “I want the time first, and a bit about the question.” each word's name tag (key) match where time? 0 question? 1 0.5 did time? 1 question? 0 1.0 the time? 0 question? 0 0.0 cat time? 0 question? 0 0.0 match = query × key, slot by slot, added up each word's message (value) where “this is a where-question” did “it happened in the past” the “a thing comes next” cat “I am a cat” Best match: did. So cat mostly takes did's message: “past” → a past-tense verb like “sat” fits next.

Every word gets three things: a question (what am I looking for?), a name tag (what do I have?) and a message (what do I pass on?). These numbers are made up by hand.

question = query, name tag = key, message = value. Match = dot product q·k.

2How one row is computed
How cat's query row is computed from its X row and W_Q cat's row of X 0.0 0.9 −0.2 W_Q 3 × 3 −0.7 0.1 0.3 −0.1 0.4 0.1 0.4 0.9 −0.4 slot 1 slot 2 slot 3 each query slot = cat's row × one column, added up 0.0×(−0.7) + 0.9×(−0.1) + −0.2×0.4 = −0.17 0.0×0.1 + 0.9×0.4 + −0.2×0.9 = 0.18 0.0×0.3 + 0.9×0.1 + −0.2×(−0.4) = 0.17 cat's query −0.17 0.18 0.17 These are random numbers, so they mean nothing yet. Training will shape them, like the hand-made example.

Cat's question comes from cat's row of X times a table W_Q. Each slot: multiply pairs, add them up.

qcat = xcat · WQ (1×3 · 3×3 = 1×3). That is a matrix multiplication.

3Three tables, three jobs
X times three different tables gives Q, K and V Q · questions where −1.2 −0.2 −0.5 did −0.9 0.9 −0.3 the 0.2 0.4 −1.9 cat 0.0 0.9 −0.2 × −0.7 0.1 0.3 −0.1 0.4 0.1 0.4 0.9 −0.4 W_Q = 0.66 −0.65 −0.18 0.42 0.00 −0.06 −0.94 −1.53 0.86 −0.17 0.18 0.17 Q 4 × 3 K · name tags where −1.2 −0.2 −0.5 did −0.9 0.9 −0.3 the 0.2 0.4 −1.9 cat 0.0 0.9 −0.2 × 0.1 −0.3 0.1 −0.7 −0.3 −0.1 0.5 0.7 −0.8 W_K = −0.23 0.07 0.30 −0.87 −0.21 0.06 −1.21 −1.51 1.50 −0.73 −0.41 0.07 K 4 × 3 V · messages where −1.2 −0.2 −0.5 did −0.9 0.9 −0.3 the 0.2 0.4 −1.9 cat 0.0 0.9 −0.2 × −0.5 0.4 −1.2 −0.3 −0.1 0.8 0.4 −0.2 −0.2 W_V = 0.46 −0.36 1.38 0.06 −0.39 1.86 −0.98 0.42 0.46 −0.35 −0.05 0.76 V 4 × 3 Same X, three different tables → three different jobs.

Do that for every word with three different tables, and you get all questions, name tags and messages.

Q = X·WQ, K = X·WK, V = X·WV. Each 4 × 3. The W tables are learned.

Each word now has a question, a name tag and a message: Q, K, V, each 4 × 3. Next, cat uses its question to look back at the others.
4

Attention: cat looks back

Cat compares its question with every name tag, turns the matches into shares, and mixes the messages.

Hover or tap a word or a cell to follow it. Tap empty space to reset.

blue frame: learned weights (training changes them)green frame: numbers worked out for this sentence
1Match every question with every name tag
Every question is matched against every name tag name tag (key) of … where did the cat question of … where −0.25 later later later did −0.11 −0.37 later later the 0.37 1.19 4.74 later cat 0.10 0.12 0.19 0.06 • match = question × name tag, slot by slot, added • grey: no peeking at words that come later • cat (last row) may look at all four

A high number means “this word has what I'm looking for”. Words can't look at later words.

Scores = Q · Kᵀ (4×3 · 3×4 = 4×4). Grey cells = causal mask.

2Turn cat's matches into shares
Cat's four matches become shares that add up to 100% match ÷ √3 eˣ share cat → where 0.10 0.06 1.06 25% did 0.12 0.07 1.07 25% the 0.19 0.11 1.12 26% cat 0.06 0.04 1.04 24% total 4.28 100% 1 shrink: divide by √3 ≈ 1.73 2 make positive: e to the power 3 share: divide each by the total Nearly equal shares. With random weights, cat doesn't know what to look for yet. Training changes that (module 6).

Three small moves turn any four numbers into four shares that add up to 100%.

This is softmax(scores / √d), with d = 3. The result is cat's attention weights.

3Mix the messages
Cat mixes the messages by its shares, then keeps its own row share × message (V row) = part where 25% × 0.46 −0.36 1.38 = 0.11 −0.09 0.34 did 25% × 0.06 −0.39 1.86 = 0.02 −0.10 0.47 the 26% × −0.98 0.42 0.46 = −0.26 0.11 0.12 cat 24% × −0.35 −0.05 0.76 = −0.08 −0.01 0.18 add up: −0.21 −0.09 1.11 what cat gathered keep cat's own row, add what it gathered 0.00 0.90 −0.20 cat's X row −0.21 −0.09 1.11 gathered −0.21 0.81 0.91 new cat row h + =

Cat takes that share of each word's message, adds them up, and adds the result to its own row.

z = shares · V; h = x + z. Keeping x is the residual connection.

4Every word at once
All four words do this at the same time shares (attention weights) where did the cat where 100% = 100% did 54% 46% = 100% the 6.6% 11% 83% = 100% cat 25% 25% 26% 24% = 100% each row: one word's shares of everyone's messages. “where” can only see itself, so it gives itself 100%. H = X + shares × V −0.74 −0.56 0.88 −0.63 0.53 1.30 −0.57 0.68 −1.23 −0.21 0.81 0.91 4 × 3: every word, now mixed with its context

The same three moves happen for every row in one go, giving a new 4 × 3 table.

H = X + softmax(mask(Q·Kᵀ / √3)) · V. One attention head.

Real models stack many of these Our model has one attention block with one “head”. Real models run dozens of heads side by side and stack dozens of blocks, each with a few extra steps in between. The idea inside every block is the same as here. See the big picture on the course map
Cat's row now carries a bit of every earlier word: h = [−0.21, 0.81, 0.91]. Only this last row is needed to guess the next word.
5

Probabilities for the next word

Turn cat's final vector into a score for every token, then into chances that add up to 1.

Hover or tap a token to follow its column, score and chance. Tap empty space to reset.

blue frame: learned weights (training changes them)green frame: numbers worked out for this sentence
1A score for every token
Cat's final row times the table U gives one score per token U (3 × 10): one column per token . ? cat did dog mat on sat the where −0.21 0.81 0.91 cat h −0.2 0.9 −0.3 −0.2 0.2 −0.1 −0.1 −0.7 0.1 −0.3 0.7 0.4 0.1 0.4 −0.2 0.6 0.1 0.4 −0.8 0.2 −1.0 −1.2 −0.2 −0.5 0.1 1.3 −0.5 −0.4 0.1 0.3 scores −0.3 −1.0 0.0 −0.1 −0.1 1.7 −0.4 0.1 −0.6 0.5 each score = h × that column, slot by slot, added: sat: −0.21×(−0.70) + 0.81×0.40 + 0.91×(−0.40) = 0.11 mat: −0.21×(−0.10) + 0.81×0.60 + 0.91×1.30 = 1.69

One more table, U, has a column for each of the 10 tokens. Cat's row times each column gives that token's score.

scores = h · U (1×3 · 3×10 = 1×10). The scores are called logits.

2Scores become chances
Softmax turns the ten scores into chances that add up to 100% score eˣ chance . −0.30 0.74 5.5% ? −0.96 0.38 2.9% cat −0.04 0.96 7.2% did −0.09 0.91 6.9% dog −0.11 0.89 6.7% mat 1.69 5.43 41% on −0.35 0.70 5.3% sat 0.11 1.11 8.3% the −0.58 0.56 4.2% where 0.50 1.65 12% total 13.34 100% 1 make every score positive: e to the power 2 divide each by the total Bigger score → bigger chance. Order never changes.

Scores can be negative and don't add up to anything. Softmax makes them positive chances that add up to 100%.

p = softmax(scores) — the same two moves as in module 4. A probability distribution over the vocabulary.

3Choosing means picking from chances
The model must choose one token from the chances all chances laid end to end (0 to 100%) mat sat where Way 1 · always take the biggest mat 41% — not “sat” ✗ Way 2 · roll a dice: 20 draws each roll lands somewhere on the strip above cat mat mat . cat where ? cat where mat mat mat mat dog cat sat mat mat sat mat “sat” came up 2 of 20 times. The guess is poor: every table is still random. Module 6 trains them.

The model never just “knows” the word. It gives chances, and then one token is picked from them.

Way 1 = greedy (argmax). Way 2 = sampling. Dice rolls here are fixed in code.

The model's answer is a list of 10 chances. Right now “sat” only gets 8.3% and “mat” gets 41%. That's the end of the forward pass. Next: learning from this mistake.
6

Training: nudging the weights

Measure how wrong the guess was, find which way each number should move, nudge, repeat.

Hover or tap a token to follow it. In step 5, drag the slider or tap − / +.

blue frame: learned weights (training changes them)green frame: numbers worked out for this sentence
1The training data: our corpus
The training data is our corpus from module 1 our corpus, cleaned and tokenized in module 1 where did the cat sat ? 5 questions the cat sat on the mat . 6 questions the dog sat on the mat . 6 questions where did the dog sat ? 5 questions 22 questions Every token except the last is a question: “what comes next?” The next token is its answer. where did where did the where did the cat where did the cat sat where did the cat sat ? … and the same for the other three sentences.

Training uses nothing but the four sentences cleaned in module 1: the same tokens and the same IDs. They hold 22 “guess the next token” questions, each with a known right answer.

Each question is a (context, next token) pair. This is self-supervised: the text supplies its own answers.

2The training loop
The training loop training text: 4 sentences = 22 next-token questions 1 Guess run the forward pass → chances for each token 2 Score the guess compare with the right token → loss (how wrong) 3 Which way? for every number: should it go up or down? 4 Nudge move every number a small step that way repeat × 150 Only step 4 changes the model. Every blue-framed table (E, P, W_Q, W_K, W_V, U) gets nudged.

Training is four moves, repeated. Only the last move changes the model.

forward pass → loss → gradients (backpropagation) → gradient descent step. This next-token training is the only kind of training in this course; other methods are out of scope.

3How wrong was the guess?
The loss: a penalty that grows as the right token's chance shrinks 0% 25% 50% 75% 100% 0 1 2 3 4 chance given to the right token “sat” loss before training 8.3% → loss 2.48 after training 99% → loss 0.01 100% sure and right → no penalty. Near 0% → a huge penalty.

One number scores each guess: small when the right token got a big chance, big when it got a small one.

loss = −log p(right token). Called cross-entropy loss.

4Which way should each score move?
For each token: chance minus right answer says which way to push its score chance right? c − r ← raise lower → . 5.5% 0 0.06 ? 2.9% 0 0.03 cat 7.2% 0 0.07 did 6.9% 0 0.07 dog 6.7% 0 0.07 mat 41% 0 0.41 on 5.3% 0 0.05 sat 8.3% 1 −0.92 the 4.2% 0 0.04 where 12% 0 0.12 Only “sat” is right (1), so only its score is pushed up. Every other score is pushed down by its own chance.

Subtract the right answer (1 for “sat”, 0 for the rest) from the chances. Negative → raise that score. Positive → lower it.

∂loss/∂scores = p − y, where y is the one-hot right answer.

5One nudge, worked by hand
One nudge of the sat column of U, worked out by hand push for “sat”: 8.3% − 1 = −0.92 step size η = 0.3 h h × push old new U column “sat” slot 1 −0.21 0.19 −0.70 −0.76 slot 2 0.81 −0.74 0.40 0.62 slot 3 0.91 −0.83 −0.40 −0.15 new = old − η × (h × push) push is negative, so the sat column moves toward h. Run the guess again with the new U: before sat 8.3% after one nudge sat 13% Every other column of U moves too, by its own push.

The push travels back to the table U: each number moves by (cat's row × push), times a small step size.

∂loss/∂U = hᵀ(p − y); U ← U − η · ∂loss/∂U. The same idea reaches E, P and the W tables, one step further back each time (chain rule).

6Now repeat, for every question
Training on all four sentences, step by step step 0 2.8 0 150 steps “where did the cat ___” . ? cat did dog mat on sat the where − + drag, tap, or use − / +

Drag the slider. Each step nudges every table using all 22 questions at once. The loss falls and “sat” wins.

150 steps of plain gradient descent, η = 0.3. All 26 frames are computed in Python, not in your browser.

After training, the same forward pass gives “sat” 99% (it started at 8.3%). The tables now hold what our four-sentence corpus taught them.
7

Inference: predicting “sat”

Same forward pass with frozen weights: pick a word from the chances, append it, go again.

Hover or tap a token to follow it. In step 2, drag the temperature slider or tap − / +.

blue frame: learned weights (training changes them)green frame: numbers worked out for this sentence
1Same forward pass, trained tables
The same forward pass, now with the trained tables where did the cat → ? cat's shares (attention) grey = before training where 20% did 27% the 22% cat 31% chances for the next token (top 4) sat 99% the 0.7% . 0.5% mat 0.1% pick the biggest: sat ✓ the right answer No right answer needed. No loss. No nudge. The tables stay exactly as training left them.

Exactly modules 1 to 5 again, with the tables from training. Now “sat” wins by far.

Inference = forward pass only. No loss, no gradients, no weight updates.

2Temperature: how bold to be
Temperature: how adventurous the dice roll is temperature . ? cat did dog mat on sat the where 20 dice rolls (the same rolls at every temperature) − + 0.1 3.0 drag, tap, or use − / +

Before rolling the dice, divide every score by the temperature. Low = almost always the top token. High = more variety.

p = softmax(scores / T). Every frame is computed in Python with the same 20 fixed dice rolls.

3Append and repeat
Append the chosen token and run again 1 where did the cat → picks sat 99% 2 where did the cat sat → picks ? 100% “?” ends the question, so we stop: where did the cat sat ?

The picked token is added to the input and the whole forward pass runs again, one token at a time.

This loop is called autoregressive generation.

4Back to our corpus
The trained model finishes every sentence of our corpus give it the first 4 tokens of each corpus sentence → it keeps picking the top token until “.” or “?” where did the cat sat 99% ? 100% ✓ the cat sat on the 99% mat 98% . 96% ✓ the dog sat on the 99% mat 98% . 96% ✓ where did the dog sat 97% ? 100% ✓ ✓ = same ending as in the corpus. It learned the patterns in its training text, and nothing else: it has never seen any other text.

The test: start each sentence from module 1's corpus and let the trained model finish it on its own.

Greedy generation, computed in Python with the trained tables from module 6.

5Training vs inference
Training versus inference training inference forward pass yes yes right answer needed not needed loss computed none which-way step yes no tables (weights) nudged frozen result better tables next token how often 150 steps here each time you ask Same maths for the guess. Only training learns.

Both run the same forward pass. Only training compares with a right answer and changes the tables.

The full journey: text → tokens → vectors → question, name tag, message → attention → chances → “sat”. Training made the tables; inference just uses them.