Attention and Next-Token Generation — Which Words It Looks At and How It Chooses the Next Word

With pictures and motion, we see which words in a sentence a small model trained for this book (not GPT) gathers information from, and how it chooses the next word to write a sentence.

In tab ① you follow Q, K, V → scores → mask → softmax weights → output numerically with small hand-set matrices, and check what dividing by √dk means and how the causal mask works. In tab ② you run a small Transformer trained for this book inside the browser and examine the next-token probabilities, how the distribution changes with temperature, top-k, and top-p, and whether the generated sentences are correct. Notice also that a high-probability sentence is not always a correct one. The small model was trained on Japanese text, so its tokens appear in Japanese; English glosses are given alongside.

① Calculation demo with hand-set weightsTab ①All matrix values are entered by hand. Nothing is trained. It is meant for following the steps of the attention computation numerically.
② Small model trained for this bookTab ②A decoder-only Transformer (2 layers, 2 heads, dmodel = 32, 28,384 parameters). It was trained only on a synthetic teaching corpus of short Japanese sentences about materials. It is a small model of the same type as GPT, but it is not GPT.
③ A real GPTNot hereIt does not run on this page. Both its scale (number of parameters and layers) and its training data (huge amounts of real text) differ by orders of magnitude, so the numbers in ② (such as the error rates) do not carry over directly.

Which earlier words does this word look at?

When a small trained model reads a sentence, the position of each word gathers information from the words before it. Choose a word, and the thickness of the lines shows which words it gathers from and in what proportions (the attention weights).

These are actual computed values from a small model trained for this book only on synthetic data for teaching purposes (short sentences made from a table of material properties). It is not GPT.

Back to Machine Learning — From Probability to GPT (Contents) | Text: Chapter 24, Section 24.3, Chapter 26, Section 26.6 | Equations and explanation (explanation page) | Equations are typeset with the browser’s built-in MathML (no external library).