QuiddityML

By · 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:

Three transformer arrangements. Encoder-only: a stack of encoder layers with no causal mask, so every input position uses every other input position. Decoder-only: a stack of decoder layers with a causal mask, so a position uses itself and earlier positions only. Encoder-decoder: an encoder stack and a decoder stack joined by cross-attention, so source information moves one way, into the decoder.

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.

Attention access patterns. The arithmetic is the same in all three, and the mask decides which entries survive. Encoder self-attention: every pos 0 to pos 2 cell is allowed, and Q, K and V all come from the input positions. Decoder self-attention: the cells above the diagonal are blocked, and Q, K and V all come from the target positions. Cross-attention: target positions 0 and 1 use all three source positions, with Q from the decoder and K and V from the encoder source representations.

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.

Encoder-only: use the whole input. The tokens the, cute, axolotl at positions 0 to 2 go through encoder self-attention, where every real input position may use every other one, and give H with rows h_the, h_cute and h_axolotl, of shape 1 x 3 x 6. Decoder self-attention, shown for comparison, lets a target position use earlier positions only. H feeds tasks such as classification, span prediction and retrieval.

Self-attention weights over the, cute and axolotl: 0.42, 0.33, 0.25 for the, 0.20, 0.50, 0.30 for cute and 0.31, 0.28, 0.41 for axolotl, with every row summing to 1.00. O = A V turns the 1 x 3 x 3 weights and the 1 x 3 x 6 values into one output vector of length 6 per query position.

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.

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.

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.

Causal attention weights for T = 3. M_causal has 0 on and below the diagonal and -inf above it. After softmax, A has rows 1.00, 0.00, 0.00 for pos 0, 0.37, 0.63, 0.00 for pos 1 and 0.18, 0.24, 0.58 for pos 2. Every row of A sums to 1, 0.63 and 0.58 come from QKᵀ, and row 0's 1.00 is forced by the mask.

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.

Generation repeats the same model, one token per run, appended to the prefix each time. Run 1: BOS goes through the decoder stack and vocabulary head and gives the. Run 2: BOS, the gives cute. Run 3: BOS, the, cute gives axolotl. Generation stops on an end-of-sequence token or at a maximum number of new tokens.

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.

Encoder-decoder: condition on a source. The English source the cute axolotl goes through the encoder and becomes the source representations. Cross-attention connects them to the decoder, which writes the German target BOS der niedliche Axolotl left to right while staying conditioned on the encoded source. Tasks that fit this shape: translation, summarization, rewriting, extraction as text, and question answering from a passage.

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$.

Cross-attention connects the decoder to the encoder. The source sequence the cute axolotl goes through the encoder stack and gives E of shape 1 x S x d_model with S = 3. In the decoder stack, each layer runs LayerNorm and masked self-attention, then LayerNorm and cross-attention that reads E, then LayerNorm and the feed-forward network, each followed by a residual add. D goes through W_Q to give Q of shape 1 x T x d_k, and E goes through W_K and W_V to give K and V of shape 1 x S x d_k and 1 x S x d_v.

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.

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.

Finish the decoder layer. 1 LayerNorm, masked self-attention, residual add. 2 LayerNorm, cross-attention from encoder output E, residual add. 3 LayerNorm, feed-forward network, residual add. The target stream of T rows of width d_model passes through the three sublayers, and E with S source rows feeds the cross-attention.

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.

Step 3 masks: source padding only. Target self-attention over the prefix BOS, der allows BOS to use BOS and der to use both, and blocks BOS from der. Cross-attention from BOS and der to the source positions h0, h1, h2 for the, cute, axolotl allows all three and blocks h3, which is PAD. M_tgt is the causal mask plus target padding if needed, and M_src is the source padding mask.

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.

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.

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

Architecture before brand names: the first question is what each position may attend to. Encoder-only, with examples BERT, RoBERTa and DistilBERT: every input position may attend to every other one. Decoder-only, with GPT as the example: earlier positions are allowed and later ones are blocked by the causal mask. Encoder-decoder, with examples T5 and BART: an encoder processes the source the cute axolotl and the decoder reads it through cross-attention.

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

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.