Encoder, Decoder and Encoder-Decoder Models
The same transformer block, stacked, gives three model families that look almost identical in code and behave very differently. Which one you pick decides what the model can see, what it is trained to predict and which tasks it is good at. Building a Transformer Block listed them in a table; this lesson goes through what really separates them (the mask, the objective and how the output is produced), builds a complete encoder-decoder forward pass in NumPy, trains a small one in PyTorch, and ends with the question every NLP engineer gets asked: why did decoder-only models win for LLMs?
Three families
| Encoder-only | Decoder-only | Encoder-decoder | |
|---|---|---|---|
| Examples | BERT, RoBERTa, DeBERTa, ELECTRA | GPT-2, GPT-3, Llama, Mistral, Qwen | T5, BART, mT5, Whisper, the 2017 transformer |
| Attention | bidirectional self-attention | causal self-attention | encoder: bidirectional; decoder: causal self + cross |
| Pretraining objective | masked LM (fill in hidden tokens), replaced-token detection | next-token prediction (causal LM) | span corruption (T5), denoising (BART), or a supervised pair task |
| Output | one vector per input token | a next-token distribution at every position | target tokens, generated one at a time |
| Typical tasks | classification, NER, retrieval embeddings, reranking | generation, chat, code, any task phrased as text | translation, summarisation, speech recognition |
| Generation | not natively | yes | yes |
The objectives are the subject of Pretraining Objectives; Inside a Pretrained BERT and Inside a Decoder-Only LM open up one model of each of the first two kinds.
The masks are the real difference. Each family is defined by which (query, key) pairs are allowed. The example prints them for a 5-slot sequence whose last slot is padding, and adds a fourth variant, the prefix LM (used by some T5 and PaLM variants and by many vision-language models): bidirectional over a prompt, causal after it.
import numpy as np
def show(name, M):
print(name)
for row in M.astype(int):
print(" ", " ".join(".x"[v] for v in row))
T, n_real = 5, 4 # 5 slots, the last one is padding
real = np.arange(T) < n_real
encoder = np.broadcast_to(real[None, :], (T, T)) # every query sees every real key
decoder = np.tril(np.ones((T, T), dtype=bool)) & real[None, :]
prefix = 2 # prefix LM: the first 2 tokens see each other fully
prefix_lm = decoder | ((np.arange(T)[None, :] < prefix) & (np.arange(T)[:, None] < prefix))
show("encoder (BERT): bidirectional, padding key masked", encoder)
show("decoder-only (GPT): causal", decoder)
show("prefix LM: bidirectional over the prompt, causal after it", prefix_lm)
S, Tt = 4, 3 # encoder-decoder: 4 source, 3 target tokens
cross = np.ones((Tt, S), dtype=bool)
show("encoder-decoder cross-attention (3 target x 4 source): no causal mask", cross)
print("allowed pairs per family:", int(encoder.sum()), int(decoder.sum()), int(prefix_lm.sum()))encoder (BERT): bidirectional, padding key masked
x x x x .
x x x x .
x x x x .
x x x x .
x x x x .
decoder-only (GPT): causal
x . . . .
x x . . .
x x x . .
x x x x .
x x x x .
prefix LM: bidirectional over the prompt, causal after it
x x . . .
x x . . .
x x x . .
x x x x .
x x x x .
encoder-decoder cross-attention (3 target x 4 source): no causal mask
x x x x
x x x x
x x x x
allowed pairs per family: 20 14 15
The encoder lets every query see every real key (20 allowed pairs of 25; only the padding column is removed). The decoder allows only (14 pairs): a token never sees what comes after it, which is exactly what makes "predict the next token" a non-trivial training task at every position simultaneously. The prefix LM differs from the decoder in one cell: the first two tokens see each other. Cross-attention has no causal structure at all: each of the 3 target tokens may read all 4 source tokens.
An encoder-decoder forward pass in NumPy
An encoder-decoder model runs in two stages. The encoder reads the whole source once and produces one vector per source token, the memory. The decoder produces the target: each of its blocks has three sub-layers, causal self-attention over the target so far, cross-attention whose queries come from the target and whose keys and values come from the memory (cross-attention), and an MLP. During training the decoder input is the target shifted right behind a BOS token (teacher forcing), and the labels are the target followed by EOS.
The toy task is reversing a digit string. The example builds one encoder block and one decoder block with random weights (one head, pre-norm, as in the deep-learning course) and traces the shapes, the padding, the loss and the two dependency checks that a correct implementation must pass.
import numpy as np
rng = np.random.default_rng(0)
V, E = 13, 16 # tokens 0-9 = digits, 10 = PAD, 11 = BOS, 12 = EOS
PAD, BOS, EOS = 10, 11, 12
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def layer_norm(x):
return (x - x.mean(-1, keepdims=True)) / np.sqrt(x.var(-1, keepdims=True) + 1e-5)
def attn(q_in, kv_in, W, mask): # one head; W = (Wq, Wk, Wv, Wo)
Q, K, Vv = q_in @ W[0], kv_in @ W[1], kv_in @ W[2]
S = np.where(mask, Q @ np.swapaxes(K, -1, -2) / np.sqrt(E), -np.inf)
A = softmax(S)
return (A @ Vv) @ W[3], A
def mlp(x, W1, W2):
return np.maximum(x @ W1, 0) @ W2
def new(*shape):
return rng.normal(0, shape[0] ** -0.5, shape)
emb = rng.normal(0, 1, (V, E))
pos = rng.normal(0, 0.5, (16, E))
enc_p = dict(sa=[new(E, E) for _ in range(4)], W1=new(E, 4 * E), W2=new(4 * E, E))
dec_p = dict(sa=[new(E, E) for _ in range(4)], ca=[new(E, E) for _ in range(4)], W1=new(E, 4 * E), W2=new(4 * E, E),
out=new(E, V))
def encode(src): # src (B, S) -> memory (B, S, E)
x = emb[src] + pos[:src.shape[1]]
key_ok = (src != PAD)[:, None, :] # (B, 1, S) padding mask
x = x + attn(layer_norm(x), layer_norm(x), enc_p["sa"], key_ok)[0]
x = x + mlp(layer_norm(x), enc_p["W1"], enc_p["W2"])
return layer_norm(x), key_ok
def decode(tgt_in, memory, src_ok): # tgt_in (B, T) -> logits (B, T, V)
T = tgt_in.shape[1]
y = emb[tgt_in] + pos[:T]
causal = np.tril(np.ones((T, T), dtype=bool))
y = y + attn(layer_norm(y), layer_norm(y), dec_p["sa"], causal)[0] # 1. causal self-attention
c, A_cross = attn(layer_norm(y), memory, dec_p["ca"], src_ok) # 2. cross-attention
y = y + c
y = y + mlp(layer_norm(y), dec_p["W1"], dec_p["W2"]) # 3. MLP
return layer_norm(y) @ dec_p["out"], A_cross # output head
# Toy task: reverse the digits. Two source sequences, the second padded.
src = np.array([[3, 1, 4, 1, 5], [9, 2, 6, PAD, PAD]])
tgt = np.array([[5, 1, 4, 1, 3, EOS], [6, 2, 9, EOS, PAD, PAD]]) # what the decoder must output
tgt_in = np.concatenate([np.full((2, 1), BOS), tgt[:, :-1]], axis=1) # shifted right: BOS + target
print("decoder input:", tgt_in[0].tolist(), " labels:", tgt[0].tolist())
memory, src_ok = encode(src)
logits, A_cross = decode(tgt_in, memory, src_ok)
print("memory", memory.shape, " logits", logits.shape, " cross-attention", A_cross.shape)
print("cross weights on padded source keys:", float(A_cross[1, :, 3:].sum()))
# Teacher-forced cross-entropy over real target tokens only (labels == PAD are ignored).
logp = logits - np.log(np.exp(logits).sum(-1, keepdims=True))
real = tgt != PAD
nll = -np.take_along_axis(logp, tgt[..., None], -1)[..., 0]
print(f"untrained loss {nll[real].mean():.3f} vs ln V = {np.log(V):.3f}")
# Causality: changing decoder input 4 cannot change the predictions at positions 1-3.
t2 = tgt_in.copy(); t2[0, 3] = 7
l2, _ = decode(t2, memory, src_ok)
print("earlier positions unchanged:", np.allclose(l2[0, :3], logits[0, :3]), " later changed:", not np.allclose(l2[0, 3:], logits[0, 3:]))
# Every target position reads the whole source: changing the LAST source digit moves the FIRST prediction.
s2 = src.copy(); s2[0, 4] = 8
l3, _ = decode(tgt_in, *encode(s2))
print("first prediction depends on the last source token:", not np.allclose(l3[0, 0], logits[0, 0]))decoder input: [11, 5, 1, 4, 1, 3] labels: [5, 1, 4, 1, 3, 12]
memory (2, 5, 16) logits (2, 6, 13) cross-attention (2, 6, 5)
cross weights on padded source keys: 0.0
untrained loss 2.562 vs ln V = 2.565
earlier positions unchanged: True later changed: True
first prediction depends on the last source token: True
- The source batch is
(2, 5)with the second sequence padded; the memory is(2, 5, 16), one vector per source token. The decoder input[11, 5, 1, 4, 1, 3]isBOSfollowed by the reversed digits, and the labels[5, 1, 4, 1, 3, 12]are the same shifted left, ending inEOS. - The logits are
(2, 6, 13): a distribution over the 13 tokens at each of the 6 target positions, all computed in one pass. The cross-attention weights are(2, 6, 5), target by source, and the padded source keys get weight 0.0. - The untrained loss is 2.562 nats, close to , the loss of a uniform guess: a sanity check that the initialisation is sensible. Padded label positions are left out of the mean.
- Changing decoder input 4 leaves positions 1 to 3 unchanged (causality), while the first prediction depends on the last source digit, which is exactly what reversal needs and what cross-attention without a causal mask allows.
Training a small one in PyTorch
No pretrained encoder-decoder (T5, BART) is cached in this course's environment, so the recorded example trains one from scratch: nn.Transformer with 2 encoder and 2 decoder layers, , 4 heads, on random digit strings of length 3 to 8. Note the three masks passed to it: the causal tgt_mask, and the source padding mask given twice, once for the encoder's self-attention and once (memory_key_padding_mask) for the decoder's cross-attention. Generation encodes the source once and then calls the decoder repeatedly, appending the argmax token each time.
import math
import warnings
import torch
from torch import nn
import torch.nn.functional as F
warnings.filterwarnings("ignore", message="enable_nested_tensor") # harmless notice for norm_first=True
torch.manual_seed(0)
PAD, BOS, EOS, V = 10, 11, 12, 13 # digits 0-9 + three special tokens
E, max_len = 64, 12
def make_batch(n, g): # random digit strings of length 3-8 and their reversal
lens = torch.randint(3, 9, (n,), generator=g)
src = torch.full((n, 8), PAD)
tgt = torch.full((n, 9), PAD) # reversed digits + EOS
for i, L in enumerate(lens.tolist()):
d = torch.randint(0, 10, (L,), generator=g)
src[i, :L] = d
tgt[i, :L] = d.flip(0)
tgt[i, L] = EOS
tgt_in = torch.cat([torch.full((n, 1), BOS), tgt[:, :-1]], dim=1) # shifted right
tgt_in[tgt_in == EOS] = PAD
return src, tgt_in, tgt
class Seq2Seq(nn.Module):
def __init__(self):
super().__init__()
self.emb = nn.Embedding(V, E)
self.pos = nn.Embedding(max_len, E)
self.tf = nn.Transformer(E, nhead=4, num_encoder_layers=2, num_decoder_layers=2,
dim_feedforward=4 * E, dropout=0.0, batch_first=True, norm_first=True)
self.head = nn.Linear(E, V)
def embed(self, x):
return self.emb(x) + self.pos(torch.arange(x.shape[1]))
def forward(self, src, tgt_in):
causal = nn.Transformer.generate_square_subsequent_mask(tgt_in.shape[1])
h = self.tf(self.embed(src), self.embed(tgt_in), tgt_mask=causal, tgt_is_causal=True,
src_key_padding_mask=src == PAD, memory_key_padding_mask=src == PAD)
return self.head(h)
model = Seq2Seq()
print("parameters:", sum(p.numel() for p in model.parameters()))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
g = torch.Generator().manual_seed(0)
steps = 400
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1, (s + 1) / 50) * 0.5 * (1 + math.cos(math.pi * s / steps)))
for step in range(steps):
src, tgt_in, tgt = make_batch(64, g)
loss = F.cross_entropy(model(src, tgt_in).reshape(-1, V), tgt.reshape(-1), ignore_index=PAD)
opt.zero_grad(); loss.backward(); opt.step(); sched.step()
if step in (0, 49, 149, 399):
print(f"step {step + 1:3d} teacher-forced loss {loss.item():.3f}")
@torch.no_grad()
def greedy(src): # encode once, then decode token by token
model.eval()
memory = model.tf.encoder(model.embed(src), src_key_padding_mask=src == PAD)
out = torch.full((src.shape[0], 1), BOS)
for _ in range(9):
causal = nn.Transformer.generate_square_subsequent_mask(out.shape[1])
h = model.tf.decoder(model.embed(out), memory, tgt_mask=causal, memory_key_padding_mask=src == PAD)
nxt = model.head(h[:, -1]).argmax(-1, keepdim=True)
out = torch.cat([out, nxt], dim=1)
return out[:, 1:]
def text(row):
s = []
for t in row.tolist():
if t == EOS or t == PAD:
break
s.append(str(t))
return "".join(s)
src, _, tgt = make_batch(500, torch.Generator().manual_seed(123)) # new, unseen strings
pred = greedy(src)
exact = sum(text(p) == text(t) for p, t in zip(pred, tgt))
print(f"exact-match on 500 new strings: {exact / 500:.3f}")
for i in range(3):
print(f" {text(src[i]):>8s} -> {text(pred[i]):>8s} (target {text(tgt[i])})")parameters: 236173
step 1 teacher-forced loss 2.676
step 50 teacher-forced loss 1.511
step 150 teacher-forced loss 0.025
step 400 teacher-forced loss 0.008
exact-match on 500 new strings: 1.000
6431407 -> 7041346 (target 7041346)
1757 -> 7571 (target 7571)
360 -> 063 (target 063)
The teacher-forced loss falls from 2.676 to 0.008 in 400 steps, and greedy decoding reverses all 500 freshly drawn strings exactly (1.000). Two honest caveats: many short test strings also occurred in training (there are only 1000 strings of length 3), and reversal is an algorithmic task with no ambiguity, so perfect accuracy here says nothing about real translation. What it does show is the mechanics: to output step the decoder has to find source position , and cross-attention is the only path to the source (inspecting the weights, as in the attention lesson, is a good exercise). A decoder-only model would do the same through causal self-attention over one concatenated "source, separator, target" sequence.
With Transformers, a pretrained model would be loaded as AutoModelForSeq2SeqLM.from_pretrained("t5-small") and called with input_ids, attention_mask and labels; the library shifts the labels right to build decoder_input_ids, exactly as above. (Not run here: the weights are not in the course image.)
Why decoder-only won for LLMs
In 2019 the encoder-decoder T5 looked like the general recipe; by 2023 almost every large language model was decoder-only. The reasons are practical rather than a proof that one architecture is better:
- One objective, every token. Next-token prediction turns every token of raw text into a training example. Masked LM only learns from the roughly 15% of positions it hides, and span corruption needs a designed noising scheme. Decoder-only pretraining is the simplest objective that scales.
- Generation and in-context learning come free. A decoder-only model is already a generator, and a prompt with examples is just more prefix. Instruction tuning, chat and tool use are all "continue this text", so a single model and a single interface cover every task.
- Simpler engineering. One stack, one mask, one KV cache. An encoder-decoder must split every input into "source" and "target", which is awkward for multi-turn chat where yesterday's output is today's input.
- Scaling evidence. The large-scale experiments of 2020 to 2022 (GPT-3, then the scaling-law studies) were run with decoder-only models, and the ecosystem followed: kernels, serving systems and fine-tuning tools were optimised for them.
The case for the others is real too. Encoder-only models are much cheaper for classification, NER, retrieval and reranking: a BERT-sized encoder with bidirectional context beats a decoder of similar size on those tasks and runs in one forward pass. Encoder-decoder models are efficient when the input is long and the output short (summarisation, speech recognition: Whisper is encoder-decoder), because the source is encoded once with full bidirectional attention, and in comparisons at equal compute they are competitive on many supervised tasks (the T5 and UL2 papers report this). The right choice depends on the task and the budget, not on fashion.
Pitfalls
- Forgetting to shift the decoder input. Feeding the labels themselves as decoder input lets position read its own answer; the loss collapses to near zero and generation fails.
- Only one padding mask. In
nn.Transformerthe source padding must be passed assrc_key_padding_maskandmemory_key_padding_mask; otherwise the cross-attention reads padding. - Re-encoding the source at every generation step. The memory does not change during decoding; compute it once (as
greedydoes) and, in real systems, cache the cross-attention keys and values too. - Calling a decoder-only model "a decoder" in PyTorch terms.
nn.TransformerDecoderLayeralways has cross-attention and needs a memory; a GPT-style stack isnn.TransformerEncoderLayerplus a causal mask. - Judging a family by one toy task. Reversal, copying and sorting are solved perfectly by any of the three with enough steps; they test the plumbing, not the architecture.
Practice
- In
ed1.py, how many query-key pairs does a prefix LM allow for with a prefix of 3 and no padding? How many does a causal decoder allow?
Answer
Causal: . Prefix LM: the prefix block is full instead of triangular, adding pairs, so 24.
- In
ed2.py, what are the shapes of the logits and the cross-attention weights for a batch of 8 sources of length 20 and targets of length 12 (includingEOS)?
Answer
The decoder input is BOS + the first 11 target tokens, so 12 positions: logits (8, 12, 13), cross-attention weights (8, 12, 20).
- Why does the first output digit of the reversal task depend on the last source digit, and could a decoder-only model with a causal mask do the same task?
Answer
The first output is the last source digit; cross-attention lets target position 1 read every source position. A decoder-only model can do it too if the input is "source, separator, target": when it predicts the first target token, the whole source is already in its past, so the causal mask allows reading it.
- You need a model that classifies 10 million support tickets a day into 20 categories, and another that writes replies. Which family would you consider for each, and why?
Answer
Classification: an encoder-only model (fine-tuned BERT-like), because one bidirectional forward pass per ticket is cheap and accurate for classification. Replies: a decoder-only LLM (or an encoder-decoder if the output is short and tightly conditioned on the input), because the task is generation.
Test yourself
Which family is BERT?
- Decoder-only
- Encoder-only, bidirectional self-attention
- Encoder-decoder
- Recurrent
During training, what is the decoder input of an encoder-decoder model?
- The source sequence
- The target shifted right behind a BOS token
- The target itself
- Only the BOS token
Which sub-layers does a decoder block of an encoder-decoder model contain?
- Bidirectional self-attention and an MLP
- Causal self-attention, cross-attention to the encoder output, and an MLP
- Only cross-attention
- Causal self-attention and an MLP
In the NumPy forward pass, the untrained loss was 2.562 nats. Why is a value near expected?
- Because 13 layers were used
- Because a random model's predictions are close to uniform over the 13 tokens
- Because the loss was averaged over 13 sequences
- Because of the causal mask
Which is NOT a main reason decoder-only models became the standard for LLMs?
- Every token of raw text is a training example for next-token prediction
- They generate text and learn from prompts without a separate output stack
- They are proven to be better than encoders at classification at equal size
- One stack, one mask and one cache keep the engineering simple