Explanation of the Attention and Next-Token Generation Simulator — What the Thickness of the Lines and the Length of the Bars Compute

This page explains what the “thickness of the lines” and the “length of the bars and the lottery” you saw in the simulator correspond to in the language of machine learning, and by what formulas they are computed, in the order words → formulas → calculation procedure. The procedure for the detailed view, the conditions of the calculation, and questions for checking are also collected here.

1. About this page

The Attention and Next-Token Generation Simulator is a tool for seeing “which earlier words a model that reads sentences gathers information from” and “how it chooses the next word and adds it to the sentence.” It is used in Chapter 24 (Attention), Chapter 25 (the structure of the Transformer), and Chapter 26 (GPT and next-token generation).

The simulator has two views.

Both scenes of the simple view are computed with the same model and the same functions as ② of the detailed view. This model is a small model trained for this book only on synthetic data for teaching purposes (short sentences generated mechanically from a table of material properties). It is of the same type as GPT (a decoder-only Transformer), but it is not GPT (Chapter 26, Section 26.1). We recommend reading in this order: try the simple view, check what it really shows in Section 2, read the formulas in Section 3, and operate the detailed view with the procedure in Section 4.

2. What the simple view really shows

The model used in the simple view is a decoder-only Transformer with 2 layers, 2 heads per layer, embedding dimension dmodel = 32, a vocabulary of 67 words, a context length of 24, and 28,384 parameters (Chapter 25, Section 25.8). Its tokens are whole words (separated by spaces), and each card on the screen is one token. The sequence begins with <bos>, which marks the start of a sentence (shown as [start] on the screen), and a sentence ends with <eos> (shown as [end] on the screen) (Chapter 26, Section 26.3).

2.1 Scene A: Which earlier words does this word look at?

One sentence is fed in and one forward pass of the model is computed. From the attention weight matrix A of the chosen layer and head, the row for the position i of the chosen word is taken out and turned into the thickness of lines. The larger the weight Aij, the thicker the line (lines with weights below 1 % are not drawn, and lines with 4 % or more are labeled with the % value). The weights in one row are 0 or more and add up to 1. Because of the causal mask, the weights on later words (j > i) are exactly 0.

Table 1: Words on the screen in Scene A and the corresponding terms and symbols
Words on the screenTermSymbol or formula
Word cards ([start], ニッケル, は, …)Tokens (whole words). The first is <bos>x1 = <bos>, x2, …, xT
Chosen word (orange frame)Query positioni
Thickness of a line, % on a lineAttention weight (share of information gathered)Aij, Σj Aij = 1
View 1–4 (Layer L, head H)Layers and heads (2 layers × 2 heads = 4 weight matrices)For layer ℓ, head h: A(ℓ, h)
Later words are not visible (weight 0)causal maskMij = −∞ (j > i), so Aij = 0
Predicted next word at this positionThe top word of the next-token distribution made from the logits at position i (τ = 1)argmaxk p(xi+1 = k | x≤i)
Gray dotted linesWeights of the layer and head before the view was changedThe previous A(ℓ′, h′), row i

Values in “Try it” (all computed with this model):

For the third sentence, “金属 の 例 に は 鉄 が ある .” (“examples of metals include iron.”), the row for “は” (View 4) has 金属 (“metal”) 0.819, the same value as recorded in Chapter 25, Section 25.8.

Where the analogy fits and where it does not

Where it fits: The thickness of the lines is exactly the attention weights computed with the same function as ② of the detailed view (forward in attention.model.js). If you choose the same context and the same layer and head in the attention-weight figure of ② in the detailed view, you get the same values.

Where it does not fit: A weight is “the share in which, in that layer and that head, information is gathered from each position.” It is not necessarily the reason itself for the model’s decision (Chapter 24, Section 24.10). There are four reasons. (1) The contribution of position j to the output is Aijvj, so even if the weight is large, the contribution is small if the value is small. (2) Different weights can give the same output. (3) The vector at position j in layer 2 has already gathered information from other positions in layer 1, so even if a thick line in layer 2 goes to “ニッケル”, you cannot say that it is looking only at the original word “ニッケル”. (4) There are 4 weight matrices (layers × heads), and the output is further affected by the output projection and the FFN. The “Predicted next word at this position” also comes not from the single head shown on the screen but from the computation of the whole model through the 4 heads and the FFN. Also, each card is a whole-word token of this model, which differs from the subword tokens of a real GPT (Chapter 26, Section 26.2).

2.2 Scene B: How is the next word chosen?

The sentence being written (the context) is fed into the model, and from the logits at the last position, the probabilities of the next word are computed by a softmax with temperature τ; the top 6 words (5 words when the picture is narrow) are shown as bars in descending order. The probabilities of the remaining words are lumped together as the hatched “Other.” The “Lottery strip” is a strip from 0 to 1 with intervals arranged in descending order of probability, and the next word is decided by where a uniform random number u falls on the strip (the position of the needle). The chosen word is added to the end of the sentence, and the same computation is done again. This is the autoregressive generation of Chapter 26, Sections 26.3–26.6.

Table 2: Words on the screen in Scene B and the corresponding terms and symbols
Words on the screenTermSymbol or formula
Sentence being written (Opening words)Context (prompt)x≤t (x1 = <bos>)
From a blank pageContext of <bos> onlyx1 = <bos>, t = 1
Words in orange framesGenerated tokensxt+1, xt+2, …
Length of a barNext-token probability (softmax with temperature)pk(τ) = p(xt+1 = k | x≤t)
Other n words (hatching)Sum of the probabilities of the words other than the top 6 (or 5)1 − Σtop pk(τ)
How to choose: Safe / Normal / Whimsicaltemperatureτ = 0.5, 1, 2
Lottery strip (Numbers = bar ranks)Cumulative intervals obtained by adding the probabilities in descending orderInterval of rank r: [cr−1, cr), cr = p(1) + … + p(r)
Needle (% from the left of the strip)Uniform random numberu ∈ [0, 1)
Erase and rewrite (new draw)Regenerating with a different random-number seedseed = 20261112 + k (k = 0, 1, 2, …)
[end]End-of-sentence token<eos>
Judgment of the sentenceJudgment of the generated sentence (checked against the table used to make the training data)Same rules as the judgment in ② of the detailed view

The judgment words correspond to those of the judgment in ② of the detailed view as follows: “✓ Matches the table” = Correct, “✗ Disagrees with the table” = Wrong (contradicts the table), “? Not in the table” = Unsupported by the training data, “— Fits no sentence template” = Fits no template, and “… Not a full sentence” = Incomplete.

Probabilities of the next word with the opening “Examples of metals” (context “<bos> 金属 の 例 に は”, “metals, for example”):

Table 3: Probabilities of the next word after “金属 の 例 に は” and the way of choosing (temperature)
How to choose鉄 (iron)銅 (copper)アルミニウム (aluminum)マグネシウム (magnesium)銀 (silver)金 (gold)Other 61 words
Safe (τ = 0.5)0.3970.3190.2750.00440.00370.00130.0004
Normal (τ = 1)0.3210.2880.2670.0340.0310.0190.040
Whimsical (τ = 2)0.1720.1630.1570.0560.0530.0410.358

The ratio of the probabilities of 鉄 (iron) and 銅 (copper) is, at τ = 1, 1.116 (= 0.3214/0.2881); at τ = 0.5, 1.245 (= 1.1162); and at τ = 2, 1.056 (= √1.116) (Section 3.3).

Values in “Try it” and on the first screen:

Where the analogy fits and where it does not

Where it fits: Both the probabilities of the bars and the lottery are computed with the same functions as ② of the detailed view (in attention.model.js, nextDist and step) and the same random-number generator (mulberry32, default seed 20261112). The position of the needle is exactly the uniform random number u actually used for sampling. The three opening sentences are the same as context presets in ② of the detailed view.

Where it does not fit: “Safe” and “Whimsical” are names given to values of the temperature τ. The formula with τ has the same form as the Boltzmann distribution of statistical mechanics, but τ is not a physical temperature; it is a number that changes the sharpness of the distribution (Chapter 26, Section 26.6). The judgment checks against the table used to make the training sentences, not against all the facts in the world. A high probability does not mean correctness (the mercury example). This model only outputs next-word probabilities by imitating the word order of the sentences it learned; it does not understand meaning and write clever text, and it also produces sequences that make no sense. The simple view does not use top-k or top-p (the same as the default “off” in the detailed view). The needle moving over the strip is only an animation; the random number is drawn only once per word.

3. How it works

3.1 Splitting the probability of a sentence into a product of “next words”

If we view a sentence as a sequence of tokens x1, x2, …, xT, we can use the product rule of probability repeatedly to split the probability of the whole sequence into a product of “the probability of the next token given the context so far” (Chapter 26, Section 26.3).

p(x1:T)=∏t=1Tp(xt∣x<t)

This is not an approximation but an identity. The model computes each factor on the right-hand side with one network. The first token is x1 = <bos>. From the context up to position t, x≤t, the model produces the logits at position t (67 real numbers, one per vocabulary word), and a softmax turns them into the probabilities of the next token xt+1. Scene B of the simple view shows these “next token” probabilities as bars, and repeatedly chooses one and adds it to the context.

3.2 Attention: gathering information from earlier positions with weights

From the vector at each position, a query qi, a key kj, and a value vj are made, and the values are averaged with weights that are larger for positions where the dot product of the query and the key is larger. The thickness of the lines in Scene A of the simple view is the weight Aij in the formula below.

The sequence is arranged in rows (in X ∈ ℝT×dmodel, row t is the vector at position t; linear maps are applied from the right).

Q=XWQ,K=XWK,V=XWV,Attention(Q,K,V)=softmax(QKTdk+M)V

The softmax is taken for each row (each query) along the columns (keys). The weights and output of row i are

sij=qi⋅kjdk+Mij,Aij=expsij∑j′expsij′,zi=∑jAijvj,Mij={0(j≤i)−∞(j>i)

(M = 0 when the causal mask is off). The softmax subtracts the maximum of each row before taking exp (the values are the same, and there is no overflow). Since exp(−∞) = 0, the weights at masked positions are 0 and the row sums stay 1.

In the trained model, two heads in one layer each do this computation with their own WQ, WK, and WV; their outputs are concatenated and multiplied by the output projection WO (multi-head attention; Chapter 24, Section 24.7). Two such layers are stacked, so there are 2 × 2 = 4 weight matrices, and “View 1–4” in Scene A of the simple view are these 4.

3.3 The probability of the next word and choosing by lottery

The bars in Scene B of the simple view are pi in the formula below (top-k and top-p are not used, so pi′ = pi).

In ②, the next-token probability is built from the logits at position t, oi (i is the vocabulary index), as

pi=exp(oi/τ)∑jexp(oj/τ),pi′=pi∑j∈kept wordspj

The order is: (1) divide the logits by τ; (2) softmax; (3) top-k: keep the k words with the largest probabilities; (4) top-p: add up the probabilities renormalized in (3) in descending order and keep words until the cumulative sum reaches p or more; (5) renormalize the probabilities of the remaining words to sum to 1. Greedy decoding picks the word with the largest logit. In sampling, one uniform random number u is drawn, probabilities are added in descending order, and the first word at which the sum exceeds u is chosen.

How temperature changes the ratio of probabilities can be read directly from the formula. If the ratio of the probabilities of two words at τ = 1 is r = eoi − oj, the ratio at τ is

pi(τ)pj(τ)=e(oi−oj)/τ=r1/τ

(Chapter 26, Section 26.6). At τ = 0.5 (Safe), the ratio is squared and widens, so the probability gathers on the top words; at τ = 2 (Whimsical), the ratio shrinks to its square root, so the lower words also get some probability. The ranking does not change when τ is changed.

The lottery (sampling) arranges the probabilities in descending order p(1) ≥ p(2) ≥ …, draws one uniform random number u, and

r=min{r′:cr′>u},cr=∑s=1rp(s)

chooses the word of rank r. The probability that u falls in the interval [cr−1, cr) is the length of that interval, p(r), so each word is chosen with exactly its probability. The “Lottery strip” in Scene B of the simple view lines up these intervals from the left.

3.4 Computation of the whole model and judgment of generated sentences

Forward pass of the model (pre-LN): ht = WE[xt] + WP[t], and in each layer h ← h + MHA(LN(h)) (MHA is multi-head attention) and h ← h + FFN(LN(h)). Finally, applying LN and multiplying by WET gives the logits. The logits at position t give the distribution of xt+1. The log-probability of a sequence uses the probabilities of the model itself (τ = 1):

lnp(xa:b∣x<a)=∑t=ablnp(xt∣x<t),perplexity=exp(−1nlnp)

(n is the number of tokens). Because of the causal mask, a single forward pass over the whole sequence gives the probabilities at all positions at once.

Generated sentences are judged against the table used to make the training data and the 8 sentence templates: correct (fits a template and agrees with the table value), wrong (contradicts the table), unsupported by the training data (fits a template, but the table has no value for that property of that material, for example the crystal structure of a polymer; a sentence that never appears in the training data), and does not fit a template. A sentence that has not ended with the period token is incomplete and is not judged.

3.5 Calculation procedure

Scene A of the simple view (for one sentence):

  1. Split the sentence at the spaces into a sequence of token numbers, and put <bos> at the head.
  2. Compute one forward pass of the model, and obtain the weight matrix A(ℓ, h) of each layer and head and the logits at each position (because of the causal mask, one computation gives all positions at once).
  3. From the matrix of the chosen view (layer and head), take the row for the position i of the chosen word, and turn the weights for j ≤ i into the thickness of lines. Sort them in descending order and read out “Where the thickest line goes.”
  4. Apply a softmax with τ = 1 to the logits at position i, and show the word with the largest probability as “Predicted next word at this position.”

Scene B of the simple view (each time one word is added):

  1. Compute the forward pass of the model on the current context (<bos>, the opening words, and the words written so far), and obtain the logits at the last position.
  2. Divide the logits by τ, apply softmax, and sort the probabilities in descending order. Show the top 6 words (or 5 words) as bars, and the sum of the rest as “Other.”
  3. Draw one uniform random number u, choose the first word at which the cumulative sum exceeds u, and add it to the context.
  4. Repeat 1–3 until <eos> appears or the context length of 24 is reached. Judge the last sentence.

The computations of the simple view call the same functions as the detailed view (forward, nextDist, step, sentences, and judge in attention.model.js). The only computations added for the simple view are sorting the rows of weights, lumping the words into the top words and “Other,” and rounding the percentages (attention.easy.js).

4. How to use the detailed view

The detailed view has two tabs: ① (hand calculation of scaled dot-product attention) and ② (small trained model). ① follows numerically the computation with small hand-entered matrices; it is not a trained model. ② uses the same trained model as the simple view and lets you check numerically the next-token distribution, generation, judgment, and attention weights.

4.1 Procedure and what to observe

  1. Look at ① with the defaults (T = 3, dmodel = dk = 2, WQ = WK = WV = identity matrix, rows of X: (1, 0), (0, 1), (1, 1)). What to see: row 1 of the scores is (1, 0, 1); dividing by √2 gives (0.7071, 0, 0.7071); the weights are (0.4011, 0.1978, 0.4011); the output is (0.8022, 0.5989). The weights of every row sum to 1.
  2. Turn on “causal mask.” What to see: the weights of row 1 become (1, 0, 0), and the output is exactly row 1 of X. Row 2 is (0.3302, 0.6698, 0). Row 3 (the last position) is the same as before masking.
  3. Select the preset “W_Q × 3 (larger scores)” and turn “Divide by √d_k” on and off. What to see: the larger the scores, the more the weights concentrate on a single key (softmax saturates). Dividing by √dk shrinks the scores and makes the weights flatter.
  4. Press “Swap rows 1 and 2 of X” (with the mask off). What to see: rows 1 and 2 of the output Z are swapped in the same way (permutation equivariance). Attention alone carries no information about order.
  5. In ②, select the context preset “金属 の 例 に は” (“metals, for example”) and set the temperature τ to 0.5, 1, and 2. What to see: the top probabilities (at τ = 1: 鉄 “iron” 0.321, 銅 “copper” 0.288, アルミニウム “aluminum” 0.267) become sharper at τ = 0.5 and flatter at τ = 2. With top-p = 0.9, four words remain and their probabilities are renormalized to sum to 1.
  6. In ②, select the preset “水銀 は 常温 で” (“mercury at room temperature is”) and press “One token, greedy.” What to see: although the table says liquid, the model chooses 固体 (“solid”) with probability 0.998, and the judgment is “Wrong (contradicts the table).” A high probability does not mean the answer is correct.
  7. In ②, select the preset “チタン酸バリウム の 結晶構造 は” (“the crystal structure of barium titanate is”) and press “One token, sampled” several times while changing the seed. What to see: the correct perovskite structure has probability 0.047 (4th place), and plausible errors (such as the rock-salt structure, 0.550) come out often. The rarer the material in the training data, the more error-prone it is.
  8. In ②, look at the attention weights of layer 2, head 2. What to see: at the last position of “ニッケル は 磁石 に” (“nickel, to magnets”), a weight of 0.94 is placed on ニッケル (“nickel”). Note, however, that the weights are proportions in which information is gathered, not necessarily the reason for a decision.

With the keyboard, Tab moves to buttons, number fields, and sliders; Enter (or Space) presses a button; the arrow keys change numbers and sliders. Tabs can be switched with the ←→ keys.

5. Conditions of the calculation

5.1 Data and random-number conditions

5.2 Conditions fixed in the simple view

5.3 Simplifications

5.4 Conditions under which results become unstable

6. Questions for checking

Questions 1 and 2 can be answered with the simple view alone. Questions 3–6 use the detailed view.

  1. In Scene A of the simple view, the row for “に” in “ニッケル は 磁石 に つく .” (“nickel sticks to magnets.”) puts a weight of 94 % on “ニッケル” (“nickel”) in View 4. Can you conclude from this that “the model predicted ‘つく’ (‘sticks’) because of ‘ニッケル’”?
    Sample answer

    No. A weight is the share in which, in that layer and that head, information is gathered from each position. As in View 1, where the row for the same “に” is split into 磁石 37 %, は 29 %, and ニッケル 18 %, the way of sharing differs among the 4 heads, and the prediction comes from a computation through all of them and the FFN. The vector at the position of “ニッケル” in layer 2 also contains information from other positions mixed in at layer 1. To say that the information of “ニッケル” was used, you would need to replace “ニッケル” with another word and examine how the prediction changes (Chapter 24, Section 24.10).

  2. In Scene B of the simple view, with “Examples of metals” and Normal, pressing “▶ Choose the next word” chose “銀” (“silver,” 3 %) rather than the top word “鉄” (“iron,” 32 %). Why? If the way of choosing is set to “Safe,” what happens to the probability that “銀” is chosen?
    Sample answer

    The next word is chosen by lottery (sampling), so even a word with a probability of 3 % is chosen with a probability of 3 %. The random number here is u = 0.931, and the first word at which the cumulative sum exceeds 0.931 is the 5th word, “銀” (cumulative 0.911–0.942). With Safe (τ = 0.5), the probability ratios to the top words are squared and widen, so the probability of “銀” drops to 0.4 %, and 99 % gathers on the top 3 words.

  1. With the defaults in ①, explain from the scores and the exp values why the weights of row 1 are (0.4011, 0.1978, 0.4011). What happens to row 1 when the causal mask is applied?
    Sample answer

    The scores of row 1 are the dot products (1, 0, 1) of q1 = (1, 0) with each key, divided by √2, giving (0.7071, 0, 0.7071). Taking exp gives (2.028, 1, 2.028), and dividing by the sum 5.056 gives (0.4011, 0.1978, 0.4011). Columns 1 and 3 have the same query–key dot product, so they get the same weight. With the causal mask, row 1 can see only itself (j = 1), so the weights are (1, 0, 0) and the output is v1 = (1, 0).

  2. If WQ is multiplied by 3, how skewed are the weights of row 3 when you do not divide by √dk? What happens when you do divide?
    Sample answer

    The scores of row 3 are (3, 3, 6). Without dividing, the weights are (0.0453, 0.0453, 0.9094), almost entirely on column 3. Dividing by √2 gives (2.121, 2.121, 4.243), and the weights are (0.0967, 0.0967, 0.8066). The more the scores are shrunk, the flatter the weights become, which avoids softmax saturation (small gradients).

  3. In ②, for “水銀 は 常温 で” (“mercury at room temperature is”), why does the model choose 固体 (“solid”) with probability 0.998? Are a high probability and correctness the same thing?
    Sample answer

    In the training data, sentences like “<metal> is solid at room temperature” are frequent, and there is only one sentence about mercury (liquid). The next-token prediction loss only raises the likelihood of words that tend to come next in the training data, so a rare exception is pulled toward the majority value. The ln p of the whole sentence is also larger for the wrong “solid” sentence (−9.57) than for the correct “liquid” sentence (−17.68), so a high probability does not mean correctness.

  4. For “金属 の 例 に は” (“metals, for example”), what are the probabilities of the top 3 words at τ = 0.5 and τ = 2? How many words remain with top-p = 0.9?
    Sample answer

    At τ = 1: 鉄 (iron) 0.321, 銅 (copper) 0.288, アルミニウム (aluminum) 0.267. At τ = 0.5: 0.397, 0.319, 0.275 (the probability ratios are squared, so the mass gathers on the larger ones). At τ = 2: 0.172, 0.163, 0.157 (the ratios become square roots, so the distribution is flatter). With top-p = 0.9 (τ = 1), four words remain: 鉄, 銅, アルミニウム, and マグネシウム (magnesium) (cumulative 0.910), and each probability is divided by 0.910.

7. Corresponding sections of the text and references

References (from the ends of Chapters 24 and 26):

Back to the Attention and Next-Token Generation Simulator | Machine Learning — From Probability to GPT (Contents) | Equations are typeset with the browser’s built-in MathML (no external library).