How a model guesses the next word
One example, start to finish. The model reads four tokens and has to fill the gap:
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.
Whole course on one page (one file, works offline, good for printing or saving).
From text to tokens
Clean the raw text, chop it into tokens, and give every distinct token an ID number.
raw text → tokens → IDs [9, 3, 8, 2] 2From tokens to vectors
Each ID picks a row of numbers from a table, and a second table adds where the word sits.
IDs 1×4 → E rows + P rows → X 4×3 3Query, key, value
Every word makes a question, a name tag and a message by multiplying with three matrices.
X 4×3 · W_Q, W_K, W_V 3×3 → Q, K, V 4×3 4Attention: cat looks back
Cat compares its question with every name tag, turns the matches into shares, and mixes the messages.
Q·Kᵀ 4×4 → no peeking → shares → ·V → H 4×3 5Probabilities for the next word
Turn cat's final vector into a score for every token, then into chances that add up to 1.
h 1×3 · U 3×10 → scores 1×10 → softmax → p 1×10