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:
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 :
where and are the mean and standard deviation computed over the dimensions of , and are learned scale and shift parameters initialised to and .
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 parameters ( and ) 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):
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:
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.
where , , and is the standard intermediate dimension.
Position-wise means the same FFN is applied independently to every position's -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 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 contributes parameters per block.
The Complete Block
With Pre-LN notation, one transformer block computes:
The input shape passes through and the output has exactly the same shape. Each block is a pure function from to : the sequence length and embedding dimension are preserved, making blocks trivially stackable.
Parameter Count Per Block
For a model with embedding dimension :
| Component | Count |
|---|---|
| MHA (4 weight matrices ) | |
| FFN ( and ) | |
| Two LayerNorm () | |
| Total per block |
For GPT-2 small (, 12 blocks): each block holds million parameters, for a total of million parameters across all blocks (plus the embedding table of million).
Stacking N Blocks
A transformer model consists of identical blocks in sequence, where the output of block is the input to block . All blocks share the same structure but have independent parameters. For GPT-2 sizes:
| Model | (layers) | Parameters | |
|---|---|---|---|
| GPT-2 small | 768 | 12 | 117 M |
| GPT-2 medium | 1,024 | 24 | 345 M |
| GPT-2 large | 1,280 | 36 | 762 M |
| GPT-2 XL | 1,600 | 48 | 1.5 B |
Deeper networks (more ) have more capacity to learn hierarchical abstractions. Wider networks (larger ) have more representational capacity per layer. The optimal / 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 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.