Highlights

Contents

Part XII
12

The Decoder Block and the Whole Model

Attention exchanges information but cannot do every transformation alone. The MLP changes each position’s features. Norms and residual paths connect these operations into a stack that produces next-token scores.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#Section 63Attention Alone Is Not a Model

Attention exchanges context through learned projections and weighted values. The MLP provides a separate nonlinear transformation of each contextual position. Together they serve different parts of the prediction task.

That job belongs to the MLP, short for multi-layer perceptron, a small neural network applied to each token on its own. (You will also see it called the feed-forward network, or FFN.) A decoder block wraps the two together: attention, where tokens share information with each other, then the MLP, where each token processes what it gathered. Two helpers hold the block together: normalization, which keeps the numbers at a steady size, and residual connections, which let each part add to the token’s vector rather than replace it.

Stack the same block many times and you have a language model. GPT-2 small stacks 12. Llama 3 8B stacks 32. Finch-19 stacks 8. Each block has its own weights; only the design repeats.

#Section 64One Trip Through a Block

Follow one token’s vector through a Finch-19 block. It enters as xx, a 512-number vector (or, for the whole sentence, a T×512T \times 512 grid). It travels straight up a main line, the residual stream, and takes two side trips.

On the first side trip, a copy of xx is normalized and fed to multi-head attention. Attention's output is added back onto the main line. Call the result hh. On the second side trip, a copy of hh is normalized and fed to the MLP, and the MLP's output is added back onto the main line. That is the block's output.

h=x+Attn(LN(x))out=h+MLP(LN(h))h = x + \text{Attn}\big(\text{LN}(x)\big) \qquad \text{out} = h + \text{MLP}\big(\text{LN}(h)\big)

Read the formula left to right: the new vector is the old vector plus a correction computed from a normalized copy of it. The formula preserves the input shape, T×512T \times 512, so blocks can be stacked as many times as you like. And nothing is ever overwritten: each part only adds.

ONE PRE-NORM DECODER BLOCK, BOTTOM TO TOP (FINCH-19 SHAPES)x (T × 512)out (T × 512)LayerNormmulti-head attention+tokens talk:mixes across positionsLayerNormMLP 512 → 2,048 → 512+each token thinks:works within a positionhresidualstreamh = x + Attn(LN(x)) out = h + MLP(LN(h))
Figure 1.87One pre-norm decoder block. The residual stream runs straight up; attention and the MLP sit on side trips that read a normalized copy and add their result back at the plus signs.
python
class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.ln1, self.attn = nn.LayerNorm(512), MultiHeadAttention(512, 8)
        self.ln2, self.mlp = nn.LayerNorm(512), MLP(512, 2048)

    def forward(self, x):                 # x: (B, T, 512)
        x = x + self.attn(self.ln1(x))    # tokens share information
        x = x + self.mlp(self.ln2(x))     # each token processes it
        return x                          # (B, T, 512)

#Section 65The Residual Stream

The residual connection, x+f(x)x + f(x), looks like a small detail. It is one of the most important ideas in deep learning, and it came from image recognition: Kaiming He and colleagues introduced residual networks, ResNets, in 2015 and used them to train networks over a hundred layers deep for the first time.

The best way to think of the residual stream is as a shared notebook that runs through the whole model. The embedding writes the first page. Each sub-layer, every attention and every MLP, reads the current notebook, works something out, and writes a short note at the bottom. Nothing gets erased. By the top of the model, the notebook contains the original token plus every layer's contributions.

THE RESIDUAL STREAM: EVERY SUB-LAYER READS IT AND ADDS A SMALL NOTE (ILLUSTRATIVE)embedding+ attn 1change size 0.36+ MLP 1change size 0.32+ attn 2change size 0.26+ MLP 2change size 0.26nothing is erased, only added to
Figure 1.88The residual stream as a shared notebook. Each row is the same token's vector after another sub-layer; outlined cells are the ones that sub-layer changed. Most changes are small additions. (Illustrative.)

Why does this help so much? Two reasons. First, learning becomes easier: a layer that has nothing useful to add can output nearly zero and the stream passes through unchanged, so adding layers never has to make things worse. Second, and more important, it gives training a direct path. Part XIII explains that training sends a correction signal backwards through the model. Every time it passes through a plus sign, part of the signal goes straight down the main line, untouched by the sub-layer. So even the first layer of a deep model receives a clear signal. Without residuals, that signal is multiplied through every layer on the way down and tends to shrink to nothing or blow up.

#Section 66Where the Norm Goes

Pre-norm versus post-norm

The original 2017 Transformer put normalization on the main line, after each addition: x←LN(x+f(x))x \leftarrow \text{LN}(x + f(x)). That is post-norm. Every layer's output gets squashed before moving on, so the main line is interrupted at every step, and deep post-norm stacks were hard to train without a carefully tuned warm-up of the learning rate.

GPT-2 moved the normalization onto the side trips, before attention and before the MLP: x←x+f(LN(x))x \leftarrow x + f(\text{LN}(x)). That is pre-norm, and almost every model since uses it. The main line stays a clean path from bottom to top with nothing in the way, which is exactly what the residual argument above wants. Deep pre-norm models train much more reliably.

WHERE THE NORM GOES: POST-NORM (2017) VERSUS PRE-NORM (GPT-2 ONWARD)post-norm: LN on the main lineattention+LNMLP+LNpre-norm: LN on the side tripsLNattention+LNMLP+clean highwaytop to bottom
Figure 1.89Post-norm places LayerNorm on the residual stream after each addition; pre-norm places it on the side trips, leaving the stream an uninterrupted highway.

One consequence of pre-norm: the main line itself is never normalized inside the blocks, and it tends to grow as layers keep adding to it. So pre-norm models need one final normalization after the last block, before the output head. Forgetting it is a classic bug.

What LayerNorm does

Normalization keeps the numbers in each token's vector at a steady size, so they neither blow up nor shrink away as they pass through dozens of layers. LayerNorm, introduced by Jimmy Lei Ba and colleagues in 2016, does two things to each token's vector separately. It subtracts the vector's average, so the numbers centre on zero. Then it divides by their standard deviation, so their spread is one. Finally it multiplies each entry by a learned gain γ\gamma and adds a learned shift β\beta, one of each per channel, so the model can undo the normalization wherever that helps.

LN(x)=γ⊙x−μσ2+ε+β\text{LN}(x) = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \varepsilon}} + \beta

The formula subtracts the mean and divides by the standard deviation, with epsilon guarding the denominator. Learned gain and shift then adjust each channel.

LAYERNORM ON x = [2, −1, 4, 3] (γ = 1, β = 0)x2-143mean = 2x − mean0-321variance = (0 + 9 + 4 + 1) / 4 = 3.5÷ √3.5 = 1.8710-1.6041.0690.535mean 0, spread 1then multiply by a learned γ and add a learned β, per channel
Figure 1.90LayerNorm by hand. Subtract the mean, divide by the standard deviation, then apply the learned gain and shift.

Finch-19 has two LayerNorms per block plus the final one, each with 512 gains and 512 shifts. Unit II replaces LayerNorm with RMSNorm, which skips the mean subtraction.

#Section 67The MLP: Widen, Bend, Narrow

The MLP is three steps applied to each token separately. Widen the vector with a matrix, usually to four times its size: for Finch-19, 512 numbers become 2,048. Pass every one of those numbers through a bendy function called an activation. Shrink back to 512 with a second matrix.

MLP(x)=W2 GELU(W1x+b1)+b2\text{MLP}(x) = W_2\, \text{GELU}(W_1 x + b_1) + b_2

Why the bend? Without it, the two matrices would multiply together into one plain matrix, and a stack of plain matrices can only represent straight-line relationships, no matter how many you stack. The activation is what lets the network represent curved, complicated ones. GPT-2 and Finch-19 use GELU, the Gaussian error linear unit, which behaves like "keep positive inputs, suppress negative ones" but smoothly: GELU(1)=0.841\text{GELU}(1) = 0.841, GELU(0)=0\text{GELU}(0) = 0, GELU(−1)=−0.159\text{GELU}(-1) = -0.159, and very negative inputs give almost exactly 0. An older, simpler choice is ReLU, which outputs zero for negatives and the input itself for positives, with a sharp corner at zero.

THE MLP: WIDEN, BEND, NARROW (FINCH-19: 512 → 2,048 → 512)512W1+ b12,048GELUW2+ b2512xGELU (orange), ReLU (grey)GELU(−1) = −0.159without the bend, two matricescollapse into one
Figure 1.91The MLP widens each token's vector four times, bends every number with GELU, and narrows it back. Right: GELU next to ReLU; GELU is smooth and dips slightly below zero.

MLPs hold substantial learned feature transformations. Attention supplies context; the MLP changes how that context is represented.

Two halves, two axes

The clearest way to see what each half of the block does is to picture the input as a grid with one column per token and one row per feature. Attention moves information across columns: the value from cat's column flows into it's column. The MLP works within each column: it transforms it's features using only it's own features, with no idea what the other tokens contain. A block alternates the two. Share, then think. Share, then think.

ATTENTION MIXES ACROSS TOKENS; THE MLP WORKS WITHIN EACH TOKENattention: arrows cross columnsThecatsatbec.itwasMLP: arrows stay in their columnThecatsatbec.itwascolumns are tokens, rows are features. A block alternates: share, then think.
Figure 1.92Attention mixes across tokens, the MLP mixes within each token. Every block does one of each.

#Section 68The Whole Model, to the Next Token

Stack eight blocks and add the two ends and you have Finch-19. At the bottom: the tokenizer, the embedding lookup and the position table (Parts I to III). In the middle: eight decoder blocks. At the top: a final LayerNorm, then the LM head, which turns each position's final 512-number vector into 32,000 scores, one per token in the vocabulary.

Those raw scores are called logits. A logit can be any number; a higher logit means "more likely next". The LM head is a 512×32,000512 \times 32{,}000 matrix, and in Finch-19 it is tied to the embedding table (Section 14), so the logit for token jj is the dot product of the final vector with row jj of EE: how well the model's final thought matches each token's embedding. Softmax turns the 32,000 logits into the probabilities from Part I.

During training, every position's logits are used, one prediction per position (Part VIII). During generation, only the last position's logits matter, because that is the prediction for the token after the text.

Temperature

Before softmax, the logits are usually divided by a number called the temperature, τ\tau:

pj=ezj/τ∑kezk/τp_j = \frac{e^{z_j / \tau}}{\sum_k e^{z_k / \tau}}

Lower temperature concentrates probability on leading choices; higher temperature spreads it more broadly. This changes sampling, not the learned weights. The figure shows the same logits under different settings.

LOGITS [2.0, 1.0, 0.1, −1.0] AT THREE TEMPERATUREST = 0.50.862tea0.117coffee0.019water0.002rocksT = 10.638tea0.235coffee0.095water0.032rocksT = 20.451tea0.274coffee0.174water0.101rockssharper: safe, repetitiveflatter: varied, riskier
Figure 1.93The same logits at three temperatures. Low temperature sharpens the distribution toward the top token; high temperature flattens it.

Where learned weights live

WHERE FINCH-19’S 42,128,384 PARAMETERS LIVE (TIED EMBEDDINGS)token embeddings (= LM head)16,384,00038.9%position table524,2881.2%attention, 8 layers8,404,99220.0%MLP, 8 layers16,797,69639.9%LayerNorm gains and biases17,4080.0%total42,128,384the MLP istwice attention
Figure 1.94Where Finch-19's parameters live. The embedding table and the MLPs dominate; attention is a fifth; the norms are a rounding error.

The embedding table can dominate a small model; wider, deeper models spend more of their parameters in decoder blocks. The architecture, not the model name, determines that balance.

Sharp edges of the block

Forgetting the final norm. With pre-norm, the stream is never normalized inside the blocks, so the final LayerNorm before the LM head is required. Leave it out and the logits come out at a wild scale.

The stream grows with depth. Every layer adds to the stream, so without care the vectors grow with depth. GPT-2 scales the initial weights of the layers that write into the stream by 1/Nres1/\sqrt{N_{\text{res}}}, where NresN_{\text{res}} is the number of residual additions (two per block), so the sum of all contributions starts at a sensible size.

Never assume the MLP is 4d4d. Finch-19 and GPT-2 use 4d4d, but Unit II's SwiGLU uses three matrices and a hidden width near 83d\tfrac{8}{3}d, rounded. Read the hidden size from the config.

Norm epsilon and precision. Normalization divides by a standard deviation. Compute it in 32-bit precision and keep ε\varepsilon at what the model was trained with, typically 10−510^{-5} or 10−610^{-6}; too small an epsilon in 16-bit arithmetic causes blow-ups.

Dropout placement. Dropout randomly zeroes parts of the network during training to reduce overfitting. GPT-2 used it after attention and after the MLP. Most large models trained on huge datasets use none at all in pretraining.