The Transformer, Number by Number  ·  Part 7

Where the Encoder Stack Meets the Decoder Stack

Part 6 showed how the decoder’s final hidden-state vector helps select the next token. That vector already contains information from the source sentence. This part explains how the decoder reads that information: through cross-attention.

We continue with I love LLMs and the illustrated translation J’aime les grands modèles. As in Part 6, each displayed word counts as one token in this teaching example. We focus on run 1, when the target prefix contains only <start> and the first French token has not yet been selected.

First we will identify the information that cross-attention reads. Then we will calculate the cross-attention output \(\mathbf Z_{\text{cross}}\) and follow \(\mathbf Z_{\text{cross}}\) into the next step of a decoder block.

We build on attention from Part 1, Add & Norm from Part 5, and the generation loop from Part 6.

7.1Why the decoder needs the source sentence

Imagine translating two different sentences. I love LLMs could lead to a translation beginning with J’aime. LLMs love me could lead to one beginning with Les. This is the comparison from Part 6, Section 6.1.3.

The decoder receives the same <start> input and uses the same learned weights for both source sentences. To produce different translations, the decoder also needs information about the source sentence.

Think for a moment How does the decoder get information about the source sentence?

The encoder provides the source information. It has already processed the source sentence into one contextual vector per source token. Each vector represents its token in the context of the whole source sentence. Together, these output vectors form the encoder memory, denoted by \(\mathbf C\). \(\mathbf C\) is the “source memory” introduced in Part 6. The decoder can read \(\mathbf C\) throughout the translation.

Same decoder input, different source information

Both translations begin with <start>. The model weights are unchanged.

I love LLMsencoder → encoder memory
decoder + output headdecoder input: <start>possible first token: J’aime
LLMs love meencoder → encoder memory
decoder + output headdecoder input: <start>possible first token: Les

The encoder memory is different, so the next-token probabilities can differ.

Figure 1. The encoder supplies the information that distinguishes the two source sentences. J’aime and Les are illustrative first-token choices.

Cross-attention is the operation that reads the encoder memory. For each decoder position, it computes a weight for each source position, then uses those weights to combine information from the encoder output vectors in \(\mathbf C\). That combination becomes an update to the decoder’s vector.

Every decoder block has a cross-attention sublayer. This is the connection Part 6 called the “side door”: source information enters partway through a decoder block, while the current prefix enters at the bottom of the decoder stack.

Without cross-attention, the decoder’s next-token probabilities for a fixed prefix would not depend on the source sentence. Cross-attention gives the decoder the source-dependent information it needs for translation.

7.2How the decoder reads the encoder memory

On run 1, cross-attention must connect one decoder position, <start>, with three source positions, I, love and LLMs. Figure 2 shows where the two inputs meet inside the first decoder block.

Two inputs to cross-attention Read the first decoder block upward. The start-token input passes through masked self-attention and Add and Norm to produce D. Cross-attention receives D from below and encoder memory C from the right. Three residual paths bypass the three sublayers. The remaining operations are shown in muted colours. FIRST DECODER BLOCK Run 1 Read bottom to top block output Add & Norm feed-forward Add & Norm cross-attention C · encoder memory I · love · LLMs D Add & Norm masked self-attention <start> input vector residual
Figure 2. Follow the <start> input upward through masked self-attention and the first Add & Norm to reach \(\mathbf D\). Cross-attention reads \(\mathbf D\) from below and encoder memory \(\mathbf C\) from the side. The later sublayers are shown in muted colours; Section 7.5 follows the calculation through them.

On the source side, the encoder has finished. Each row of the encoder memory \(\mathbf C\) is the encoder output vector for one source token. The three rows follow the source order: I, love, LLMs.

Cross-attention can read all three source positions

The encoder has already processed I, love and LLMs, so each decoder Query can read all three rows of \(\mathbf C\). Cross-attention does not use the target-side causal mask. A source padding mask excludes padding positions when present; Part 8 explains both masks.

On the decoder side, the <start> embedding has entered the first decoder block. It has passed through masked self-attention, followed by residual addition and LayerNorm—the first Add & Norm. The resulting \(1\times4\) row vector is the input to cross-attention. We call this decoder state \(\mathbf D\).

\(\mathbf D\) is a \(1\times4\) row vector. The encoder memory \(\mathbf C\) stacks three \(1\times4\) row vectors, one per source position:

InputRows representShape on run 1
\(\mathbf C\): encoder memoryI, love, LLMs — three source positions\(3\times4\)
\(\mathbf D\): decoder state<start> — one decoder position\(1\times4\)

These are contextual vectors, not token IDs. Cross-attention transforms them into three kinds of vector with different jobs.

7.2.1Give the vectors three different jobs

The decoder needs to use information from the encoder memory \(\mathbf C\) to update its current state \(\mathbf D\). Cross-attention uses the same three kinds of vector introduced in Part 1—Queries, Keys and Values—but draws them from two different inputs, \(\mathbf D\) and \(\mathbf C\):

Each transformation is a matrix multiplication, called a projection. The three learned projection matrices are written \(\mathbf W^Q_{\text{cross}}\), \(\mathbf W^K_{\text{cross}}\) and \(\mathbf W^V_{\text{cross}}\). The superscript identifies the projection’s result—\(\mathbf Q_{\text{cross}}\), \(\mathbf K_{\text{cross}}\) or \(\mathbf V_{\text{cross}}\); “cross” distinguishes them from the self-attention projections.

Call the resulting matrices \(\mathbf Q_{\text{cross}}\), \(\mathbf K_{\text{cross}}\) and \(\mathbf V_{\text{cross}}\), shortened to \(\mathbf Q\), \(\mathbf K\) and \(\mathbf V\) in the figures. Figure 3 shows their sources and shapes; each projection matrix is \(4\times4\) in this example.

Build three kinds of vector from two inputs

Run 1: \(\mathbf D\) has one decoder position; \(\mathbf C\) has three source positions.

\(\mathbf D\)1 × 4
\(\mathbf{W}^{Q}_{\text{cross}}\)4 × 4
\(\mathbf Q\) · one Query1 × 4
\(\mathbf C\)3 × 4
\(\mathbf{W}^{K}_{\text{cross}}\)4 × 4
\(\mathbf K\) · three Keys3 × 4
\(\mathbf C\)3 × 4
\(\mathbf{W}^{V}_{\text{cross}}\)4 × 4
\(\mathbf V\) · three Values3 × 4

Each small square is one vector component, not a token. Each row is one token position.

Figure 3. \(\mathbf D\) is the decoder state after masked self-attention and Add & Norm; \(\mathbf C\) is the encoder memory. \(\mathbf D\) supplies \(\mathbf Q\). \(\mathbf C\) is used twice, with different projection matrices, to supply \(\mathbf K\) and \(\mathbf V\). The square grids show the matrix shapes. Section 7.4 calculates the numerical entries of \(\mathbf Q\), \(\mathbf K\) and \(\mathbf V\).
\[ \mathbf Q_{\text{cross}}=\mathbf D\mathbf W^Q_{\text{cross}}. \] \[ \mathbf K_{\text{cross}}=\mathbf C\mathbf W^K_{\text{cross}},\qquad \mathbf V_{\text{cross}}=\mathbf C\mathbf W^V_{\text{cross}}. \]

\(\mathbf C\) is used twice because comparison and information gathering have different jobs. A source position’s Key is used to calculate an attention score. Softmax converts the scores into attention weights; each weight multiplies the Value from the same source position.

In self-attention, all three projections read the same sequence of vectors. In cross-attention, the Query comes from the decoder state, while the Keys and Values come from encoder memory. The score-and-weight calculation itself is the same.

7.2.2Compare, weight, and combine

We now follow the Query for <start> through scaled dot-product attention: compare it with the three Keys, turn the scores into weights, and combine the Values. These are the same operations used in Part 1.

  1. Compare the Query with each Key. Each dot product produces a score. There are three Keys, so we obtain three scores in the order I, love, LLMs. Divide each score by \(\sqrt{d_k}\), where \(d_k\) is the number of components in a Key. Here \(d_k=4\), so the divisor is 2. This scaling controls how the score size grows with vector width.
  2. Turn the scores into attention weights. Softmax produces three weights that sum to 1 before rounding. We collect them in a row called \(\mathbf A_{\text{cross}}\). Each weight specifies how much of the corresponding Value to include.
  3. Combine the Values. Multiply each Value by its attention weight and add the three weighted vectors component by component. Call the result \(\mathbf Z_{\text{cross}}\), the cross-attention output.

One Query produces \(\mathbf Z_{\text{cross}}\)

1 · CompareOne score for each source position
\(\underbrace{\mathbf Q_{\text{cross}}}_{1\times4}\;\underbrace{\mathbf K_{\text{cross}}^{\top}}_{4\times3}\,/\,2\quad\longrightarrow\quad\underbrace{\text{scores}}_{1\times3}\)

Columns: I · love · LLMs

2 · WeightTurn the scores into attention weights
\(\underbrace{\text{scores}}_{1\times3}\quad\xrightarrow{\text{softmax}}\quad\underbrace{\mathbf A_{\text{cross}}}_{1\times3}\)

One weight for I, one for love, one for LLMs

3 · CombineWeight the three Values and add them
\(\underbrace{\mathbf A_{\text{cross}}}_{1\times3}\;\underbrace{\mathbf V_{\text{cross}}}_{3\times4}\quad\longrightarrow\quad\underbrace{\mathbf Z_{\text{cross}}}_{1\times4}\)

\(\mathbf Z_{\text{cross}}\) · information from the Values, used to update \(\mathbf D\).

Follow one decoder position through the three operations. Use the buttons to focus on a step.

Figure 4. The source length determines how many scores and weights the Query needs. The Query count determines how many output vectors are produced. Here the three source positions contribute to one decoder position.

Written as two expressions, those operations are:

\[ \mathbf A_{\text{cross}}=\operatorname{softmax}\!\left(\frac{\mathbf Q_{\text{cross}}\mathbf K_{\text{cross}}^{\top}}{\sqrt{d_k}}\right), \qquad \mathbf Z_{\text{cross}}=\mathbf A_{\text{cross}}\mathbf V_{\text{cross}}. \]

Transposing \(\mathbf K_{\text{cross}}\) puts one Key in each column, so \(\mathbf Q_{\text{cross}}\mathbf K_{\text{cross}}^{\top}\) compares the Query with all three Keys at once. \(\mathbf A_{\text{cross}}\) has shape \(1\times3\). Multiplying \(\mathbf A_{\text{cross}}\) by \(\mathbf V_{\text{cross}}\), which has shape \(3\times4\), sums over the three source positions and returns the \(1\times4\) row vector \(\mathbf Z_{\text{cross}}\).

Think for a moment We read the three encoder output vectors in \(\mathbf C\). Why does \(\mathbf Z_{\text{cross}}\) have shape \(1\times4\) here?

Because we asked it to update one decoder position. All three rows of \(\mathbf C\) contribute to \(\mathbf Z_{\text{cross}}\). With two decoder Queries, the same operation would produce two output vectors, one per Query.

The weighted sum \(\mathbf Z_{\text{cross}}\) combines information from the three Values derived from encoder memory \(\mathbf C\). This information is used to update the decoder state \(\mathbf D\) that produced the Query. On this run, \(\mathbf D\) is the state for the only input token, <start>. Section 7.5 shows how this update is applied.

Projection weights and attention weights

The projection matrices \(\mathbf W\) are model parameters that stay fixed during inference. The attention weights \(\mathbf A_{\text{cross}}\) are calculated from \(\mathbf Q_{\text{cross}}\) and \(\mathbf K_{\text{cross}}\), so they can change with the source sentence or decoder state \(\mathbf D\). The entries of \(\mathbf A_{\text{cross}}\) weight the source Values; they are not next-token probabilities.

7.2.3Prepare for the numerical example

We will calculate cross-attention by hand using one head. Each token position is represented by a \(1\times4\) row vector, so the two inputs have shapes \(\mathbf C:3\times4\) and \(\mathbf D:1\times4\).

The projection matrices are hand-picked to demonstrate the calculation; they have not been trained to produce the illustrated French translation. This numerical example is separate from Part 6’s output-head calculation.

Use these settings throughout the hand calculation:

How this extends to multi-head attention

The full multi-head version performs this calculation separately in each head, concatenates the head outputs, then applies a learned \(\mathbf{W}^{O}\), as in Part 2. In each head, \(\mathbf Q_{\text{cross}}\) comes from \(\mathbf D\), while \(\mathbf K_{\text{cross}}\) and \(\mathbf V_{\text{cross}}\) come from \(\mathbf C\).

7.3Put numbers into the two inputs

Figure 5 locates the symbols used in the calculation. Follow the <start> input upward, and trace \(\mathbf C\) from the encoder into the cross-attention projections.

Where the mathematical symbols belong in the first decoder blockRead the decoder upward: X dec enters masked self-attention with separate Query, Key and Value projection matrices. Add and Norm gives D. The cross-attention Query is projected from D; Keys and Values are projected from the fixed encoder memory C. The attention weights A combine the Values into Z. Add and Norm produces H, then feed-forward and a final Add and Norm complete this block. Dashed paths carry X dec, D and H for residual addition.Where the symbols liveFIRST DECODER BLOCK · RUN 1To decoder block 203Finish the blockAdd & NormFeed-forward · FFN(H)H · 1 × 4Add & Norm · D + ZcrossZcross = AcrossVcross · 1 × 402Cross-attentionAcross = softmax(QcrossKTcross / 2) · 1 × 3QUERY FROM THE DECODER · 1 × 4Qcross = DWQcrossKcross = CWKcross · 3 × 4Vcross = CWVcross · 3 × 4D · 1 × 4Add & Norm01Masked self-attentionQdec-self = XdecWQdec-self1 × 4Kdec-self = XdecWKdec-self1 × 4Vdec-self = XdecWVdec-self1 × 4Xdec · 1 × 4 · <start>XdecDHSource memoryC3 × 4Final encoder outputFixed throughout decodingEncoder stackI love LLMsPROJECTION MATRICESW · 4 × 4dec-self and cross identifyseparate parameter sets.Weights stay fixed in inference.Read the decoder upward.Data flowResidual path
Figure 5. Locate the symbols before starting the calculation. The dec-self projection matrices act on \(\mathbf X_{\text{dec}}\). The cross-attention projection matrices act on \(\mathbf D\) for the Query and on \(\mathbf C\) for the Keys and Values. Solid arrows carry intermediate results; dashed arrows carry the inputs used in residual addition. As specified in Section 7.2.3, both attention output projections are \(\mathbf W^O=\mathbf I_4\). Section 7.5 follows the path through \(\mathbf H\) and the feed-forward network.

Sections 7.3 and 7.4 revisit calculations you have already learned. Use the supplied inputs and projection matrices to try each calculation before reading its result. Then compare your work with the steps shown below, checking both the numbers and where each input came from.

We now give the encoder memory \(\mathbf C\) and decoder state \(\mathbf D\) numerical values.

Encoder memory: \(\mathbf C\). Read these rows from top to bottom as I, love and LLMs:

\[ \mathbf{C} \;=\; \begin{pmatrix} 1.13 & -1.48 & -0.30 & 0.66 \\ 0.73 & -1.24 & -0.69 & 1.20 \\ 1.57 & -1.21 & -0.24 & -0.13 \end{pmatrix} \]

We reuse all three output rows from Part 5’s Figure 10 as the encoder memory \(\mathbf C\), in source order: I, love, LLMs. For this worked example, we use this \(3\times4\) matrix directly instead of calculating all six encoder blocks. \(\mathbf C\) stays fixed throughout decoding.

Decoder state: \(\mathbf D\). The only token in the current prefix is <start>. For this exercise, we set its embedding to \((1,0,0,0)\). Because our hand calculation omits positional encoding and embedding scaling, that vector is also the input to the first decoder block. We name it \(\mathbf X_{\text{dec}}\).

To obtain \(\mathbf D\), we apply masked self-attention to \(\mathbf X_{\text{dec}}\), then Add & Norm. Here is the calculation.

1. Project the block input. These are the three projection matrices supplied for masked self-attention in this example. The subscript “dec-self” identifies the decoder’s masked self-attention. These matrices are separate from the cross-attention matrices that we will use later:

\[ \mathbf{W}^{Q}_{\text{dec-self}} = \begin{pmatrix} -1 & 0 & -1 & 1 \\ 0 & 0 & -1 & -1 \\ -1 & -1 & 0 & 1 \\ 0 & -1 & -1 & 1 \end{pmatrix} \] \[ \mathbf{W}^{K}_{\text{dec-self}} = \begin{pmatrix} 1 & 0 & 0 & -1 \\ -1 & 0 & -1 & -1 \\ 1 & 0 & 0 & -1 \\ -1 & 0 & 0 & 1 \end{pmatrix} \] \[ \mathbf{W}^{V}_{\text{dec-self}} = \begin{pmatrix} 1 & 0 & -1 & 1 \\ 0 & 1 & 0 & 1 \\ -1 & -1 & -1 & 0 \\ 0 & -1 & 1 & 0 \end{pmatrix} \]

Multiplying \(\mathbf X_{\text{dec}}=(1,0,0,0)\) by each projection matrix selects that matrix’s first row. Therefore:

\[ \mathbf Q_{\text{dec-self}}=(-1,0,-1,1),\qquad \mathbf K_{\text{dec-self}}=(1,0,0,-1), \] \[ \mathbf V_{\text{dec-self}}=(1,0,-1,1). \]

2. Compute the self-attention output. On run 1 there is only one position to attend to, <start> itself. \(\mathbf Q_{\text{dec-self}}=(-1,0,-1,1)\) and \(\mathbf K_{\text{dec-self}}=(1,0,0,-1)\) give one scaled score:

\[ \frac{(-1)(1)+(0)(0)+(-1)(0)+(1)(-1)}{\sqrt4}=-1. \]
What does the mask do on run 1?

With only <start> in the prefix, the additive causal mask is \(\mathbf M=[0]\). It blocks no positions, so the score remains \(-1+0=-1\). Part 8 shows how the causal mask blocks later positions in a longer prefix.

Softmax over that single score gives \(e^{-1}/e^{-1}=1\). The weighted output is therefore \(1\times(1,0,-1,1)=(1,0,-1,1)\). Our identity output projection leaves it unchanged.

3. Add the original block input. The residual addition combines \(\mathbf X_{\text{dec}}\) with the self-attention output:

\[ (1,0,0,0)+(1,0,-1,1)=(2,0,-1,1). \]

4. Apply LayerNorm to obtain \(\mathbf D\). The residual sum \((2,0,-1,1)\) has mean \(0.5\) and variance \(1.25\). Using the LayerNorm settings from Section 7.2.3:

\[ \mathbf D=\frac{(2,0,-1,1)-0.5}{\sqrt{1.25+10^{-5}}} \approx(1.34,-0.45,-1.34,0.45). \]

Carry \(\mathbf D=(1.34,-0.45,-1.34,0.45)\) into Section 7.4. This is the decoder state that enters cross-attention.

THE DECODER ROW ON RUN 1 <start> lookupXdec · block input masked self-attentionthen Add & Norm D · input to cross-attention One input position remains one position. Its four numbers have changed. 10001.34−0.45−1.340.45
Figure 6. In this simplified example, the <start> embedding is the input to the first decoder block. \(\mathbf D\) is the updated vector that reaches cross-attention. They refer to the same input position at different stages.

We can now start cross-attention: \(\mathbf D\) will supply its Query, while \(\mathbf C\) will supply its Keys and Values.

7.4Calculate one cross-attention output

Our task is to use \(\mathbf D\) to retrieve information from the three rows of \(\mathbf C\). The output \(\mathbf Z_{\text{cross}}\) will be a \(1\times4\) row vector for the <start> position.

We are inside one decoder block on run 1 of the loop from Part 6, Section 6.4. The prefix contains <start> only. The decoder stack must finish before the output head and selection rule choose the first French token.

Choose a decoder run: fixed source memory, current prefix, and newly selected token.FIXED SOURCE MEMORYC · 3 source rowsI / love / LLMsDECODERsix decoder blocksmasked self-attentioncross-attentionfeed-forwardAdd & Norm after eachSame C in every runEach block builds its K, V1 final hidden-state rowuse only the last rowoutput head → selectNEW SELECTIONJ’aimeAppend it for run 2.RUN 1 · decoder input<start>

Run 1: input <start>; one final hidden-state row; select J’aime.

Figure 7. Select a run to follow the full prefix. The new selection is appended only after this run finishes. Run 1 therefore has one input row; run 2 has two. The token choices illustrate Part 6’s generation loop.

Follow the calculation in four steps: Query, Keys, attention weights, then Values and output. Each projection matrix is shown where it is used.

For this hand calculation, use the displayed rounded results in the next step; keeping full precision may give slightly different final decimals.

7.4.1Step 1 — build the Query from \(\mathbf D\)

Start with \(\mathbf D=(1.34,-0.45,-1.34,0.45)\). \(\mathbf D\) is the decoder state produced by masked self-attention and the first Add & Norm. We now apply the cross-attention Query projection:

\[ \mathbf{W}^{Q}_{\text{cross}} = \begin{pmatrix} -1 & -1 & 1 & 0 \\ -1 & 0 & 1 & 0 \\ 1 & 1 & 0 & -1 \\ 0 & 0 & 1 & 0 \end{pmatrix} \]

A row vector times a matrix produces one output component per column of that matrix. For the first component of \(\mathbf Q_{\text{cross}}\), take the dot product of \(\mathbf D\) with column 1 of \(\mathbf W^Q_{\text{cross}}\), \((-1,-1,1,0)^{\top}\):

\[ 1.34(-1)+(-0.45)(-1)+(-1.34)(1)+0.45(0)=-2.23. \]

Taking the dot product of \(\mathbf D\) with columns 2, 3 and 4 of \(\mathbf W^Q_{\text{cross}}\) gives the remaining Query components:

\[ \mathbf Q_{\text{cross}}=\mathbf D\mathbf W^Q_{\text{cross}} =(-2.23,-2.68,1.34,1.34). \]

\(\mathbf Q_{\text{cross}}\) is the \(1\times4\) Query row vector for the <start> position. Next we build \(\mathbf K_{\text{cross}}\), whose three Key rows will each be compared with \(\mathbf Q_{\text{cross}}\).

7.4.2Step 2 — build the three Keys from \(\mathbf C\)

Multiply each row of the encoder memory \(\mathbf C\) from Section 7.3 by the Key projection matrix \(\mathbf W^K_{\text{cross}}\):

\[ \mathbf{W}^{K}_{\text{cross}} = \begin{pmatrix} 0 & 0 & 0 & 1 \\ 1 & -1 & 1 & 0 \\ -1 & 0 & -1 & -1 \\ 0 & -1 & 1 & -1 \end{pmatrix} \]

For I, use row 1 of \(\mathbf C\), \((1.13,-1.48,-0.30,0.66)\). Column 1 of \(\mathbf W^K_{\text{cross}}\) is \((0,1,-1,0)^{\top}\), so the first component of the Key for I is:

\[ 1.13(0)+(-1.48)(1)+(-0.30)(-1)+0.66(0)=-1.18. \]

Use all four columns of \(\mathbf W^K_{\text{cross}}\) for row 1 of \(\mathbf C\), then repeat for rows 2 and 3 (love and LLMs). The rows of \(\mathbf K_{\text{cross}}\) keep this source order:

\[ \mathbf{K}_{\text{cross}} \;=\; \mathbf{C}\,\mathbf{W}^{K}_{\text{cross}} \;=\; \begin{pmatrix} -1.18 & 0.82 & -0.52 & 0.77 \\ -0.55 & 0.04 & 0.65 & 0.22 \\ -0.97 & 1.34 & -1.10 & 1.94 \end{pmatrix} \]

We now have one Query and three Keys. Each Key belongs to a source position.

Check one component Why is the first component of the Key for love −0.55?
Check your calculation

Take the dot product of row 2 of \(\mathbf C\), \((0.73,-1.24,-0.69,1.20)\), with column 1 of \(\mathbf W^K_{\text{cross}}\), \((0,1,-1,0)^{\top}\):

\[ 0.73(0)+(-1.24)(1)+(-0.69)(-1)+1.20(0)=-0.55. \]

The same projection matrix is applied to every row of \(\mathbf C\); each row contains a different encoder output vector.

7.4.3Step 3 — turn the comparisons into attention weights

In the projection \(\mathbf D\mathbf W^Q_{\text{cross}}\), each dot product with a column of \(\mathbf W^Q_{\text{cross}}\) produced one Query component. Now each dot product of the Query with a Key produces one attention score.

Write \(\mathbf q=(-2.23,-2.68,1.34,1.34)\) for the only row of \(\mathbf Q_{\text{cross}}\), and \(\mathbf k_I=(-1.18,0.82,-0.52,0.77)\) for row 1 of \(\mathbf K_{\text{cross}}\), the Key for I. Their dot product is:

\[ \begin{aligned} \mathbf q\cdot\mathbf k_I &=(-2.23)(-1.18)+(-2.68)(0.82)\\ &\quad +(1.34)(-0.52)+(1.34)(0.77)\\ &=0.7688\approx0.77. \end{aligned} \]

Repeat \(\mathbf q\cdot\mathbf k\) for rows 2 and 3 of \(\mathbf K_{\text{cross}}\), the Keys for love and LLMs. Divide each dot product by \(\sqrt{d_k}=2\):

Source positionDot product, roundedScore after ÷ 2, rounded
I0.770.39
love2.291.15
LLMs−0.30−0.15

The scaled score row is \((0.39,1.15,-0.15)\), in the order I, love, LLMs. Apply softmax across this row to obtain the attention weights.

First exponentiate the scores and round to two decimals:

\[ \left(e^{0.39},e^{1.15},e^{-0.15}\right)\approx(1.48,3.16,0.86). \]

The total is \(1.48+3.16+0.86=5.50\). Divide every entry by that same total:

\[ \mathbf A_{\text{cross}}=\operatorname{softmax}(0.39,1.15,-0.15) \approx\left(\frac{1.48}{5.50},\frac{3.16}{5.50},\frac{0.86}{5.50}\right) \approx(0.27,0.57,0.16). \]

The entries of \(\mathbf A_{\text{cross}}=(0.27,0.57,0.16)\) multiply the Values for I, love and LLMs, respectively. These are attention weights over source positions. Part 6 applied softmax to output-head scores to obtain probabilities over possible next tokens; here softmax weights the source Values.

The largest weight is on love, but all three Values contribute to the output.

7.4.4Step 4 — combine the Values into one output

We have \(\mathbf A_{\text{cross}}=(0.27,0.57,0.16)\). Now build the three Values that these weights will multiply, using \(\mathbf W^V_{\text{cross}}\) to project \(\mathbf C\):

\[ \mathbf{W}^{V}_{\text{cross}} = \begin{pmatrix} -1 & -1 & -1 & 0 \\ 0 & 0 & -1 & -1 \\ -1 & 1 & 1 & 0 \\ 1 & 0 & 1 & 0 \end{pmatrix} \]

For the first component of the Value for I, take the dot product of row 1 of \(\mathbf C\), \((1.13,-1.48,-0.30,0.66)\), with column 1 of \(\mathbf W^V_{\text{cross}}\), \((-1,0,-1,1)^{\top}\):

\[ 1.13(-1)+(-1.48)(0)+(-0.30)(-1)+0.66(1)=-0.17. \]

Apply all four columns of \(\mathbf W^V_{\text{cross}}\) to all three rows of \(\mathbf C\):

\[ \mathbf{V}_{\text{cross}} \;=\; \mathbf{C}\,\mathbf{W}^{V}_{\text{cross}} \;=\; \begin{pmatrix} -0.17 & -1.43 & 0.71 & 1.48 \\ 1.16 & -1.42 & 1.02 & 1.24 \\ -1.46 & -1.81 & -0.73 & 1.21 \end{pmatrix} \]

In \(\mathbf V_{\text{cross}}\), row 1 is the Value for I, row 2 for love, and row 3 for LLMs. Multiply every component of row 1 by \(0.27\), row 2 by \(0.57\), and row 3 by \(0.16\).

The table shows the three weighted contributions. Each one multiplies two numbers with two decimals, so it has four decimals. Keep all four, add each column, and round only the column sum to two decimals:

Source positionWeightWeighted Value components
1234
I0.27−0.0459−0.38610.19170.3996
love0.570.6612−0.80940.58140.7068
LLMs0.16−0.2336−0.2896−0.11680.1936
Sum → \(\mathbf Z_{\text{cross}}\)0.38−1.490.661.30

For component 3, the contributions are \(0.27(0.71)=0.1917\), \(0.57(1.02)=0.5814\), and \(0.16(-0.73)=-0.1168\). Their sum is \(0.1917+0.5814-0.1168=0.6563\), which rounds to \(0.66\). Rounding each contribution first would give \(0.19+0.58-0.12=0.65\) instead; this part and Parts 8 to 10 round only the sum. The four column sums form the \(1\times4\) row vector \(\mathbf Z_{\text{cross}}\):

\[ \mathbf Z_{\text{cross}}=\mathbf A_{\text{cross}}\mathbf V_{\text{cross}} \approx(0.38,-1.49,0.66,1.30). \]

Attention applies an output projection before the residual addition. Here \(\mathbf W^O=\mathbf I_4\), so \(\mathbf Z_{\text{cross}}\mathbf W^O=\mathbf Z_{\text{cross}}\). We can add \(\mathbf Z_{\text{cross}}=(0.38,-1.49,0.66,1.30)\) directly to \(\mathbf D\).

Cross-attention: Query and Keys, scores, weights, weighted Values and output.01 QUERY & KEYSQcross · from D−2.23−2.681.341.34Kcross · from CI−1.180.82−0.520.77love−0.550.040.650.22LLMs−0.971.34−1.101.9402 SCORESq · k ÷ 20.77→0.392.29→1.15−0.30→−0.1503 WEIGHTSAcross = softmax(scores)0.27I0.57love0.16LLMsΣ weights = 104 WEIGHTED VALUESVcross · from Cweightweighted vectorI−0.17−1.430.711.48× 0.27=−0.0459−0.38610.19170.3996love1.16−1.421.021.24× 0.57=0.6612−0.80940.58140.7068LLMs−1.46−1.81−0.731.21× 0.16=−0.2336−0.2896−0.11680.1936add ↓0.38−1.490.661.3005 OUTPUTZcross
Figure 8. One Query scores three Keys. Softmax gives three attention weights, which scale the three Values. Add each column of weighted Values to obtain \(\mathbf Z_{\text{cross}}\). Use the step buttons to follow the calculation.
Cross-attention updates the current decoder position

Here \(\mathbf Z_{\text{cross}}\) is a \(1\times4\) update for <start>. The next residual sum is \(\mathbf D+\mathbf Z_{\text{cross}}\). Cross-attention has not selected a French token; token selection happens after all six decoder blocks and the output head.

7.5Follow the update through the rest of the block

We continue through the original Transformer’s decoder block: each sublayer is followed by residual addition and LayerNorm, or Add & Norm.

7.5.1Add the update to \(\mathbf D\), then normalise

First, add. The residual path carries the cross-attention input \(\mathbf D\) around the sublayer. \(\mathbf Q_{\text{cross}}\) is a projection made inside the sublayer, so the residual sum is \(\mathbf D+\mathbf Z_{\text{cross}}\):

\[ \underbrace{\mathbf D}_{(1.34,-0.45,-1.34,0.45)}+ \underbrace{\mathbf Z_{\text{cross}}}_{(0.38,-1.49,0.66,1.30)} =(1.72,-1.94,-0.68,1.75). \]

The sum \(\mathbf D+\mathbf Z_{\text{cross}}\) still represents the <start> position. It combines the existing decoder state with the source-dependent update.

Then, normalise. Apply LayerNorm across the four columns of the \(1\times4\) row vector \(\mathbf D+\mathbf Z_{\text{cross}}\), using the settings from Section 7.2.3. This row has mean \(0.2125\) and variance \(2.51656875\).

Call the normalised result \(\mathbf H\). It is the input to this block’s feed-forward network:

\[ \mathbf H=\frac{(1.72,-1.94,-0.68,1.75)-0.2125}{\sqrt{2.51656875+10^{-5}}} \approx(0.95,-1.36,-0.56,0.97). \]

7.5.2Finish this block, then enter the next one

We now finish the block shown in Figure 2. The numerical trace below collects its input, intermediate states and output.

To finish this block, we use the following supplied feed-forward output:

\[ \operatorname{FFN}(\mathbf H)=(-1.51,-0.15,-0.15,-0.39). \]

Part 9, Appendix A prints the feed-forward weights that produce this output.

Add \(\operatorname{FFN}(\mathbf H)\) to its input \(\mathbf H\), then apply LayerNorm to the sum:

\[ \mathbf H+\operatorname{FFN}(\mathbf H)=(-0.56,-1.51,-0.71,0.58), \] \[ \operatorname{LayerNorm}(-0.56,-1.51,-0.71,0.58) \approx(-0.01,-1.29,-0.21,1.52). \]
Numerical trace · read this table from top to bottom
StageVector for the <start> position
Block input \(\mathbf X_{\text{dec}}\)(1, 0, 0, 0)
Self-attention output(1, 0, −1, 1)
First Add & Norm → \(\mathbf D\)(1.34, −0.45, −1.34, 0.45)
Cross-attention output \(\mathbf Z_{\text{cross}}\)(0.38, −1.49, 0.66, 1.30)
Second Add & Norm → \(\mathbf H\)(0.95, −1.36, −0.56, 0.97)
\(\operatorname{FFN}(\mathbf H)\) · supplied(−1.51, −0.15, −0.15, −0.39)
Final Add & Norm → block output(−0.01, −1.29, −0.21, 1.52)
All six decoder blocks belong to one run

The output of block 1 enters block 2, then block 3, and so on. On run 1, every block receives and returns one \(1\times4\) row for <start>. Each block has its own weights. The next run begins only after token selection extends the prefix.

What changes in a higher block? Before the first block’s cross-attention, \(\mathbf D\) comes only from the target-side input. In later blocks, the input has already passed through earlier cross-attention sublayers, so it can already contain source information. Each block forms its own \(\mathbf D\) and Query, then reads \(\mathbf C\) again to refine that position’s state.

The \(1\times4\) row vector \((-0.01,-1.29,-0.21,1.52)\) is the output of the first decoder block in this example. We have not calculated the other five blocks. After the sixth block, each decoder position has a final hidden-state vector.

Only the last row goes to the output head

To select the next token during inference, the output head reads only the last row of the sixth decoder block’s output. On run 1, this is the row for <start>. On run 2, the prefix is <start> J’aime, so row 2—the row for J’aime—enters the output head to select the next token.

7.5.3Review the three sublayers

With the numerical path complete, Figure 9 compares the decoder block with the encoder block from Part 5. The decoder has three sublayers:

Encoder and decoder blocks; the decoder adds cross-attention and its own Add & Norm.ENCODER BLOCKDECODER BLOCKPart 5Read from bottom to topAdd & Normfeed-forwardAdd & Normself-attentionAdd & Normfeed-forwardAdd & Normmasked self-attentionAdd & Normcross-attentionC2 sublayers3 sublayers
Figure 9. The encoder block has two sublayers; the decoder block has three. In the decoder, masked self-attention is followed by cross-attention and then the feed-forward network. Each sublayer has its own residual addition and LayerNorm. Read the blocks from bottom to top. Press Play to watch the comparison, the added cross-attention sublayer, and the complete decoder block.

7.6Connect the block to the generation loop

We can now connect the encoder from Part 5, the decoder block from this part, and the token-selection loop from Part 6. Figure 10 shows how one completed decoder run leads to the next.

Encoder–decoder generation loop with fixed source memory and a growing target prefix.ENCODER · onceI love LLMssix encoderblocksC · three rowsEmbed + positionsonceDECODER · each runsix decoder blocksmasked self-attentioncross-attentionfeed-forward<start> J’aime les …same Ceach blockEmbed + positionscurrent prefixoutput headlast rowselected tokenordinary token:append; next run<end>: stopC stays fixed; the prefix grows by one token after each ordinary selection.
Figure 10. The whole encoder–decoder Transformer. \(\mathbf C\) is computed once and read by every decoder block. After all six decoder blocks finish, the last position’s final hidden-state vector goes to the output head. A selected ordinary token extends the prefix; <end> stops the loop. Press Play to watch the full sequence automatically, or use Figure 7 to inspect the five runs individually.
  1. Encode the source once. Look up the source-token embeddings, add positional information, and process the sequence through the encoder stack. Keep its output \(\mathbf C\) for the whole translation.
  2. Process the current target prefix. On run 1 it contains only <start>. Embed the prefix, add positional information, and pass its vectors through all six decoder blocks. Every block reads the same \(\mathbf C\) through cross-attention.
  3. Select one new token. Take only the last row of the sixth decoder block’s output. The output head converts that row into next-token scores and probabilities; a selection rule chooses one token.
  4. Extend the prefix or stop. If the selected token is ordinary, append its token ID to the prefix. The next run embeds that enlarged prefix and processes it through the same decoder stack. If the selected token is <end>, stop.

There are two different kinds of progress here. Moving through blocks changes the vectors within one run, while keeping the same positions. Moving to the next run adds the selected token to the input prefix. As in Part 6, we describe the full-prefix calculation.

On run 1, the only final hidden-state vector is also the last one. On run 2, the prefix is <start> J’aime, so the decoder produces two final hidden-state rows: row 1 for <start> and row 2 for J’aime. Only row 2 enters the output head for the next-token selection. The illustrated translation has four ordinary tokens and requires one additional selection of <end>: five runs in total.

On run 2, \(\mathbf D\) has two rows: row 1 represents <start>, and row 2 represents J’aime. Multiplying each row by \(\mathbf W^Q_{\text{cross}}\) produces its own Query, so \(\mathbf Q_{\text{cross}}\) also has two rows in that order.

Run 2: two Queries read the same three source positions

Query positionIloveLLMsRow total
<start>1
J’aime1

The six squares show the entries of \(\mathbf A_{\text{cross}}\), a \(2\times3\) matrix. Each row belongs to a decoder Query; each column belongs to a source position. The three weights in each row sum to 1.

  1. Compare: two Queries against three Keys give a \(2\times3\) score matrix.
  2. Weight: apply softmax separately to each row of the score matrix to produce \(\mathbf A_{\text{cross}}\). Each row contains three weights that sum to 1.
  3. Combine: \(\mathbf A_{\text{cross}}\mathbf V_{\text{cross}}\) multiplies the \(2\times3\) weight matrix by the \(3\times4\) Value matrix, producing \(\mathbf Z_{\text{cross}}\) with shape \(2\times4\): one update per decoder position.
What stays fixed across runs?

The encoder memory \(\mathbf C\) stays fixed throughout translation, and all decoder blocks read the same \(\mathbf C\). Each block has its own \(\mathbf W^K_{\text{cross}}\) and \(\mathbf W^V_{\text{cross}}\). Therefore, \(\mathbf K_{\text{cross}}\) and \(\mathbf V_{\text{cross}}\) stay fixed across runs within that block, but generally differ between blocks.

The target prefix grows. The newly appended token adds a decoder position, which produces its own Query in each block and can combine the fixed Values differently.

The causal mask prevents old positions from reading a newly appended token. Under the same inference conditions, their states stay unchanged. Part 10 explains how caching reuses this work.

Where positional encoding and embedding scaling fit

The full architecture adds positional encodings at the bottoms of both stacks. The original Transformer scales token embeddings by \(\sqrt{d_{\text{model}}}\) before that addition. We omitted both operations from the hand calculation.

\(\mathbf C\) is the encoder stack’s output, so its vectors already reflect source order. We do not add positional encodings again when \(\mathbf C\) is read by cross-attention.

Try it On run 4, the prefix is <start> J’aime les grands. What are the shapes of \(\mathbf C\), \(\mathbf D\), \(\mathbf A_{\text{cross}}\) and \(\mathbf Z_{\text{cross}}\)? Which position is used to select the next token after the decoder stack finishes?
Check your answer
MatrixShapeReason
\(\mathbf C\)\(3\times4\)The source still has three positions.
\(\mathbf D\)\(4\times4\)The target prefix has four positions: <start>, J’aime, les, grands.
\(\mathbf A_{\text{cross}}\)\(4\times3\)Each of four Queries compares with three Keys.
\(\mathbf Z_{\text{cross}}\)\(4\times4\)Each Query produces one \(1\times4\) row of \(\mathbf Z_{\text{cross}}\).

All four decoder positions receive source-dependent updates. After the final block, the final hidden-state vector for the last position, grands, is used to select the next token: modèles in the illustrated translation.

7.7Optional: the parameter count

How many parameters does cross-attention add?

For the original Transformer’s base architecture, use \(d_{\text{model}}=512\) and \(d_{ff}=2048\), as in Part 5. This is the full architecture’s count, not our toy example with \(d_{\text{model}}=4\).

Part 5’s encoder block has 3,150,336 parameters under the convention used here: count \(\mathbf W^Q\), \(\mathbf W^K\), \(\mathbf W^V\) and \(\mathbf W^O\) projection weights, feed-forward weights and biases, and LayerNorm scales and offsets. Omit attention projection biases; embeddings and the output head are outside the block count.

A decoder block adds a cross-attention sublayer, with four projection matrices, and one more LayerNorm:

Added parametersCalculationCount
\(\mathbf W^Q\), \(\mathbf W^K\), \(\mathbf W^V\) and \(\mathbf W^O\) projection weights\(4\times512\times512\)1,048,576
LayerNorm scale and offset\(2\times512\)1,024
\[ 3{,}150{,}336+1{,}048{,}576+1{,}024=4{,}199{,}936. \]

Six decoder blocks contain 25,199,616 parameters. Six encoder blocks contain 18,902,016. Together the two stacks contain 44,101,632, before counting embeddings and the output head. The four projections in cross-attention account for most of the extra parameters in each decoder block.

NextControl which positions a row can read

We have followed one decoder position from its decoder state \(\mathbf D\) to a cross-attention update, through Add & Norm, and onward through the rest of a block. Cross-attention reads encoder memory and updates an existing decoder position.

The next question appears when the decoder input has several positions. Suppose the prefix is <start> J’aime les. All three tokens are present, but the position for J’aime may read only <start> and J’aime during masked self-attention. How do we stop it from reading les while processing the whole prefix together?

Part 8 builds that causal mask. It also introduces the padding mask, which excludes padding positions when sequences of different lengths are processed in a batch. These rules prepare us for training in Part 9, where many prediction positions are processed together.

Part 10 then returns to inference, including other token-selection methods and caching to avoid repeated calculations.