Skip to content
Transformers

The Transformer Block

Residual connections, layer normalization, and the feed-forward network that complete each transformer layer.

Multi-head attention gives every position direct access to every other position. But attention alone is not a complete layer: it aggregates information from across the sequence, but it does not transform the aggregated representations non-linearly. And without normalization, stacking many such layers produces training instability. The transformer block wraps multi-head attention in two additional components — residual connections and layer normalization — and pairs it with a position-wise feed-forward network.

Residual Connections

A residual connection adds the input of a sub-layer directly to its output:

x←x+SubLayer(x)\mathbf{x} \leftarrow \mathbf{x} + \text{SubLayer}(\mathbf{x})

This idea, introduced by He et al. (2016) for deep convolutional networks, has two benefits in the context of transformers.

Gradient flow. During backpropagation, the gradient passes through both paths: the sub-layer computation and the direct shortcut. Even if the sub-layer has a near-zero gradient (due to saturation or weight initialization), the gradient still flows unimpeded through the shortcut. This makes it practical to train very deep networks — 12, 24, or even 96 layers — without the vanishing gradient problem that plagued early deep architectures.

Incremental refinement. The sub-layer only needs to learn the residual — the improvement over the identity. If the best transformation at some layer is close to doing nothing, the sub-layer learns weights near zero and the output approaches the input. This is far easier to learn than an unconstrained transformation.

Layer Normalization

Layer normalization stabilises training by normalising the feature dimension of each token's representation. For a token vector x∈RD\mathbf{x} \in \mathbb{R}^D:

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

where μ=1D∑ixi\mu = \frac{1}{D}\sum_i x_i and σ=1D∑i(xi−μ)2\sigma = \sqrt{\frac{1}{D}\sum_i (x_i - \mu)^2} are the mean and standard deviation computed over the DD dimensions of x\mathbf{x}, and γ,β∈RD\boldsymbol{\gamma}, \boldsymbol{\beta} \in \mathbb{R}^D are learned scale and shift parameters initialised to 1\mathbf{1} and 0\mathbf{0}.

Why not batch normalization? The Regularization article introduced batch normalization, which computes statistics across the batch dimension. Layer normalization computes statistics across the feature dimension for each individual token, making it:

  • Independent of batch size (works with batch size 1).
  • Independent of sequence length (each position is normalised separately).
  • Compatible with variable-length sequences and autoregressive generation, where batches may contain sequences of very different lengths.

Layer norm adds 2D2D parameters (γ\boldsymbol{\gamma} and β\boldsymbol{\beta}) per normalisation, negligible compared to the attention matrices.

Pre-Norm vs Post-Norm

The original 2017 Transformer paper applied layer normalisation after the residual add (Post-LN):

x←LN(x+SubLayer(x))\mathbf{x} \leftarrow \text{LN}(\mathbf{x} + \text{SubLayer}(\mathbf{x}))

Later work found that applying layer normalisation before the sub-layer (Pre-LN) leads to more stable training and removes the need for careful learning rate warmup:

x←x+SubLayer(LN(x))\mathbf{x} \leftarrow \mathbf{x} + \text{SubLayer}(\text{LN}(\mathbf{x}))

GPT-2 and most modern transformers use Pre-LN. In Pre-LN, each sub-layer receives a normalised input, the sub-layer output is unconstrained, and the residual path remains clean. The difference matters most for very deep models where gradients in Post-LN can become problematic.

The Feed-Forward Network

The second sub-layer in each block is a position-wise feed-forward network (FFN): two linear transformations with a non-linearity between them.

FFN(x)=W2 GELU(W1x+b1)+b2\text{FFN}(\mathbf{x}) = \mathbf{W}_2\,\text{GELU}(\mathbf{W}_1 \mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2

where W1∈RD×dff\mathbf{W}_1 \in \mathbb{R}^{D \times d_{ff}}, W2∈Rdff×D\mathbf{W}_2 \in \mathbb{R}^{d_{ff} \times D}, and dff=4Dd_{ff} = 4D is the standard intermediate dimension.

Position-wise means the same FFN is applied independently to every position's DD-dimensional vector. There is no interaction across positions inside the FFN — that mixing already happened in the attention sub-layer. The FFN applies a richer non-linear transformation to each position's individual representation.

Why 4D? The 4×4\times expansion gives each position enough capacity to represent and transform the information aggregated by attention. The expansion factor of four has been empirically stable across a wide range of model sizes and tasks, though values between two and eight are also used in practice.

GELU (Gaussian Error Linear Unit) is the activation function used in GPT-2 and BERT. From the Activation Functions article: GELU is a smooth approximation to ReLU that allows small negative outputs and is everywhere differentiable. The FFN with GELU and dff=4Dd_{ff} = 4D contributes 2×D×4D=8D22 \times D \times 4D = 8D^2 parameters per block.

The Complete Block

With Pre-LN notation, one transformer block computes:

x←x+MHA(LN(x))(attention sub-layer)\mathbf{x} \leftarrow \mathbf{x} + \text{MHA}(\text{LN}(\mathbf{x})) \qquad \text{(attention sub-layer)} x←x+FFN(LN(x))(FFN sub-layer)\mathbf{x} \leftarrow \mathbf{x} + \text{FFN}(\text{LN}(\mathbf{x})) \qquad \text{(FFN sub-layer)}

The input shape T×DT \times D passes through and the output has exactly the same shape. Each block is a pure function from RT×D\mathbb{R}^{T \times D} to RT×D\mathbb{R}^{T \times D}: the sequence length and embedding dimension are preserved, making blocks trivially stackable.

transformer blockx (T × D)LayerNormMulti-Head Attention+LayerNormFeed-Forward (d_ff = 4D)+x' (T × D)residualPre-LN: x = x + SubLayer(LayerNorm(x))

Parameter Count Per Block

For a model with embedding dimension DD:

ComponentCount
MHA (4 weight matrices D×DD \times D)4D24D^2
FFN (W1\mathbf{W}_1 and W2\mathbf{W}_2)8D28D^2
Two LayerNorm (2×2D2 \times 2D)4D4D
Total per block≈12D2\approx 12D^2

For GPT-2 small (D=768D = 768, 12 blocks): each block holds ≈7.1\approx 7.1 million parameters, for a total of ≈85\approx 85 million parameters across all blocks (plus the embedding table of 38.638.6 million).

Stacking N Blocks

A transformer model consists of NN identical blocks in sequence, where the output of block ℓ\ell is the input to block ℓ+1\ell + 1. All blocks share the same structure but have independent parameters. For GPT-2 sizes:

ModelDDNN (layers)Parameters
GPT-2 small76812117 M
GPT-2 medium1,02424345 M
GPT-2 large1,28036762 M
GPT-2 XL1,600481.5 B

Deeper networks (more NN) have more capacity to learn hierarchical abstractions. Wider networks (larger DD) have more representational capacity per layer. The optimal NN/DD ratio depends on compute budget and data scale.

In Code

import math

import torch
import torch.nn as nn
import torch.nn.functional as F

# MultiHeadAttention from the previous article (included for self-containment)
class MultiHeadAttention(nn.Module):
    def __init__(self, d_model: int, num_heads: int):
        super().__init__()
        assert d_model % num_heads == 0
        self.H, self.dk = num_heads, d_model // num_heads
        self.W_Q = nn.Linear(d_model, d_model, bias=False)
        self.W_K = nn.Linear(d_model, d_model, bias=False)
        self.W_V = nn.Linear(d_model, d_model, bias=False)
        self.W_O = nn.Linear(d_model, d_model, bias=False)

    def forward(self, x: torch.Tensor, causal: bool = True) -> torch.Tensor:
        B, T, D = x.shape
        split = lambda t: t.view(B, T, self.H, self.dk).transpose(1, 2)   # (B, H, T, dk)
        Q, K, V = split(self.W_Q(x)), split(self.W_K(x)), split(self.W_V(x))
        scores = Q @ K.transpose(-2, -1) / math.sqrt(self.dk)
        if causal:
            mask = torch.triu(torch.ones(T, T, dtype=torch.bool, device=x.device), diagonal=1)
            scores = scores.masked_fill(mask, float("-inf"))
        out = F.softmax(scores, dim=-1) @ V
        return self.W_O(out.transpose(1, 2).contiguous().view(B, T, D))

# ── FFN: two linear layers with a GELU in between ─────────────────────────────
# 4× expansion, then back to d_model; applied to every position independently.

class FFN(nn.Module):
    def __init__(self, d_model: int, d_ff: int = None):
        super().__init__()
        d_ff = d_ff or 4 * d_model
        self.fc1 = nn.Linear(d_model, d_ff)
        self.fc2 = nn.Linear(d_ff, d_model)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.fc2(F.gelu(self.fc1(x)))

# ── TransformerBlock: pre-LN residuals around attention and FFN ───────────────
# nn.LayerNorm holds the learnable gamma and beta and normalizes over the last dimension.

class TransformerBlock(nn.Module):
    def __init__(self, d_model: int, num_heads: int, d_ff: int = None):
        super().__init__()
        self.ln1 = nn.LayerNorm(d_model)
        self.mha = MultiHeadAttention(d_model, num_heads)
        self.ln2 = nn.LayerNorm(d_model)
        self.ffn = FFN(d_model, d_ff)

    def forward(self, x: torch.Tensor, causal: bool = True) -> torch.Tensor:
        x = x + self.mha(self.ln1(x), causal=causal)   # attention sub-layer
        x = x + self.ffn(self.ln2(x))                   # FFN sub-layer
        return x                                         # shape preserved: (B, T, D)

# ── Stack N identical blocks ──────────────────────────────────────────────────

class TransformerStack(nn.Module):
    def __init__(self, n_layers: int, d_model: int, num_heads: int):
        super().__init__()
        self.blocks = nn.ModuleList([
            TransformerBlock(d_model, num_heads) for _ in range(n_layers)
        ])

    def forward(self, x: torch.Tensor, causal: bool = True) -> torch.Tensor:
        for block in self.blocks:
            x = block(x, causal=causal)
        return x

# ── Forward pass on a tiny stack ──────────────────────────────────────────────
tiny = TransformerStack(n_layers=2, d_model=8, num_heads=2)
out  = tiny(torch.randn(1, 6, 8))   # T=6 tokens, d_model=8
print(out.shape)                     # torch.Size([1, 6, 8]) — shape preserved through all blocks
for name, p in tiny.blocks[0].named_parameters():
    print(name, tuple(p.shape))      # every weight of the first block

# ── Sequence classifier built on a TransformerStack ───────────────────────────

class TransformerClassifier(nn.Module):
    def __init__(self, d_model, num_heads, n_layers, num_classes):
        super().__init__()
        self.stack = TransformerStack(n_layers, d_model, num_heads)
        self.ln    = nn.LayerNorm(d_model)
        self.head  = nn.Linear(d_model, num_classes)

    def forward(self, x):
        x = self.ln(self.stack(x, causal=True))
        return self.head(x[:, -1])   # classify from the last position

clf       = TransformerClassifier(d_model=8, num_heads=2, n_layers=2, num_classes=3)
optimizer = torch.optim.Adam(clf.parameters(), lr=1e-2)

seq    = torch.randn(1, 6, 8)
target = torch.tensor([0])           # the true class is 0

for step in range(20):
    optimizer.zero_grad()
    logits = clf(seq)
    loss   = F.cross_entropy(logits, target)
    loss.backward()
    optimizer.step()

    if step % 5 == 0:
        print(f"step {step:2d}  loss={loss.item():.4f}  pred={logits.argmax().item()}")

# GPT-2 small dimensions: D=768, H=12, N=12
model = TransformerStack(n_layers=12, d_model=768, num_heads=12)
x = torch.randn(2, 64, 768)    # batch=2, seq_len=64, d_model=768
out = model(x)
print(out.shape)                # torch.Size([2, 64, 768])

# Count parameters
total = sum(p.numel() for p in model.parameters())
print(f"{total:,}")             # 85,017,600

The transformer block is complete: multi-head attention to mix information across positions, a feed-forward network to transform each position independently, and residual connections with layer normalisation to keep gradients flowing and training stable. Stacking NN of these blocks produces a powerful sequence encoder or decoder. The next article builds a complete language model from these components: a GPT-2 implementation from scratch.