The Transformer, Number by Number  ·  Part 5

What Attention Needs Around It

Attention lets each token gather information from other tokens. This part follows what happens next, as we build one complete encoder block from the original Transformer paper. Using I love LLMs, we work through the residual additions, layer normalisation, and feed-forward network by hand.

By the end, you will be able to follow a token's row through the whole block, explain what each step does, and see why the output can enter another block of the same shape. You will also learn to recognise two common arrangements: Post-LN applies layer normalisation after the residual addition; Pre-LN applies it before the sublayer. Here, LN stands for layer normalisation.

This part builds on Parts 1 to 4. You should be comfortable with matrix multiplication, the dot product, softmax, and how attention produces one output row for each token. It also helps to recall how multi-head attention splits the width and how positional encodings are added to the input. If needed, revisit Part 1, Section 1.3.2 for the \(\sqrt{d_k}\) scaling. Residual connections, layer normalisation, and activation functions are introduced here from scratch.

The decoder and how a word comes out at the top are covered in Part 6, cross-attention is Part 7, and the masks are Part 8. Training is Part 9.

To keep the arithmetic manageable, we reuse Part 1's simplified attention example for I love LLMs, with four numbers in each row. Section 5.2 explains how that example differs from the full architecture. We also introduce toy feed-forward weights, printed in Appendix F, so you can reproduce the calculations.

5.1What the block needs after attention

Part 1 built a self-attention calculation, and Part 2 extended it to multiple heads. In each head, attention forms a weighted sum of Value rows; multi-head attention then combines the heads' outputs. The result is one updated row for each token. For example, the row for I can now contain information gathered from love and LLMs.

What happens to that updated row? Figure 1 shows the complete encoder block from the original paper. Read it from the bottom up: attention, Add and Norm, the feed-forward network, then Add and Norm again. Attention and the feed-forward network are the block's two sublayers; each has its own Add and Norm steps.

ONE ENCODER BLOCK  ·  what you have, and what this part adds Multi-Head Self-Attention Add & Norm Feed-Forward Add & Norm and comes out here the sentence goes in here built in Sections 5.2 and 5.3 built in Section 5.4 built in Section 5.5 you already have this — Parts 1 and 2 Section 5.6 asks where the Norm belongs; Section 5.7 stacks six of these.
Figure 1. One encoder block, read from the bottom up, with the part or section that builds each box. Only the bottom box exists so far; Sections 5.2 to 5.5 build the other three.

The feed-forward network, or FFN, gives the model a way to transform the values, or features, within each token's row. It receives the row after the first Add and Norm step. It processes each token position separately, using the same learned weights at every position. The row for I already contains information gathered by attention; the FFN transforms that row without reading the rows for the other tokens again.

How does this transformation work? Start with a linear layer: multiply the row by a learned matrix, then add a learned vector called a bias. Strictly, multiplication plus a bias is an affine map, but machine-learning texts commonly call the whole operation a linear layer.

Two consecutive linear layers combine into one. Ignoring biases:

\[ (\mathbf{x}\mathbf{W}_1)\mathbf{W}_2 \;=\; \mathbf{x}(\mathbf{W}_1\mathbf{W}_2). \]

Including biases still gives one affine map. To go beyond this, the original Transformer's FFN puts a nonlinear activation function between the layers:

\[ \mathrm{ReLU}(a) \;=\; \max(0,\ a) \]

ReLU, short for rectified linear unit, sets negative values to zero and leaves other values unchanged: \((-2,\ 0,\ 3)\) becomes \((0,\ 0,\ 3)\). It is nonlinear: one fixed matrix and bias cannot describe it over all inputs. Section 5.4 works through the resulting linear–ReLU–linear transformation.

Attention also uses a nonlinear operation, softmax. The distinction is where they act: attention gathers information across token positions; the FFN transforms the features within each row.

That leaves the two Add and Norm boxes in Figure 1. Each wraps one sublayer: Add adds the sublayer's input to its output through a residual connection; Norm then applies layer normalisation to the sum. The residual connection lets a sublayer learn a change to its input. LayerNorm uses the feature values within each row to centre and rescale it, then applies a learned scale and offset.

We now have a map of the block. The next sections follow its actual calculation order: the first residual addition in Section 5.2, LayerNorm in Section 5.3, the FFN in Section 5.4, and the second Add and Norm in Section 5.5.

Key takeaway

For an optional example of what nonlinearity adds, Appendix A constructs a small ReLU network that fits three target values which one linear layer cannot fit. You can continue to Section 5.2 without reading the appendix.

5.2Add: the input comes back

We now follow the block in calculation order, starting just after attention. For I, Part 1 gives us two rows: the input \((0,\ 0,\ 1,\ 1)\) and the attention output \((1.21,\ 0.58,\ 0.21,\ 0.21)\). We will carry these numbers through the remaining steps, finishing the block in Section 5.5.

This is a simplified example: Part 1 used one head without an output projection \(\mathbf{W}^O\), and its input did not include Part 4's positional encoding. Including those components would change the numerical calculation, but the residual addition and LayerNorm would follow the same procedure. Reusing Part 1's numbers lets us focus on those new steps.

The first step is to add the attention input to the attention output. The two matrices below contain all three token rows: \(\mathbf{X}\) is the input and \(\mathbf{Z}\) is what attention returned.

\[ \underbrace{\begin{pmatrix}0 & 0 & 1 & 1\\ 0 & 1 & 0 & 1\\ 1 & 0 & 0 & 1\end{pmatrix}}_{\mathbf{X}} \;+\; \underbrace{\begin{pmatrix}1.21 & 0.58 & 0.21 & 0.21\\ 1.63 & 0.14 & 0.23 & 0.63\\ 1.14 & 0.23 & 0.63 & 0.14\end{pmatrix}}_{\mathbf{Z}} \;=\; \begin{pmatrix}1.21 & 0.58 & 1.21 & 1.21\\ 1.63 & 1.14 & 0.23 & 1.63\\ 2.14 & 0.23 & 0.63 & 1.14\end{pmatrix} \]
THE ADDITION  ·  cell by cell, nothing else X · what went in 0 0 1 1 I 0 1 0 1 love 1 0 0 1 LLMs 3 × 4 Attention(X) · what came back 1.21 0.58 0.21 0.21 1.63 0.14 0.23 0.63 1.14 0.23 0.63 0.14 3 × 4 X + Attention(X) 1.21 0.58 1.21 1.21 1.63 1.14 0.23 1.63 2.14 0.23 0.63 1.14 3 × 4 + = row 1  =  (0, 0, 1, 1)  +  (1.21, 0.58, 0.21, 0.21)  =  (1.21, 0.58, 1.21, 1.21) third entry  =  1 + 0.21  =  1.21 no row meets another row, and no slot meets another slot
Figure 2. Add corresponding entries in the input matrix and the attention output. The highlighted row follows I: each of its four values is added to the value in the same slot of its attention output. This addition does not mix token positions.

Add the corresponding entries, one slot at a time. For I, the third entry is \(1+0.21=1.21\); the full result is \((1.21,\ 0.58,\ 1.21,\ 1.21)\). A slot is a location within one row, whereas a position identifies a token in the sentence, as in Part 3, Section 3.2. The addition pairs matching slots at matching positions.

The input takes two paths

Let \(x\) be the input to a sublayer. One path passes it through the sublayer, which computes \(\text{Sublayer}(x)\). A second path carries \(x\) directly to the addition. This second route is the skip path, also called a shortcut. Together, the two paths form a residual connection:

\[ y \;=\; x + \text{Sublayer}(x) \tag{5-1} \]

Here \(y\) is the output of the addition. In this part of the block, \(\text{Sublayer}\) means attention. The same formula will apply to the feed-forward network in Section 5.5, using that network's own input.

THE SKIP PATH  ·  one copy goes through the sublayer, one goes around it x the row for I (0, 0, 1, 1) the row splits here Sublayer it gives back (1.21, 0.58, 0.21, 0.21) around: no weights, nothing changes — still (0, 0, 1, 1) + x + Sublayer(x) (1.21, 0.58, 1.21, 1.21) the + adds the two, slot by slot: 0 + 1.21 = 1.21     0 + 0.58 = 0.58     1 + 0.21 = 1.21     1 + 0.21 = 1.21 Four numbers meet four numbers, so both arrivals at the + must be the same width.
Figure 3. Two paths reach the addition: the sublayer computes an output, while the skip path carries the input unchanged. The plus sign adds their corresponding entries. A zero sublayer output would leave the input unchanged at this addition; LayerNorm comes next.

The sublayer learns a change to its input

Rearranging Equation 5-1 shows what the sublayer contributes:

\[ \text{Sublayer}(x) \;=\; y - x. \]

The input already reaches the addition through the skip path. The sublayer's output supplies the change added to it. This difference between the resulting row and the input is the residual. The equation describes how the outputs are related; the model does not run a separate subtraction to compute the sublayer.

For example, suppose the desired result of the addition were \((0.1,\ 0,\ 1,\ 1)\), starting from \(x=(0,\ 0,\ 1,\ 1)\). The sublayer would need to contribute \((0.1,\ 0,\ 0,\ 0)\). Only the first slot needs a change. This is a separate illustration of the formula; our attention calculation above still gives \((1.21,\ 0.58,\ 1.21,\ 1.21)\).

Think for a moment What would the sublayer need to output for the addition to return \(x=(0,\ 0,\ 1,\ 1)\) unchanged?

A zero vector: \(x+(0,\ 0,\ 0,\ 0)=x\). This condition concerns the sublayer's output; it does not require every learned parameter to be zero. The skip path itself carries the input unchanged and has no learned weights.

Why this can help training

Suppose a useful transformation is close to leaving its input unchanged. A residual branch can learn the small difference, while the skip path provides the input directly. This changes what the learned branch must produce, and it can make optimisation easier when many layers are stacked.

This is the motivation proposed in the original residual-network paper. Its image-classification experiments found that residual networks were easier to train than comparable plain networks. Learning a change is a useful explanation for that result, not a guarantee that every residual network will train successfully. Appendix B gives the background and a separate toy example of repeated attention mixing; Appendix C explains the optimisation argument in more detail.

The shape stays the same; LayerNorm comes next

For the elementwise addition in Figure 3, both paths must deliver the same shape. In the Transformer, the sublayer takes n × d_model and returns n × d_model, matching the unchanged input on the skip path. The sum therefore has one row per token and \(d_{\text{model}}\) values per row.

We have now completed the Add step. In the original paper's arrangement, LayerNorm acts on \(y\) next, so the complete Add and Norm output is \(\text{LayerNorm}(y)\). Even if a sublayer outputs zero, LayerNorm may still change the row. Section 5.3 follows that next step using our actual result for I, \((1.21,\ 0.58,\ 1.21,\ 1.21)\).

Key takeaway

Try it (2 minutes): Add the rows for love by hand: \((0,1,0,1)\) and \((1.63,0.14,0.23,0.63)\). Check your result against the middle row of the sum above. Which two slots receive an extra 1 from the skip path?

5.3Norm: put the row on one scale

Section 5.2 ended with the addition result for I, \((1.21,\ 0.58,\ 1.21,\ 1.21)\). In the original paper's block, the next step is layer normalisation, or LayerNorm. It centres and rescales each row, then applies a learned scale and offset to each feature.

Which numbers belong in the calculation?

LayerNorm uses the feature values within one token's row. For I, all four values above enter the same mean and variance calculation. The rows for love and LLMs each get their own mean and variance. We do not average across token positions or across sentences in a batch.

For a row \(\mathbf{x}\) containing \(d_{\text{model}}\) values, the mean \(\mu\) is their average. The variance \(\sigma^2\) is the average squared distance from that mean; its square root \(\sigma\) is the standard deviation:

\[ \mu = \frac{1}{d_{\text{model}}}\sum_{k=1}^{d_{\text{model}}} x_k, \qquad \sigma^2 = \frac{1}{d_{\text{model}}}\sum_{k=1}^{d_{\text{model}}}(x_k-\mu)^2. \]

The full operation is:

\[ \text{LayerNorm}(\mathbf{x}) = \boldsymbol{\gamma}\odot \frac{\mathbf{x}-\mu}{\sqrt{\sigma^2+\varepsilon}} + \boldsymbol{\beta}. \tag{5-2} \]

Subtract the same mean from every entry, then divide every entry by the same denominator. The small positive constant \(\varepsilon\) keeps that denominator nonzero. Finally, \(\odot\) means multiply corresponding entries by the learned scale vector \(\boldsymbol{\gamma}\), then add the learned offset vector \(\boldsymbol{\beta}\). We will work through the numbers first, then explain these three extra ingredients.

Follow the row for I

For this worked example, use:

\[ \varepsilon=10^{-5},\qquad \boldsymbol{\gamma}=(1,1,1,1),\qquad \boldsymbol{\beta}=(0,0,0,0). \]

These scales and offsets leave the normalised values unchanged. We use the displayed input \((1.21,\ 0.58,\ 1.21,\ 1.21)\) and keep full precision during the calculation. Intermediate values below show extra digits; final row vectors and the summary table are rounded to two decimal places.

1. Find the mean. Add the four entries and divide by four:

\[ \mu=\frac{1.21+0.58+1.21+1.21}{4}=1.0525. \]

2. Centre the row. Subtract that mean from every entry:

\[ \mathbf{x}-\mu=(0.1575,\ -0.4725,\ 0.1575,\ 0.1575). \]

These deviations sum to zero. The second entry is negative because it was below the original mean; the other three were above it.

3. Compute the denominator. First average the squared deviations, then add \(\varepsilon\) and take the square root:

\[ \sigma^2=\frac{3(0.1575)^2+(-0.4725)^2}{4}=0.07441875, \] \[ \sqrt{\sigma^2+\varepsilon} =\sqrt{0.07441875+0.00001}\approx0.27281633. \]

4. Rescale, then apply the scale and offset. Divide each deviation by this denominator. With our scales of 1 and offsets of 0, these are also the final outputs:

\[ \text{LayerNorm}(\mathbf{x}) =\frac{(0.1575,\ -0.4725,\ 0.1575,\ 0.1575)}{\sqrt{0.07442875}} \approx(0.58,\ -1.73,\ 0.58,\ 0.58). \]

The unrounded output has mean zero. The printed entries sum to 0.01 because of rounding. Its standard deviation is slightly below 1 because the denominator includes \(\varepsilon\). The three equal input entries remain equal in this example because we use the same scale and offset for them.

The other rows follow the same steps, each using its own statistics and the same example parameters. The standard-deviation column shows \(\sigma\); the actual division uses \(\sqrt{\sigma^2+\varepsilon}\). Calculate from the input rows, not from the rounded statistics in the table.

row after the addition mean μ variance σ² std dev σ output (γ = 1, β = 0)
I 1.21, 0.58, 1.21, 1.21 1.05 0.07 0.27 0.58, −1.73, 0.58, 0.58
love 1.63, 1.14, 0.23, 1.63 1.16 0.33 0.57 0.83, −0.03, −1.62, 0.83
LLMs 2.14, 0.23, 0.63, 1.14 1.04 0.51 0.71 1.55, −1.13, −0.57, 0.15

From Section 5.4 onward, we use the printed two-decimal row vectors as the inputs to the next calculation. For I, that input is \((0.58,\ -1.73,\ 0.58,\ 0.58)\).

Why include ε?

Consider \((2,2,2,2)\). Subtracting its mean gives four zeros, so its variance is also zero. Without \(\varepsilon\), normalisation would attempt to divide zero by zero. With \(\varepsilon=10^{-5}\), the denominator is positive and all four normalised values are zero. The small constant also limits amplification when the variance is very small.

For our worked rows, the variance is much larger than \(\varepsilon\), so the normalised standard deviation is close to 1. This is not true for every possible row: the constant row above still has standard deviation zero.

Think for a moment A row already has mean 0 and standard deviation 1. Before the scale and offset, does Equation 5-2 leave it exactly unchanged?

Almost, but not exactly. Subtracting zero leaves it unchanged, but the division is by \(\sqrt{1+\varepsilon}\), slightly larger than 1. Its entries therefore shrink slightly. If we ignored \(\varepsilon\), this normalisation step would leave it unchanged.

What do γ and β learn?

After normalisation, each slot in the token's row gets its own learned scale and offset. For slot \(k\), multiply the normalised value by \(\gamma_k\), then add \(\beta_k\). These parameters let the model adjust the values passed to the next step. Each slot is also called a feature or vector component here; it need not represent a single named property, such as word class or sentiment. The vectors each contain \(d_{\text{model}}\) parameters and are shared across token positions within this LayerNorm. Other LayerNorms in the model have their own parameters.

These parameters do not store each row's original mean or standard deviation and do not generally restore them. For example, adding the same constant to every input entry leaves the centred row unchanged, so the normalised values cannot tell the scale and offset which original mean to recover.

A common initialisation sets all scales to 1 and offsets to 0, as in our example. Training can change them independently for each feature. After that learned step, the output need not have mean 0 or standard deviation near 1, and entries that were equal before the scale and offset can become different.

ONE ROW  ·  the row for I, four slots before mean 0, std dev ≈ 1 after γ and β illustration with different γ and β 1.21 0.58 1.21 1.21 0.58 −1.73 0.58 0.58 − μ, ÷ √(σ² + ε) × γ, + β 0
Figure 4. Left: the input row for I. Middle: after subtracting its mean and dividing by √(σ² + ε). Right: a schematic illustration of how different per-feature scales and offsets could change the row, not a result calculated from the parameters in our example. With our γ = 1 and β = 0, the final row is the middle panel.

Why normalise here?

The residual addition can change a row's centre and scale. LayerNorm gives the next sublayer a representation whose centre and scale have been controlled before the learned scales and offsets are applied. This can help stabilise computation and training as blocks are stacked. Each row is processed separately; putting rows on a comparable scale does not make their feature patterns identical.

In the original paper's Post-LN arrangement, this operation completes the first Add and Norm. The resulting rows now enter the feed-forward network in Section 5.4.

Optional: how is this different from batch normalisation?

Batch normalisation uses statistics across examples in a batch (and, in some settings, other axes). Here, LayerNorm uses only the features of the current token row, so its statistics do not depend on the other sentences in the batch. Part 8 discusses batches and padding.

Key takeaway

Try it (2 minutes): Apply Equation 5-2 to \((2,2,2,2)\), using \(\varepsilon=10^{-5}\), all scales equal to 1, and all offsets equal to 0. What changes if you set \(\boldsymbol{\beta}=(1,0,-1,2)\) instead?

5.4The feed-forward network

The first Add and Norm has produced the row \((0.58,\ -1.73,\ 0.58,\ 0.58)\) for I. We now pass that row through the feed-forward network, or FFN, the encoder block's second sublayer. As introduced in Section 5.1, the FFN transforms each token row separately.

A BLOCK HAS TWO SUBLAYERS, AND THIS SECTION BUILDS THE SECOND the Add and Norm steps are not sublayers; each one follows a sublayer one block Multi-Head Self-Attention Add & Norm Feed-Forward Add & Norm sublayer 1 Parts 1 and 2 sublayer 2 this section out: the same shape in: one row per word, four numbers each Section 5.3 produced the rows going in. For I that row is (0.58, −1.73, 0.58, 0.58).
Figure 5. The feed-forward network is the second sublayer in the encoder block. It receives the output of the first Add and Norm. Its own residual addition and LayerNorm come next, in Section 5.5.

The input, parameters, and three steps

Our input has four slots. The first linear layer expands it to sixteen, ReLU acts on those sixteen values, and the second linear layer returns four values. These are the same three steps used in the original Transformer:

\[ \text{FFN}(\mathbf{x})= \mathrm{ReLU}(\mathbf{x}\mathbf{W}_1+\mathbf{b}_1)\mathbf{W}_2+\mathbf{b}_2. \tag{5-3} \]

The matrices and biases are learned parameters. For this hand calculation, \(\mathbf{W}_1\) has shape 4 × 16 and \(\mathbf{W}_2\) has shape 16 × 4. We use the toy matrices printed in Appendix F and set both bias vectors to zero:

\[ \mathbf{x}=(0.58,\ -1.73,\ 0.58,\ 0.58),\qquad \mathbf{b}_1=\mathbf{0}_{16},\qquad \mathbf{b}_2=\mathbf{0}_{4}. \]

Here \(\mathbf{0}_{16}\) means a vector of sixteen zeros. The biases therefore add nothing in this example, although a trained FFN can have nonzero biases. Following Section 5.3's rounding convention, we use the four displayed input values exactly.

THE FEED-FORWARD SUBLAYER AS A NETWORK  ·  read from the bottom up the row in 4 numbers after ReLU 16 numbers the row out 4 numbers W₁  every input unit joins every middle unit W₂  every middle unit joins every output unit filled: ReLU kept it dashed: value is 0 after ReLU 7 positive, 9 zero, for this row A zeroed unit sends 0 along every one of its connections, so nine of the sixteen contribute nothing to the row that comes out. Another input may produce a different pattern and number of zeros.
Figure 6. Our toy FFN, read from the bottom up: four input slots, sixteen hidden units, and four output slots. The dashed hidden units have zero output after ReLU for this input. All sixteen units remain part of the network. The biases are zero in this example.
WHERE THE SIXTEEN COMES FROM one output number per column of the matrix, so the count of columns is the count of numbers the row 4 numbers × W₁ 4 rows, 16 columns = the wide row 16 numbers ReLU count unchanged × W₂ 16 rows, 4 columns = back to 4 Sixteen columns in W₁ means sixteen numbers out. Sixteen rows in W₂ means it accepts them all, and its four columns bring the row back to the width it started with, which is what lets the block stack. ReLU changes the numbers, never how many there are.
Figure 7. Follow the shapes: 1 × 4 becomes 1 × 16 after the first linear layer. ReLU keeps that shape. The second linear layer returns it to 1 × 4. Each matrix column produces one output value.

Step 1: compute sixteen intermediate values

Multiply the input row by \(\mathbf{W}_1\). Each of its sixteen columns gives one output value. For example, the sixth column is \((1,0,-1,1)^\top\), giving:

\[ 0.58(1)+(-1.73)(0)+0.58(-1)+0.58(1)=0.58. \]

The fifth column, \((-1,1,-1,0)^\top\), gives a negative value:

\[ 0.58(-1)+(-1.73)(1)+0.58(-1)+0.58(0)=-2.89. \]

Repeating this dot product for every column produces the first row of the table below. You can check any entry against the corresponding column in Appendix F.

Step 2: apply ReLU to each value

ReLU uses \(\max(0,a)\): a negative value becomes zero, while a positive value stays unchanged. Zero stays zero. Applying it separately to all sixteen values gives:

the sixteen numbers
before ReLU 0.00 −1.15 −1.74 −1.15 −2.89 0.58 −1.15 −0.58 −1.73 0.58 0.57 1.73 −0.58 1.16 1.16 0.58
after ReLU 0.00 0.00 0.00 0.00 0.00 0.58 0.00 0.00 0.00 0.58 0.57 1.73 0.00 1.16 1.16 0.58

Eight values were negative and one was already zero, so the result has nine zeros and seven positive values. The vector still has sixteen slots. ReLU changes the values; it does not remove slots or shrink the matrix used by the next step. A different input may produce a different pattern or number of positive values.

Step 3: return to four values

Multiply the sixteen-value row by \(\mathbf{W}_2\). This matrix has four columns, so it produces four output values. For the first output, only the nonzero entries of the input row need to be included in the arithmetic:

\[ 0.58(1)+0.58(1)+0.57(1)+1.73(0)+1.16(1)+1.16(1)+0.58(-1)=3.47. \]

The seven terms correspond to the seven positive values after ReLU, using their coefficients from the first column of \(\mathbf{W}_2\). The other nine terms are zero. Notice that a positive input can still contribute zero or a negative amount, depending on its coefficient. Using the remaining three columns, then adding our zero bias \(\mathbf{b}_2\), gives:

\[ \text{FFN}\bigl((0.58,\ -1.73,\ 0.58,\ 0.58)\bigr) =(3.47,\ -0.58,\ -0.01,\ 2.32). \]

The FFN output can contain negative numbers. ReLU acts on the intermediate sixteen-value row; there is no second ReLU after the final linear layer in this FFN.

The same calculation at every token position

The paper calls this a position-wise feed-forward network. The rows for I, love, and LLMs all use the same \(\mathbf{W}_1,\mathbf{b}_1,\mathbf{W}_2,\mathbf{b}_2\) within this block. Each row is processed separately, so different inputs can produce different outputs even though the parameters are shared.

The FFN does not read another token's row during this calculation. Its input already contains information gathered by attention. Figure 8 contrasts attention's mixing across positions with the FFN's transformation of each individual row.

ATTENTION  ·  moves information between rows I 1.21 0.58 0.21 0.21 love 1.63 0.14 0.23 0.63 LLMs 1.14 0.23 0.63 0.14 the row for love is built from all three rows arrows cross between rows; that crossing is the part only attention does FEED-FORWARD  ·  works inside one row at a time I 3.47 -0.58 -0.01 2.32 W₁ ReLU W₂ love 6.52 3.98 6.52 7.32 W₁ ReLU W₂ LLMs 5.51 0.84 2.84 2.42 W₁ ReLU W₂ same two matrices in all three boxes; no arrow crosses between rows
Figure 8. Comparing the two sublayers: attention combines information across token positions; the FFN applies the same learned transformation separately to each row. The Add and Norm steps between them are omitted from this comparison.

Why expand the row?

The middle width is called \(d_{ff}\), where “ff” stands for feed-forward. It is the number of hidden units: the intermediate slots between the two linear layers. The first layer computes a learned combination of input values for each hidden unit. ReLU acts on each result, and the second layer combines them into the output.

More hidden units provide room for more such combinations before the output is formed. The original paper uses \(d_{\text{model}}=512\) and \(d_{ff}=2048\), a factor of four. Our toy example uses the same ratio: 4 → 16 → 4. This ratio is a design choice. The matrix shapes are d_model × d_ff and d_ff × d_model.

ONE ROW THROUGH THE FEED-FORWARD NETWORK 0.58 -1.73 0.58 0.58 the row for I  ·  4 numbers W₁ 0.00 -1.15 -1.74 -1.15 -2.89 0.58 -1.15 -0.58 -1.73 0.58 0.57 1.73 -0.58 1.16 1.16 0.58 16 numbers, at their real heights    d_ff = 4 × d_model ReLU flattens every bar below the line — eight negatives, plus one existing zero W₂ 3.47 -0.58 -0.01 2.32 4 numbers out bar 6  =  0.58(1) + (−1.73)(0) + 0.58(−1) + 0.58(1)  =  0.58, from column 6 of W₁ Same two matrices for every row in the sentence; no row is mixed with any other row here.
Figure 9. The sixteen intermediate values for I. ReLU sets the eight negative values to zero and leaves the existing zero unchanged, giving nine zeros and seven positive values. Another input can produce a different pattern and number of zeros.

As Section 5.1 showed, removing ReLU would let the two linear layers combine into one affine map. Expanding the middle alone would then add no nonlinear expressive power. With ReLU between them, different inputs can activate different hidden units, allowing transformations that one affine map cannot represent.

Think for a moment If we replaced ReLU with \(f(a)=2a\), would the two layers still combine into one affine map?

Yes. Multiplying every intermediate value by 2 can be absorbed into the second matrix. The operation is still linear, so it does not provide the nonlinearity that ReLU supplies. Softmax and LayerNorm are nonlinear too, but have different roles elsewhere in the block.

Optional: the universal approximation theorem

One version of the universal approximation theorem states that a network with one ReLU hidden layer, a linear output layer, and learnable weights and biases can approximate any continuous function uniformly on a compact (closed and bounded) input region, given enough hidden units. “Uniformly” means the error can be made arbitrarily small throughout that region.

The theorem guarantees that suitable parameters exist—not that training will find them or that our chosen width is sufficient.

What goes into the next Add and Norm?

The FFN has returned four values, matching the width of its input. Section 5.5 adds its output \((3.47,\ -0.58,\ -0.01,\ 2.32)\) to the row that entered the FFN, \((0.58,\ -1.73,\ 0.58,\ 0.58)\), then applies LayerNorm. Keep both rows: they are the two inputs to that residual addition.

Key takeaway

Try it (2 minutes): Apply ReLU to \((1,-2,3,-4)\). How many slots remain? How many values are zero? Explain why a subsequent matrix multiplication can still produce a negative output.

5.5Add and Norm again, and the block is done

Look back at Figure 1. Only the top box remains: the second Add and Norm, after the feed-forward network. Completing it finishes the encoder block.

In this Post-LN block, we repeat the same two steps used after attention: add the sublayer's input to its output, then apply LayerNorm.

Two rows go into that arithmetic. Both were computed earlier, so here they are again:

Add. Here the skip path carries the FFN's input: the normalised row from Section 5.3. Add it to the FFN's output, slot by slot:

\[ (0.58,\ -1.73,\ 0.58,\ 0.58) \;+\; (3.47,\ -0.58,\ -0.01,\ 2.32) \;=\; (4.05,\ -2.31,\ 0.57,\ 2.90) \]

Norm. This second LayerNorm has its own learned scale and offset parameters. For this example, we again set every \(\gamma_k=1\), every \(\beta_k=0\), and \(\varepsilon=10^{-5}\). The sum above has mean 1.3025 and variance approximately 5.9219. Subtract the mean from each value, then divide by \(\sqrt{\text{variance}+\varepsilon}\). For the first value:

\[ \frac{4.05-1.3025}{\sqrt{5.9219+10^{-5}}}\approx1.13 \]

Applying this to all four values gives:

\[ (1.13,\ -1.48,\ -0.30,\ 0.66) \]

This is the block's output row for I. The same Add and Norm steps apply separately to the rows for love and LLMs. Figure 10 shows all three rows at every stage, with the skip path at each addition.

ONE BLOCK, EVERY ROW · read from the bottom up the same four boxes as Figure 1, with the numbers at every stage 0 0 1 1 0 1 0 1 1 0 0 1 I love LLMs X · the rows entering the block the rows split here Self-Attention (single head) simplified example 1.21 0.58 0.21 0.21 1.63 0.14 0.23 0.63 1.14 0.23 0.63 0.14 I love LLMs what attention returned + 1.21 0.58 1.21 1.21 1.63 1.14 0.23 1.63 2.14 0.23 0.63 1.14 I love LLMs after the Add LayerNorm Section 5.3 0.58 -1.73 0.58 0.58 0.83 -0.03 -1.62 0.83 1.55 -1.13 -0.57 0.15 I love LLMs after the Norm and again here Feed-Forward Section 5.4 3.47 -0.58 -0.01 2.32 6.52 3.98 6.52 7.32 5.51 0.84 2.84 2.42 I love LLMs what the feed-forward network returned + 4.05 -2.31 0.57 2.90 7.35 3.95 4.90 8.15 7.06 -0.29 2.27 2.57 I love LLMs after the Add LayerNorm Section 5.5 1.13 -1.48 -0.30 0.66 0.73 -1.24 -0.69 1.20 1.57 -1.21 -0.24 -0.13 I love LLMs leaving the block the skip: these rows travel round untouched the skip: these rows travel round untouched
Figure 10. One block with the numbers in place, laid out like Figure 1 and read from the bottom up. At each sublayer the rows split: one copy goes through, the other travels round on the blue skip line, and the plus sign adds them back together.
Think for a moment The row that went into the block was \((0,\ 0,\ 1,\ 1)\) and the row leaving it is \((1.13,\ -1.48,\ -0.30,\ 0.66)\). Four numbers in, four numbers out. What can you do with that output row that you could not do if it had come out five numbers long?

Pass all three output rows together to the next encoder block. Each row still has the four values that the next block expects, and its self-attention can combine information across the rows. This fixed width lets blocks be stacked, as Section 5.7 explains. Part 6 introduces how the decoder uses the output of the full encoder stack.

Key takeaway

Try it (3 minutes): Do the same two steps for love. Its normalised row from Section 5.3 is \((0.83,\ -0.03,\ -1.62,\ 0.83)\); take the feed-forward output for that row as \((6.52,\ 3.98,\ 6.52,\ 7.32)\). Add the two rows, then normalise the sum using \(\varepsilon = 10^{-5}\), \(\boldsymbol{\gamma}=(1,1,1,1)\), and \(\boldsymbol{\beta}=(0,0,0,0)\), as in Section 5.3. Check that the answers add up to about 0 and have a standard deviation close to 1.

5.6Where the Norm goes: Post-LN and Pre-LN

The walk you just finished used the original paper’s arrangement: sublayer, then add, then normalise. Many later Transformer designs put LayerNorm before each sublayer instead. These arrangements are called Post-LN and Pre-LN, where LN means layer normalisation. The names describe where normalisation happens; neither one means “correct” or “incorrect.”

The paper normalises after the addition. That's the formula Part 2, Section 2.5.1 wrote down:

\[ \text{output} \;=\; \text{LayerNorm}\bigl(x + \text{Sublayer}(x)\bigr) \tag{5-4} \]

In the Pre-LN arrangement, LayerNorm runs before the sublayer, while the residual addition remains unchanged:

\[ \text{output} \;=\; x + \text{Sublayer}\bigl(\text{LayerNorm}(x)\bigr) \tag{5-5} \]

Post-LN normalises the sum after the residual addition. Pre-LN puts LayerNorm inside the sublayer branch, so the skip path carries \(x\) around both LayerNorm and the sublayer.

Figure 11 puts the two side by side at the same scale as Figure 1. Read either column from the bottom up and the boxes are the same; only the gold one has moved. In the Pre-LN column the blue skip lines run from one addition to the next without meeting a LayerNorm. In the Post-LN column a LayerNorm sits on top of every addition, so the same path goes through two LayerNorms per encoder block.

THE SAME BLOCK, TWO ORDERS  ·  read from the bottom up the same boxes as Figure 1 in both columns; only the LayerNorm has moved Multi-Head Self-Attention + LayerNorm Feed-Forward + LayerNorm in out LayerNorm Multi-Head Self-Attention + LayerNorm Feed-Forward + in out POST-LN the paper, and Sections 5.2 to 5.5 PRE-LN used in many implementations gold sits after every addition gold sits before every sublayer
Figure 11. Post-LN and Pre-LN encoder blocks. Follow the blue skip paths: in Post-LN, each addition is followed by LayerNorm; in Pre-LN, the skip paths bypass LayerNorm as well as the sublayers.

This placement changes both the values computed and the routes gradients follow during training. Xiong and colleagues found that, at initialisation, Post-LN can produce large parameter gradients near the output. Gradually increasing the learning rate at the start (warmup) helps stabilise training. Pre-LN had better-behaved gradients in their analysis, though training behaviour also depends on the rest of the setup. Part 9 explains warmup.

A simplified numerical comparison

Figure 12 uses the same input and learned parameters as Figure 10, with LayerNorm moved into each sublayer branch. To keep the comparison simple, we hold the attention probabilities at Part 1's values. These probabilities describe how much attention each token gives to the others; they are distinct from the learned projection matrices. In a full attention calculation, normalising the input changes Q and K and generally changes these probabilities too.

THE SAME BLOCK WIRED PRE-LN · read from the bottom up simplified comparison: same input and parameters, attention probabilities held fixed 0 0 1 1 0 1 0 1 1 0 0 1 I love LLMs X · the rows entering the block the rows split here LayerNorm before the sublayer, not after -1 -1 1 1 -1 1 -1 1 1 -1 -1 1 I love LLMs after the Norm Self-Attention (single head) simplified example 0.42 0.16 -0.58 -0.58 1.26 -0.72 -0.54 0.26 0.28 -0.54 0.26 -0.72 I love LLMs what attention returned + 0.42 0.16 0.42 0.42 1.26 0.28 -0.54 1.26 1.28 -0.54 0.26 0.28 I love LLMs after the Add and again here LayerNorm before the sublayer again 0.58 -1.73 0.58 0.58 0.92 -0.38 -1.47 0.92 1.49 -1.33 -0.09 -0.06 I love LLMs after the Norm Feed-Forward Section 5.4 3.47 -0.58 -0.01 2.32 6.25 2.72 6.25 6.79 5.65 0.24 1.60 1.53 I love LLMs what the feed-forward network returned + 3.89 -0.42 0.41 2.74 7.51 3 5.71 8.05 6.93 -0.30 1.86 1.81 I love LLMs leaving the block the skip: these rows travel round untouched the skip: these rows travel round untouched
Figure 12. A simplified Pre-LN example with attention probabilities held fixed. The input and learned parameters match Figure 10. Each blue skip path bypasses LayerNorm; each sublayer receives a normalised input.

Compare the two at the second skip line. Both figures take the first one from \(\mathbf{X}\) itself. In Figure 10 the second starts from a row a \(\text{LayerNorm}\) has just produced; in Figure 12 it starts from the first addition's output, which is passed directly along the skip path.

For example, Figure 12 adds the attention output \((0.42,\ 0.16,\ -0.58,\ -0.58)\) to \(I\)'s input \((0,\ 0,\ 1,\ 1)\), giving \((0.42,\ 0.16,\ 0.42,\ 0.42)\). This sum goes directly to the next skip path. A separate branch normalises it before the FFN.

Think for a moment In the Pre-LN half of Figure 11, imagine six copies of that half stacked, and follow the blue line through all of them. Does that route pass through any LayerNorm?

No. Within the Pre-LN stack, each sublayer adds an update to the current representation, and the skip route bypasses every LayerNorm. The representation still changes as updates are added. In Post-LN, every residual addition is followed by LayerNorm, so that route passes through two LayerNorms per block.

This comparison concerns the inside of the stack. A common Pre-LN design adds one final LayerNorm after the entire stack, as in Xiong and colleagues' architecture.

The rest of this part draws Post-LN, because this series is following the paper. When you read an implementation, check where its normalisation happens.

Key takeaway

5.7The encoder block, and why you can stack it

You now have every piece of the Post-LN encoder block used in this tutorial: multi-head self-attention, then Add and Norm, then the feed-forward network, then Add and Norm again. Two sublayers, each wrapped the same way (Figure 13).

ONE BLOCK Multi-Head Self-Attention Add & Norm Feed-Forward Add & Norm n × d_model out n × d_model in skip paths SIX OF THEM, N = 6 block 1 block 4 block 5 block 6 ⋮ n × d_model n × d_model n × d_model Same structure in every block. Each has its own learned parameters.
Figure 13. On the left, one encoder block. On the right, the encoder stack the base model uses: six of those blocks, one on top of another. The output shape at each join matches the next block's input shape.

Look at the shape labels running up the right-hand side of Figure 13. A block takes n × d_model and returns n × d_model. Here, \(n\) is the number of tokens and \(d_{\text{model}}\) is the width of each row. Matching shapes let us pass all the output rows directly to the next block. Each successive block can combine information across tokens again and further transform their representations. The original base model uses \(N = 6\) blocks.

Think for a moment Block 3 gets rows of the same shape that block 1 got. Does it get the same numbers?

Block 3 receives block 2's output. The values will generally have changed as the first two blocks process them, while the shape stays the same. Matching shapes allow direct connection; they do not require the values to stay fixed or to change.

✗  Common mistake The six blocks are drawn the same and described as identical, so it is tempting to think they share their weights, but that is wrong. They are identical in structure only. Each block has its own \(\mathbf{W}^Q\), \(\mathbf{W}^K\), \(\mathbf{W}^V\), \(\mathbf{W}^O\), its own \(\mathbf{W}_1\) and \(\mathbf{W}_2\), its own feed-forward biases, and its own \(\boldsymbol{\gamma}\) and \(\boldsymbol{\beta}\) for each of its two LayerNorms. Six blocks means six full sets.

During training, the original model also uses dropout. Inside each block, it acts on each sublayer's output before residual addition and LayerNorm. At the entrance to the stack, it also acts on the sum of token embeddings and positional encodings. Some implementations additionally apply dropout to attention probabilities after softmax.

With the base model's dropout rate of 0.1, each value has a 10% chance of being set to zero; each retained value is multiplied by \(1/0.9\), preserving its expected value. This discourages reliance on individual activations and can help the model generalise. Dropout is disabled during evaluation and inference. Our worked calculations omit dropout so that their results are reproducible.

How many parameters are in one block?

Use the base model's dimensions, \(d_{\text{model}} = 512\) and \(d_{ff} = 2048\). For this count, attention projections have no biases, the FFN has two bias vectors, and each LayerNorm has a learned scale and offset. We count only the encoder blocks, excluding the embedding parameters.

Combine all heads' Q projections into one matrix, and do the same for K and V. Each combined matrix has shape 512 × 512. Including the output projection gives four matrices:

\[ 4 \times 512 \times 512 \;=\; 1{,}048{,}576 \]

Two feed-forward matrices, one 512 × 2048 and one 2048 × 512:

\[ 2 \times 512 \times 2048 \;=\; 2{,}097{,}152 \]

Then the small things, which are easy to forget and come to about 0.15 per cent of the block. Two feed-forward bias vectors, \(2048 + 512 = 2{,}560\). Two LayerNorms, each with a \(\boldsymbol{\gamma}\) and a \(\boldsymbol{\beta}\) of length 512, so \(4 \times 512 = 2{,}048\). Adding the four lines:

\[ 1{,}048{,}576 + 2{,}097{,}152 + 2{,}560 + 2{,}048 \;=\; 3{,}150{,}336 \]

Under these assumptions, six blocks contain \(18{,}902{,}016\) learned parameters. The two feed-forward matrices contain twice as many parameters as all four attention projection matrices together. The FFN biases and LayerNorm parameters account for only 4,608 of the 3,150,336 parameters per block, despite their roles in the computation. Implementations that include attention projection biases have additional parameters.

Key takeaway

Try it (3 minutes): Count the parameters in a full encoder block with \(d_{\text{model}}=4\) and \(d_{ff}=16\), including all four attention projection matrices. Use the assumptions above: no attention biases, two FFN bias vectors, and two LayerNorms with learned scales and offsets. Count the attention matrices, FFN matrices, FFN biases, and LayerNorm parameters separately, then add them. How many parameters would six such blocks contain?

Check your answer

Attention matrices: \(4\times4\times4=64\). FFN matrices: \(2\times4\times16=128\). FFN biases: \(16+4=20\). LayerNorm parameters: \(2\times2\times4=16\).

One block contains \(64+128+20+16=228\) parameters; six contain \(6\times228=1{,}368\).

NextWhat this block still cannot do

You now have a complete encoder block and know how six of them form an encoder stack. Self-attention lets each token use information from other positions, and the FFN transforms each row separately. The stack returns an n × d_model matrix: one updated row per input token.

These rows represent the input sequence. To generate an output sequence one token at a time, the encoder–decoder Transformer in this tutorial adds three components:

Next, Part 6 introduces the decoder and generation: predict a token, append it to the prefix, and repeat.

Appendix AA three-point example: what ReLU adds

Section 5.1 showed why consecutive linear layers combine into one. This optional appendix uses Part 1's numbers to build a three-point example that one linear layer cannot fit, then shows how a small ReLU network fits it. The target values are exact 0-or-1 outputs at those three inputs; this is different from producing a score for a later classification threshold. Nothing later in the series depends on reading it.

One number, and where it came from

Part 1, Section 1.2.2 ended with a new row of four numbers for the word I:

\[ \mathbf{z}_1 \;=\; (1.21,\ 0.58,\ 0.21,\ 0.21) \]

Using the displayed attention weights, the first value is:

\[ \begin{pmatrix}0.58 & 0.21 & 0.21\end{pmatrix} \begin{pmatrix}1\\ 2\\ 1\end{pmatrix} \;=\; 1.21 \]

The first output component is the weighted sum of the first components of the three Value vectors: 1, 2 and 1. The weights are the attention probabilities from I to I, love and LLMs.

This is the weighted sum \(A\mathbf{V}\) for one attention head, where \(A\) contains the attention probabilities. Figure 14 shows the calculation. A complete multi-head attention sublayer also concatenates the head outputs and applies \(\mathbf{W}^O\). Here we isolate the weighted sum to construct a small example.

attention weights 0.58 0.21 0.21 I 0.14 0.63 0.23 love 0.23 0.14 0.63 LLMs 3 × 3 × V 1 1 0 0 v₁ 2 0 0 1 v₂ 1 0 1 0 v₃ 3 × 4 = Z 1.21 0.58 0.21 0.21 I 1.63 0.14 0.23 0.63 love 1.14 0.23 0.63 0.14 LLMs 3 × 4 row 1 of Z  =  0.58·v₁  +  0.21·v₂  +  0.21·v₃ first entry  =  0.58(1) + 0.21(2) + 0.21(1)  =  1.21 every number in Z is a weighted sum of numbers already in V; the weights only choose the proportions
Figure 14. The multiply by \(\mathbf{V}\), with every number from Part 1 in place; the gold boxes follow I's weights into I's output row. Each output row is a weighted sum of the Value rows.

Three inputs and their target values

We will construct three possible mixtures of the Value rows and assign each an exact target, 0 or 1, using this question:

?  The question Did love get at least a quarter of I's attention?

For easy arithmetic, choose weights that give LLMs zero and divide the remaining weight between I and love. These are idealised mixtures chosen by hand: an ordinary softmax with finite logits produces strictly positive probabilities, so it does not give these exact 0 and 1 endpoints.

Each row is then \(w_{\texttt{I}}\,\mathbf{v}_1 + w_{\texttt{love}}\,\mathbf{v}_2\), with \(\mathbf{v}_1 = (1,1,0,0)\) for I and \(\mathbf{v}_2 = (2,0,0,1)\) for love — both read straight off the \(\mathbf{V}\) block in Figure 14. Here are the three, with their target values (0 for no, 1 for yes):

Weight on I Weight on love Weight on LLMs The row that comes out Target value
100\((1,\ 1,\ 0,\ 0)\)0 (no)
0.50.50\((1.5,\ 0.5,\ 0,\ 0.5)\)1 (yes)
010\((2,\ 0,\ 0,\ 1)\)1 (yes)

Check the middle one if you like: \(0.5 \times (1,1,0,0) + 0.5 \times (2,0,0,1) = (0.5,\ 0.5,\ 0,\ 0) + (1,\ 0,\ 0,\ 0.5) = (1.5,\ 0.5,\ 0,\ 0.5)\).

Our fitting task is to output exactly \(0,1,1\) on these three rows. If we only wanted a class label, we could read the last value and compare it with 0.25. Here we ask whether a linear layer can produce the target numbers directly, without that extra threshold operation.

A linear layer preserves the midpoint

Try a linear layer \(f(\mathbf{z})=\mathbf{z}\mathbf{W}+b\), with \(\mathbf{W}\) of shape \(4\times1\) and a scalar bias \(b\). It must use the same parameters for all three inputs.

Think for a moment Suppose \(f\) maps the first row, \(\mathbf{z}_a=(1,1,0,0)\), to 0 and the last row, \(\mathbf{z}_b=(2,0,0,1)\), to 1. What must it output for the middle row?

The middle row is the average of the endpoints:

\[ (1.5,\ 0.5,\ 0,\ 0.5) =\frac{\mathbf{z}_a+\mathbf{z}_b}{2}. \]

A linear layer, including its bias, maps this midpoint to the average of the endpoint outputs:

\[ f\!\left(\frac{\mathbf{z}_a+\mathbf{z}_b}{2}\right) =\frac{f(\mathbf{z}_a)+f(\mathbf{z}_b)}{2} =\frac{0+1}{2}=0.5. \]

The bias is included because \((b+b)/2=b\). Halfway between 0 and 1 is 0.5, but the target value for the middle input is 1. Therefore, \(f\) cannot fit all three targets exactly (Figure 15).

Adding more linear layers without an activation does not help: they combine into one affine map, which still preserves midpoints. This argument applies to linear post-processing of the three fixed rows. It does not establish a limitation of attention as a whole, whose probabilities depend nonlinearly on its input.

THE THREE ROWS (1, 1, 0, 0) (1.5, 0.5, 0, 0.5) (2, 0, 0, 1) no love half of love all of love exactly halfway exactly halfway TARGET: AT LEAST A QUARTER TO LOVE? 0   no 1   yes the correct answer, all the way up already linear-layer output: 0.5 halfway between 0 and 1 cannot get across this gap
Figure 15. The middle input is halfway between the endpoints, but its target is not halfway between their targets. A linear layer that fits the endpoint targets must output 0.5 for the middle input.

Two ReLU units fit the three targets

Now add a nonlinear activation. \(\mathrm{ReLU}\) sends negative numbers to 0 and leaves nonnegative numbers unchanged.

In these rows, the last value equals the weight given to love: 0, 0.5, or 1. Call it \(w\); it is the fourth and last component. Compute:

\[ g(w) \;=\; \mathrm{ReLU}(8w-1) \;-\; \mathrm{ReLU}(8w-2) \]
Row \(w\) (fourth component) \(\mathrm{ReLU}(8w-1)\) \(\mathrm{ReLU}(8w-2)\) Output \(g(w)\)
\((1,\ 1,\ 0,\ 0)\)0000
\((1.5,\ 0.5,\ 0,\ 0.5)\)0.5321
\((2,\ 0,\ 0,\ 1)\)1761

The outputs are exactly \(0,1,1\), as required. Why these two ReLUs? The first starts increasing at \(w=1/8\), and the second at \(w=1/4\). Once both are increasing, their equal slopes cancel in the subtraction, leaving an output of 1. Together they form a continuous ramp:

\[ g(w)= \begin{cases} 0 & w\leq 1/8,\\ 8w-1 & 1/8<w<1/4,\\ 1 & w\geq 1/4. \end{cases} \]

For example, \(g(0.2)=0.6\), although the threshold question's target there is 0. This construction fits the three selected targets; it does not implement the threshold rule for every possible weight. A finite network of linear layers and ReLUs is continuous, so it cannot exactly reproduce that discontinuous step over the whole interval.

A linear layer with biases produces \(8w-1\) and \(8w-2\), ReLU acts on both, and a second linear layer subtracts the results. This is the linear–ReLU–linear structure of the FFN in Section 5.4, here with just two hidden units and one output. The activation lets the network fit target values that do not obey the midpoint rule.

Try it (2 minutes): Give love a weight of 0.75 and I the other 0.25. Work out the row — you should get \((1.75,\ 0.25,\ 0,\ 0.75)\). It sits three quarters of the way from the no-love row to the all-love row, so a linear layer that fits the two endpoint targets must output 0.75. The target is 1. Then put the row through the two ReLUs above and check that they give 1.

Appendix BWhat the residual addition changes

Section 5.2 introduced the residual connection as a way to add a learned update to the input. This optional appendix examines two ideas: how that form can help express an identity mapping, and how a skip connection changes repeated mixing in a small numerical example.

The mixing example uses fixed weights to isolate the effect of addition. Appendix C discusses the optimisation hypothesis and experimental evidence; Appendix D examines gradients.

B1. More capacity does not guarantee easier training

If a deeper architecture can reproduce the shallower network and make its extra layers act as identities, it can represent an equally good solution. An identity mapping returns its input unchanged. Having such a solution available, however, does not guarantee that training will find it (Figure 16).

A PLAIN NETWORK IS JUST LAYERS, ONE ON TOP OF ANOTHER nothing goes around a layer 20 layers ⋮ input its output 56 layers ⋮ the same 20 layers, copied ⋮ 36 more, each returning its input unchanged the same input its output the same numbers arrive here and the 36 above change nothing, so the two outputs are the same Every setting on the right exists. Training does not find it.
Figure 16. A schematic identity-mapping construction: copy a shallower network and insert extra layers that pass their inputs through unchanged, where dimensions permit. This illustrates representational capacity, not the parameters found by training or the exact layout of the experimental networks.

B2. Expressing an identity mapping

First consider a single bias-free linear layer, \(\mathbf{x}\mathbf{W}\). To return every input unchanged, it must use the identity matrix \(\mathbf{W}=\mathbf{I}\). For example:

\[ (0,\ 0,\ 1,\ 1) \begin{pmatrix} 1 & 0 & 0 & 0\\ 0 & 1 & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 1 \end{pmatrix} =(0,\ 0,\ 1,\ 1). \]

For a residual mapping \(\mathbf{x}+F(\mathbf{x})\), the identity target is instead \(F(\mathbf{x})=\mathbf{0}\). The branch learns an update; when no update is needed, it can output zero. This does not require every parameter to be zero. For example, a branch with a zero final projection and zero final bias can output zero even when its earlier weights are nonzero.

For our Post-LN block, keep the addition and LayerNorm separate. If \(F(\mathbf{x})=0\), the residual sum equals \(\mathbf{x}\), but the output after LayerNorm is \(\mathrm{LayerNorm}(\mathbf{x})\), generally not \(\mathbf{x}\). Section 5.6 explains why the placement matters.

B3. A single weighted sum

Recall the Value rows \(\mathbf{v}_1=(1,1,0,0)\), \(\mathbf{v}_2=(2,0,0,1)\), and \(\mathbf{v}_3=(1,0,1,0)\). A single head forms \(\sum_j a_{ij}\mathbf{v}_j\) at position \(i\). For these particular rows, returning exactly \(\mathbf{v}_1\) requires weights \((1,0,0)\): the third and fourth components force the weights on \(\mathbf{v}_3\) and \(\mathbf{v}_2\) to be zero.

In exact arithmetic, unmasked softmax with finite scores assigns strictly positive probabilities. It can approach \((1,0,0)\) as closely as desired, but cannot reach it exactly:

Scores \(a_{11}\), the weight on I \(a_{12}\) and \(a_{13}\), the weight on each of the others
\(0,\ -5,\ -5\)0.9867030.006648
\(0,\ -20,\ -20\)0.999999996\(2.06\times10^{-9}\)
\(0,\ -50,\ -50\)approximately \(1-3.86\times10^{-22}\)\(1.93\times10^{-22}\)

This is a narrow statement about this weighted sum. Masks can impose exact zeros, and finite-precision computation can round probabilities to zero or one. The argument also does not cover all combinations of learned projections and attention heads, or establish how difficult an approximate identity is to learn.

B4. One mixing step, with and without a skip connection

To compare the two operations, define a toy model whose input is \(H_0=V\), the three Value rows above. Use the fixed mixing matrix:

\[ A=\begin{pmatrix} 0.58 & 0.21 & 0.21\\ 0.14 & 0.63 & 0.23\\ 0.23 & 0.14 & 0.63 \end{pmatrix}. \]

Each row of \(A\) sums to 1, so \(AH_0\) forms weighted averages of the input rows. Compare mixing alone, \(AH_0\), with a residual sum, \(H_0+AH_0\). This toy model has no learned projections, FFNs or LayerNorms.

Here the skip path carries \(H_0\), the toy model's input. In the actual attention sublayer from Section 5.2, it carries \(X\); the projected Value matrix \(V\) is used inside the attention computation.

The initial difference between the rows for I and LLMs is \((0,1,-1,0)\). Mixing alone gives:

\[ (1.21,\ 0.58,\ 0.21,\ 0.21)-(1.14,\ 0.23,\ 0.63,\ 0.14) =(0.07,\ 0.35,\ -0.42,\ 0.07). \]

With the residual addition, the old difference is added to that update difference:

\[ (0,\ 1,\ -1,\ 0)+(0.07,\ 0.35,\ -0.42,\ 0.07) =(0.07,\ 1.35,\ -1.42,\ 0.07). \]
ONE STEP OF THE TOY MODEL · NO LAYERNORM H0 = V toy-model inputI1.001.000.000.00love2.000.000.001.00LLMs1.000.001.000.00I minus LLMs(0.00, 1.00, -1.00, 0.00) A H0 mixing onlyI1.210.580.210.21love1.630.140.230.63LLMs1.140.230.630.14I minus LLMs(0.07, 0.35, -0.42, 0.07) H0 + A H0 unscaled residual sumI2.211.580.210.21love3.630.140.231.63LLMs2.140.231.630.14I minus LLMs(0.07, 1.35, -1.42, 0.07)
Figure 17. One unscaled mixing step, with and without a skip connection. The residual sum adds the old row difference to the difference in the updates. The next example divides each residual sum by 2 when comparing repeated mixing.

The skip path contributes the old difference directly to the sum. In a general learned network, the update difference can reinforce or cancel it, so residual addition does not guarantee that distinct inputs remain distinct.

B5. Repeating the mixing operation

To see what repeated mixing can do, keep the same matrix \(A\) fixed and apply it several times. With mixing alone, the update is \(H_{l+1}=AH_l\), where \(H_l\) contains the rows after \(l\) steps:

After I love LLMs
0 steps\((1,\ 1,\ 0,\ 0)\)\((2,\ 0,\ 0,\ 1)\) \((1,\ 0,\ 1,\ 0)\)
1 step\((1.21,\ 0.58,\ 0.21,\ 0.21)\)\((1.63,\ 0.14,\ 0.23,\ 0.63)\) \((1.14,\ 0.23,\ 0.63,\ 0.14)\)
3 steps\((1.31,\ 0.35,\ 0.34,\ 0.31)\)\((1.38,\ 0.27,\ 0.35,\ 0.38)\) \((1.27,\ 0.31,\ 0.42,\ 0.27)\)
6 steps\((1.32,\ 0.31,\ 0.37,\ 0.32)\)\((1.32,\ 0.31,\ 0.37,\ 0.32)\) \((1.31,\ 0.31,\ 0.38,\ 0.31)\)

The rows become closer, but are still different after six steps. Some entries look equal only because the table rounds to two decimal places. Six is a convenient comparison with the base model's depth, not a general collapse threshold.

For the right panel of Figure 18, add a skip connection and divide the sum by 2 at each step to keep the scales comparable:

\[ H_{l+1}=\frac{H_l+AH_l}{2}. \]

This division is part of the plotted comparison; it is not LayerNorm or the unscaled residual addition used in the main tutorial.

THE FIRST NUMBER OF EACH WORD'S ROW, LAYER BY LAYER H next = A H rows become more alike 0 2 4 6 1.0 1.5 2.0 I love LLMs mixing steps H next = (H + A H) / 2 differences shrink more slowly 0 2 4 6 1.0 1.5 2.0 I love LLMs mixing steps Both panels start at H0 = V and reuse the same fixed matrix A. Right: divide by 2 at every step to compare scales. This is not LayerNorm.
Figure 18. The first component of each row under two fixed mixing rules. The scaled residual rule preserves larger differences over these six steps. Both rules approach equal rows as the number of steps grows; the right-hand rule mixes them more slowly in this example.

Because this fixed \(A\) has strictly positive entries and rows summing to 1, repeated mixing approaches a state with identical rows. The scaled residual rule does too, but the differences shrink more slowly in this example. It does not demonstrate that skip connections prevent convergence to equal rows.

Further reading: Dong, Cordonnier and Loukas (2021) analyse how rows can become alike in pure attention networks and how skip connections and MLPs affect this behaviour. Their analysis concerns attention probabilities that depend on the input; our example keeps them fixed.

Key takeaway

Appendix CWhy learning a residual may be easier

Appendix B showed that a residual sum returns its input unchanged when the branch outputs zero. Why might learning an update help training? This optional appendix explains the hypothesis in He and colleagues' residual-network paper and the evidence they give for it.

Rewrite the learning target

Let \(H(x)\) denote a desired mapping from an input to an output of the same shape. Ordinary layers try to learn \(H(x)\) directly. A residual branch instead tries to learn the update:

\[ F(x)=H(x)-x. \]

If the branch can represent this update, adding \(x\) gives the desired output: \(x+F(x)=H(x)\). This is the mathematical identity behind the rewrite.

The optimisation hypothesis is that, when a useful mapping is close to the identity, learning its small changes may be easier than learning the whole mapping directly. Appendix B illustrated the special case where the desired mapping is the identity.

A small matrix example

Suppose we want to turn \((0,0,1,1)\) into \((0.1,0,1,1)\). One possible matrix for the direct form \(\mathbf{x}\mathbf{W}\) is:

\[ \mathbf{W}= \begin{pmatrix} 1 & 0 & 0 & 0\\ 0 & 1 & 0 & 0\\ 0.1 & 0 & 1 & 0\\ 0 & 0 & 0 & 1 \end{pmatrix}. \]

For the residual form, choose \(\mathbf{W}'=\mathbf{W}-\mathbf{I}\):

\[ \mathbf{W}'= \begin{pmatrix} 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0\\ 0.1 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 \end{pmatrix}. \]

The branch now produces just the update:

\[ \mathbf{x}\mathbf{W}'=(0.1,0,0,0),\qquad \mathbf{x}+\mathbf{x}\mathbf{W}'=(0.1,0,1,1). \]

Because \(\mathbf{W}=\mathbf{I}+\mathbf{W}'\), these two forms compute the same function for every input, not only the displayed row. The example makes the change in learning target visible. For this single linear layer, however, subtracting \(\mathbf{I}\) is only a translation of the parameters; it does not by itself show that optimisation is easier.

What the experiments support

In the paper's CIFAR-10 experiments, a 56-layer plain network had higher training error than a 20-layer one. This is an optimisation problem: overfitting concerns poor generalisation despite fitting the training data. The authors reported healthy gradient norms in the tested plain networks, so vanishing gradients alone did not explain the result. Residual networks trained more successfully than comparable plain networks in the tested settings.

The paper also examined layer responses in CIFAR-10 models. Its Figure 7 reports their standard deviations, measured after batch normalisation and before the following nonlinearity. These responses were generally smaller in residual networks than in their plain counterparts; deeper residual networks also tended to have smaller responses.

The authors interpret these observations as support for learning updates around an identity mapping. They do not prove that every useful mapping is close to identity, or fully explain why the residual form is easier to optimise.

This argument concerns the residual sum. For the effect of the following LayerNorm in our Post-LN block, see Appendix B, B2 and Section 5.6.

Appendix DWhat the addition does to the gradient

A residual addition gives the loss gradient a direct contribution through the skip path. The branch contributes another term, and the two are added. This can help gradient propagation, but it does not guarantee that the total gradient stays large. This optional appendix shows why.

The loss measures the model's error. Backpropagation uses the chain rule to calculate how the loss changes with each intermediate value and parameter. Here we follow the gradient with respect to a unit's input.

One residual unit

Consider \(y=x+F(x)\), where \(x\) and \(y\) have the same number of components. We call this one residual unit: one branch and one addition. An encoder block contains two such additions, plus its normalisation operations.

For a vector-valued function, the derivatives form a matrix called the Jacobian. We use output components for its rows and input components for its columns:

\[ (J_F)_{ij}=\frac{\partial F_i}{\partial x_j}. \]

For the row-vector calculation \(F(\mathbf{x})=\mathbf{x}\mathbf{W}\), with

\[ \mathbf{W}=\begin{pmatrix}0.2 & 0.1\\0 & 0.3\end{pmatrix}, \]

the outputs are \(F_1=0.2x_1\) and \(F_2=0.1x_1+0.3x_2\). With our Jacobian convention, this gives:

\[ J_F=\mathbf{W}^{\mathsf T} =\begin{pmatrix}0.2 & 0\\0.1 & 0.3\end{pmatrix}. \]

The skip path \(x\) has derivative \(I\), so the residual unit has Jacobian \(I+J_F\). Writing loss gradients as column vectors, the chain rule gives:

\[ \nabla_x L=(I+J_F)^{\mathsf T}\nabla_y L =\nabla_y L+J_F^{\mathsf T}\nabla_y L. \]

The first term passes the incoming gradient through the skip path unchanged. The second comes through the branch. Backpropagation adds both contributions.

Two units: four contributions

Now take \(x_1=x_0+F_1(x_0)\), followed by \(x_2=x_1+F_2(x_1)\). Let \(J_1\) and \(J_2\) be the branch Jacobians evaluated at their respective inputs. The Jacobian of the full forward mapping is:

\[ \frac{\partial x_2}{\partial x_0}=(I+J_2)(I+J_1). \]

For backpropagation, transpose this product. If \(g_2=\nabla_{x_2}L\) and \(g_0=\nabla_{x_0}L\), then:

\[ \begin{aligned} g_0 &=(I+J_1^{\mathsf T})(I+J_2^{\mathsf T})g_2\\ &=g_2+J_1^{\mathsf T}g_2+J_2^{\mathsf T}g_2 +J_1^{\mathsf T}J_2^{\mathsf T}g_2. \end{aligned} \]

These four terms correspond to the routes in Figure 19: through neither branch, through the first only, through the second only, or through both. All four contribute to the same gradient.

FOUR CONTRIBUTIONS THROUGH TWO RESIDUAL UNITS Each highlighted route contributes to the input gradient; all four contributions are added. through neither I J₂ᵀ J₁ᵀ first branch only J₁ᵀ J₂ᵀ J₁ᵀ second branch only J₂ᵀ J₂ᵀ J₁ᵀ both branches J₁ᵀ J₂ᵀ J₂ᵀ J₁ᵀ Each term multiplies the incoming gradient. Contributions can reinforce or cancel one another.
Figure 19. Four terms in the backpropagation expansion for two residual units. The first uses only identity skip paths. The other terms involve branch Jacobians. Their sum determines the input gradient; the identity term alone does not set its magnitude.

Why an identity term is not a guarantee

The branch contribution can oppose the skip contribution. For example, if \(F(x)=-x\), then \(J_F=-I\), so:

\[ y=x+F(x)=0,\qquad \nabla_x L=(I-I)^{\mathsf T}\nabla_y L=0. \]

The identity term is present, but the branch term cancels it. More generally, the sum can shrink or amplify gradients. The useful structural feature is the direct contribution; there is no universal lower bound on the total gradient's magnitude.

Connecting this to Pre-LN and Post-LN

In Pre-LN, a unit has the form \(x+F(\mathrm{LN}(x))\). Its skip path bypasses both LayerNorm and the sublayer, so the derivative still contains an identity term. This applies within the stack; a final LayerNorm or output layer still affects the gradient entering it.

In Post-LN, \(y=\mathrm{LN}(u)\) with \(u=x+F(x)\). If \(J_{\mathrm{LN}}\) is the LayerNorm Jacobian at \(u\), then:

\[ \nabla_x L=(I+J_F)^{\mathsf T}J_{\mathrm{LN}}^{\mathsf T}\nabla_y L. \]

Gradients still propagate, but even the skip contribution passes through LayerNorm's derivative. This is the distinction illustrated in Section 5.6.

He and colleagues' follow-up paper, Identity Mappings in Deep Residual Networks studies direct signal propagation through identity paths. It helps explain why the operations on those paths matter, while the training behaviour of a complete model depends on more than the identity term alone.

Appendix EWhat stacking changes in a simplified attention-only calculation

Consecutive linear layers combine into one, as Section 5.1 explained. Attention is different: its probabilities depend nonlinearly on the input. This optional appendix shows how we can regroup the matrix products in an attention stack, and why that does not make the stack equivalent to one layer.

The simplified setup

We keep multi-head self-attention, including its Q, K, V and output projections and softmax. We omit the FFN, residual connections and LayerNorm. All projection biases are zero and dropout is disabled. Softmax still makes this model nonlinear; the omitted FFN would provide an additional nonlinear transformation at each token position.

One layer: mixing rows and mixing components

Start with a single head. Let \(X\) contain the input token rows, \(A(X)\) be the attention probability matrix computed from Q and K, and \(M=W^V W^O\). Then:

\[ Z=A(X)(XW^V)W^O=A(X)XM. \]

Left multiplication by \(A(X)\) combines rows, mixing information across token positions. Right multiplication by \(M\) combines components within each row, using the same learned matrix at every position.

The averaging property applies specifically to the left multiplication. Each component of a row of \(A(X)X\) lies between the smallest and largest values of that component in \(X\). Similarly, \(A(X)V\) averages Value rows. A subsequent learned projection can move the results outside those ranges.

For multiple heads, split the output projection into row blocks \(W_i^O\), one for each head's part of the concatenated input. Define \(M_i=W_i^V W_i^O\). Concatenation followed by the output projection is then equivalent to summing the head contributions:

\[ Z=\sum_{i=1}^{h}A_i(X)XM_i. \]

This sum of projected contributions need not itself be a weighted average of the original input rows.

Two layers: regrouping the products

For clarity, use one head per layer. The second layer receives \(Z\) and computes its own attention matrix \(A'(Z)\). Associativity gives:

\[ \begin{aligned} Z' &=A'(Z)\bigl(A(X)XM\bigr)M'\\ &=\bigl(A'(Z)A(X)\bigr)X(MM'). \end{aligned} \]

Only the grouping of the multiplications has changed. The dependence \(A'(Z)\) remains: the second attention matrix is computed from the first layer's output.

The combined matrix \(B=A'(Z)A(X)\) is a valid averaging matrix. Its entries are nonnegative, and each row sums to 1:

\[ \sum_j B_{ij} =\sum_k A'_{ik}\underbrace{\sum_j A_{kj}}_{=1} =\sum_k A'_{ik}=1. \]

These properties alone do not show that a single attention layer with specified Q/K dimensions can generate \(B\) for every input. Regrouping the product therefore does not remove the need to compute the two layers' attention probabilities.

With several heads, the expansion contains one term for each pair of heads:

\[ Z'=\sum_i\sum_j \bigl(A'_i(Z)A_j(X)\bigr)X(M_jM'_i). \]

Each term describes a path through a head in the first layer and a head in the second. The matrices on these paths still depend on the intermediate representations.

A numerical check

Use Part 1's \(X\), attention matrix \(A\), and Value projection. For this single-head calculation, set \(W^O=I\), so \(M=W^V\). Choose the following second mixing matrix and projection by hand:

\[ A'=\begin{pmatrix} 0.30 & 0.50 & 0.20\\ 0.10 & 0.10 & 0.80\\ 0.45 & 0.45 & 0.10 \end{pmatrix}, \qquad M'=\begin{pmatrix} 1 & 0 & 0 & 2\\ 0 & 1 & 0 & 0\\ 0 & 0 & 1 & 0\\ 1 & 3 & 0 & 1 \end{pmatrix}. \]

We are checking the matrix identity with fixed numbers here, not deriving \(A'\) from a second set of Q/K projections. Calculating layer by layer, \(A'(AXM)M'\), gives:

\[ \begin{pmatrix} 1.812 & 1.508 & 0.304 & 3.218\\ 1.392 & 0.844 & 0.548 & 2.588\\ 1.784 & 1.523 & 0.261 & 3.176 \end{pmatrix}. \]

Regrouping as \((A'A)X(MM')\) gives the same result, with:

\[ A'A=\begin{pmatrix} 0.290 & 0.406 & 0.304\\ 0.256 & 0.196 & 0.548\\ 0.347 & 0.392 & 0.261 \end{pmatrix}. \]

All three rows sum to 1. Figure 20 shows the regrouped calculation.

THE SAME TWO-LAYER CALCULATION, REGROUPED A′A · one row-mix 0.290 0.406 0.304 I 0.256 0.196 0.548 love 0.347 0.392 0.261 LLMs 3 × 3, rows still add to 1 × X 0 0 1 1 0 1 0 1 1 0 0 1 3 × 4 × MM′ · one slot-mix 0 0 1 0 2 3 0 3 0 1 0 0 1 0 0 2 4 × 4 1.812 1.508 0.304 3.218 I 1.392 0.844 0.548 2.588 love 1.784 1.523 0.261 3.176 LLMs 3 × 4 · the same answer both ways computing the two layers one after the other gives these same twelve numbers
Figure 20. Regrouping the numerical products gives the same twelve output values. The combined mixing matrix has nonnegative entries and rows summing to 1. This does not establish an equivalent single attention layer.

A special case: one token

If the entire sequence contains only one token, every head has just one attention probability, equal to 1. In our bias-free setup, a multi-head layer therefore reduces to:

\[ z=\sum_i xM_i=x\left(\sum_i M_i\right). \]

This is a linear map. Stacking such layers still gives a linear map, so the midpoint rule from Appendix A applies: the output for the average of two input rows is the average of their outputs. Here “one token” means exactly one row, with no additional special tokens.

With multiple tokens, input-dependent attention probabilities can produce nonlinear behaviour. With only one token, that source of nonlinearity disappears. The FFN's activation works within each row and provides nonlinearity even in this single-token case.

Key takeaway

Appendix FThe toy feed-forward weights

These are the two matrices used in Section 5.4. Their entries are \(-1\), \(0\) or \(1\), chosen for hand calculation rather than learned through training. Use them in:

\[ \mathrm{FFN}(\mathbf{x}) =\mathrm{ReLU}(\mathbf{x}\mathbf{W}_1+\mathbf{b}_1)\mathbf{W}_2+\mathbf{b}_2, \qquad \mathbf{b}_1=\mathbf{0}_{16},\quad \mathbf{b}_2=\mathbf{0}_4. \]

To reproduce the tutorial's numbers, use the displayed two-decimal input values directly, rather than recomputing them from an unrounded LayerNorm output.

\(\mathbf{W}_1\) has shape 4 × 16. Each column contains the input weights for one hidden unit. Taking the dot product of the four-value input row with that column gives one intermediate value. Apply ReLU to each of the sixteen results.

\[ \mathbf{W}_1 = \begin{pmatrix} -1 & -1 & -1 & 0 & -1 & 1 & 1 & 0 & 0 & 1 & -1 & 1 & -1 & 1 & 1 & -1\\ 0 & 1 & 0 & 1 & 1 & 0 & 1 & 0 & 1 & 0 & -1 & -1 & 0 & 0 & 0 & 0\\ 0 & 1 & -1 & 1 & -1 & -1 & -1 & -1 & -1 & 0 & -1 & -1 & 1 & 1 & 0 & 1\\ 1 & 1 & -1 & 0 & 0 & 1 & 1 & 0 & 1 & 0 & 0 & 0 & -1 & 0 & 1 & 1 \end{pmatrix} \]

\(\mathbf{W}_2\) has shape 16 × 4. Below we display its transpose, \(\mathbf{W}_2^\top\), with shape 4 × 16, so it fits the page. Each displayed row corresponds to one final output component: take its dot product with the sixteen values after ReLU to obtain that output.

\[ \mathbf{W}_2^{\top} = \begin{pmatrix} 0 & 0 & 1 & 0 & 1 & 1 & -1 & 0 & 1 & 1 & 1 & 0 & 0 & 1 & 1 & -1\\ 1 & 0 & 0 & 0 & 1 & -1 & 1 & 0 & 1 & 1 & -1 & 1 & 1 & -1 & -1 & 1\\ 1 & 0 & 1 & 1 & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 1 & -1 & -1 & 0 & -1\\ -1 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 1 & 0 & 1 & -1 & -1 & 1 & 1 & 1 \end{pmatrix} \]

Check your calculation. With both bias vectors set to zero, the input row for I gives:

\[ \mathrm{FFN}\bigl((0.58,\ -1.73,\ 0.58,\ 0.58)\bigr) =(3.47,\ -0.58,\ -0.01,\ 2.32). \]

The intermediate values are listed in Section 5.4.