What Does a Transformer Block Actually Do?

On this page

English · 中文 · Français

First Principles of LLMs & RL · Article 07 · Previous article · Next article

Writing note: The ideas and initial material are mine. ChatGPT assisted with drafting, editing, translation, numerical checks, and the original figures and animation sources.

Consider these two sentences:

Alice deposited money at the bank.

Alice sat beside the river bank.

The word bank has two meanings here. Money and river give us clues about which meaning fits. A model also needs to use the surrounding words so that the two occurrences of bank can affect later calculations differently.

In a Transformer, each token position holds a vector: a list of numbers called its representation. Think of it as a record card with a fixed number of cells. The card holds the information available at that position. As the text passes through the network, the numbers on the card change. The text itself stays the same.

A Transformer block performs one round of these changes. Attention brings information from other positions into the calculation. A feed-forward network then works with the information now available at the current position. Both produce updates that are added to the same card.

Let’s follow the bank position in the first sentence. For this explanation, treat each English word as one token; actual tokenization can split words more finely.

Bring the context to bank

Before bank, money and deposited already suggest a financial setting.

Attention lets the bank position assign a weight to each position it can read, then add up the vectors those positions provide, multiplied by their weights. Here we use causal attention: bank can read itself and the preceding positions. It cannot read a later word.

The Query at bank is used to score the Keys at those positions. These scores determine the weights. The Values supply the content being added. A larger weight gives that position’s Value a larger coefficient in the sum. That is how the calculation at bank can depend on money elsewhere in the sentence.

One attention head produces one set of position weights. Multi-head attention computes several sets, using a separate set of Query, Key, and Value projections for each head. One head could give more weight to money while another gives more to deposited. Training determines what they actually do; there is no assigned “noun head” or “verb head.”1

Next, the head outputs are placed side by side and passed through a learned linear transformation: the output projection. It combines the numbers from the heads into an update with the same number of cells as the original card. The projection decides how the head outputs contribute to each cell; it does more than set the output’s size. Below, MHA means the whole multi-head attention calculation, including this projection.

Keep the card and change its numbers

We now have the old representation and an attention output. The Transformer uses the output as an amount to add to the old representation.

Call the original vector x, the attention update a, and the result u. All three have the same length:

\[u=x+a.\]

This addition is a residual connection. To change a number from 3 to 5, the branch only needs to supply +2. To leave it alone, it supplies 0. Learning the change needed at each step is the basic residual idea.2

The record card keeps its size. We change numbers in existing cells. Negative updates can reduce or cancel a value, too: adding −1 to 1 gives 0. The input has a direct path into the sum, but the sum does not necessarily let us recover every previous value.

To make the next steps visible, we will use a hand-built card with three cells. We choose the cell meanings and the 0/1 values, supply the final attention output directly, and leave out normalization for this example. The supplied output includes the output projection described above.

Cell Meaning in this example
1 A cue that this token is bank
2 A cue from a financial context
3 A feature for the financial sense of bank

Here 0 means the feature is absent, and 1 means it is present. Start with just the first cue:

\[x=\begin{bmatrix}1\\0\\0\end{bmatrix}.\]

Suppose attention supplies a financial-context cue, giving this update:

\[a=\begin{bmatrix}0\\1\\0\end{bmatrix}.\]

Add each update to the matching cell:

\[u=x+a =\begin{bmatrix}1\\0\\0\end{bmatrix} +\begin{bmatrix}0\\1\\0\end{bmatrix} =\begin{bmatrix}1\\1\\0\end{bmatrix}.\]

The first cell stays at 1. The second changes from 0 to 1. Now the bank cue and the financial-context cue are on the same card. The third cell is still zero.

A fixed three-cell card receives an update in its existing cells; zero leaves a value unchanged and a negative update can cancel it.

Follow each update to its matching cell. The card stays the same size; the numbers change.

Combine the cues that are now here

We want one more calculation: activate the third feature only when the first two cues are both present.

There is no need to look at another word to perform this step. The two numbers we need are already on the card. Call them u₁ and u₂, and define a response r:

\[r=\max(0,u_1+u_2-1).\]

Think of 1 as a threshold for the sum. Add the two cues, subtract that threshold, and keep only a positive remainder. If the sum reaches 1, nothing is left. If it reaches 2, the remainder is 1.

Cues Their sum After subtracting 1 Response r
Neither: 0, 0 0 −1 0
One: 1, 0 or 0, 1 1 0 0
Both: 1, 1 2 1 1

The operation that turns a negative number into zero and keeps a positive number is ReLU. With our binary cues, this calculation gives the desired “both present” response. With general real numbers, it returns the amount above the threshold, which need not be 0 or 1.

The sums 0, 1, and 2 are compared with a threshold of 1; ReLU keeps only the positive remainder.

One cue reaches the threshold. Two cues exceed it by one. The output is the excess, not a label attached to the input.

Why include a nonlinearity? The sum minus 1 already gives the right answer for one cue and for two cues, but with no cues it gives −1. ReLU clips that unwanted negative response to zero while leaving the other answers alone. No single linear transformation with a bias can satisfy all four binary cases; the short proof is in the mathematical notes. ReLU is one way to supply the needed nonlinearity.

Finally, put r into the third cell of an update vector. Call this whole calculation F, and call the result of the second addition y:

\[F(u)=\begin{bmatrix}0\\0\\r\end{bmatrix}, \qquad y=u+F(u).\]

Our card contains 1, 1, 0, so r is 1. The second update gives

\[y= \begin{bmatrix}1\\1\\0\end{bmatrix} +\begin{bmatrix}0\\0\\1\end{bmatrix} =\begin{bmatrix}1\\1\\1\end{bmatrix}.\]

This F is a tiny feed-forward network, or FFN. It makes a linear combination of the input, applies ReLU, and maps the response back into an update vector. The original Transformer’s FFN uses this structure with many hidden units, so it can compute many combinations at once.1

Stage Bank cue Financial context Financial-sense feature
Input x 1 0 0
After attention: u 1 1 0
After the FFN: y 1 1 1

Attention can take information from other positions. The FFN continues the calculation within the current position. The same FFN parameters are used at every position, but different inputs can produce different results. Computing at one position does not mean processing an isolated word: that position already holds information from its context.

In the animation, follow the same card through both additions. Copies of its first two numbers enter the FFN; the resulting update returns to the third cell. The whole updated card then goes to the next layer.

The bank card changes from 1,0,0 to 1,1,0 after attention, then to 1,1,1 after the FFN, before the full card enters the next layer.

One card, two updates. This animation follows the same constructed example as the hand calculation.3

Set the scale before computing an update

Repeated additions can change the size of the numbers arriving at later layers. That size affects the next calculation.

For example, take Query and Key projections without biases. Double all the input vectors, and the Queries and Keys both double. Their dot products become four times as large. Softmax can then assign more concentrated attention weights, even though all we changed was the input’s overall scale.

Normalization adjusts the scale of a branch’s input. Think of adjusting the volume before sending a signal into another device. Here we use RMSNorm: divide a position’s vector by a measure of its overall size, its root mean square, then apply learned gains to the individual coordinates.4

If the whole vector doubles, its root mean square doubles too, so the division cancels that overall change. With the small term used to prevent division by zero, this cancellation is approximate when that term is negligible. Each position has its own scale calculation; we do not average across words.

The common division preserves coordinate ratios. The learned gains can then change those ratios. Normalization also changes the vector’s magnitude, so “adjusting the volume” should not be read as a promise to preserve every piece of information.

Where should this adjustment happen? In the Pre-Norm arrangement used here, attention and the FFN each receive a normalized version of their input. Picture copying the numbers on the card and adjusting their scale to compute an update. The update is still added to the original card.

One block, two additions

Put all the position vectors into a table X, with one row per token. If there are n positions and d numbers per vector, X has n rows and d columns. U is the table after attention, and Y is the block’s output.

Let N₁ and N₂ apply RMSNorm to each row, with separate learned parameters. MHA includes causal multi-head attention and its output projection. FFN acts on each row separately. Omitting the batch dimension and dropout, the block is

\[U=X+\operatorname{MHA}\bigl(N_1(X)\bigr).\]

First, normalize the branch input, compute the attention update, and add it to X.

\[Y=U+\operatorname{FFN}\bigl(N_2(U)\bigr).\]

Then normalize the updated branch input, compute the FFN update, and add it to U, which already includes the attention update. X, U, and Y all have the same shape. The block changes the numbers while keeping the number of positions and the width of each card fixed.

“Pre-Norm” names the placement of normalization before each sublayer’s calculation. The original Transformer placed LayerNorm after the addition. Our block uses a different ordering, with RMSNorm at the branch entrances.5 The earlier binary trace isolates the updates; these equations specify what to compute once normalization is included.

All positions go through these operations. During one attention calculation, they read representations from the input to that layer. The next layer receives the updated representations.

For bank, that next layer can therefore start with information influenced by money. It uses its own parameters to form new Queries, Keys, and Values from the updated input. Later calculations can build on what earlier layers have already computed.

A trained model learns its matrices and biases; its coordinates need not line up with our three labels or implement this particular rule about bank. Nor does one block have to settle the word’s meaning. What the structure provides is a way to update each position using the context, then continue from that updated state.

After the final layer, the model still has a vector. The next article follows that vector to a distribution over the vocabulary and the choice of the next token.

Mathematical notes

The small FFN can be written with two matrices and two biases. Keep u as a three-dimensional column vector. W₁ maps three numbers to one; W₂ maps that one number back to three:

\[W_1=\begin{bmatrix}1&1&0\end{bmatrix}, \quad b_1=-1, \qquad W_2=\begin{bmatrix}0\\0\\1\end{bmatrix}, \quad b_2=\begin{bmatrix}0\\0\\0\end{bmatrix}.\]

Then

\[F(u)=W_2\operatorname{ReLU}(W_1u+b_1)+b_2.\]

W₁ and b₁ form the sum minus 1. ReLU clips the negative result. W₂ sends the response to the third coordinate.

For the impossibility claim, consider any affine rule on the first two cells:

\[f(u_1,u_2)=c_1u_1+c_2u_2+b.\]

Requiring f(0, 0) = 0 forces b = 0. Requiring f(1, 0) = 0 then forces c₁ = 0; requiring f(0, 1) = 0 forces c₂ = 0. These choices give f(1, 1) = 0, but we need 1. The contradiction depends on all four cases. Chaining linear transformations with biases cannot fix it, because their composition is still affine.

For completeness, RMSNorm at one position has the following form. Let z have d coordinates, let γₖ be the learned gain for coordinate k, and let ε be a small positive constant:

\[\operatorname{RMSNorm}(z)_k =\gamma_k\frac{z_k} {\sqrt{\frac{1}{d}\sum_{j=1}^{d}z_j^2+\epsilon}}.\]

The sum runs over the d coordinates of that one vector. RMSNorm controls the scale used inside each branch; it does not keep the magnitude of the whole residual stream fixed after each addition.4

  1. Vaswani et al., Attention Is All You Need, sections 3.1–3.3, for multi-head attention, output projection, the position-wise FFN, and the original normalization ordering. The binary bank example is constructed here, rather than an experimental result from the paper. ↩ ↩2

  2. He et al., Deep Residual Learning for Image Recognition, for the motivation of learning a residual relative to the input. The zero-update and cancellation properties here follow directly from addition. ↩

  3. The figures borrow teaching ideas from 3Blue1Brown’s MLP lesson (following a feature through a nonlinearity and back into the representation), Transformer Explainer (opening a block to follow a local computation), and Brendan Bycroft’s LLM Visualization (tracking a representation across layers). The examples, drawings, and animation code here are original. ↩

  4. Zhang and Sennrich, Root Mean Square Layer Normalization; the numerical stability term follows PyTorch’s RMSNorm definition. ↩ ↩2

  5. Xiong et al., On Layer Normalization in the Transformer Architecture, for the distinction between normalization placements. The concrete block here uses RMSNorm before each branch. ↩