BERT vs. GPT: Encoders, Decoders, and Their Impact on NLP

How BERT and GPT use the same Transformer block differently: attention masks, training objectives, what each is good at, and how to choose today.

Generative AI

BERT and GPT appeared within a few months of each other in 2018, and both are built from the same Transformer block. One became the default way to classify, tag and search text. The other grew into the chat models most people now think of as AI. The difference between them comes down to one design decision: which tokens each position is allowed to look at, and what the model is asked to predict during training.

The previous article built a small GPT-style decoder in PyTorch, and The Transformer Architecture: Self-Attention Explained covered the attention mechanism and its masks. This article puts the two families side by side: how each is trained, what each produces, what they changed in natural language processing, and how to decide which one a given job needs.

One block, two directions

Both models stack the same layer: multi-head self-attention followed by a feed-forward network, each wrapped in a residual connection and a LayerNorm. Strip away the training details and the main structural difference is the attention mask.

  • An encoder such as BERT uses no causal mask. Every token attends to every other token, left and right. The output is one context-aware vector per input token.
  • A decoder such as GPT uses a causal mask. Each token attends only to itself and the tokens before it. The output at each position is a prediction of the next token.

The short script below prints which positions each token can see under the two masks. An x means the row token can attend to the column token.

tokens = ["the", "bank", "raised", "rates"]
n = len(tokens)

def show(name, allowed):
    print(name)
    print("        " + " ".join(f"{t:>6}" for t in tokens))
    for i, t in enumerate(tokens):
        row = " ".join(f"{'x' if allowed(i, j) else '.':>6}" for j in range(n))
        print(f"{t:>6}  {row}")
    print()

show("Encoder (BERT): every token sees every token", lambda i, j: True)
show("Decoder (GPT): token i sees positions 0..i", lambda i, j: j <= i)
Encoder (BERT): every token sees every token
           the   bank raised  rates
   the       x      x      x      x
  bank       x      x      x      x
raised       x      x      x      x
 rates       x      x      x      x

Decoder (GPT): token i sees positions 0..i
           the   bank raised  rates
   the       x      .      .      .
  bank       x      x      .      .
raised       x      x      x      .
 rates       x      x      x      x

Look at the row for “bank”. In the encoder it can see “rates”, which is the word that tells you this is a financial bank rather than a river bank. In the decoder it cannot, because “rates” comes later. That is the whole trade: the encoder builds better representations of text it already has, and the decoder can generate text it does not have yet, because nothing it computes depends on the future.

flowchart LR
    subgraph ENC["Encoder: BERT"]
        direction TB
        E1["Full input sentence"] --> E2["Bidirectional attention"]
        E2 --> E3["One vector per token"]
        E3 --> E4["Task head: label, tag, span"]
    end
    subgraph DEC["Decoder: GPT"]
        direction TB
        D1["Prompt so far"] --> D2["Causal attention"]
        D2 --> D3["Next-token probabilities"]
        D3 --> D4["Sample, append, repeat"]
    end

How BERT is trained

BERT, from Devlin and colleagues at Google, is short for Bidirectional Encoder Representations from Transformers. Bidirectional attention creates a training problem: if every token can see every other token, the model cannot be asked to predict a word that is sitting in plain view. BERT solved this with two pretraining tasks.

Masked language modelling

About 15% of the input tokens are selected for prediction. Of those, 80% are replaced with a special [MASK] token, 10% with a random token, and 10% are left unchanged. The model has to predict the original token at each selected position, using context from both sides.

The 80/10/10 split exists because [MASK] never appears in real text. If every selected token were masked, the model would learn that only masked positions need careful prediction, which does not match how it is used after training. Mixing in random and unchanged tokens means the model has to build a good representation of every position.

Next sentence prediction

The second task gives the model two segments, A and B, and asks whether B actually followed A in the source text or was picked at random. The input format puts a [CLS] token at the start and a [SEP] token after each segment. The final vector at [CLS] feeds the yes/no prediction, which is why that position became the standard summary vector for classification.

Later work questioned this second task. RoBERTa (Liu and colleagues, 2019) dropped it, trained longer on more data with masks chosen fresh each time, and matched or beat BERT on the benchmarks it reported.

Sizes and data

The original release had two sizes. BERT-base has 12 layers, a hidden size of 768 and 12 attention heads, about 110 million parameters. BERT-large has 24 layers, a hidden size of 1,024 and 16 heads, about 340 million parameters. Both used a WordPiece vocabulary of about 30,000 tokens, a maximum input length of 512 tokens, and were pretrained on BookCorpus and English Wikipedia.

Why does BERT use masked language modelling instead of next-token prediction?

  • Masked prediction needs less training data
  • Next-token prediction only works with WordPiece vocabularies
  • With bidirectional attention every token can already see the next word, so the task would be trivial

Correct! Hiding the target tokens is what makes a prediction task meaningful when attention runs in both directions.

How GPT is trained

GPT, from Radford and colleagues at OpenAI, stands for Generative Pre-trained Transformer. Its objective is the one from the RNNs to Transformers article: predict the next token at every position. The causal mask makes this valid, and it is efficient, because one sequence of length T gives T training examples in a single forward pass. BERT gets a learning signal from only the 15% of positions it selected, which is one reason the ELECTRA paper (Clark and colleagues, 2020) proposed a more sample-efficient alternative for encoders.

The GPT line changed how the models were used more than how they were built:

  • GPT (2018) was a 12-layer decoder pretrained on BookCorpus. Like BERT, it was then fine-tuned separately for each downstream task, with a small task-specific head.
  • GPT-2 (2019) scaled to 1.5 billion parameters and showed that a large enough language model could attempt tasks with no fine-tuning, just from the way the input was phrased.
  • GPT-3 (2020) scaled to 175 billion parameters. Its paper, “Language Models are Few-Shot Learners”, showed that putting a few examples in the prompt was often enough to get useful results. This is in-context learning: the task description lives in the prompt, not in the weights.

Instruction tuning and reinforcement learning from human feedback came next, turning raw next-token predictors into assistants that follow requests. Introduction to Reinforcement Learning in Generative AI covers that step. The architecture underneath stayed a decoder-only stack.

Using each model

The two families plug into applications in different ways. An encoder gives you vectors, and you attach something small on top to make decisions. A decoder gives you text, and the task is described in the prompt.

flowchart TB
    T["Input text"] --> Q{"What do you need?"}
    Q -->|"A label or score"| C["Encoder + classification head on CLS"]
    Q -->|"A label per token"| N["Encoder + token head: NER, tagging"]
    Q -->|"A span from a passage"| S["Encoder + start/end head: extractive QA"]
    Q -->|"A vector for search"| V["Encoder + pooling: embeddings"]
    Q -->|"New text"| G["Decoder + prompt: generate"]

With the Hugging Face transformers library, both are a few lines. The first example asks BERT to fill a masked word, which is exactly its pretraining task:

from transformers import pipeline

unmasker = pipeline("fill-mask", model="google-bert/bert-base-uncased")
for guess in unmasker("The bank raised interest [MASK] this quarter."):
    print(guess["token_str"], round(guess["score"], 3))

The pipeline returns the top candidates for the masked position, each with a probability. BERT ranks every word in its vocabulary for that one slot, using the words on both sides. It cannot write the next paragraph.

The second example asks GPT-2, whose weights are openly available, to continue a prompt:

from transformers import pipeline

generator = pipeline("text-generation", model="openai-community/gpt2")
out = generator(
    "The bank raised interest rates this quarter because",
    max_new_tokens=30,
    do_sample=True,
    temperature=0.8,
)
print(out[0]["generated_text"])

The output changes on every run because sampling is on. The implementing Transformers article explains what temperature, top-k and top-p do inside that loop.

For a production task, you would not use the raw pretrained BERT. You would fine-tune it on labelled examples for your task. For a base-sized model and a few thousand examples, that is a modest job on a single GPU. The next article in this series covers fine-tuning pretrained models in detail.

Side by side

BERT (encoder)GPT (decoder)
AttentionBidirectional, no causal maskCausal, left to right
Pretraining objectiveMasked language modelling (plus next sentence prediction in the original)Next-token prediction
Training signal per sequenceOnly the selected positions, about 15%Every position
OutputOne contextual vector per tokenProbability distribution over the next token
Typical tasksClassification, tagging, extractive QA, embeddings, rerankingGeneration, chat, summarization, code, open-ended QA
How you adapt itFine-tune with a small task headPrompting, few-shot examples, or fine-tuning
Typical size todayHundreds of millions of parametersBillions to hundreds of billions
Cost per requestLow; one forward pass over the inputHigher; one forward pass per generated token
Original context limit512 tokens512 tokens (GPT), 1,024 (GPT-2), 2,048 (GPT-3)

Two rows deserve a closer look. Training signal explains why decoders were cheaper to scale per token of data. Cost per request explains why encoders are still everywhere: classifying a document with an encoder is one forward pass, while generating a 200-token answer with a decoder is 200 of them.

You need to label ten million support tickets by topic every day. Why is a fine-tuned encoder often the better fit than a large decoder?

  • It produces a label in one forward pass with a much smaller model, so it is far cheaper and faster at that volume
  • Decoders cannot output category names
  • Encoders do not need any labelled examples

Correct! For fixed-label tasks at high volume, a small encoder with a classification head costs a fraction of what generating text with a large decoder does.

What they changed in NLP

Before 2018, most NLP systems were built per task. Teams trained a model for sentiment, another for named entities and another for question answering, usually starting from static word embeddings such as word2vec or GloVe, where “bank” had one vector regardless of context. Each task needed its own architecture and plenty of labelled data.

BERT made pretrain-then-fine-tune the default. One pretrained encoder, plus a thin task head and a short fine-tuning run, outperformed the specialized systems on most standard benchmarks. The paper reported state-of-the-art results on eleven tasks, including a GLUE benchmark score of 80.5% (7.7 points above the previous best) and a SQuAD v1.1 test F1 of 93.2. Within a year, starting from a pretrained checkpoint was standard practice, and the Hugging Face hub grew around sharing them.

GPT’s lasting change came later and was larger. Once decoders reached the scale of GPT-3, the task itself moved into the prompt. You no longer needed labelled data or a training run for many problems, only a description and perhaps a few examples. That shifted a lot of NLP work from training models to writing prompts, retrieving context and evaluating outputs.

flowchart LR
    TR["Transformer 2017: encoder-decoder"] --> ENCF["Encoder-only"]
    TR --> DECF["Decoder-only"]
    TR --> EDF["Encoder-decoder"]
    ENCF --> B["BERT 2018"]
    B --> R["RoBERTa, ALBERT, DistilBERT 2019"]
    R --> EL["ELECTRA 2020"]
    EL --> MB["ModernBERT 2024"]
    DECF --> G1["GPT 2018"]
    G1 --> G2["GPT-2 2019"]
    G2 --> G3["GPT-3 2020"]
    G3 --> IT["Instruction-tuned chat models"]
    EDF --> T5["T5, BART 2019"]

The third branch is worth knowing about. Encoder-decoder models such as T5 (Raffel and colleagues) and BART (Lewis and colleagues) keep both halves: a bidirectional encoder reads the input, and a causal decoder writes the output while attending to the encoder’s vectors. They suit tasks with a clear input and output, such as translation and summarization. T5 framed every task, classification included, as text in and text out.

Where encoders still win

It is easy to assume decoders made encoders obsolete. They did not, for three reasons.

  • Embeddings for search. Retrieval-augmented generation, semantic search and deduplication all need a vector per document. Most embedding models are encoders, many descended from BERT and trained further with contrastive objectives, starting with Sentence-BERT (Reimers and Gurevych, 2019). The answer your chat assistant gives often depends on an encoder having found the right documents first.
  • Reranking. A cross-encoder reads a query and a candidate passage together, with full bidirectional attention between them, and outputs a relevance score. It is slower than comparing precomputed embeddings but more accurate, so it is typically used to reorder the top results of a first-pass search.
  • High-volume classification. Spam filtering, content moderation, intent routing and PII detection run on huge volumes with fixed labels. A fine-tuned encoder with a few hundred million parameters handles them at low latency on modest hardware.

Encoders also kept improving. ModernBERT (Warner and colleagues, December 2024) updated the design with rotary position embeddings, alternating local and global attention layers and a native context of 8,192 tokens, up from BERT’s 512. It comes in a base size of 149 million parameters and a large size of 395 million, trained on 2 trillion tokens, with weights released under Apache 2.0.

Choosing between them

Start from the output you need, not from the model that is most talked about.

  1. The output is new text (an answer, a summary, a draft, code): use a decoder, usually through a hosted API or an open-weight model.
  2. The output is a fixed label, a set of tags or a span from the input, and you have or can get labelled examples: a fine-tuned encoder will usually be cheaper and faster, and often just as accurate. If you have no labels yet, prompting a decoder is a quick way to get a baseline and to label data for an encoder later.
  3. The output is a vector for search, clustering or similarity: use an embedding model, which is almost always encoder-based.
  4. The output is a ranking of candidates you already retrieved: a cross-encoder reranker.

Many real systems use both. A typical retrieval-augmented assistant uses an encoder to embed documents, a cross-encoder to rerank results and a decoder to write the answer.

In a retrieval-augmented chat assistant, which model family usually produces the document embeddings?

  • The same large decoder that writes the answer
  • An encoder-based embedding model
  • An encoder-decoder translation model

Correct! Embedding models are typically encoders: bidirectional attention gives a strong summary of the whole passage in one cheap forward pass.

Running them in the cloud

All three major providers host both kinds of model. The decoders appear as hosted chat and completion APIs, and the encoders appear mostly as embedding and reranking endpoints, or as open models you deploy yourself. Comparing Cloud Platforms for Generative AI maps where each sits on AWS, Azure and Google Cloud.

The sizing difference matters when you self-host. A BERT-base model fits comfortably on a CPU instance or a small GPU, and batching thousands of short inputs is easy because there is no generation loop. A decoder of several billion parameters needs GPU memory for the weights plus a KV cache that grows with every concurrent conversation, which the self-attention article explains. Check which kind of model a workload really needs before you size instances for it.

Further reading

Key takeaways

  • BERT and GPT use the same Transformer block; the key difference is the attention mask. BERT attends in both directions, GPT only to earlier tokens.
  • BERT is pretrained by predicting masked tokens (about 15% of positions, with an 80/10/10 replacement split); GPT is pretrained by predicting the next token at every position.
  • Encoders produce contextual vectors and are adapted with a small task head; decoders produce text and are adapted mostly through prompts.
  • BERT made pretrain-then-fine-tune the standard approach in NLP, and the GPT line, at GPT-3 scale, moved many tasks into the prompt itself.
  • Encoders remain the right tool for embeddings, reranking and high-volume classification, where one cheap forward pass beats generating text.
  • Pick the model from the output you need: text calls for a decoder, labels, spans, vectors and rankings usually call for an encoder, and many systems use both.

Part 10 of 10 · Deep Dive into Generative Models

  1. 01Mathematical Foundations of VAEs
  2. 02Implementing VAEs: A Step-by-Step Guide
  3. 03Training GANs: Tips, Tricks, and Common Pitfalls
  4. 04Conditional GANs: Controlling the Output
  5. 05StyleGAN: Generating High-Resolution Images
  6. 06CycleGAN: Image-to-Image Translation
  7. 07Text Generation Models: From RNNs to Transformers
  8. 08The Transformer Architecture: Self-Attention Explained
  9. 09Implementing Transformers for Text Generation
  10. 10BERT vs. GPT: Encoders, Decoders, and Their Impact on NLP
Ready to check your understanding?Take the Word Up! Bot quiz
esc

Type to search all articles · ↑↓ to move · ↵ to open