Modern AIEncoder, Decoder & Encoder-Decoder Models

Encoder, Decoder & Encoder-Decoder Models

Background
  • Sequence-to-sequence (seq2seq) architecture by Sutskever et al. (2014) used RNN encoders and decoders for machine translation
  • T5 (Raffel et al. 2020) reframed every NLP task as text-to-text, unifying diverse tasks under one encoder-decoder model
  • BART (Lewis et al. 2019) added denoising pre-training for encoder-decoder models
The Concept

Encoder-decoder models compress an input sequence to a latent representation (encoder), then decode it to an output sequence (decoder). Attention between encoder and decoder (cross-attention) lets the decoder selectively focus on relevant parts of the encoded input.

How it Links
  • Cross-attention in encoder-decoder connects to the attention mechanism and the original Transformer paper
  • T5 framing as text-to-text connects to instruction tuning and prompt design for LLMs
  • Connects to seq2seq tasks: translation, summarization, code generation, question answering
Concrete Example
Machine translation (English->French): the encoder reads the full English sentence into a rich contextual representation. The French decoder generates one word at a time, using cross-attention to look back at the English encoder output. When generating "chien" (dog), the decoder attends strongly to the English word "dog".
Learning outcomes
  • Place BERT, GPT, T5, and BART in the encoder / decoder / encoder-decoder taxonomy and name what each one masks during pretraining.
  • Explain BERT masked-language modelling and next-sentence prediction, and the role of the [CLS] token at fine-tuning time.
  • Explain why GPT-style autoregressive pretraining scales cleanly to in-context learning while BERT-style MLM does not.
  • Describe the T5 text-to-text framing and the BART denoising objective, and when an encoder-decoder still beats a decoder-only model.
  • Pick the right HuggingFace AutoModel head for a sequence-classification, generation, or seq2seq task and justify the choice.

TL;DR

TL;DR

Three flavours of Transformer dominate modern NLP, all built from the same blocks but pretrained on different objectives. Encoder-only (BERT [2], RoBERTa [3], DeBERTa [4]) reads bidirectionally and excels at classification and span extraction; the [CLS] token gives a single pooled vector for downstream heads. Decoder-only (GPT-1 [5], GPT-2 [6], GPT-3 [7] and the modern Llama / Mistral family) reads left-to-right with a causal mask and learns to generate, which scales into emergent in-context learning at GPT-3 scale. Encoder-decoder (the original Vaswani Transformer [1], T5 [8], BART [9]) keeps a separate encoder for the input and a separate decoder for the output, which still wins on translation and on tasks where the input and output are naturally distinct sequences. Decoder-only became the default for general-purpose LLMs because next-token prediction is a universal training signal that subsumes most other objectives at scale, but encoders are not dead: production search, classification, and retrieval pipelines still lean heavily on BERT-style models for cost reasons.

Intuition

The Transformer block from [1] is one architectural unit, but it can be used three ways depending on what you mask during training and inference. Think of the difference as what direction information flows:

  • Bidirectional. Every token sees every other token. Good for understanding a fixed input. Cannot generate by default because there is no left-to-right ordering to exploit.
  • Left-to-right (causal). Each token sees only the past. Naturally generative. Slightly worse at pure understanding tasks at small scale because right-context is unavailable, but the gap closes (and reverses) as models get bigger.
  • Encoder-decoder. The input runs through a bidirectional encoder, then a causal decoder generates the output one token at a time, with cross-attention to the encoder output. Best when the input and output are different shapes (translate English to French, summarize a document, transcribe audio).
The objective is the architecture

A BERT and a GPT with the same number of parameters and the same Transformer blocks differ in exactly two things: BERT has no causal mask, GPT does; BERT trains by predicting masked tokens from full context, GPT trains by predicting the next token from past context. Everything else is the same. The pretraining objective is what makes the model what it is, not the layer count or the residual layout. This is why “BERT vs GPT vs T5” is really a story about objectives, not about three unrelated networks.

A short visual taxonomy:

Transformer-based language modelsEncoder-only (BERT, RoBERTa, DeBERTa)Decoder-only (GPT, Llama, Mistral)Encoder-decoder (T5, BART, mT5)

The three inner regions are disjoint at the architecture level but overlap heavily in their building blocks: every one of them is a stack of pre-norm or post-norm Transformer blocks with multi-head attention, a position-wise FFN, and a residual stream. What differs is whether the attention mask is full (encoder), upper-triangular (decoder), or both at once (encoder-decoder), and what objective the gradient comes from.

BERT and the encoder-only family

BERT [2] took the encoder half of the original Transformer and asked: what if we pretrain it on raw text with a self-supervised objective, then fine-tune for downstream tasks? The result was the model that, in 2018, briefly held SOTA on essentially every natural-language understanding benchmark.

BERT: masked language modelling, NSP, and the [CLS] token

Architecture

BERT-base is a 12-layer Transformer encoder with d=768d = 768, H=12H = 12 heads, dff=3072d_{\mathrm{ff}} = 3072. BERT-large is 24 layers, d=1024d = 1024, H=16H = 16, dff=4096d_{\mathrm{ff}} = 4096. Both use post-norm LayerNorm placement (the original Vaswani recipe) and learned absolute positional embeddings up to nmax⁡=512n_{\max} = 512 tokens. The vocabulary is 30K WordPiece tokens with a [UNK] fallback.

Two special tokens shape every input: [CLS] is prepended to every sequence, [SEP] separates the two segments in a pair. So a single sentence becomes [CLS] tok1 tok2 ... [SEP]; a sentence pair (used for NLI, NSP, etc.) becomes [CLS] toks_A [SEP] toks_B [SEP]. A learned segment embedding (EAE_A or EBE_B) is added to the input embedding so the model can tell which segment a token belongs to.

Masked language modelling (MLM)

The headline pretraining objective. For each input sequence, randomly select 15% of the token positions and replace them with one of:

  • [MASK] 80% of the time. The most common case, and the one the loss is computed against.
  • A random vocabulary token 10% of the time. Forces the model not to over-rely on the literal [MASK] symbol, which never appears at fine-tuning time.
  • The original token 10% of the time. A “no-op” replacement that keeps the model honest about predicting the right answer even when the input looks unmodified.

Pass the whole sequence through the encoder. The loss is cross-entropy on the predicted distribution at the masked positions versus the original token id at those positions. Crucially every token attends bidirectionally to every other token, so the model is using both left and right context to recover the masked word. This is the bidirectionality that gives encoder-only models their understanding edge at small to mid scale.

The 15% rate, the 80/10/10 noise distribution, and the use of WordPiece are all from the original paper and have stuck around in every BERT-style derivative.

Next sentence prediction (NSP)

Pretraining sees pairs of segments. NSP trains a binary classifier on the [CLS] representation: was the second segment the actual continuation of the first segment in the corpus, or was it a randomly sampled paragraph from elsewhere? 50/50 split. NSP was supposed to teach the model about discourse-level coherence and was thought to help downstream NLI and QA.

RoBERTa [3] later showed NSP is essentially worthless: removing it has no measurable effect on downstream metrics and frees compute for more MLM. Modern BERT-style models (RoBERTa, DeBERTa, ELECTRA, MosaicBERT) drop NSP entirely.

Why [CLS] for classification

At fine-tuning time, the simplest classifier head on top of BERT is: take the encoder hidden state at position 0 (the [CLS] slot), feed it through a single linear layer, and classify. The intuition is that [CLS] was trained to aggregate information across the whole sequence (because of NSP and because attention from [CLS] can reach every other token), so its final hidden state is a sensible whole-sequence pooling.

This is a load-bearing convention more than a deep theoretical statement. You can equally well average-pool or max-pool across token hidden states, and many production retrieval models (Sentence-BERT) do exactly that. But [CLS] plus a linear head is what the original paper used and is the default in every HuggingFace AutoModelForSequenceClassification.

A subtle point: GPT does not need [CLS] because GPT does not classify by pooling, it classifies by generating the answer (“the sentiment is: positive”). Encoder-only models pool a sequence into a vector; decoder-only models continue the sequence with a verbal label.

What MLM learns that LM does not

MLM lets the model see both left and right context, so the representation at every position is informed by the whole sequence. This is strictly more information than left-to-right LM provides at any given position. Empirically this translates to an edge on tasks where understanding the input matters more than producing fluent text: span extraction (SQuAD), classification (GLUE), token labelling (NER, POS).

The price BERT pays is that it is not naturally generative. To generate, you would have to mask every position and predict autoregressively, which is awkward and slow. Decoder-only models give up the right context but get cheap, natural generation.

RoBERTa: the same model, trained right

RoBERTa [3] is BERT-large with a re-tuned recipe: 10x more pretraining data (160 GB vs 16 GB), longer training, larger batches, dynamic masking (re-mask every epoch instead of once), no NSP, no shorter-sequence ramp-up. Same architecture, no new ideas, just a more careful experimental sweep. It outperforms the original BERT by 5-10 points across GLUE and SQuAD, and the lesson stuck: BERT was undertrained. The same lesson would re-emerge for LLMs four years later (see Scaling Laws & Training).

DeBERTa: disentangled attention

DeBERTa [4] introduces two refinements:

  1. Disentangled attention. Each token is represented by two vectors: a content vector HH and a position vector PP. The attention score is computed as a sum of four cross-product terms, Hi⊤Hj+Hi⊤Pj+Pi⊤Hj+Pi⊤PjH_i^\top H_j + H_i^\top P_j + P_i^\top H_j + P_i^\top P_j, instead of one. The intuition: content-content interaction is fundamentally different from position-content interaction, so let the model learn them separately. In practice the diagonal terms (Pi⊤PjP_i^\top P_j) are dropped or simplified.
  2. Enhanced mask decoder. At pretraining, the absolute positions of masked tokens are injected only at the very last decoding layer (not as input embeddings). This prevents the model from “cheating” by exploiting absolute-position artefacts during MLM.

The wins are modest but consistent: DeBERTa-v3 sits on top of the SuperGLUE leaderboard for several years.

The GPT family and decoder-only models

Where BERT keeps the encoder half of the original Transformer, GPT keeps the decoder half (without the cross-attention sublayer). Pretraining is the simplest possible language-model objective: maximize the probability of the next token given the past.

LLM(θ)=−∑t=1nlog⁡pθ(xt∣x<t).\mathcal{L}_{\mathrm{LM}}(\theta) = -\sum_{t=1}^{n} \log p_\theta(x_t \mid x_{<t}).

The causal mask in self-attention enforces that position tt can only attend to positions 1,…,t−11, \dots, t-1, so the same forward pass produces nn independent loss terms (one per position) that the optimizer sums.

  1. 2018GPT-1: 117M params, BookCorpus pretrain + supervised fine-tunepaper

    Radford et al. show that pretraining a Transformer decoder on raw text and then fine-tuning the same model on downstream tasks beats every earlier non-pretrained baseline. The recipe: pretrain on next-token prediction, fine-tune the whole model with a small classification head on the final hidden state of the last token.

  2. 2019GPT-2: 1.5B params, WebText pretrain, zero-shot framingpaper

    Radford et al. push the scale 13x and show the model can do many tasks (translation, QA, summarization) with zero gradient updates by phrasing the task in natural language at the prompt. The phrase "language models are unsupervised multitask learners" enters the field.

  3. 2020GPT-3: 175B params, in-context learning emergespaper

    Brown et al. scale 100x further. The headline result: with a few worked examples in the prompt (few-shot prompting), GPT-3 matches or beats fine-tuned smaller models on many benchmarks, with no parameter updates. In-context learning becomes the new transfer-learning interface.

  4. 2022InstructGPT and RLHFsystem

    Ouyang et al. fine-tune GPT-3 on human-written instructions and align it with reinforcement learning from human feedback. This produces ChatGPT, which makes prompted instruction-following the dominant interaction pattern.

  5. 2023Llama 1, Llama 2, Mistral 7Brelease

    Open-weight decoder-only models match closed GPT-3.5 quality at 7B-70B scale, on the same recipe (causal LM, RoPE positions, pre-norm, RMSNorm, GQA at 70B). The decoder-only template is now industry default for general-purpose LLMs.

What changes from GPT-1 to GPT-3 architecturally

Almost nothing. All three are pre-norm (GPT-1 used post-norm; GPT-2 onward switched to pre-norm) decoder-only Transformers with causal self-attention, learned absolute positional embeddings up to nmax⁡n_{\max} (1024 for GPT-2, 2048 for GPT-3), and a 50K BPE tokenizer. What changes is depth, width, and pretraining tokens:

  • GPT-1: 12 layers, d=768d = 768, 117M params, 5 GB pretraining (BookCorpus).
  • GPT-2: 48 layers, d=1600d = 1600, 1.5B params, 40 GB pretraining (WebText).
  • GPT-3: 96 layers, d=12288d = 12288, 175B params, 300B-token pretraining (filtered Common Crawl + WebText2 + books + Wikipedia).

The 1500x compute increase from GPT-1 to GPT-3 is the entire story. New capabilities (zero-shot prompting, then few-shot in-context learning) appear at scale without any architecture change. Brown et al. [7] demonstrate this directly: a 13B GPT-3 still does few-shot poorly; a 175B GPT-3 does it well; the only thing different is parameter count and training compute.

Why decoder-only won for general-purpose LLMs

Three reasons, in roughly increasing order of importance:

  1. Generation is the universal interface. A decoder can do classification by generating a label, span extraction by generating the span, summarization by generating the summary, translation by generating the target language. An encoder cannot generate without surgery. Once you commit to “the user asks a natural-language question and the model writes a natural-language answer”, decoder-only is the natural shape.
  2. Causal LM gives you nn training signals per sequence. A length-nn sequence produces nn independent next-token loss terms in one forward pass. MLM produces 0.15nn loss terms (15% of positions are masked). At equal compute, causal LM trains roughly 6x more efficiently per parameter, which compounds at scale.
  3. In-context learning emerges from scale. GPT-3 [7] showed that a sufficiently large autoregressive language model develops the ability to learn new tasks from worked examples in the prompt, with no gradient updates. This is the property that turned LLMs from “fine-tunable embeddings” into a reasoning interface, and it appears in causal LMs, not in MLMs. The reason is mechanical: the prompt is the training distribution for the predicted continuation, so a sufficiently capable next-token predictor must implicitly run a Bayesian inference over the prompt to do well.

A useful heuristic: if your task is “given an input, label or extract” and your latency budget is tight, encoder-only beats decoder-only on quality per dollar. If your task is “given a description, produce open-ended text” or “answer arbitrary questions”, decoder-only is the only sane choice.

T5 and the encoder-decoder family

T5 [8] takes the third architectural slot: the full Vaswani encoder-decoder. Its big idea is text-to-text framing: every NLP task is reformulated as “input text in, output text out”, with a task-specific prefix.

"translate English to German: That is good."   ->  "Das ist gut."
"cola sentence: He are at home."                ->  "not acceptable"
"summarize: <long article>"                     ->  "<short summary>"
"squad question: ... context: ..."              ->  "<answer span>"

A single model, a single training objective, and a uniform interface. No task-specific heads.

Pretraining: span corruption

T5 does not use MLM. Instead it uses span corruption: select random spans of consecutive tokens, replace each span with a sentinel token (<X>, <Y>, …), and train the decoder to produce <X> <span_x_tokens> <Y> <span_y_tokens> ... as the target. Roughly: the encoder sees the corrupted input, the decoder produces the missing pieces in order.

input  : Thank you <X> me to your party <Y> week.
output : <X> for inviting <Y> last <Z>

Span corruption sits between BERT MLM (mask single tokens, predict in place) and BART denoising (corrupt the input in many ways, reconstruct the original). It naturally produces variable-length outputs, which matches the encoder-decoder shape.

Architecture details

T5 keeps a few choices that distinguish it from BERT and GPT:

  • Relative positional bias. No absolute embeddings; instead, the attention score gets a learned bias indexed by a bucketed relative offset. This is a precursor to RoPE and ALiBi [1].
  • Pre-norm with RMSNorm. Pre-norm placement (LayerNorm inside the residual), with a simplified RMSNorm variant that skips the mean-centering. RMSNorm is now the modern default in LLMs.
  • No bias terms in attention or FFN linears. A small parameter saving that compounds at scale and slightly improves training stability.
  • Encoder-decoder split. The encoder is bidirectional over the input; the decoder is causal over the output and has cross-attention to the encoder output.

T5 is trained at sizes from T5-Small (60M) up to T5-XXL (11B). The 11B variant is the model that fine-tunes well on most NLP benchmarks and is still a credible choice in 2024 for translation, summarization, and structured-output tasks.

BART: denoising sequence-to-sequence

BART [9] is the same encoder-decoder architecture trained on a richer denoising objective. The input is corrupted by an arbitrary noising function (token masking, token deletion, sentence permutation, document rotation, text infilling), and the decoder produces the original document. Token infilling alone is comparable to T5 span corruption; the full set of noising operations gives BART slightly stronger performance on summarization and translation than T5 at matched scale.

The mental model: BART is to T5 what RoBERTa is to BERT. Same architecture, more careful pretraining, slightly better numbers.

The four-way comparison

ModelArchitecturePretraining objectivePretrain tokensDecoding styleBest downstream taskParam-efficient use
BERT-baseEncoder-only, 12L, 110MMasked LM (15% masked) + NSP, bidirectional self-attn~ 3.3B (BookCorpus + Wikipedia)No generation; pool [CLS] for classificationSentence/span classification (GLUE, SQuAD), token labelling (NER, POS)Adapter / LoRA fine-tuning of attention layers; freeze embeddings
GPT-3Decoder-only, 96L, 175BCausal next-token LM, no auxiliary loss~ 300B (Common Crawl, books, Wikipedia)Autoregressive top-k / top-p / temperature samplingOpen-ended generation, instruction following, in-context learningPrompt engineering at first; LoRA / QLoRA on attention projections; full fine-tune is rare
T5-XXLEncoder-decoder, 24+24L, 11BSpan corruption (15% spans replaced by sentinels)~ 1T (C4)Encoder one-shot, then autoregressive decode with cross-attentionTranslation, summarization, structured prediction; any task with input/output mismatchPrefix tuning on the encoder; LoRA on cross-attention queries
BART-largeEncoder-decoder, 12+12L, 406MDenoising (mask, delete, permute, rotate, infill); reconstruct original~ 160 GB (CC-News + BookCorpus + Wikipedia + OpenWebText)Encoder one-shot, then autoregressive decodeSummarization (CNN/DailyMail SOTA at release), translation, QA generationLoRA on cross-attention; prefix tuning

How to pick the right model

The selection rule is small enough to memorize:

  • Classification, span extraction, retrieval (does the embedding live in a vector database?). Use an encoder-only model. BERT-base or RoBERTa-base for cheap; DeBERTa-v3 if you can pay; specialized retrieval models like E5 or BGE for embedding tasks.
  • Open-ended generation, chat, instruction following, code, agents. Use a decoder-only model. The 7B-13B class (Llama-3-8B, Mistral-7B, Qwen2-7B) covers most application work; 70B+ for hard reasoning; closed APIs (GPT-4, Claude) for state of the art.
  • Translation, summarization, audio-to-text, OCR-to-text, any task where input and output are different shapes. Use an encoder-decoder. T5-XXL or BART for text; Whisper for audio; specialized T5 derivatives (mT5 for multilingual, ByT5 for byte-level) where they apply.
  • Structured extraction with hard format constraints. Decoder-only with constrained decoding (JSON schema, grammar-guided sampling) usually beats fine-tuned encoder heads now, but encoder + CRF or T5 + structured decoder are still competitive for high-throughput batch jobs.
Encoder-only is alive and well in production

The “decoder-only ate everything” narrative is true for general-purpose chatbots and code assistants, but it overlooks how much of the world’s NLP compute still runs through encoder-only models. Google Search ranks queries with a BERT-derived model (publicly disclosed in 2019). Most production retrieval pipelines (semantic search, RAG retrievers, vector databases) embed text with BERT-class encoders because dense embeddings are cheap, the model fits on a CPU, and quality per dollar is unbeatable for “give me one vector per document”. When you read “BERT is dead”, read it as “BERT is no longer the SOTA general-purpose model”; it remains alive as the workhorse of search and retrieval.

A from-the-API view

Three idiomatic snippets, one per archetype, using HuggingFace transformers:

python
# Encoder-only: classify sentiment with a fine-tuned BERT.
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

ckpt = "distilbert-base-uncased-finetuned-sst-2-english"
tokenizer = AutoTokenizer.from_pretrained(ckpt)
model = AutoModelForSequenceClassification.from_pretrained(ckpt)
model.eval()

texts = ["The food was incredible.", "The service was terrible."]
inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True)
with torch.no_grad():
  logits = model(**inputs).logits

probs = torch.softmax(logits, dim=-1)
labels = ["NEGATIVE", "POSITIVE"]
for text, p in zip(texts, probs):
  pred = int(p.argmax())
  print(f"{labels[pred]:>9s}  ({p[pred]:.2%})  {text}")
AutoModelForSequenceClassification puts a single linear layer on top of the [CLS] hidden state of a BERT-class encoder. The logits shape is (batch, num_labels). For zero-shot classification on a fresh task, use AutoModelForZeroShotClassification with a pretrained NLI head.

Pitfalls

Confusing MLM with denoising

MLM (BERT) masks single tokens at fixed positions and predicts them in place: the model output at position ii is a distribution over the vocabulary for token ii. Span corruption (T5) and denoising (BART) corrupt spans or whole structures and predict the original sequence as a separate decoder output, with the encoder-decoder shape doing the work. They are not the same objective and not interchangeable: an encoder-only model can do MLM but not span corruption, and an encoder-decoder can do span corruption but not in-place MLM in a useful way.

Treating GPT logits as bidirectional

A decoder-only model has a causal mask. Its hidden state at position ii depends only on tokens 1,…,i1, \dots, i. If you take a GPT and try to use the hidden state at the last token as a sentence embedding (the “EOS pooling” recipe), you do get something usable, but the embedding has not seen the right context that a BERT [CLS] embedding would. For dense retrieval and classification you want bidirectional context, which means BERT or a bidirectional fine-tune of the decoder (the GPT-Neo-encoder-style hack).

A symptom of this confusion: people compute cosine similarity between GPT-2 mean-pooled embeddings and find very low quality. The fix is to use a model trained for embeddings (E5, BGE, OpenAI text-embedding-3, voyage) or a BERT-class encoder, not to mean-pool GPT-2.

The pretrain-fine-tune mismatch in BERT

[MASK] only appears at pretraining. It never appears at fine-tuning or inference. This train-test mismatch is one reason BERT replaces 10% of the masked positions with random tokens and another 10% with the original token: to force the model to make a sensible prediction even when the input does not contain the special token. This is also why ELECTRA’s “replaced token detection” objective beats BERT MLM at the same compute budget: ELECTRA never inserts a special token, so train and test distributions match.

If unsure, default to decoder-only

For a brand-new project where you do not know yet which task family will dominate, default to a decoder-only model in the 7B-13B range (Llama-3, Mistral, Qwen). The reason is portfolio: a decoder-only LLM with a strong instruction-tuned variant can do classification (via prompting), generation, retrieval (via the embedding side-channel of E5-Mistral or NV-Embed), and agent loops. An encoder-only model can only classify and embed; an encoder-decoder is great at translation but bad at chat. Switch back to a specialized encoder when you have measured the cost / latency tradeoff and a BERT is genuinely cheaper.

Pop quiz

Check yourself
Score: 0 / 5(0 answered)
  1. 1. Why does BERT use a [CLS] token while GPT does not?
  2. 2. Which of the following is NOT a difference between BERT MLM and T5 span corruption?
  3. 3. RoBERTa improves over BERT primarily by:
  4. 4. Why is causal next-token prediction more compute-efficient per parameter than MLM at the same sequence length?
  5. 5. When is an encoder-decoder still the right choice over a decoder-only LLM?

Interview Q&A

Why does BERT need a [CLS] token, but GPT does not?phone

BERT is an encoder-only model. It pools the whole sequence into a single hidden state at the [CLS] position, then a linear classification head reads that vector. The [CLS] slot is trained by next-sentence prediction (and by MLM through indirect supervision) to aggregate sentence-level information, which makes it a sensible pooling point. Without [CLS], you would have to invent a pooling rule (mean, max, attention-weighted) at fine-tuning time.

GPT is a decoder-only model. It does not classify by pooling; it classifies by generating. To do sentiment, you put the prompt “The sentiment of the sentence "…\dots" is:” and read the next-token distribution over {positive, negative}. The classification “head” is the existing language-modelling head, so any token’s hidden state can drive the prediction. There is nothing for [CLS] to do.

A subtler point: a [CLS]-style pooling token is occasionally added to decoder-only models for embedding tasks (E5-Mistral, NV-Embed), but it is not part of the original GPT architecture. When you see a “[CLS]-like” token in a decoder model, it is for a custom embedding objective, not for the LM pretraining itself.

Argue that next-token prediction subsumes MLM under enough scale.onsite

The argument has two pieces.

Information-theoretic. Causal LM optimizes ∑tlog⁡pθ(xt∣x<t)\sum_t \log p_\theta(x_t \mid x_{<t}). MLM optimizes ∑t∈Mlog⁡pθ(xt∣x∖t)\sum_{t \in M} \log p_\theta(x_t \mid x_{\setminus t}) for a randomly chosen masked set MM. The conditional in causal LM uses only the past; MLM uses past and future. At small scale this asymmetry helps MLM: predicting “the cat sat on the ___” is much easier with the right context than without it, and BERT will get a tighter representation per parameter than GPT will.

But the optimal causal-LM solution is the true conditional distribution p(xt∣x<t)p(x_t \mid x_{<t}), which by Bayes contains all information about the joint distribution that the past constrains. As the model and data grow, the causal LM’s representation becomes a sufficient statistic of the past for predicting any future quantity, including any masked token’s context-conditional distribution. Concretely, p(xt∣x<t)p(x_t \mid x_{<t}) is enough to compute p(xt∣x∖t)p(x_t \mid x_{\setminus t}) via integration over the future, which a sufficiently capable model effectively learns to approximate inside its activations.

Empirical. At scale this prediction holds. Causal LMs above ∼30\sim 30B parameters match or beat encoder-only models of any size on classification benchmarks (GLUE, SuperGLUE) when prompted appropriately. The 175B GPT-3 zero-shot beats a 340M BERT-large fine-tuned on many tasks [7]. The advantage of bidirectional context shrinks as the model grows, because the model’s internal representations become rich enough to recover the right context implicitly.

Caveat. “At enough scale” is doing real work in this argument. At 1B parameters, a fine-tuned BERT-large still beats a zero-shot GPT-2 on most NLU benchmarks. The crossover is somewhere in the 10-100B range, depending on the task family. For embedding and retrieval, encoders still win on quality per dollar at any scale, because the task does not need generation and the bidirectional context is structurally useful.

Explain the prefix-LM unification and why some people see encoder-decoder, decoder-only, and encoder-only as one architecture.staff

Setup. A prefix language model is a single Transformer with two attention masks stitched together: tokens in the prefix attend bidirectionally to other prefix tokens, and tokens in the continuation attend causally (only to the prefix and to earlier continuation tokens). The training objective is next-token prediction on the continuation, with no loss on the prefix.

In one diagram: the attention mask is a block matrix where the prefix block is full ones, the continuation-on-prefix block is full ones, the continuation-on-continuation block is upper-triangular, and the prefix-on-continuation block is zeros.

Reductions. Three special cases:

  • Empty prefix. Pure causal decoder-only. The mask is upper-triangular everywhere.
  • Empty continuation. No generation; the model is just a bidirectional encoder over the prefix. With an MLM objective on the prefix, this is BERT.
  • Prefix = source, continuation = target, with cross-attention between them. Encoder-decoder. The “cross-attention” is actually just full attention from continuation to prefix in the prefix-LM view; running the prefix through a separate stack first is an optimization, not a fundamental change.

So encoder-only, decoder-only, and encoder-decoder are three points on a continuum parameterized by the attention-mask structure and where the loss is computed. T5 and UL2 explicitly use this view in their pretraining: UL2 trains a single prefix-LM-shaped Transformer with three mixed objectives (R-denoiser like T5, S-denoiser like causal LM, X-denoiser an extreme version of span corruption) and shows it matches the best of each individual style.

Why this matters. In practice, the prefix-LM view explains why instruction tuning works: the system prompt + user message is the prefix (bidirectional context the model can attend to fully), and the assistant’s reply is the continuation (causal generation, conditioned on the full prefix). A decoder-only LLM running with KV cache is doing exactly this, with the attention mask compiled into the implementation but not exposed as a knob. UL2 and PaLM-2 expose the mask as a training-time choice and get to mix and match objectives.

The big recent result: at 100B+ parameters, the architectural distinction collapses. A well-trained decoder-only with instruction tuning matches an encoder-decoder on translation; a well-prompted decoder-only matches an encoder on classification. The objective and the recipe matter; the mask matters less than people thought in 2018-2020.

Build it yourself

A weekend project that fits all three archetypes on the same compute:

  1. Pretrain a tiny BERT (4 layers, d=128d = 128, 2 heads) on 10410^4 Wikipedia sentences with MLM. Confirm the loss at masked positions descends below log⁡V\log V.
  2. Pretrain a tiny GPT (same shape) on the same data with causal LM. Compare the two loss curves at equal compute - the causal LM trains faster per step and gets to a lower bits-per-character.
  3. Pretrain a tiny T5 (2-layer encoder + 2-layer decoder, same total parameter count) with span corruption. Evaluate all three on a held-out classification task by adding a lightweight head and fine-tuning for 200 steps.
  4. The pattern you should see: BERT wins on classification at this tiny scale; T5 wins on translation between two artificial token grammars; GPT wins on free-form continuation. This is the same ranking you would see at 7B scale, just with much wider gaps.

References

  1. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., and Polosukhin, I. (2017). Attention Is All You Need. NeurIPS 2017. arXiv:1706.03762
  2. Devlin, J., Chang, M.-W., Lee, K., and Toutanova, K. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL 2019 (arXiv preprint 2018). arXiv:1810.04805
  3. Liu, Y., Ott, M., Goyal, N., Du, J., Joshi, M., Chen, D., Levy, O., Lewis, M., Zettlemoyer, L., and Stoyanov, V. (2019). RoBERTa: A Robustly Optimized BERT Pretraining Approach. arXiv preprint. arXiv:1907.11692
  4. He, P., Liu, X., Gao, J., and Chen, W. (2020). DeBERTa: Decoding-enhanced BERT with Disentangled Attention. ICLR 2021 (arXiv preprint 2020). arXiv:2006.03654
  5. Radford, A., Narasimhan, K., Salimans, T., and Sutskever, I. (2018). Improving Language Understanding by Generative Pre-Training. OpenAI technical report. https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf
  6. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., and Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI technical report. https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf
  7. Brown, T. B., Mann, B., Ryder, N., Subbiah, M., Kaplan, J., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G., Askell, A., Agarwal, S., Herbert-Voss, A., Krueger, G., Henighan, T., Child, R., Ramesh, A., Ziegler, D. M., Wu, J., Winter, C., Hesse, C., Chen, M., Sigler, E., Litwin, M., Gray, S., Chess, B., Clark, J., Berner, C., McCandlish, S., Radford, A., Sutskever, I., and Amodei, D. (2020). Language Models are Few-Shot Learners. NeurIPS 2020. arXiv:2005.14165
  8. Raffel, C., Shazeer, N., Roberts, A., Lee, K., Narang, S., Matena, M., Zhou, Y., Li, W., and Liu, P. J. (2019). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. JMLR 2020 (arXiv preprint 2019). arXiv:1910.10683
  9. Lewis, M., Liu, Y., Goyal, N., Ghazvininejad, M., Mohamed, A., Levy, O., Stoyanov, V., and Zettlemoyer, L. (2019). BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension. ACL 2020 (arXiv preprint 2019). arXiv:1910.13461