Anatomy of a Transformer Block and the Three Model Families
The parts of a transformer and why each is there: token embeddings, positional information (sinusoidal and rotary), multi-head attention, the feed-forward layer, residual connections and layer normalisation in a pre-norm block, measured in code; then how the same block gives encoder-only, decoder-only and encoder-decoder models, how each is pretrained, and which to use for which task.
Contentsand lesson path
On this page
- Why it matters
- Tokens in, and why positions must be added
- Inside the block
- Three families from one block
- Check your understanding
- Apply it
- Review prompt
Lessons of Transformer Architecture
- Attention as Soft Lookup: Queries, Keys and Values Concept · 20 min
- Lab: Build Multi-Head Causal Self-Attention from Scratch Lab · 30 min
- Anatomy of a Transformer Block and the Three Model Families Concept · 25 min
- Tokens In, Tokens Out: Tokenizers, Decoding Controls and the KV Cache Concept · 25 min
- Lab: Fine-Tune a Pretrained Encoder for Classification Lab · 30 min
- Check: Inside the Transformer Knowledge check · 8 questions
What you will learn
- Explain the parts of a transformer block (embeddings, positional information, attention, feed-forward layers, residuals, layer normalization) and when to use encoder-only, decoder-only or encoder-decoder models.
Prerequisites: Deep Learning Fundamentals
01. Why it matters
BERT, GPT, Llama and T5 look like very different systems, but inside they are stacks of nearly the same transformer block, repeated 6 to more than 100 times. What differs is mostly how attention is masked and how the model is trained. Once you can read one block, you can read the architecture section of almost any model card or paper, estimate where its parameters are, and choose the right kind of model for a task.
This lesson builds on multi-head causal self-attention. All examples run on a CPU with Python 3.12 and PyTorch 2, in a few seconds each.
02. Tokens in, and why positions must be added
A transformer reads a sequence of token ids (how text becomes ids is the topic of the next lesson). An embedding table, one learned vector per id, turns them into vectors of size d_model. Attention then mixes these vectors, but notice what it does not use: the scores compare contents only. Nothing in softmax(QKᵀ/√d)V knows that one token came before another. The script checks the consequence on a PyTorch encoder layer, then tests two ways of adding order back.
Sinusoidal positions, from the original transformer paper, add a fixed vector to each embedding, built from sines and cosines of the position at many frequencies. Learned positions add a trained vector per position instead, as in BERT and GPT-2. Rotary position embedding (RoPE), used by Llama and many recent models, does not add anything to the embeddings: it rotates each pair of query and key features by an angle proportional to the position, just before the scores are computed.
"""Attention alone ignores order; sinusoidal positions and RoPE put it back."""
import math
import torch
from torch import nn
torch.manual_seed(0)
T, D = 5, 16
layer = nn.TransformerEncoderLayer(D, nhead=2, dim_feedforward=32, dropout=0.0,
batch_first=True).eval()
x = torch.randn(1, T, D) # five token embeddings
perm = torch.tensor([4, 2, 0, 3, 1]) # the same tokens in another order
with torch.no_grad():
same = torch.allclose(layer(x)[0, perm], layer(x[:, perm])[0], atol=1e-5)
print("no positions: permuting the input just permutes the output:", same)
def sinusoidal(T, D):
pos = torch.arange(T)[:, None]
freq = torch.exp(-math.log(10000.0) * torch.arange(0, D, 2) / D)
pe = torch.zeros(T, D)
pe[:, 0::2], pe[:, 1::2] = torch.sin(pos * freq), torch.cos(pos * freq)
return pe
pe = sinusoidal(T, D)
with torch.no_grad():
out, out_perm = layer(x + pe)[0], layer(x[:, perm] + pe)[0]
same = torch.allclose(out[perm], out_perm, atol=1e-5)
print("with sinusoidal positions added:", same)
def rope(v, pos):
"""Rotate each pair of features (v[2i], v[2i+1]) by an angle pos * theta_i."""
theta = 10000.0 ** (-torch.arange(0, v.size(-1), 2) / v.size(-1))
cos, sin = torch.cos(pos * theta), torch.sin(pos * theta)
even, odd = v[0::2], v[1::2]
return torch.stack([even * cos - odd * sin, even * sin + odd * cos], -1).flatten()
q, k = torch.randn(D), torch.randn(D)
for m, n in ((2, 0), (7, 5), (12, 10), (3, 0)):
score = rope(q, m) @ rope(k, n)
print(f"RoPE score, query at {m:2d}, key at {n:2d} (offset {m - n}): {score:.4f}")python positions.pyno positions: permuting the input just permutes the output: True
with sinusoidal positions added: False
RoPE score, query at 2, key at 0 (offset 2): -1.2605
RoPE score, query at 7, key at 5 (offset 2): -1.2605
RoPE score, query at 12, key at 10 (offset 2): -1.2605
RoPE score, query at 3, key at 0 (offset 3): -1.1706Without positions, shuffling the input tokens only shuffles the outputs: each token gets exactly the same vector whatever order the words are in, so "dog bites man" and "man bites dog" would look alike to the model. This property is called permutation equivariance. Adding sinusoidal positions breaks it, as it must. The RoPE lines show its useful property. Rotating the query by angle mθ and the key by nθ leaves a score that depends only on m − n: the pairs (2, 0), (7, 5) and (12, 10) give exactly the same score, and offset 3 gives a different one. Attention thus sees relative positions, which tends to suit language, where "the word two places back" matters more than "word number 417".
03. Inside the block
A block has two sub-layers. Multi-head attention is the only place where tokens exchange information. The feed-forward network (FFN) then processes each token on its own: a linear layer that widens the vector, usually to 4 × d_model, a non-linearity such as GELU, and a linear layer back. A useful mental model is that attention gathers context and the FFN transforms what was gathered.
Each sub-layer is wrapped the same way. Layer normalisation (LayerNorm) rescales each token vector to mean 0 and standard deviation 1 across its features, then applies a learned scale and shift; it keeps activations in a stable range however many blocks are stacked. The residual connection adds the sub-layer's output to its input, x = x + sublayer(norm(x)), so each sub-layer only has to learn a change to the running representation, often called the residual stream. This order, with the norm inside the residual branch, is the pre-norm block used by GPT-2 onwards and most current models; the original paper normalised after the addition (post-norm), which is harder to train when the model is deep.
"""A pre-norm transformer block, and where its parameters are."""
import torch
import torch.nn.functional as F
from torch import nn
class Block(nn.Module):
def __init__(self, d, n_heads, causal=True):
super().__init__()
self.n_heads, self.causal = n_heads, causal
self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.qkv, self.proj = nn.Linear(d, 3 * d), nn.Linear(d, d)
self.ffn = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
def attn(self, x):
B, T, D = x.shape
q, k, v = (t.view(B, T, self.n_heads, -1).transpose(1, 2)
for t in self.qkv(x).split(D, -1))
y = F.scaled_dot_product_attention(q, k, v, is_causal=self.causal)
return self.proj(y.transpose(1, 2).reshape(B, T, D))
def forward(self, x):
x = x + self.attn(self.norm1(x)) # tokens exchange information
x = x + self.ffn(self.norm2(x)) # each token is processed on its own
return x
if __name__ == "__main__":
torch.manual_seed(0)
d = 256
block = Block(d, n_heads=8)
groups = {"attention": [block.qkv, block.proj], "feed-forward": [block.ffn],
"layer norms": [block.norm1, block.norm2]}
total = sum(p.numel() for p in block.parameters())
for name, mods in groups.items():
n = sum(p.numel() for m in mods for p in m.parameters())
print(f"{name:12} {n:7,} parameters ({n / total:.0%})")
x = torch.randn(2, 10, d) * 3 + 1 # shifted, scaled activations
h = block.norm1(x)
print(f"before LayerNorm: mean {x.mean():.2f}, std {x.std():.2f}")
print(f"after, per token: mean {h.mean(-1).abs().max():.3f}, "
f"std {h.std(-1, unbiased=False).mean():.3f}")
print("block output shape:", tuple(block(x).shape))python block.pyattention 263,168 parameters (33%)
feed-forward 525,568 parameters (67%)
layer norms 1,024 parameters (0%)
before LayerNorm: mean 0.94, std 2.99
after, per token: mean 0.000, std 1.000
block output shape: (2, 10, 256)Two thirds of the parameters are in the feed-forward layer. The reason is simple arithmetic: attention has four d × d matrices (queries, keys, values and output), 4d² in all, while the FFN has a d × 4d and a 4d × d matrix, 8d². LayerNorm is almost free. The LayerNorm line shows its job: inputs with a mean near 1 and a spread near 3 come out with mean 0 and standard deviation 1 for every token. The output has the input's shape, which is what makes blocks stackable.
What do the residual connections buy? The next script stacks 6, 24 and 48 blocks and measures the gradient that reaches the first block, with and without the additions.
"""Gradient reaching the first block of a deep stack, with and without residuals."""
import torch
from torch import nn
from block import Block
class Plain(Block):
def forward(self, x): # same layers, no residual additions
x = self.attn(self.norm1(x))
return self.ffn(self.norm2(x))
def first_block_grad(cls, depth):
torch.manual_seed(0)
stack = nn.Sequential(*[cls(64, n_heads=4) for _ in range(depth)])
stack(torch.randn(8, 16, 64)).pow(2).mean().backward()
return stack[0].qkv.weight.grad.norm().item()
for depth in (6, 24, 48):
res, plain = first_block_grad(Block, depth), first_block_grad(Plain, depth)
print(f"{depth:2d} blocks: first-block grad norm {res:.3f} with residuals, "
f"{plain:.3f} without ({res / plain:.0f}x)")python depth.py 6 blocks: first-block grad norm 0.200 with residuals, 0.064 without (3x)
24 blocks: first-block grad norm 0.627 with residuals, 0.052 without (12x)
48 blocks: first-block grad norm 2.052 with residuals, 0.093 without (22x)Without the additions, the first block receives a small gradient at every depth (0.05 to 0.09): with no direct path, all of it has to go through the later blocks' layers. With the additions, the first block's gradient does not fade as the stack grows; in this freshly initialised stack it even grows, so the ratio rises from about 3 times at 6 blocks to about 22 times at 48. The reason is a direct path: the derivative of x + f(x) with respect to x contains the identity, so part of the gradient skips every block on its way down. The same idea made very deep CNNs trainable (ResNets); in transformers it is what allows stacks of dozens of blocks.
04. Three families from one block
The block above, with or without a causal mask, gives the three families.
- Encoder-only models (BERT, RoBERTa, DeBERTa) use attention without a mask, so every token sees the whole input in both directions. They produce one contextual vector per token, which suits classification, tagging and embeddings for search.
- Decoder-only models (the GPT series, Llama, Mistral) use the causal mask, so they can generate text one token at a time.
- Encoder-decoder models (the original transformer, T5, BART) have an encoder that reads the input and a decoder that generates the output. Each decoder block has an extra cross-attention sub-layer whose queries come from the decoder and whose keys and values come from the encoder output.
The families are also pretrained differently. A decoder learns next-token prediction: the labels are the inputs shifted by one place. An encoder learns masked-token prediction: some tokens are selected for prediction (about 15% in BERT, where most of them are replaced by a [MASK] token and the rest by a random token or left unchanged), and the loss is computed only at those positions. T5 masks whole spans and lets the decoder generate them.
"""Encoder-only, decoder-only and encoder-decoder: masks, shapes and training labels."""
import torch
from torch import nn
torch.manual_seed(0)
D = 32
src = torch.randn(1, 7, D) # 7 input tokens, e.g. a sentence to translate
tgt = torch.randn(1, 4, D) # 4 output tokens generated so far
enc = nn.TransformerEncoderLayer(D, 4, 64, dropout=0.0, batch_first=True)
dec = nn.TransformerDecoderLayer(D, 4, 64, dropout=0.0, batch_first=True)
causal = nn.Transformer.generate_square_subsequent_mask(4) # -inf above diagonal
print("encoder-only: every token sees all 7 ->", tuple(enc(src).shape))
memory = enc(src)
out = dec(tgt, memory, tgt_mask=causal, tgt_is_causal=True)
print("encoder-decoder: decoder reads its 4 tokens causally and attends to the 7")
print(" encoder outputs through cross-attention ->", tuple(out.shape))
tokens = ["the", "cat", "sat", "on", "the", "mat"]
print("next-token prediction (decoder-only)")
print(" inputs:", " ".join(tokens[:-1]))
print(" labels:", " ".join(tokens[1:]))
g = torch.Generator().manual_seed(1)
masked = torch.rand(len(tokens), generator=g) < 0.3 # 30% for a visible demo; BERT: 15%
inputs = ["[MASK]" if m else t for t, m in zip(tokens, masked)]
labels = [t if m else "-" for t, m in zip(tokens, masked)]
print("masked-token prediction (encoder-only)")
print(" inputs:", " ".join(inputs))
print(" labels:", " ".join(labels), " ('-' = no loss at that position)")python families.pyencoder-only: every token sees all 7 -> (1, 7, 32)
encoder-decoder: decoder reads its 4 tokens causally and attends to the 7
encoder outputs through cross-attention -> (1, 4, 32)
next-token prediction (decoder-only)
inputs: the cat sat on the
labels: cat sat on the mat
masked-token prediction (encoder-only)
inputs: the [MASK] sat on [MASK] mat
labels: - cat - - the - ('-' = no loss at that position)The cross-attention output has the decoder's length, 4, not the encoder's 7: each output row belongs to one decoder query, which reads a weighted mix of the 7 encoder vectors. In the label lines, every position of the decoder input has a target, so one sentence gives many training examples at once; the encoder only learns from the masked positions, but sees context on both sides of each.
Which family to start from? For classification, extraction or embeddings with a fixed label set and tight latency, an encoder-only model is small, fast and fine-tunes well, as the fine-tuning lab shows. For open-ended generation, chat and tasks you want to solve with prompts, a decoder-only model. For tasks that map one sequence to a different one, such as translation or summarisation, encoder-decoder models are a natural fit, although large decoder-only models now handle many of these tasks well too. These are starting points, not laws: measure on your own data.
05. Check your understanding
06. Apply it
For your decoder-only practice model:
- Assemble token embeddings, learned position embeddings, 4 pre-norm blocks from
block.py, a final LayerNorm and a linear layer to the vocabulary. - Print the parameter count per component and check it against the 4d² and 8d² arithmetic.
- Swap the learned positions for RoPE applied to q and k inside attention, and confirm with a permutation test that order now matters.
07. Review prompt
Without looking back, draw a pre-norm transformer block and name each part and its job; explain why attention needs positional information and compare sinusoidal, learned and rotary positions; say where most of a block's parameters are and why; explain what residual connections do for deep stacks; and describe the mask, the training objective and a typical task for encoder-only, decoder-only and encoder-decoder models.
References
- Vaswani et al. (2017): Attention Is All You Need
- Su et al. (2021): RoFormer, Enhanced Transformer with Rotary Position Embedding
- Xiong et al. (2020): On Layer Normalization in the Transformer Architecture
- Hugging Face LLM Course: Transformer architectures
- Dive into Deep Learning: Attention Mechanisms and Transformers
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.