Sub topic 2
How an Encoder-Decoder Model Works
This chapter assumes you know basic Python, how a neural network is trained with a loss function, and the idea of self-attention in a Transformer. It also assumes you have used PyTorch tensors or the Hugging Face Transformers library. Cross-attention, tokenisation, the training objective and decoding each get their own chapter. Here you will see how the pieces fit into one model.
The problem the design solves
Summarisation and translation both map one text to another. The output length is not fixed, it usually differs from the input length, and output words do not line up one-to-one with input words. A classifier produces one label. A tagger produces one label per input token. Neither fits.
An encoder-decoder model (also called a sequence-to-sequence or seq2seq model) splits the job in two:
- The encoder reads the whole source text and turns it into a sequence of context-aware vectors.
- The decoder writes the target text one token at a time. At each step it looks at the tokens it has already written and at the encoder's vectors.
The source is understood once. The target is produced step by step.
The encoder
The encoder is a stack of identical layers. Each layer has two parts:
- Bidirectional self-attention. Every source token can attend to every other source token, left and right. No causal mask is used. Because of this, the vector for "bank" can depend on a word that appears ten tokens later.
- A feed-forward network applied to each position, with residual connections and layer normalisation around both parts.
The encoder's output is a tensor of shape (batch, source_length, d_model). This tensor is the model's entire view of the source. The decoder never sees the original token IDs, only these vectors. A padding mask stops attention from reading padded positions in batches.
The decoder
The decoder is also a stack of layers, but each layer has three parts:
- Masked (causal) self-attention over the target tokens produced so far. Position t can attend only to positions up to t. This keeps the model from using future tokens during training and keeps training consistent with generation.
- Cross-attention. The queries come from the decoder. The keys and values come from the encoder's output. This is the only route by which source information reaches the decoder. The next chapter covers it in detail.
- A feed-forward network, as in the encoder.
On top of the last decoder layer sits a linear layer that maps each position's vector to one score per vocabulary item (the logits). A softmax turns those scores into a probability distribution over the next token.
Comparison with other Transformer designs
| Design | Attention over input | Typical use | Examples |
|---|---|---|---|
| Encoder only | Bidirectional | Classification, tagging, embeddings | BERT |
| Decoder only | Causal | Open-ended text generation | GPT-style models |
| Encoder-decoder | Bidirectional encoder, causal decoder, cross-attention between them | Tasks with a distinct source and target | BART, T5, MarianMT, mBART |
A decoder-only model can also do these tasks by putting the source and target in one sequence. The encoder-decoder design instead gives the source its own bidirectional representation and its own parameters. That fits well when a task has a clear source and a clear target.
Looking inside a real model
The following code uses t5-small to run the encoder alone, then drives the decoder by hand with greedy selection. It is slower than generate() because it recomputes the decoder over the whole prefix at each step. It shows the mechanics, though.
import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
model.eval()
source = "translate English to German: The house is wonderful."
inputs = tokenizer(source, return_tensors="pt")
# 1. The encoder runs once.
with torch.no_grad():
encoder_outputs = model.get_encoder()(**inputs)
print("encoder states:", tuple(encoder_outputs.last_hidden_state.shape))
# 2. The decoder runs once per generated token.
start_id = model.config.decoder_start_token_id
eos_id = model.config.eos_token_id
decoder_ids = torch.tensor([[start_id]])
for _ in range(30):
with torch.no_grad():
out = model(
encoder_outputs=encoder_outputs,
attention_mask=inputs["attention_mask"],
decoder_input_ids=decoder_ids,
)
next_id = out.logits[:, -1, :].argmax(dim=-1, keepdim=True)
decoder_ids = torch.cat([decoder_ids, next_id], dim=1)
if next_id.item() == eos_id:
break
print("logits shape:", tuple(out.logits.shape))
print(tokenizer.decode(decoder_ids[0], skip_special_tokens=True))Points to notice in the output and the code:
- The encoder states have shape
(1, source_length, 512). The source length is the number of subword tokens, including the end-of-sequence token that T5's tokeniser appends. - The logits have shape
(1, target_length_so_far, vocab_size). Only the last position is used to pick the next token. - The
encoder_outputsare computed once and reused at every step. Only the decoder is re-run. - The decoder starts from a special start token (
decoder_start_token_id) and stops when it produces the end-of-sequence token or reaches a length cap.
The same loop is what model.generate() does, plus caching, beam search and the length and repetition controls covered in the decoding chapter.
Training versus generation
The model is used in two different ways, and the difference explains most of its behaviour.
During training, the true target is known. The model receives the source and the target shifted right by one position: the decoder input is [start, y1, y2, ..., yn-1] and the labels are [y1, y2, ..., yn]. The causal mask lets all positions be computed in one parallel pass. Each position predicts the next token given the correct previous tokens. This is called teacher forcing. The loss is cross-entropy between the predicted distribution at each position and the true next token, averaged over non-padding positions.
During generation, no true target exists. The decoder must feed its own previous choices back in, so tokens come one at a time and cannot be parallelised across positions.
The next snippet shows the training side. Passing text_target makes the tokeniser produce labels, and the model builds the shifted decoder inputs internally.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
source = "summarize: The city council approved a plan to add 40 kilometres of bike lanes over three years."
target = "The council approved 40 km of new bike lanes."
batch = tokenizer(source, text_target=target, return_tensors="pt")
print("labels:", batch["labels"][0].tolist())
output = model(**batch)
print("loss:", output.loss.item())
print("logits:", tuple(output.logits.shape))The logits have one row per label token. The loss is a single number you can back-propagate.
The train/generate gap
Teacher forcing means the model never sees its own mistakes during training. At generation time one wrong token becomes part of the input for every later step. This mismatch is called exposure bias. In practice it contributes to drift, repetition and unfaithful continuations. Beam search, length limits and fine-tuning on realistic data reduce the effect but do not remove it.
Special tokens and where models differ
The architecture is shared, but the conventions around it are not. Wrong conventions give silently poor output, not errors.
| Model | Decoder start token | Notes |
|---|---|---|
| T5 | The pad token (ID 0) | The task is chosen by a text prefix such as `translate English to German:` |
| BART | The end-of-sequence token | Pretrained as a denoising autoencoder; summarisation checkpoints are fine-tuned on news |
| MarianMT | The pad token | One checkpoint per language pair, such as `Helsinki-NLP/opus-mt-en-de` |
| mBART | A language code token | Source and target languages are set through language codes |
Always read the values from model.config and the tokeniser instead of hard-coding them. Chapter 6 compares these model families.
Common errors
- Forgetting the attention mask in a hand-written loop. If you pass
encoder_outputswithout the matchingattention_mask, the decoder may attend to padding in batched inputs. Pass the mask whenever you pass encoder outputs. - Using the wrong start token. Hard-coding
0for BART gives the wrong start. Usemodel.config.decoder_start_token_id. - Passing decoder inputs and labels that disagree. If you supply
labels, the model createsdecoder_input_idsfor you by shifting them right. Supplying your owndecoder_input_idsas well is rarely needed and easy to get wrong. - Masking padding in labels. Padded label positions should be
-100so the loss ignores them. A data collator for seq2seq does this. Building labels by hand and leaving pad IDs in them trains the model to predict padding. - Ignoring source truncation. Tokenisers cut the source at a maximum length. Text beyond that limit is never seen by the encoder, so the output cannot reflect it. Long-input strategies are in a later chapter.
- Expecting fixed output length. Output length is decided by when the decoder emits end-of-sequence, within the limits you set. It is not tied to input length.
Costs to keep in mind
- Encoder cost grows with the square of the source length because of self-attention, and it is paid once per input.
- Decoder cost is paid once per generated token, and cross-attention at each step looks over the whole source. Long sources and long outputs both add time.
- Memory holds the encoder states plus the decoder's cached keys and values for every layer.
- Parameters are split between the two stacks, so an encoder-decoder with the same number of layers per stack has more parameters than an encoder-only model of one stack.
Summary
The encoder reads the source bidirectionally and produces one vector per source token. The decoder generates target tokens left to right, using causal self-attention on its own prefix and cross-attention on the encoder's vectors. Training uses teacher forcing with shifted labels and a cross-entropy loss. Generation feeds the model's own outputs back in. Special tokens differ across models, so read them from the configuration.
Exercise
In a batch of two sources, the second source is shorter and is padded. You call the decoder with encoder_outputs but omit attention_mask. What can go wrong, and what does the decoder's cross-attention do when the mask is supplied?
Show answer
Without the mask, cross-attention in the decoder can attend to the padded positions of the shorter source, which carry no information, and this can change the output for that example. With the mask supplied, padded source positions are excluded from the attention scores, so the decoder reads only the real source tokens.
Exercise
A label sequence is [y1, y2, y3, eos]. What is the decoder input during teacher-forced training, and why is a causal mask needed?
Show answer
The decoder input is the labels shifted right with the start token in front: [start, y1, y2, y3]. Position t predicts label t from the inputs up to and including position t. The causal mask is needed so that position t cannot look at later inputs. Those later inputs include the very token it must predict, and they would not exist at generation time.
Exercise
Why is generation slower per token than training, even though training processes the same number of target tokens?
Show answer
In training, the whole target is known, so all positions are computed in one parallel pass. In generation, each token depends on the previous choice, so the decoder must run once per token in sequence. Caching reduces the work per step but does not remove the sequential dependency.