The Transformer, Number by Number  ·  Part 6

How the Decoder Writes

Part 5 showed how the encoder turns an input sentence into vectors. Those vectors carry information about the sentence, but they are not yet a translation. How does the decoder use that information to generate a translation, one token at a time?

Our example. We start with the English sentence I love LLMs and use J’aime les grands modèles (“I love large models”) as a simplified French translation. We will follow how an encoder–decoder model chooses each French token and decides when to stop.

For this illustration, treat each displayed word—including J’aime—as one token: three in the English sentence and four in the French translation. Real tokenizers may split these words differently. The French choices are illustrative, so we can concentrate on the generation process.

This is inference: we use a model that has already been trained, keeping its weights fixed. Here, we use it to generate a translation one token at a time. We call this repeated process the generation loop.

We will first identify the decoder’s inputs, then examine its output vectors and how one vector becomes a token choice. Finally, we will connect the runs to generate the complete translation.

What you need. Vectors, dot products, softmax, embedding lookup, and the encoder block from Part 5.

6.1What information does the decoder use?

Imagine that the model has already generated J’aime les and is now choosing what comes next. Each decoder run is used to choose one next token, so this is run 3.

The decoder receives two inputs:

Figure 1 shows the target prefix entering from the bottom and source memory entering from the side. These are the two “doors” into the decoder.

Two inputs to the decoder on run 3The target prefix start, J’aime, les enters from below. The three source-memory vectors for I love LLMs enter from the side. The muted upper path previews the three output vectors and the choice grands, explained in Sections 6.2 and 6.3.Run 3 · identify the two inputsSOURCE MEMORY · side inputThree vectors from the English sentenceIloveLLMsencoder · already runFixed throughout this translationdecoderuses both inputsTARGET PREFIX · bottom inputGrows as French tokens are generated<start>J’aimelesOutput pathExplained in Sections 6.2–6.3Three output vectorslast rowoutput head+ token selectiongrands
Figure 1. The target prefix enters from below; source memory enters from the side. One group of squares represents one vector. Focus on these two inputs here; Section 6.2 explains the output vectors above the decoder.

6.1.1The bottom input: the target prefix

Each token in <start> J’aime les is represented by an embedding vector, with positional information to indicate its place in the sequence. These three tokens therefore give three input rows. Self-attention lets the decoder use information from this prefix when choosing the next French token.

As more French tokens are generated, they join the target prefix. Section 6.4 will trace that process across all the runs.

6.1.2The side input: source memory

The encoder processes I love LLMs once, before generation begins. The resulting source memory stays fixed throughout this translation. Cross-attention lets the decoder use information from these vectors when choosing each French token.

Both inputs happen to have three rows in Figure 1. Their lengths do not have to match: the target prefix grows, while source memory still contains the same three vectors.

6.1.3How the source sentence changes the result

To see why source memory matters, go back to the beginning, before any French token has been generated.

Consider translating I love LLMs and LLMs love me. Both tasks begin with the same target prefix, <start>, and use the same model. Why can their first French tokens be different?

The English sentences produce different source memory. The decoder therefore has different source information to use when choosing the first French token, even though the starting target prefix is the same.

Same start token, different source memoryTwo tasks use the same model and the same start token. The source sentences I love LLMs and LLMs love me produce different source memory. The decoder uses that memory when choosing the first French token. J’aime and Les are illustrative choices.Same model and <start> token · different source sentencesCASE AI love LLMsencoderSource memory Adecoder+ token selection<start>same starting inputExample first tokenJ’aimeCASE BLLMs love meencoderSource memory Bdecoder+ token selection<start>same starting inputExample first tokenLes
Figure 2. The starting target prefix is <start> in both cases. Different source memory gives the decoder different information for choosing the first French token. J’aime and Les are illustrative choices.
Key takeawayThe decoder uses two inputs together: the target prefix, which grows as French tokens are generated, and source memory, which carries information about the English sentence and stays fixed throughout its translation.

Try it (1 minute): Begin a new translation with LLMs love me instead of I love LLMs. Before generating the first French token, which of the decoder’s two inputs changes, and which stays the same?

Check your answer

Source memory changes because the encoder processes a different English sentence. The starting target prefix is still the single token <start>.

We now know what goes into the decoder. What vectors come out, and which one is used to choose the next token?

6.2What does one decoder run produce?

On run 3 in Figure 1, we feed <start> J’aime les into the decoder: the start token followed by the French tokens generated so far. The decoder updates the vectors for these three tokens using information from the target prefix and source memory. When its calculations finish, we have three output vectors: one for <start>, one for J’aime, and one for les.

These output vectors are called the decoder’s final hidden states. Here, “final” means that the decoder has finished its calculations for the current run. There is one such vector for each input token.

The next step is to use one of these vectors to choose the next French token. Which vector should we use?

6.2.1Why use the vector for the last input token?

We already have <start> J’aime les. Our next task is to choose the token that comes after les.

During training, the model learns to use the output vector at each position to predict the token immediately after that position. For this run, we therefore use the output vector for les.

We send this vector to the output head, which computes a score for each possible next token. This vector corresponds to the position of les, but it already incorporates information from earlier French tokens through self-attention and from the English sentence through cross-attention.

Arrange the output vectors as a matrix in the same order as the input tokens, with one vector per row. The vector for les is in the last row, highlighted in Figure 3.

Figure 3. The last row of the decoder output matrix Three rows correspond to start, J’aime, and les in input order. Each row contains four schematic vector components. Only the last row, corresponding to les, is highlighted and connected to the output head. Input tokenFinal hidden states<start>J’aimeleslast rowoutput headnext-token scoresone vector per row
Figure 3. Output vectors in input order. The last row, for les, goes to the output head. Small cells represent vector components; numerical values are omitted.
Key takeawayProcessing the full prefix produces one final hidden-state vector per input token. We use the vector for the last input token to choose the next token. This vector already incorporates information from the preceding tokens and the English source sentence.

Try it (1 minute): The input is <start> J’aime les grands.

  1. How many final hidden-state vectors does the decoder produce?
  2. Which token’s vector goes to the output head?
  3. Does using that vector mean ignoring J’aime? Why or why not?
Check your answers
  1. Four—one for each input token.
  2. The vector for grands, the last input token.
  3. No. Through self-attention, the vector for grands can use information from the earlier tokens, including J’aime. Cross-attention also supplies source information.

We now know which vector to use. But a vector contains numbers, not a token choice. How does the output head turn those numbers into scores for the possible next tokens?

6.3How does one vector become a token choice?

We already have <start> J’aime les and want to choose the token after les. Section 6.2 showed which vector to use: the decoder’s final hidden-state vector for les. We will call this vector \(\mathbf{h}\).

For this worked example, suppose the decoder has produced:

\[\mathbf{h}=(1,\ 2,\ -1,\ 0.5).\]

The decoder’s output vector is the output head’s input. The four numbers in \(\mathbf{h}\) are the starting point for our calculation. The vector and output weights below are illustrative values chosen for hand calculation.

To choose the next token, the model first assigns a score to each token in its vocabulary. The output head computes these scores from \(\mathbf{h}\). We will calculate the scores, turn them into probabilities, and then select a token.

6.3.1Score each vocabulary token

The vocabulary is the set of tokens the model can choose from. Our small example uses six entries: <start>, J’aime, les, grands, modèles, and <end>. We will compute a score for every entry.

<end> is a special token that signals the end of the translation; selecting it tells the generation program to stop.

Each score indicates how strongly the model favours a candidate as the next token. A higher score means a stronger preference.

For this prediction, we use the decoder’s final vector \(\mathbf{h}\) for les. The output head has a learned weight vector for each candidate token. On this run, all six candidates are scored using the same \(\mathbf{h}\), but each candidate has its own output weights. On the next run, the decoder computes a new \(\mathbf{h}\); the output weights stay fixed.

Each output-weight vector contains four numbers to match the four components of \(\mathbf{h}\). To score a candidate, take the dot product of \(\mathbf{h}\) and that candidate’s weights: multiply matching components, then add the products.

For grands, use the output weights \((1,1,0,0)\). Call its score \(z_{\text{grands}}\). The calculation is:

\[ z_{\text{grands}}=(1)(1)+(2)(1)+(-1)(0)+(0.5)(0)=3. \]

The table applies the same calculation to all six candidates, always using the same input vector \(\mathbf{h}=(1,2,-1,0.5)\):

Candidate tokenOutput weightsDot product with hScore
<start>0, −1, 0, 02 × (−1)−2
J’aime0, 0, 1, 0(−1) × 1−1
les0, 0, 0, 10.5 × 10.5
grands1, 1, 0, 01 + 23
modèles1, 0, 0, 01 × 11
<end>0, 0, 1, 1−1 + 0.5−0.5

These six scores are called logits. They are the output of the output head: one number for each vocabulary token. They can be negative and do not have to sum to one. The largest score here belongs to grands.

Compute all six scores with one matrix multiplication

Place each candidate’s output-weight vector in a column of a matrix called \(\mathbf{W}_{\text{out}}\). Keep the same candidate order as the table:

\[ \mathbf{W}_{\text{out}}= \begin{bmatrix} 0 & 0 & 0 & 1 & 1 & 0\\ -1 & 0 & 0 & 1 & 0 & 0\\ 0 & 1 & 0 & 0 & 0 & 1\\ 0 & 0 & 1 & 0 & 0 & 1 \end{bmatrix}. \]

Collect the six scores into a vector called \(\mathbf{z}\), keeping the vocabulary order shown in the table. Each entry of \(\mathbf{z}\) corresponds to one candidate token. Multiplying \(\mathbf{h}\) by the weight matrix computes all six scores at once:

\[ \mathbf{z}=\mathbf{h}\mathbf{W}_{\text{out}} =(1,2,-1,0.5)\mathbf{W}_{\text{out}} =(-2,\ -1,\ 0.5,\ 3,\ 1,\ -0.5). \tag{6-1} \]

The dimensions show what changes: a 1 × 4 input vector multiplied by a 4 × 6 weight matrix gives 1 × 6 logits. The four entries of \(\mathbf{h}\) describe the decoder’s hidden state; the six entries of \(\mathbf{z}\) score the six candidate tokens.

6.3.2Turn logits into probabilities

Softmax takes all six logits together and converts them into probabilities. First, exponentiate each score. Then divide each result by the sum of all six exponentials.

For candidate token \(j\), let \(z_j\) be its logit and \(p_j\) its probability. With \(V=6\) vocabulary entries:

\[p_j=\frac{e^{z_j}}{\sum_{k=1}^{V}e^{z_k}}.\]

Every candidate uses the same denominator:

\[ \begin{aligned} S &=e^{-2}+e^{-1}+e^{0.5}+e^3+e^1+e^{-0.5}\\ &\approx25.562285. \end{aligned} \]

For grands, divide the exponential of its score, 3, by this total:

\[p_{\text{grands}}=\frac{e^3}{S}\approx\frac{20.085537}{25.562285}\approx0.7857.\]

Repeating that division for each candidate gives:

Candidate tokenLogitExponentialProbability
<start>−20.13530.0053
J’aime−10.36790.0144
les0.51.64870.0645
grands320.08550.7857
modèles12.71830.1063
<end>−0.50.60650.0237

The probabilities sum to one before rounding. Keep full precision in the calculation; the table displays four decimal places. The value 0.7857 is the probability assigned to grands in this example.

Choose the next token

Softmax gives us six probabilities. To select a token, this example uses greedy selection: choose the token with the largest probability. That token is grands, with probability about 0.7857.

Softmax preserves the order of the scores, so greedy selection could also choose the largest logit directly. Calculating the probabilities lets us see how the score for grands compares with all the other candidates.

Figure 4. From the decoder vector for les to the next token grands The decoder output vector h equals 1, 2, minus 1, 0.5. This vector is the input to the output head, which multiplies h by the output-weight matrix W out. A separate output table lists six logits in vocabulary order: minus 2, minus 1, 0.5, 3, 1, minus 0.5. All six go into softmax with denominator approximately 25.562285. The largest probability is approximately 0.7857 for grands; greedy selection chooses grands. Decoder output for lesh = (1, 2, −1, 0.5)This is the output head’s input. 1 · Output head z = h Wout Output: six logitsTokenLogit2 · SoftmaxUse all six logits.p = exp(logit) / SS ≈ 25.562285ProbabilitiesTokenp<start>−2<start>0.0053J’aime−1J’aime0.0144les0.5les0.0645grands3grands0.7857modèles1modèles0.1063<end>−0.5<end>0.02373 · Greedy selectionChoose the largest probability.grands
Figure 4. The output head multiplies the decoder’s vector for les by \(\mathbf{W}_{\text{out}}\), producing six logits. Softmax converts them into six probabilities; greedy selection chooses grands. The vector and weights are illustrative, and probabilities are rounded.

We have now selected grands. Append it to the existing tokens, giving <start> J’aime les grands as the input for the next run.

Optional: computing softmax without very large exponentials

Subtract the largest logit \(m\) before exponentiating: \(p_j=e^{z_j-m}/\sum_k e^{z_k-m}\). The shared factor cancels, so the probabilities are unchanged. Here \(m=3\); the shifted logits are \((-5,-4,-2.5,0,-2,-3.5)\). This form helps avoid numerical overflow.

Extra practice: use the same weights on the next run

The next input is <start> J’aime les grands. Suppose the decoder’s final vector for grands is now \(\mathbf{h}'=(2,-1,0,0)\). This is another illustrative vector. Keep the output weights fixed. Calculate all six logits and identify the greedy choice.

Check the calculation

In the same vocabulary order, the logits are \((1,0,0,1,2,0)\). The largest score is 2 for modèles, so greedy selection chooses modèles. Softmax would give approximately \((0.1718,0.0632,0.0632,0.1718,0.4669,0.0632)\); it preserves that ordering.

The decoder supplies a new hidden-state vector on each run, while the learned output weights stay fixed during generation.

Optional: weight tying saves parameters

Weight tying uses the same learned parameters for the decoder’s input embeddings and output weights. In our six-token example, separate matrices need 24 + 24 = 48 parameters; sharing needs only 24. These counts cover those two matrices, not the whole model.

For example, with weight tying, the output-weight vector \((1,1,0,0)\) for grands also serves as its input embedding. At input, the token ID selects this vector; at output, its dot product with \(\mathbf{h}\) scores grands. The decoder still computes \(\mathbf{h}\) from the current context.

If the embedding table is \(\mathbf{E}\), with one token per row, sharing gives \(\mathbf{W}_{\text{out}}=\mathbf{E}^{\top}\), because the output matrix stores candidate weights in columns. Weight tying is optional; the scoring and token-selection steps work with separately learned weights too.

Optional: an output bias

The output head may also add a learned bias \(\mathbf{b}\), giving \(\mathbf{z}=\mathbf{h}\mathbf{W}_{\text{out}}+\mathbf{b}\). Our worked calculation omits this bias.

Key takeawayThe vector for les is the output head’s input. The output head produces one logit per vocabulary token. Softmax turns the logits into probabilities, and greedy selection chooses grands in this example.

Try it (3 minutes):

  1. What do the four numbers in \(\mathbf{h}\) represent? What do the six numbers in \(\mathbf{z}\) represent?
  2. Suppose a later run produces \(\mathbf{h}=(0,0,1,1)\). Use the same output weights to calculate all six logits. Which token does greedy selection choose, and what should the generation code do?
  3. If the vocabulary grew to eight entries while each hidden-state vector still had four numbers, what would be the shape of \(\mathbf{W}_{\text{out}}\)? How many logits would it produce?
Check your answers
  1. \(\mathbf{h}\) contains the four components of the decoder’s final vector for the last input token. \(\mathbf{z}\) contains six logits, one for each vocabulary token.
  2. In the table’s vocabulary order, the logits are \((0,1,1,0,0,2)\). The largest belongs to <end>, so greedy selection chooses it and generation stops.
  3. \(\mathbf{W}_{\text{out}}\) would have shape 4 × 8. Multiplying a 1 × 4 hidden-state vector by it would produce eight logits.

We have worked through one choice: selecting grands after J’aime les. Section 6.4 follows the complete translation, from the initial <start> to the end token.

6.4How does the model generate a complete translation?

Section 6.3 showed how to choose one token. To generate a complete translation, we add the selected token to the target prefix and run the decoder again.

The encoder processes the English sentence once. The same source memory is used on every decoder run; the target prefix changes as new French tokens are selected. The model weights stay fixed throughout generation.

6.4.1Start, select, append, and repeat

Before the first run, no French tokens have been generated. Begin with the single token <start>, which lets the decoder compute a vector for choosing the first French token.

  1. Read the prefix. Take <start> and all French tokens generated so far as this run’s target input.
  2. Compute the vectors. Represent the input tokens with embeddings and positional information, then run the decoder with source memory. This produces one final hidden-state vector per input token.
  3. Select a token. Apply the output head to the vector for the last input token. Greedy selection chooses the token with the largest score; as Section 6.3 showed, softmax gives the same ranking.
  4. Append or stop. The special token <end> tells the generation code to stop. Otherwise, append the selected token to the target prefix and begin the next run.

For example, run 1 takes <start> as its input and selects J’aime. Append that token: run 2 now takes <start> J’aime as its input and selects the next token.

Figure 5 lets you follow the complete translation. Each run is shown in the same four steps: read the prefix, compute the vectors, select a token, and append or stop. The demonstration processes the whole prefix again on each run.

SOURCE MEMORY · FIXED3 source tokens → 3 vectorsOne square group = one vector / rowIloveLLMsencoder · already runsame three vectors on every runSource length stays at 3.DECODER · RUN 5 OF 5Valuesself-attentionweighted mixAdd & Normcross-attentionremaining decodercomputationsFinalstates<start>J’aimelesgrandsmodèlesThis run’s input · 5 positionsSTOP · no next runlast rowoutput head+ token selection<end>NEW SELECTION

Run 5 / 5 · Step 4 / 4 — Append or stop

The selected token is <end>, so generation stops. The displayed translation contains the four French tokens.

Translation written so far

J’aimelesgrandsmodèles

Finished · <end> is not added to the translation.

Figure 5. Each run is shown in four steps. Follow one run at a time with the step buttons, or jump to a run or stage. Blue arrows show how target-prefix information reaches the last token’s self-attention calculation; the gold arrow supplies cross-attention with source memory. Each view waits for your next action. The token choices illustrate the loop; Section 6.3 works through the choice of grands on run 3.

All five runs

Read each row from left to right: the decoder processes the input tokens, produces one final hidden-state row per input token, and uses the last row to select the next token. If the selected token is <end>, generation stops. Otherwise, it is appended to form the next run’s input. Selecting a token does not add a row to the hidden states already computed. The source memory stays fixed at three rows throughout.

RunInput tokens at the start of this runHidden-state rows produced in this runToken selected after this computationWhat happens next
1<start>1J’aimeAppend J’aime; include it in run 2.
2<start> J’aime2lesAppend les; include it in run 3.
3<start> J’aime les3grandsAppend grands; include it in run 4.
4<start> J’aime les grands4modèlesAppend modèles; include it in run 5.
5<start> J’aime les grands modèles5<end>Stop. The displayed translation still has four tokens.

For example, run 1 starts with only <start>, so it produces one hidden-state row. After J’aime is selected and appended, the sequence has two tokens. Those two tokens are processed in run 2, which produces two hidden-state rows.

The completed example has three English source tokens and four French translation tokens. Their lengths can differ because each decoder run selects one new token, and the model can continue until it selects <end>. The source memory stays at three vectors throughout.

6.4.2Stop when the model selects <end>

The output vocabulary includes the special token <end>. The output head scores it along with the other candidate tokens. When token selection chooses it, the generation code stops.

On run 5, the input is <start> J’aime les grands modèles. The final hidden-state vector for modèles goes to the output head, and token selection chooses <end>. The program then stops: there is no run 6. The end marker is not displayed, so the translation contains the four French tokens.

During training, completed target sequences include an end token. The model learns to predict it after the final translation token. During generation, the program stops when that token is selected. A practical implementation also sets a maximum generation length, so generation can stop at that limit even if no end token is selected.

Looking ahead to Part 10: selection rules and caching

Other ways to choose a token. Greedy selection is the rule used in this example. Sampling and beam search use the scores differently; Part 10 develops these choices. Softmax supplies probabilities; the selection rule determines what happens next.

Avoiding repeated work. This demonstration processes the whole prefix on every run. A KV cache saves part of the earlier computation so later runs can process only the new token while still using information from earlier tokens. Part 10 explains what is saved and how it is reused.

Key takeawayBegin with <start>. Use the decoder’s final vector for the last input token to select the next token. If it is <end>, stop; otherwise, append it to the prefix for the next run. The prefix grows, while source memory and model weights stay fixed. A generation-length limit provides another stopping condition.

Try it (2 minutes): Run 4 has just selected modèles. Use the full-prefix version shown above.

  1. What is the input prefix on run 5?
  2. Which token’s vector goes to the output head?
  3. If run 5 selects <end>, is another run needed?
  4. What stays unchanged across all five runs?
Check your answers
  1. <start> J’aime les grands modèles.
  2. The vector for modèles, the last input token.
  3. No. Selecting <end> stops generation.
  4. The source memory and learned model weights.

6.5What changes in a decoder-only model?

So far, we have used an encoder–decoder model: the encoder processes the English sentence, and the decoder generates the French translation. We now consider a different architecture, a decoder-only language model, to see how the same token-by-token generation loop works there.

For the same translation task, the initial input could be:

Translate into French: I love LLMs. French:

This initial text is the prompt. It contains the translation instruction and the English source sentence; French: cues the model to continue with the translation. As French tokens are generated, they are appended after the prompt.

Before the first run, the prompt is converted into tokens. The model processes these tokens to choose the first French token—in our example, J’aime. On the next run, the input contains the prompt followed by J’aime.

Compare how the two models receive the English source information:

ModelWhere the source sentence enters
Encoder–decoderThe encoder processes I love LLMs. Its output becomes source memory, read by the decoder through cross-attention.
Decoder-onlyThe source is part of the prompt shown above. The prompt and the French tokens generated so far enter together as one sequence, processed through self-attention.

The decoder-only model has no separate encoder and no cross-attention to encoder outputs. Like the decoder in our encoder–decoder model, it uses causal self-attention: each position can use information from that position and earlier positions. The last input position can therefore use information from the entire input so far: the prompt and any French tokens already generated. A suitably trained model can use that information to translate.

As in the earlier walkthrough, we describe generation by processing the complete input sequence on each run, without a KV cache. The model produces one final hidden-state row per input token. On run 1, that means one row for each prompt token; the last row belongs to the prompt’s last token and is used to choose the first French token.

Now follow the first two runs. We keep the simplified French token units used earlier and suppose this model selects J’aime, then les:

RunInput at the start of this runVector sent to the output headSelected token
1Translate into French: I love LLMs. French:The final hidden-state vector for the prompt’s last token.J’aime
2Translate into French: I love LLMs. French: J’aimeThe final hidden-state vector for J’aime.les

Run 1 selects J’aime, which is appended for run 2. Run 2 computes its hidden-state vector and uses it to select les, which is appended for run 3. A selected token gets its own hidden-state row when it is processed on the next run. As in Section 6.3, the output head converts the last row into vocabulary scores, and token selection chooses the next token.

Continue appending selected tokens and running the model until a stopping condition is met, such as selecting an end token or reaching the generation-length limit. The displayed translation contains the generated French tokens; the prompt remains part of the model’s input.

Key takeawayAn encoder–decoder model receives source information through separate source memory. A decoder-only model receives it within the prompt. In both, the final vector for the last input token goes to the output head. Select the next token; if generation continues, append it for the next run.

NextHow cross-attention uses source memory

The generation loop follows the four stages in Figure 5. Read the prefix: take the current input tokens. Compute the vectors: run the decoder to obtain their final hidden states. Select a token: use the output head to score candidates from the last hidden-state vector, then apply the selection rule. Append or stop: stop at <end>; otherwise, append the selected token for the next run. A generation-length limit can also stop the loop.

How does source memory contribute to the decoder’s hidden-state vectors? Part 7 returns to our encoder–decoder translation example and works through cross-attention numerically, following the source-memory connections shown in this part.

Part 8 explains how masks control which positions attention can use. Part 9 shows how training teaches the model to predict the next token. Part 10 explores other token-selection rules and how a KV cache avoids repeating earlier computation.

Technical references