Encoder and Decoder Models
A transformer stack can be used in three ways. They differ in their attention masks:
- Encoder-only (BERT): bidirectional self-attention, in which every token reads every token. The model outputs one contextual vector per input token. A downstream task uses these vectors as features.
- Decoder-only (GPT-3): causal self-attention, in which token reads tokens to . The model predicts the next token at every position and generates text one token at a time.
- Encoder-decoder (the original transformer, T5): an encoder reads the input with bidirectional attention. A decoder generates the output with causal self-attention, and its cross-attention reads the encoder’s output vectors.
Each type is pretrained with its own self-supervised task on unlabeled text:
- Masked language modeling (encoder): hide about of the input tokens and predict them from the rest. With the set of hidden positions, the loss is .
- Next-token prediction (decoder): the model factors the probability of a text as
and the loss is . A<start>token in front lets the model predict too.- Sequence to sequence (encoder-decoder): the same next-token loss on the output , given the input : .
| Type | Self-attention | Pretraining task | Typical use | Example |
|---|---|---|---|---|
| Encoder-only | bidirectional | masked tokens | classification, tagging, features | BERT |
| Decoder-only | causal | next token | text generation, prompting | GPT-3 |
| Encoder-decoder | bidirectional in, causal out, plus cross-attention | next output token given the input | translation, summarization | original transformer, T5 |
Intuition
An encoder is built to understand a whole input. Every token can use the words on both sides, which helps with tasks like tagging names or classifying a review. Such a model cannot generate text from left to right. During training each token saw its right context, which a generator does not have.
A decoder is built to continue a text. It predicts each token from the tokens before it, so it never needs the future. Generation feeds each predicted token back in. Prince adds a point about data. A decoder gets a loss term at every position. BERT gets one only at the hidden positions, about of them.
An encoder-decoder separates reading from writing. The encoder builds a representation of the source sentence. The decoder writes the target sentence and looks up the source through cross-attention. This is the RNN encoder-decoder with the RNNs replaced by attention.
All three need a lot of data, because transformers have a weak inductive bias. The Spring 2023 lecture 18 notes describe the solution. A model is pretrained once on a large amount of unlabeled text. It is then adapted to each task with a small labeled dataset. Many tasks share the same kind of data, so one pretrained model serves them all.
Properties
(BERT’s Masking Recipe) BERT selects of the tokens. It masks of those, replaces with random tokens and keeps .
The model must predict the original token at every selected position. If the selected tokens were always [MASK], the model would learn that unmasked tokens never need predicting. It could then neglect its representation of the visible tokens. The token [MASK] also never appears during fine-tuning. Random replacements force it to check every token, as in a denoising autoencoder. Unchanged tokens put a small amount of pressure on the visible tokens themselves. The Fall 2022 lecture 20 notes explain the split this way.
(BERT’s Second Task) BERT also predicts whether its second sentence really followed the first, using the output at a [CLS] token.
The input is [CLS] sentence A [SEP] sentence B. In half of the examples, B is the sentence that followed A in the text. In the other half, B is a random sentence. A small classifier on the [CLS] output predicts which case holds. The task is called next sentence prediction. It was meant to teach relations between sentences, for tasks such as question answering. Prince notes that it improves performance only slightly. The Spring 2023 lecture 21 notes mention doubts about its value in larger models.
(BERT’s Size) Prince describes BERT with blocks, width and heads, for about million parameters.
The vocabulary has tokens, and each head has queries, keys and values of size . The MLPs have a hidden width of . Pretraining uses inputs of up to tokens and batches of inputs. It runs for a million steps, about passes over a corpus of billion words. 7.2. Transformer Architecture counts the parameters.
(Using an Encoder Downstream) A pretrained encoder is either a fixed feature extractor or the starting point for training on the new task.
A small head goes on top of the encoder’s outputs. Prince gives three common heads:
- Text classification: a linear map from the
[CLS]output, such as the probability that a review is positive. - Word classification: a map from each token’s output to classes, such as person, place or no entity.
- Span prediction: two scores per token for the start and the end of an answer inside a passage.
In feature extraction, the encoder stays frozen and only the head trains. The Spring 2023 lecture 21 notes allow features from any layer, or an average of several layers. The Fall 2022 lecture 20 notes report that the second-to-last layer often works better than the last one. In fine-tuning, the whole network trains. The usual recipe first trains the head with the encoder frozen and then trains everything. A random head would otherwise send noisy gradients into the pretrained weights. 8.2. Transfer Learning covers these methods in general.
(GPT-3’s Size and Few-Shot Prompting) GPT-3 is a decoder with billion parameters, and it can learn a task from examples in its input.
Prince gives the details. GPT-3 has blocks of width , each with heads of size . It reads tokens. Some of its layers use a sparse form of attention. It trained on billion tokens with batches of million tokens. A large decoder can do many tasks without any gradient step. The input states a few solved examples and then a new question, and the model continues the text. The Spring 2023 lecture 20 notes call the case with no examples zero-shot and with a few examples few-shot. Prince warns that the results vary a lot. It is unclear how much the model extrapolates and how much it copies from training data. 9.3. In-Context Learning and 9.2. Prompt-Based Learning continue this topic.
(Training and Generating With a Decoder) A decoder trains on every position at once and generates one token at a time with a KV cache.
Prince explains why the mask is needed. If the whole sentence entered unmasked, the prediction of word could read word itself. The model would learn to copy. Setting the scores of later positions to removes that path. Then all predictions train in one forward pass. For generation, the model starts from <start> or a prompt, picks a next token, appends it and repeats. Earlier keys and values do not change, so the KV cache reuses them. Greedy decoding, sampling and beam search pick the tokens, as in 5.3.3. Sequence-to-Sequence Models.
(Which Encoder Layer the Decoder Reads) In the standard encoder-decoder, the cross-attention of every decoder block reads the encoder’s last layer.
The Fall 2022 lecture 19 notes describe two options. In the standard one, all decoder blocks read the final encoder output. This follows the autoencoder idea that the last layer holds the distilled input. The other option resembles a U-Net. Decoder blocks read encoder layers of matching depth, which gives them representations at several levels. Each decoder block has its own key and value maps for cross-attention. The decoder’s loss trains them to read the encoder’s output for its task.
Examples
(Easy) Three Masks
An encoder and a decoder each have tokens. In an encoder-decoder, a decoder with tokens reads an encoder with tokens.
Write the allowed pairs as / masks, and count the query-key pairs that each one computes. The encoder mask is all ones, , with pairs. The decoder mask is lower triangular: with pairs. The cross-attention mask is all ones and , with pairs. Every decoder token may read every encoder token, since the whole input is known. Only the decoder's self-attention needs a mask.
(Medium) What a Masked Sequence Trains On
BERT reads a sequence of tokens and applies its masking recipe.
How many positions are selected, and how many are masked, replaced and kept on average? How does the number of loss terms compare with a decoder? of , about positions. Of these, , about , become
[MASK]. About become random tokens, and about stay unchanged. The loss has about terms. A decoder reading the same tokens gets loss terms, one per position. That is times as many. BERT's terms each use both sides of the context, while the decoder's terms use only the left side.The model selects
(Hard) Choosing an Answer Span
A question-answering head on BERT gives start scores and end scores for the tokens of a passage. A softmax over each list gives start and end probabilities. A span from token to token needs , and its probability is the product of the two.
Find the most probable valid span. Why does picking the best start and the best end separately fail here? . The softmax of the end scores is . The best start is token and the best end is token . That span ends before it starts, so it is invalid.
The softmax of the start scores is
Among valid spans, the products are largest for
The answer is tokens to , with probability . The search over all pairs takes products for a passage of tokens. Separate choices fail because the two softmaxes do not know about each other. Only the search over pairs enforces .
See Also
- 7.2. Transformer Architecture, the block stack shared by all three types.
- 7.1. Attention, for bidirectional, causal and cross-attention.
- 5.3.3. Sequence-to-Sequence Models, the RNN encoder-decoder and the decoding rules.
- 8.1. Self-Supervised Learning, for pretext tasks such as masking and next-token prediction.
- 8.2. Transfer Learning, for feature extraction and fine-tuning.
- 9.1. LLMs, decoder-only models at large scale.
- 7.3. Token Embeddings, for contextual and static embeddings.