Highlight the key differences between language models like GPT (Generative Pre-trained Transformer) and BERT (Bidirectional Encoder Representations from Transformers).
GPT is a decoder-only Transformer trained autoregressively with causal (masked) self-attention to predict the next token given left context, making it naturally suited for open-ended text generation and in-context learning. BERT is an encoder-only Transformer trained with bidirectional self-attention via Masked Language Modeling (and originally Next Sentence Prediction), allowing every token to attend to both left and right context for representation, classification, and span extraction tasks.
Study Card: Key Differences between GPT and BERT
Direct Answer
Although both GPT and BERT are built on the Transformer architecture, they differ fundamentally in attention masking, pre-training objectives, and downstream usage:
| Dimension | GPT (Decoder-Only) | BERT (Encoder-Only) |
|---|---|---|
| Attention Pattern | Causal (unidirectional left-to-right mask; token attends only to ) | Bidirectional (unmasked; token attends to all tokens in the sequence) |
| Pre-training Objective | Causal Language Modeling (CLM) | Masked Language Modeling (MLM) + Next Sentence Prediction (NSP) |
| Primary Strengths | Autoregressive generation, dialogue, reasoning, zero/few-shot prompting | Sequence classification, NER, dense retrieval embeddings, extractive QA |
| Inference Pattern | Sequential token-by-token decoding with KV caching | Single parallel forward pass over the full input |
GPT optimizes the autoregressive joint log-likelihood over every token:
BERT randomly corrupts ~15% of input tokens (80% [MASK], 10% random token, 10% unchanged in original BERT) and reconstructs them using full bidirectional context:
(Note: later encoder models such as RoBERTa found that dropping NSP and training longer on MLM improves downstream performance.)
Key Terms
- Causal (Autoregressive) Language Modeling: Predicting token conditioned strictly on preceding tokens via a lower-triangular causal attention mask.
- Bidirectional Self-Attention: Allowing each token representation to integrate context from both left and right neighbors simultaneously.
- Masked Language Modeling (MLM): Pre-training by masking a subset of tokens and predicting the original identities from bidirectional context; introduces a
[MASK]token train-test discrepancy. - Next Sentence Prediction (NSP): Binary classification over
[CLS]predicting whether Segment B immediately follows Segment A ([CLS] A [SEP] B [SEP]). - KV Caching: Storing past keys and values during GPT decoding so each new token avoids recomputing earlier states.
Example
Given "The quick brown fox jumps over the lazy dog", GPT predicts "jumps" from "The quick brown fox", then "over" from "The quick brown fox jumps", learning from 100% of tokens per sequence. BERT masks tokens like "The quick brown [MASK] jumps over the [MASK] dog" and predicts "fox" and "lazy" using context on both sides of each mask. For NSP, BERT takes two distinct segments separated by [SEP] (token_type_ids 0 for the first sentence and 1 for the second) to judge continuity.
Code Implementation
from transformers import BertForNextSentencePrediction, BertTokenizer, pipeline
import torch
# 1. Causal text generation with GPT-2
generator = pipeline("text-generation", model="gpt2")
generated_text = generator(
"The quick brown fox jumps over the",
max_new_tokens=20,
num_return_sequences=1,
)
print("GPT-2 Generated Text:", generated_text[0]["generated_text"])
# 2. Bidirectional Masked Language Modeling with BERT
unmasker = pipeline("fill-mask", model="bert-base-uncased")
masked_text = "The quick brown [MASK] jumps over the lazy dog."
filled_text = unmasker(masked_text)
print("BERT Filled Text:", filled_text[0]["sequence"])
# 3. Next Sentence Prediction (NSP) requires passing a (sentence_a, sentence_b) pair
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
nsp_model = BertForNextSentencePrediction.from_pretrained("bert-base-uncased").eval()
sentence_a = "The quick brown fox jumps over the lazy dog."
sentence_b = "The dog barked loudly in response."
encoded = tokenizer(sentence_a, sentence_b, return_tensors="pt") # Adds [SEP] + token_type_ids
with torch.no_grad():
logits = nsp_model(**encoded).seq_relationship_logits
# Label 0 = IsNext, Label 1 = NotNext
is_next = logits.argmax(dim=-1).item() == 0
print(f"Are the sentences consecutive according to BERT? {'Yes' if is_next else 'No'}")
Related Concepts
- Encoder-Decoder Models (T5, BART): Combine a bidirectional encoder with a causal cross-attending decoder for sequence-to-sequence tasks.
- PrefixLM: Allows bidirectional attention over a prompt prefix and causal attention over the generated continuation.
- RoBERTa & DeBERTa: Strengthened encoder-only models that remove NSP and refine attention/masking strategies.
- Instruction Tuning & RLHF: Post-training stages that turn base autoregressive GPT models into general-purpose assistants.