# Transformer Block Explained: Attention, FFN, Residuals and LayerNorm

> A Transformer block is multi-head attention plus a feed-forward network (FFN), each wrapped in a residual connection and LayerNorm. This page gives the equations, Pre-Norm versus Post-Norm, a parameter count (about 12d²) and runnable PyTorch code.

- URL: https://dmxsf.com/en/wiki/architecture/transformer-block/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-22
- Tags: Transformer, Attention

## After this page you will be able to

- Say what each module in a Transformer block does.
- Explain why residual connections and LayerNorm matter for deep training.
- Explain why the FFN looks simple yet holds so many parameters and so much computation.
- Write down the Pre-Norm and Post-Norm equations and say how they differ at initialization.
- Count the parameters of a block and check the count with a few lines of code.

The relationship to [Attention Basics](https://dmxsf.com/en/wiki/architecture/attention-basics/) is this: that page explains how attention works, and this one explains what role attention plays inside a whole block.

## Why look at the block level

The first thing most people remember about the Transformer is one sentence:

> It is just attention plus an FFN, stacked many times.

That is not wrong, but it is too coarse. What makes a Transformer scale stably is not only attention but also:

- whether the residual path stays clear
- where the normalization sits
- how the feed-forward layer expands the representation
- how information is progressively rewritten across many layers

Once the block level is clear, papers on GPT, BERT, LLaMA, MoE or FlashAttention become much easier to read: you can tell which building block each one changes instead of being carried along by jargon.

## What a standard Transformer block looks like

A typical block has two parts, each with a residual connection and LayerNorm:

1. The attention sublayer: every position reads information from its context.
2. The feed-forward sublayer: every position's representation is reprocessed on its own.

Let the input of block $l$ be $x_l\in\mathbb{R}^{T\times d}$ ($T$ tokens of dimension $d$). The **Pre-Norm** form used by most large models today is

$$
\begin{aligned}
h_l &= x_l + \mathrm{MHA}\big(\mathrm{LN}(x_l)\big)\\
x_{l+1} &= h_l + \mathrm{FFN}\big(\mathrm{LN}(h_l)\big)
\end{aligned}
$$

Normalize first, run the sublayer, and add its output back to the input. The original 2017 Transformer used **Post-Norm**: the sublayer output is added to the residual and then normalized, written $\mathrm{LayerNorm}(x+\mathrm{Sublayer}(x))$ in the paper. The change is only an order of operations, yet it noticeably affects the stability of deep training, so it gets its own section below.

Drawing out the whole execution path of a block makes it clear that attention is only one segment; what lets blocks stack deep is residuals and normalization working together:

*Figure: Attention routes information between positions, the FFN reprocesses each token's representation, and the residual connections and LayerNorm keep this stable when many blocks are stacked.*

## Module 1: multi-head self-attention routes information

The essential job of the attention sublayer is to let each token decide which information to read from the whole context. You can think of it this way:

- the first job of a block is not to create new knowledge
- it is to reorganize the flow of information in the context

In this layer every position produces a query, a key and a value and aggregates the other positions' values with attention weights. Multiple heads let relations in different subspaces be modeled in parallel, and $W_O$ maps the concatenated head outputs back to $d$ dimensions. So the attention sublayer has four $d\times d$ matrices: $W_Q,W_K,W_V,W_O$. It is the **only component in the block that exchanges information between positions**. The details of scoring and weighting are in [Attention Basics](https://dmxsf.com/en/wiki/architecture/attention-basics/).

## Module 2: why the FFN looks ordinary yet matters so much

Beginners often treat the FFN as an MLP bolted on after attention, which is a misunderstanding. The FFN does at least three things:

1. It applies a stronger nonlinear transformation to each token's representation.
2. It further processes the information that attention gathered.
3. It supplies a large share of the parameter capacity and is the most parameter-dense part of the block.

The standard FFN expands, applies a nonlinearity and projects back:

$$
\mathrm{FFN}(x) = W_2\,\sigma(W_1 x + b_1) + b_2,\qquad W_1\in\mathbb{R}^{d_{ff}\times d},\ W_2\in\mathbb{R}^{d\times d_{ff}}
$$

The hidden width $d_{ff}$ is usually $4d$: the original Transformer base model has $d=512$ and $d_{ff}=2048$ with ReLU, and GPT-2 keeps $4d$ but switches the activation to GELU. This is not arbitrary; it gives the model room to expand its representation. Note that the FFN applies the same weights to every position **independently**; information moves between positions only inside attention. Modern models replace it with the gated SwiGLU and shrink the hidden width to about $\tfrac{8}{3}d$, covered in [Modern LLM Architecture](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture/).

In a sense:

- attention decides where to look
- the FFN decides how to rethink what was seen

## Module 3: why residual connections are the lifeline of deep networks

Without residual connections a deep Transformer is very hard to train stably. Write one sublayer as $x_{l+1}=x_l+F_l(x_l)$ and differentiate with respect to the input:

$$
\frac{\partial x_{l+1}}{\partial x_l} = I + \frac{\partial F_l}{\partial x_l}
$$

The identity matrix $I$ is a path that **passes through no transformation at all**: whatever $F_l$ learns, gradients can still flow back to shallower layers along it almost undamaged. A residual connection lets each sublayer learn an incremental change instead of rewriting from scratch, which brings two benefits:

1. Gradients travel across layers more easily.
2. If a layer has not yet learned a useful transformation, it at least does not destroy the existing representation.

This is why the residual connection is not a small trick but a key condition for stacking Transformers deep. Residual learning was first proposed for image recognition (He et al., 2016) and the Transformer adopted it.

## Module 4: why LayerNorm sits in every layer

LayerNorm keeps the scale of each token's features steady and reduces numerical swings during training:

$$
\mathrm{LN}(x) = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta,\qquad \mu = \frac1d\sum_{i=1}^{d} x_i,\quad \sigma^2 = \frac1d\sum_{i=1}^{d}(x_i-\mu)^2
$$

The mean $\mu$ and variance $\sigma^2$ are computed over the **$d$ features of a single token**, not across samples or positions, so training and inference run exactly the same computation and the result does not depend on batch size (Ba et al., 2016). $\gamma$ and $\beta$ are learnable scale and shift, $d$ parameters each. Its importance can be seen from two angles:

- Optimization: it reduces exploding or vanishing gradients and distribution drift.
- Engineering: it gives deeper networks and larger learning rates a better chance of working stably.

Modern large models often swap it for the simpler RMSNorm (no mean subtraction and no $\beta$; Zhang and Sennrich report comparable performance and 7% to 64% less running time across models), and they put a lot of care into where the normalization sits, which is the next section.

## Hands-on: a block in PyTorch

Below is a decoder block at GPT-2 small size ($d=768$, 12 heads, $d_{ff}=3072$) with a causal mask; the `pre_norm` flag switches between the two orders (the next section compares them). The code runs two checks: the output shape is unchanged, and if every token from position 6 on is replaced, the outputs at positions 0 to 5 do not change, which shows that each position depends only on itself and what came before.

```python
import torch
import torch.nn as nn
import torch.nn.functional as F

class Block(nn.Module):
    """Decoder block. pre_norm=True: x + Attn(LN(x)); False: LN(x + Attn(x))."""

    def __init__(self, d_model=768, n_heads=12, d_ff=3072, pre_norm=True):
        super().__init__()
        self.n_heads, self.pre_norm = n_heads, pre_norm
        self.ln1, self.ln2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
        self.qkv = nn.Linear(d_model, 3 * d_model)  # W_Q, W_K, W_V in one matrix
        self.proj = nn.Linear(d_model, d_model)     # W_O
        self.fc1 = nn.Linear(d_model, d_ff)         # W_1: expand
        self.fc2 = nn.Linear(d_ff, d_model)         # W_2: project back

    def attn(self, x):
        B, T, D = x.shape
        q, k, v = self.qkv(x).view(B, T, 3, self.n_heads, D // self.n_heads).permute(2, 0, 3, 1, 4)
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True)  # causal mask
        return self.proj(y.transpose(1, 2).reshape(B, T, D))

    def ffn(self, x):
        return self.fc2(F.gelu(self.fc1(x)))

    def forward(self, x):
        if self.pre_norm:
            x = x + self.attn(self.ln1(x))
            return x + self.ffn(self.ln2(x))
        x = self.ln1(x + self.attn(x))
        return self.ln2(x + self.ffn(x))

torch.manual_seed(0)
block = Block().eval()  # GPT-2 small sizes: d=768, 12 heads, d_ff=3072
x = torch.randn(1, 10, 768)
y = block(x)

x2 = x.clone()
x2[:, 6:] = torch.randn(1, 4, 768)  # change only the tokens at position 6 and later
print("output shape:", tuple(y.shape))
print("positions 0-5 unaffected by later tokens:", torch.allclose(y[:, :6], block(x2)[:, :6], atol=1e-5))
```

Output:

```text
output shape: (1, 10, 768)
positions 0-5 unaffected by later tokens: True
```

If you can match this code to the equations above one for one, you have started to read a block for real.

## Pre-Norm versus Post-Norm

This is a key point in understanding the block.

### The two orders

**Post-Norm** (the original Transformer):

$$
\begin{aligned}
h_l &= \mathrm{LN}\big(x_l + \mathrm{MHA}(x_l)\big)\\
x_{l+1} &= \mathrm{LN}\big(h_l + \mathrm{FFN}(h_l)\big)
\end{aligned}
$$

**Pre-Norm** (the mainstream since GPT-2):

$$
\begin{aligned}
h_l &= x_l + \mathrm{MHA}\big(\mathrm{LN}(x_l)\big)\\
x_{l+1} &= h_l + \mathrm{FFN}\big(\mathrm{LN}(h_l)\big)
\end{aligned}
$$

In Post-Norm the residual trunk passes through a LayerNorm at every layer. In Pre-Norm the input is normalized before it enters the sublayer, so the trunk stays direct and the sublayer behaves more like a side branch learning an incremental change. Drawing both orders as the residual trunk of a deep stack makes the difference obvious:

*Figure: This is why modern LLMs favor Pre-Norm: the residual trunk acts like a highway, and sublayers learn incremental changes beside it instead of forcing the whole main path through a normalization gate at every layer.*

### What the research says

Xiong et al. (ICML 2020) used mean-field theory to analyze gradients at initialization. Under simplifying assumptions (single-head attention, $W_Q$ and $W_K$ initialized to zero, and so on) they obtain two results:

- **Post-LN:** the gradient norm of the last FFN layer's weights is of order $O(d\sqrt{\ln d})$, **independent of the number of layers $L$**. Gradients near the output are large, so using a large learning rate right away makes training unstable, which is why warm-up is needed.
- **Pre-LN:** the same gradient is of order $O\big(d\sqrt{\ln d/L}\big)$ and shrinks as layers are added, so gradients are well behaved at initialization. In the paper's experiments Pre-LN without warm-up reaches results comparable to the baseline with warm-up, while saving substantial training time and tuning.

GPT-2 was among the first large language models to use this recipe: it moved LayerNorm to the input of each sub-block, added one extra LayerNorm after the final self-attention block, and scaled the weights of the residual layers at initialization by $1/\sqrt{N}$ ($N$ is the number of residual layers). Why the last two changes are needed is something you can measure yourself.

### Hands-on: how depth changes signal and gradient

Stack $L$ layers of the `Block` from the previous section (the `pre_norm` flag switches the order), run one forward and one backward pass at initialization, and record two quantities: the root mean square (RMS) of the last layer's output, and the gradient norm of the last FFN's second weight matrix `fc2`. Weights are initialized as $W\sim\mathcal{N}(0,1/n_{\text{in}})$ ($n_{\text{in}}$ is the input width), with $d=256$, sequence length 64 and batch size 8; inputs and labels are random tokens, averaged over 8 random seeds. The third setting is Pre-LN with the weights of `proj` and `fc2` multiplied by $1/\sqrt{2L}$ (each block has two residual branches, attention and FFN, so $N=2L$).

```python
import math
import statistics as st

def run(n_layers, pre_norm, seed, scale_residual=False, d=256, heads=4, T=64, B=8, vocab=1000):
    torch.manual_seed(seed)
    blocks = nn.ModuleList(Block(d, heads, 4 * d, pre_norm) for _ in range(n_layers))
    emb, head = nn.Embedding(vocab, d), nn.Linear(d, vocab, bias=False)
    final_ln = nn.LayerNorm(d) if pre_norm else nn.Identity()
    for m in [*blocks.modules(), head]:
        if isinstance(m, nn.Linear):  # variance-preserving init: W ~ N(0, 1/fan_in), zero bias
            nn.init.normal_(m.weight, std=1 / math.sqrt(m.in_features))
            if m.bias is not None:
                nn.init.zeros_(m.bias)
    nn.init.normal_(emb.weight, std=1.0)
    if scale_residual:  # GPT-2's trick: scale weights that write into the residual stream by 1/sqrt(N)
        for block in blocks:  # N = number of residual branches (two per block)
            block.proj.weight.data /= math.sqrt(2 * n_layers)
            block.fc2.weight.data /= math.sqrt(2 * n_layers)

    x = emb(torch.randint(0, vocab, (B, T)))
    for block in blocks:
        x = block(x)
    rms = x.pow(2).mean().sqrt().item()  # RMS of the last layer's output
    loss = F.cross_entropy(head(final_ln(x)).view(-1, vocab), torch.randint(0, vocab, (B * T,)))
    loss.backward()
    return rms, blocks[-1].fc2.weight.grad.norm().item()  # gradient norm of the last FFN's second matrix

settings = {"Post-LN": (False, False), "Pre-LN": (True, False), "Pre-LN+1/√N": (True, True)}
for L in (6, 12, 24, 48):
    cells = []
    for name, (pre, scale) in settings.items():
        runs = [run(L, pre, seed, scale) for seed in range(8)]  # average over 8 seeds
        cells.append(f"{name}: RMS {st.mean(r for r, _ in runs):.2f} grad {st.mean(g for _, g in runs):.2f}")
    print(f"L={L:2d}  " + " | ".join(cells))
```

It takes about a minute on a CPU and prints:

```text
L= 6  Post-LN: RMS 1.00 grad 0.82 | Pre-LN: RMS 2.35 grad 0.41 | Pre-LN+1/√N: RMS 1.14 grad 0.81
L=12  Post-LN: RMS 1.00 grad 0.84 | Pre-LN: RMS 3.42 grad 0.28 | Pre-LN+1/√N: RMS 1.14 grad 0.82
L=24  Post-LN: RMS 1.00 grad 0.88 | Pre-LN: RMS 5.03 grad 0.20 | Pre-LN+1/√N: RMS 1.14 grad 0.81
L=48  Post-LN: RMS 1.00 grad 0.91 | Pre-LN: RMS 7.39 grad 0.14 | Pre-LN+1/√N: RMS 1.14 grad 0.82
```

The widget below turns this table into something draggable: the three curves are the measured values (dots) of the three settings. Drag the depth to see how RMS and the gradient norm change — the dashed 1/√L line is anchored at the single measured L = 6 point and still passes almost through Pre-LN's other three.

Three things stand out in the table:

1. **Post-LN's gradient does not shrink with depth.** The last layer's gradient norm stays between 0.82 and 0.91 and even rises slightly with depth, while Pre-LN's falls roughly in step with $1/\sqrt{L}$ (0.41, 0.28, 0.20, 0.14; multiplied by $\sqrt{L}$ they are about 1.00, 0.98, 0.96, 0.94). This agrees in trend with the theorem above.
2. **Pre-LN's residual stream keeps growing.** Every sublayer adds something to the trunk and nothing pulls it back, so the RMS grows from 2.35 at 6 layers to 7.39 at 48. That is one reason Pre-LN models normally add an extra normalization at the end. Post-LN normalizes at every layer, so its RMS is exactly 1.
3. **The gradient is roughly inversely proportional to the scale of the residual stream.** In the Pre-LN rows the gradient times the RMS barely changes (0.96 to 1.00), which fits the fact that LayerNorm divides by the input scale in its backward pass. After the residual branches are multiplied by $1/\sqrt{N}$, the RMS stays at 1.14 at every depth and the gradient stays at 0.81 to 0.82, no longer drifting with depth.

> [!NOTE] What this experiment shows, and what it does not
> This is a measurement at initialization, with no training. It supports the claim that Post-LN and Pre-LN differ in how the gradient changes with depth at initialization; it does not imply anything about the quality after training. The initialization of a real model (GPT-2 uses a Gaussian with standard deviation 0.02, for example) changes the absolute numbers; the trends are what matter.

### So why do modern LLMs prefer Pre-Norm

The core reason is that it is usually more stable for deep training: normalization happens first, so the input to the sublayer is in a healthy numerical range, the residual trunk is not interrupted, the gradient path is smoother, and training depends less on learning-rate warm-up. If an implementation such as LLaMA or GPT-NeoX looks different from the figure in the paper, do not panic; many of the differences come from exactly this.

But more stable does not mean better in the end: the paper reports that Pre-LN without warm-up **matches** Post-LN with warm-up while saving training time. It does not claim that Pre-LN reaches a higher final quality.

## How many parameters does a block have

With code in hand, you can simply count. Ignoring the $O(d)$ terms (biases and norms), a standard block with $d_{ff}=4d$ has about $12d^2$ parameters:

$$
\underbrace{4d^2}_{W_Q,\,W_K,\,W_V,\,W_O} + \underbrace{2\,d\,d_{ff}}_{W_1,\,W_2} = 4d^2 + 8d^2 = 12d^2
$$

The table gives the exact numbers per block for GPT-2 small ($d=768$, biases included):

| Part | Matrices | Leading term | Parameters (with biases) | Share |
| --- | --- | --- | --- | --- |
| Multi-head attention | $W_Q,W_K,W_V,W_O$, each $d\times d$ | $4d^2$ | 2,362,368 | 33.3% |
| Feed-forward network | $W_1$: $d\times 4d$; $W_2$: $4d\times d$ | $8d^2$ | 4,722,432 | 66.6% |
| Two LayerNorms | $\gamma,\beta$, $d$ each | small | 3,072 | 0.04% |
| Total | | $12d^2$ | 7,087,872 | 100% |

Continuing with the `block` above, count it and add up the whole of GPT-2 small:

```python
def n_params(module):
    return sum(p.numel() for p in module.parameters())

d = 768
attention = n_params(block.qkv) + n_params(block.proj)
ffn = n_params(block.fc1) + n_params(block.fc2)
print(f"attention {attention:,}  FFN {ffn:,}  norms {n_params(block.ln1) + n_params(block.ln2):,}")
print(f"total {n_params(block):,}  formula 12d²+13d = {12 * d * d + 13 * d:,}  FFN share {ffn / n_params(block):.1%}")

# GPT-2 small: 12 blocks + token embedding (shared with the output matrix) + position embedding + final LayerNorm
total = 12 * n_params(block) + 50257 * d + 1024 * d + 2 * d
print(f"GPT-2 small total parameters: {total:,}")
```

```text
attention 2,362,368  FFN 4,722,432  norms 3,072
total 7,087,872  formula 12d²+13d = 7,087,872  FFN share 66.6%
GPT-2 small total parameters: 124,439,808
```

With biases and norms the exact count is $12d^2+13d$, which matches the code. Twelve blocks plus the token embedding, the position embedding and the final LayerNorm give 124,439,808, which corresponds to the 124M model in OpenAI's own description (the GPT-2 paper originally called it 117M and this was later corrected). The estimate $N\approx 12\,n_{\text{layer}}\,d^2$ is also Eq. (2.1) in the scaling-laws paper by Kaplan et al. Keep in mind that the proportions change with the architecture: the FFN holding about two thirds depends on MHA with a $4\times$ hidden width; with GQA and SwiGLU the split differs, and in Llama 3 8B the feed-forward network is about 70%, as the calculator in [Modern LLM Architecture](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture/) shows.

## What a block actually learns

Functionally, a block does not do one thing. It alternates two kinds of operation:

1. Horizontal information mixing: attention connects different positions.
2. Vertical feature transformation: the FFN makes a single position's representation more abstract and better suited to the next layer.

Stacking many layers, you can picture the whole network like this:

- The early layers build local patterns and basic relations.
- The middle layers gradually form higher-order dependencies.
- The later layers move closer to task-specific abstract decisions.

The exact division of labor differs between models, but the rhythm of mix information, transform nonlinearly, mix again, transform again is the essence of stacking blocks.

## How an encoder block differs from a decoder block

Looking only at the core, the two are very similar, but a decoder must additionally solve the problem of not peeking at future tokens. A decoder block therefore adds a causal mask $M$ to the self-attention scores ($-\infty$ where $j>i$), so the current position sees only the past:

$$
\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V,\qquad M_{ij}=\begin{cases}0 & j\le i\\ -\infty & j>i\end{cases}
$$

An encoder-decoder architecture adds cross-attention as well:

- encoder block: mainly bidirectional context encoding.
- decoder block: mainly autoregressive generation, and it can read the encoder output.

Modern general-purpose LLMs are mostly decoder-only, so when people say Transformer block today they usually have a decoder block in mind.

## Why block design affects training and inference cost

The block is not a purely theoretical building block; it directly drives engineering cost:

- The attention part determines the memory and compute pressure of long sequences.
- The FFN part determines the large parameter count and the dense matmul cost.
- LayerNorm and the residual path affect training stability.
- The number of heads, the hidden size and the FFN expansion ratio affect overall throughput.

Much later work is essentially a modification at block level, for example:

- [Efficient attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/) (FlashAttention, MQA, GQA, MLA) optimizes how attention is executed and cached
- [MoE](https://dmxsf.com/en/wiki/architecture/mixture-of-experts/) turns the FFN into routed experts
- LoRA is usually inserted at the linear projection layers
- RoPE changes how positions are injected into attention

So understanding the block is understanding the shared interface of a large number of later papers. For the compute and memory accounting of training and inference, see [The Compute and Memory Ledger of Training](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/).

## Common mistakes

### 1. Thinking attention is everything

Without the FFN, residuals and normalization the Transformer would not be the scalable architecture it is today.

### 2. Treating the FFN as a supporting actor

The FFN often holds a large share of the parameters and compute (about two thirds of the parameters in the standard design) and is a major source of expressive capacity in the block.

### 3. Assuming the block in a paper is the production implementation

Real models often change the normalization position, the activation function, the FFN structure, the attention-head design and other details.

### 4. Looking at a single layer and ignoring the stacking logic

The power of the Transformer comes from stacking blocks. Understanding one layer is only the start; how many layers cooperate is what really matters.

### 5. Believing Pre-Norm is always better than Post-Norm

The advantage of Pre-Norm is friendlier gradients at initialization and no dependence on learning-rate warm-up, which makes training less fiddly. Its residual stream grows with depth, so it needs a final normalization (and, as in GPT-2, possibly a scaling of the residual branches). That is more stable, not necessarily higher quality.

## Summary and exercises

**Key points:**

1. A block has two sublayers, attention and an FFN, each with a residual connection and LayerNorm; attention exchanges information between positions, and the FFN processes each position on its own.
2. Pre-Norm is $x+F(\mathrm{LN}(x))$ and Post-Norm is $\mathrm{LN}(x+F(x))$. Pre-LN has a direct residual trunk, its gradient at initialization shrinks with depth and it needs no warm-up, but its residual stream grows.
3. A standard block with $d_{ff}=4d$ has about $12d^2$ parameters: $4d^2$ in attention and $8d^2$ in the FFN. A GPT-2 small block has 7,087,872 parameters and the whole model 124,439,808.

### Quick self-check

**1. In a Pre-Norm block, what is the order of computation in one sublayer (take attention as the example)?**

- [ ] LN(x + Attn(x))
- [x] x + Attn(LN(x))
- [ ] Attn(x) + LN(x)
- [ ] LN(Attn(LN(x)))

> Pre-Norm normalizes first, runs the sublayer, and then adds the sublayer output back to the original input, so the residual trunk never passes through a normalization. The first option is Post-Norm.

**2. Ignoring biases and norms, about how many parameters does a standard block with $d_{ff}=4d$ have?**

- [ ] 6d²
- [ ] 8d²
- [x] 12d²
- [ ] 16d²

> Attention has four d×d matrices, W_Q, W_K, W_V and W_O, for 4d² in total; the FFN has a d×4d and a 4d×d matrix for 8d²; together that is 12d².

**3. Which of the following statements about the FFN are correct? (select all that apply)**

- [x] It applies the same weights to every position independently
- [x] In a standard block with MHA and a 4x hidden width it holds about two thirds of the parameters
- [ ] It is responsible for exchanging information between positions
- [x] Its hidden width is usually expanded to 4d and then projected back to d

> Information moves between positions only inside attention; the FFN works position by position, and its two matrices hold 8d², which is two thirds of 12d².

**4. In the input of a causal decoder block, every token from position 6 on is replaced. What happens to the outputs at positions 0 to 5?**

- [ ] All of them change
- [x] They stay the same
- [ ] Only position 5 changes
- [ ] It depends on LayerNorm's γ and β

> The causal mask lets position i read only positions ≤ i, and both the FFN and LayerNorm are computed position by position, so the outputs at positions ≤ 5 are completely unaffected. The code on this page verifies it with allclose.

**5. In this page's experiment, as the number of layers grows from 6 to 48, how does the gradient norm of the last FFN's second weight matrix change at initialization?**

- [ ] Both Post-LN and Pre-LN shrink noticeably
- [x] Post-LN barely changes (0.82 to 0.91) while Pre-LN shrinks roughly like 1/√L (0.41 to 0.14)
- [ ] Post-LN shrinks and Pre-LN stays the same
- [ ] Both grow noticeably

> This agrees in trend with the theorem of Xiong et al.: Post-LN's gradient there is independent of the number of layers, while Pre-LN's shrinks like 1/√L with depth.

**6. Over which dimension does LayerNorm compute its mean and variance?**

- [ ] The same feature across all samples in a batch
- [x] The d features of a single token
- [ ] All features of all tokens in the sequence
- [ ] Across the attention heads

> The statistics depend on a single token only, not across samples or positions, so training and inference run the same computation and batch size does not matter. BatchNorm is the one that computes statistics across samples.

**Exercises:**

1. The original Transformer base model has $d=512$ and $d_{ff}=2048$. How many parameters does one encoder block have, biases included? Compare with $12d^2+13d$.
2. For a 12-layer Pre-LN model, scale the residual branches as GPT-2 does (two branches per block, $N=24$). By what factor should the weights of `proj` and `fc2` be multiplied, and why do this?
3. Change `is_causal=True` to `False` in the code and run the causality check again. What does it print, and what has the block become?

<details>
<summary>Reference answers</summary>

1. Attention: $4\times512^2+4\times512=1{,}050{,}624$. FFN: $2\times512\times2048+2048+512=2{,}099{,}712$. Two LayerNorms: $2\times2\times512=2{,}048$. The total is 3,152,384, which equals $12\times512^2+13\times512=3{,}152{,}384$.
2. $1/\sqrt{24}\approx0.204$. Every residual branch of a Pre-LN model adds a share to the trunk, so the variance accumulates roughly linearly with the number of branches; shrinking each branch by $\sqrt{N}$ makes the accumulated amount nearly independent of depth. In the experiment this keeps the RMS at 1.14 from 6 to 48 layers, while without scaling it grows from 2.35 to 7.39.
3. It prints `False` (we ran it). Without the mask every position can read the changed later tokens, so the outputs of the first 6 positions change. The block has become an encoder-style bidirectional attention block, which cannot be used for autoregressive generation.

</details>

## Further reading

- To go back to the paper where the block started, see [Attention Is All You Need](https://dmxsf.com/en/blog/attention-is-all-you-need/) ([arXiv:1706.03762](https://arxiv.org/abs/1706.03762)): the original Post-Norm formula, $d=512$ and $d_{ff}=2048$ come from that paper.
- Xiong et al., [On Layer Normalization in the Transformer Architecture](https://arxiv.org/abs/2002.04745) (ICML 2020): the gradient analysis of Pre-LN and Post-LN at initialization; the theorem and conclusions on this page come from it.
- Ba, Kiros and Hinton, [Layer Normalization](https://arxiv.org/abs/1607.06450) (2016); Zhang and Sennrich, [Root Mean Square Layer Normalization](https://arxiv.org/abs/1910.07467) (NeurIPS 2019).
- He et al., [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) (CVPR 2016).
- Radford et al., [Language Models are Unsupervised Multitask Learners](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) (GPT-2, 2019): where LayerNorm sits and the residual scaling; for the parameter-count correction see [OpenAI's model card](https://github.com/openai/gpt-2/blob/master/model_card.md).
- Kaplan et al., [Scaling Laws for Neural Language Models](https://arxiv.org/abs/2001.08361) (2020): $N\approx12\,n_{\text{layer}}\,d^2$.
- For how the block is modified in modern models, see [Modern LLM Architecture](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture/); for its modification in parameter-efficient fine-tuning and sparsity, see Hu et al., [LoRA](https://arxiv.org/abs/2106.09685), and Fedus et al., [Switch Transformers](https://dmxsf.com/en/blog/switch-transformers-scaling-to-trillion-parameter-models/).
- Xie et al., [mHC: Manifold-Constrained Hyper-Connections](https://arxiv.org/abs/2512.24880) (2025): widens the residual stream into several streams and constrains their mixing matrix to be doubly stochastic so the composite residual mapping stays bounded; see the [paper breakdown](https://dmxsf.com/en/blog/mhc-manifold-constrained-hyper-connections/).
- Kimi Team, [Attention Residuals](https://arxiv.org/abs/2603.15031) (2026): keeps a single residual stream but replaces the weight-1 sum of earlier layer outputs with softmax attention using one learned pseudo-query per layer; the block variant cuts the vectors to keep from O(L) to O(N); see the [paper breakdown](https://dmxsf.com/en/blog/attention-residuals/).

## Companion code

[The Transformer block and the modern recipe](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/transformer-block): Count a GPT-2 small block (12d²+13d parameters), see where real models keep their parameters, measure signal and gradient by depth for pre-norm and post-norm, then walk from GPT-2 to Llama one change at a time.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/transformer-block`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/transformer-block/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/transformer-block/README.en.md)
- [`gpt.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/architecture/gpt.py)
- [`layers.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/architecture/layers.py)
- [`configs.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/architecture/configs.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#transformer-block)

## FAQ

### What is inside a Transformer block?

A standard block has multi-head self-attention, a feed-forward network (FFN), residual connections and LayerNorm. Attention routes information between positions, the FFN applies a stronger nonlinear transformation to each position, residual connections keep information and gradients flowing, and LayerNorm keeps the numerical scale of each layer stable. Stacking many blocks gives the full model.

### What is the difference between Pre-Norm and Post-Norm, and why do modern LLMs prefer Pre-Norm?

Post-Norm adds the sublayer output to the residual and then normalizes, so the residual trunk passes through a normalization at every layer. Pre-Norm normalizes first and then runs the sublayer, so the residual trunk stays direct. The analysis of Xiong et al. (ICML 2020) shows that at initialization Post-LN has large gradients near the output layer, which is why it needs learning-rate warm-up, while Pre-LN has well-behaved gradients and reaches results comparable to the baseline even without warm-up. Modern large models therefore use Pre-Norm, usually with an extra normalization after the last block.

### Why does the FFN matter?

The FFN applies an expand, nonlinearity, project-back transformation to every position independently, and the hidden width is usually 4 times d_model. At that ratio the FFN holds about two thirds of a standard block's parameters (8d² of 12d²), making it the most parameter-dense part. A rough way to think about it: attention decides where to look, and the FFN decides how to rethink what was seen.

### How does an encoder block differ from a decoder block?

The cores are similar, but a decoder must not peek at future tokens: its self-attention uses a causal mask so each position sees only what comes before it, and in encoder-decoder models it also has a cross-attention layer that reads the encoder output. Modern general-purpose LLMs are mostly decoder-only, so when people say Transformer block they usually mean a decoder block.

### How many parameters does a Transformer block have?

Ignoring biases and norms, about 12d²: W_Q, W_K, W_V and W_O are each d×d, 4d² in total, and the two FFN matrices (d×4d and 4d×d) add 8d². For GPT-2 small (d=768), with biases and LayerNorm included, one block has 7,087,872 parameters, of which the FFN is 66.6%.
