By Sagi Shaier · 11 November 2026 · 12 min read
Encoder vs decoder vs encoder-decoder transformers (BERT, GPT, T5)
How to tell the three transformer families apart by what each position may attend to, how BERT, GPT and T5 are trained, how cross-attention connects an encoder to a decoder with worked numbers, and which family fits which task.
Transformers come in three arrangements. An encoder-only model reads a whole input at once and returns one vector per token, a decoder-only model writes text one token at a time, and an encoder-decoder model reads a source text with one stack and writes a new target text with a second stack. BERT, GPT and T5 are well-known examples of each. All three are built from the same parts, so the differences come down to which tokens each attention layer is allowed to use. Models read tokens, which can be whole words or pieces of words, and the examples here use short words as tokens.
The same parts in three arrangements
Every transformer in this post is built from the same parts. Tokens become embeddings with positional encoding added, and each layer has multi-head attention and a feed-forward network with residual connections and LayerNorm. An output head sits on top. The arrangement changes:
- Encoder-only: one stack, and each input position may attend to every real input position.
- Decoder-only: one stack, and each position may attend only to itself and earlier positions, so it can predict the next token.
- Encoder-decoder: two stacks. The encoder builds representations of the source, the decoder builds representations of the target, and cross-attention connects them.

The attention formula is the same in all three. Each token gets a query, a key and a value vector. Stacked over the sequence they form the matrices $Q$, $K$ and $V$. Attention scores every query against every key and scales the scores by $\sqrt{d_k}$, where $d_k$ is the size of each query and key. It then adds a mask $M$ before the softmax:
$$A = \operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) \qquad \text{output} = AV$$
$A$ holds the attention weights. The mask has 0 where a score is allowed and $-\infty$ where it is blocked, and since $e^{-\infty} = 0$ a blocked score gets a weight of 0. The three families differ mainly in which entries their masks block and where $Q$, $K$ and $V$ come from.

Encoder-only: use the whole input
Some tasks are not about writing the next token. Sentiment classification asks whether a review is positive or negative, and extractive question answering asks where an answer sits in a paragraph. In both, the whole input is available before the model answers, so there is no reason to hide later tokens.
An encoder therefore uses no causal mask. Every real token may use every other real token, in training and at inference. For the input the cute axolotl, one head might produce these weights, with one row per token:
$$A \approx \begin{bmatrix} 0.42 & 0.33 & 0.25 \\ 0.20 & 0.50 & 0.30 \\ 0.31 & 0.28 & 0.41 \end{bmatrix}$$
Every row sums to 1, and nothing above the diagonal is forced to zero. The row for the puts weight on cute and axolotl, which a decoder would not allow.


After a stack of encoder layers, the model still has one vector per input token. Together they form a matrix $H$ of shape $B \times T \times d_{model}$, where $B$ is the batch size, $T$ the number of tokens and $d_{model}$ the number of features per vector. Each row of $H$ now depends on the whole input. The encoder does not produce a final answer by itself, so a small task head reads $H$. For classification, a common choice is to take the vector at position 0 and map it to one score per class. Position 0 often holds a special classification token:
$$\text{logits} = h_{cls} W_{class} + b$$
For answer spans, two heads instead score every position as a possible start and end of the answer, so the token positions stay.
![Example head: sequence classification. The encoder output H has shape B × T × d_model. Position 0 is taken as h_cls = H[:, 0, :] with shape B × d_model, and the classification head computes logits = h_cls W_class + b, with W_class of shape d_model × 3 and b of shape 3, giving one logits vector of shape B × 3 over negative, neutral and positive.](images/encoder_sequence_classification_head.png)
BERT is a well-known encoder-only model. Because an encoder sees both sides of every token, it cannot be trained to predict the next token, since that token would sit in its own input. BERT is trained with masked language modeling instead: some input tokens are replaced by a [MASK] token, and the model predicts the original token at each masked position. For the [MASK] axolotl, the target is cute. Other encoder-only models include RoBERTa and DistilBERT, which differ from BERT in their training recipes or sizes.
![BERT masked-token training. The original text the cute axolotl becomes the corrupted input the [MASK] axolotl, with context on both sides. The encoder runs full self-attention with no causal mask, and the token head at the masked position gives cute 0.78, axolotl 0.10, the 0.06, runs 0.04, with the rest of the vocabulary holding about 0.02.](images/bert_masked_token_training.png)
Decoder-only: continue the text
Other tasks are about continuing a prefix, such as the cute followed by axolotl. A decoder-only model takes the tokens written so far, predicts the next one, appends it and runs again. There is no separate source, and the prefix is all the context the model has.
During training, the model reads a shifted copy of the text. With a beginning-of-sequence token BOS, the input is BOS the cute and the labels are the cute axolotl, so each position learns to predict the token after it. The position of cute must not see axolotl, because axolotl is its label. A causal mask blocks every position from the ones after it:
$$M_{causal} = \begin{bmatrix} 0 & -\infty & -\infty \\ 0 & 0 & -\infty \\ 0 & 0 & 0 \end{bmatrix}$$
After softmax, one head might produce:
$$A \approx \begin{bmatrix} 1.00 & 0.00 & 0.00 \\ 0.37 & 0.63 & 0.00 \\ 0.18 & 0.24 & 0.58 \end{bmatrix}$$
The first row is forced to 1.00 because position 0 can use only itself. The zeros above the diagonal are what make this matrix different from the encoder's. Causal masking explained works through the mask in detail.

A language-modeling head turns each final vector into one score per vocabulary token. The row at the position of cute scores the token that comes after cute, and the correct label there is axolotl. At inference time the model generates one token per run: BOS gives the, then BOS the gives cute, then BOS the cute gives axolotl. Generation stops at an end-of-sequence token or a length limit.

GPT models are a decoder-only family. They are trained on next-token prediction at every position, which written as a probability is $p(x_{t+1} \mid x_{\le t})$: the chance of token $t+1$ given every token up to $t$. Build a small GPT from scratch writes one in PyTorch and trains it.
Encoder-decoder: condition on a source
Encoder-decoder models fit tasks where the input and the output are two different texts, such as translation and summarization. The running example is a translation:
$$\text{source: the cute axolotl} \qquad \text{target: der niedliche Axolotl}$$
The encoder reads the full source once, with no causal mask, and returns one vector per source token. Call that matrix $E$. The decoder then writes the target from left to right. At each step it has two kinds of information: the target prefix written so far, and the encoder's representation of the source.

A decoder-only model has nothing like $E$. The bridge between the two stacks is cross-attention, which uses the same formula with the inputs taken from two places. The decoder states $D$ provide the queries, and the encoder output $E$ provides the keys and values:
$$Q = DW_Q \qquad K = EW_K \qquad V = EW_V$$
Each target position scores every source position, turns the scores into weights and blends the source value vectors into its own vector. With $T$ target positions and $S$ source positions, the score matrix has shape $T \times S$.

Take the first generation step, where the target prefix is only BOS. Use one head with 3 features in each query, key and value. Suppose the decoder state for BOS gives the query $[0.4, -0.8, 1.0]$, and the three source tokens give these keys and values, one row per token:
$$K = \begin{bmatrix} 0.2 & -0.5 & 0.7 \\ -0.3 & 1.0 & 0.4 \\ 1.1 & 0.2 & -0.6 \end{bmatrix} \qquad V = \begin{bmatrix} 0.5 & -1.0 & 0.2 \\ 0.1 & 0.7 & -0.3 \\ 1.2 & 0.4 & 0.8 \end{bmatrix}$$
The score for the is the dot product of the query with the first key:
$$0.4 \times 0.2 + (-0.8) \times (-0.5) + 1.0 \times 0.7 = 0.08 + 0.40 + 0.70 = 1.18$$
The same for cute and axolotl gives $-0.52$ and $-0.32$. Dividing by $\sqrt{3}$ and applying softmax gives the weights, and the weights blend the value rows:
1import torch
2
3Q = torch.tensor([[0.4, -0.8, 1.0]]) # decoder state for BOS
4K = torch.tensor([[0.2, -0.5, 0.7], # the
5 [-0.3, 1.0, 0.4], # cute
6 [1.1, 0.2, -0.6]]) # axolotl
7V = torch.tensor([[0.5, -1.0, 0.2],
8 [0.1, 0.7, -0.3],
9 [1.2, 0.4, 0.8]])
10
11scores = Q @ K.T
12weights = torch.softmax(scores / 3 ** 0.5, dim=-1)
13print(scores.round(decimals=2))
14print(weights.round(decimals=2))
15print((weights @ V).round(decimals=2))1tensor([[ 1.1800, -0.5200, -0.3200]])
2tensor([[0.5600, 0.2100, 0.2300]])
3tensor([[ 0.5800, -0.3200, 0.2400]])BOS puts 0.56 of its weight on the, and its new vector $[0.58, -0.32, 0.24]$ is $0.56\,V_{the} + 0.21\,V_{cute} + 0.23\,V_{axolotl}$. This is not a word prediction yet. In a full model the heads are merged and projected back to $d_{model}$, and the result is added to the decoder stream. The stream then still goes through the feed-forward network and the vocabulary head before the model predicts der.
![Step 3 output: source information enters BOS. Raw source scores for BOS are the 1.18, cute -0.52, axolotl -0.32. Scaling by √3 and softmax across the three source positions gives the 0.56, cute 0.21, axolotl 0.23. Blending the value rows V_the [0.5, -1.0, 0.2], V_cute [0.1, 0.7, -0.3] and V_axolotl [1.2, 0.4, 0.8] as 0.56 V_the + 0.21 V_cute + 0.23 V_axolotl gives CrossAttn_BOS [0.58, -0.32, 0.24]. Heads merge and project back to d_model, then the result updates the decoder stream.](images/cross_attention_softmax_weighted_sum.png)
So an encoder-decoder decoder layer has three sublayers instead of two: masked self-attention over the target prefix, cross-attention over the encoder output, and the feed-forward network. Each has a LayerNorm before it and a residual add after it.

The two attention sublayers use different masks. Target self-attention keeps the causal mask, so a target position cannot use later target positions. Cross-attention points from target positions to source positions, and the encoder has already processed the whole source, so there is no future source token to hide. Cross-attention needs only a padding mask that blocks the filler PAD tokens added to shorter sources in a batch. As boolean tables, where 1 means allowed:
1T = 3
2encoder_mask = torch.ones(T, T).bool()
3decoder_mask = torch.tril(torch.ones(T, T)).bool()
4print(encoder_mask.int())
5print(decoder_mask.int())
6
7src_real = torch.tensor([True, True, True, False]) # the last source token is PAD
8cross_mask = src_real[None, :].expand(2, 4) # 2 target positions, 4 source positions
9print(cross_mask.int())1tensor([[1, 1, 1],
2 [1, 1, 1],
3 [1, 1, 1]], dtype=torch.int32)
4tensor([[1, 0, 0],
5 [1, 1, 0],
6 [1, 1, 1]], dtype=torch.int32)
7tensor([[1, 1, 1, 0],
8 [1, 1, 1, 0]], dtype=torch.int32)torch.tril keeps the lower triangle of a table of ones, and expand repeats the source row once per target position.

Training and generation use the same model. During training the correct target is known, so the decoder reads the shifted target BOS der niedliche Axolotl and predicts der niedliche Axolotl EOS at all positions in one pass, a setup called teacher forcing. During generation the decoder starts from BOS, predicts one token, appends it and runs again. The encoder runs once per source, and its output is reused at every step.
![Training and inference use the same path. In training with teacher forcing, the source the cute axolotl goes through the encoder layers to E, and the decoder layers read the shifted target input BOS, der, niedliche, Axolotl with cross-attention to E and predict the labels der, niedliche, Axolotl, EOS in one pass. In inference the decoder runs on [BOS], then [BOS, der], then [BOS, der, niedliche], and stops at EOS or at the maximum length. The causal mask protects the target side, and the source padding mask protects the source side.](images/encdec_training_vs_inference.png)
T5 and BART are two well-known encoder-decoder models. T5 frames every task as text in, text out: the input might be translate English to German: the cute axolotl and the target der niedliche Axolotl. Its pretraining hides spans of text behind numbered placeholder tokens and trains the decoder to write the missing spans. BART is trained by corrupting a text, for example by hiding a token, and training the decoder to write the original text back.
![T5 and BART training recipes. T5: translate English to German: the cute axolotl goes text-to-text to der niedliche Axolotl. BART: the [noise] axolotl is denoised to the cute axolotl. T5 pretraining, span corruption: the <extra_id_0> axolotl becomes <extra_id_0> cute <extra_id_1>, and the decoder writes the sentinel back with the missing span. Both recipes train a causal decoder to generate target tokens from a source representation.](images/t5_bart_training_recipes.png)
Which family fits which task
A quick way to place any model is to ask what each position can attend to. If every input token can use both sides, the model is encoder-only. If each token can use only its prefix, it is decoder-only. If one stack reads a source and another writes a target, it is encoder-decoder.
| Family | Attention | Common training | Examples |
|---|---|---|---|
| Encoder-only | full, over the input | masked tokens | BERT, RoBERTa |
| Decoder-only | causal | next token | GPT models |
| Encoder-decoder | full, causal, cross | source to target | T5, BART |

The families overlap in what they can do. Encoder-only models are common for tasks that label or score a given input, such as classification, span extraction and retrieval. Encoder-decoder models are common for tasks that turn one text into another, such as translation and summarization. Many general-purpose language models released in recent years use decoder-only wiring. Those models also classify, translate and summarize by writing the answer as text.
Common mistakes
- Treating one model as the definition of its family. BERT is one encoder-only model, GPT is one decoder-only family, and T5 is one encoder-decoder model. The family is set by the attention pattern, not the name.
- Assuming encoders only classify and decoders only generate. Decoder-only models classify by generating a label, and encoder-decoder models can classify by writing the class as text.
- Putting a causal mask on cross-attention. The source is fully known before the decoder starts, so cross-attention needs only the source padding mask.
- Taking cross-attention keys and values from the decoder. The queries come from the decoder and the keys and values come from the encoder, which is why the score matrix is target length by source length.
- Expecting an encoder-only model to write long text. Masked language modeling trains it to fill in tokens inside a given input, not to continue text left to right.
Related concepts
How transformers work explains the layer that all three families share, and self-attention explained works through the attention formula with numbers. Encoder-decoder models explained covers the RNN version of the encoder-decoder idea, where the whole source had to fit into one vector until attention removed that limit. Static vs contextual embeddings shows why the contextual vectors in an encoder's output differ from fixed word vectors.
QuiddityML teaches the three families as separate concepts in the Intro to NLP track, each built step by step on the same three-token example. The exercises include choosing where cross-attention takes its queries, keys and values from. Others include spotting the bug in an encoder-decoder layer and typing the encoder-decoder generation loop from scratch.