BERT and Variants
Prerequisites
- Word Embeddings — static vs contextual representations
- GPT Architecture — transformer basics, attention
🎯 Learning Objectives
- Explain masked language modeling (MLM) and next sentence prediction (NSP)
- Understand why bidirectional context is advantageous over left-to-right
- Compare BERT with its variants: RoBERTa, ALBERT, DistilBERT
- Describe how to fine-tune BERT for classification, NER, and QA tasks
1. BERT Overview
BERT (Bidirectional Encoder Representations from Transformers, Devlin et al., 2018) uses the encoder of the Transformer. Unlike GPT which reads left-to-right, BERT reads the entire sequence at once — each token can attend to all other tokens, capturing both left and right context simultaneously.
Architecture:
- BERT-Base: 12 layers, 768 hidden size, 12 attention heads, 110M parameters
- BERT-Large: 24 layers, 1024 hidden size, 16 attention heads, 340M parameters
- Context length: 512 tokens maximum
- Tokenizer: WordPiece with 30,522 vocabulary size
2. Masked Language Modeling (MLM)
Masking strategy (for the selected 15% of tokens):
- 80% of the time: Replace with [MASK] token
- 10% of the time: Replace with a random token from the vocabulary
- 10% of the time: Keep unchanged
This mixed strategy prevents the model from only learning about [MASK] tokens (which don’t appear during fine-tuning or inference).
Example: MLM Training
Original: “The cat sat on the mat”
Masked input: “The [MASK] sat on the mat”
Model predicts: P(“cat” | context) should be high
The loss is only computed on the masked positions, not the entire sequence.
3. Next Sentence Prediction (NSP)
BERT’s second pretraining task: given two sentences A and B, predict whether B actually follows A in the corpus (IsNext) or is a random sentence (NotNext).
Input format: [CLS] Sentence A [SEP] Sentence B [SEP]
The [CLS] token’s final hidden state is fed through a binary classifier for NSP.
NSP Examples
Positive (IsNext):
A: “The man went to the store.” B: “He bought a gallon of milk.” → IsNext
Negative (NotNext):
A: “The man went to the store.” B: “Penguins are flightless birds.” → NotNext
Note: Later research (RoBERTa) showed that NSP may not be helpful and can be removed.
4. BERT Input Representation
Each input token is represented as the sum of three embeddings:
- Token embedding: WordPiece token ID → learned embedding vector
- Segment embedding: Indicates whether the token belongs to sentence A or B (EA or EB)
- Position embedding: Learned position embedding (similar to GPT)
Input = TokenEmbed(wi) + SegmentEmbed(si) + PositionEmbed(i)
5. Fine-tuning BERT for Downstream Tasks
BERT is fine-tuned by adding a small task-specific head on top of the pretrained encoder:
5.1 Text Classification (Sentiment, Topic)
Use the [CLS] token output → linear layer → softmax over classes.
y = softmax(W · h[CLS] + b)
5.2 Named Entity Recognition (NER)
Use each token’s output → linear layer → softmax over entity tags (B-PER, I-PER, O, etc.).
yi = softmax(W · hi + b) for each token i
5.3 Question Answering (Extractive)
Input: [CLS] Question [SEP] Passage [SEP]. Predict start and end positions of the answer span in the passage.
P(start = i) = softmax(Ws · hi)
P(end = j) = softmax(We · hj)
5.4 Sentence Pair Tasks (NLI, Paraphrase)
Input: [CLS] Sentence A [SEP] Sentence B [SEP]. Use [CLS] output for classification (entailment, contradiction, neutral).
6. BERT Variants
| Model | Key Changes from BERT | Parameters |
|---|---|---|
| RoBERTa (Liu et al., 2019) | Removes NSP; trains longer with more data; dynamic masking (different mask each epoch); larger batches | 125M–355M |
| ALBERT (Lan et al., 2019) | Cross-layer parameter sharing (all layers share weights); factorized embedding (E ≪ H); sentence-order prediction (SOP) replaces NSP | 12M–235M |
| DistilBERT (Sanh et al., 2019) | Knowledge distillation: 6-layer student trained to mimic 12-layer BERT teacher. 40% smaller, 60% faster, retains 97% of BERT’s performance | 66M |
| ELECTRA (Clark et al., 2020) | Replaced token detection instead of masked prediction. A generator replaces tokens; a discriminator identifies which tokens were replaced. More sample-efficient. | 14M–335M |
7. BERT vs GPT Comparison
| Feature | BERT (Encoder) | GPT (Decoder) |
|---|---|---|
| Attention direction | Bidirectional (full context) | Unidirectional (left-to-right) |
| Pretraining task | MLM + NSP | Causal LM (next token) |
| Best for | Understanding tasks (classification, NER, QA) | Generation tasks (text completion, dialog) |
| Fine-tuning | Task-specific head required | Can use prompting (zero/few-shot) |
| Cannot do | Text generation (no autoregressive capability) | Efficient bidirectional encoding |
8. Summary
- BERT uses the Transformer encoder with bidirectional self-attention.
- MLM: Mask 15% of tokens (80% [MASK], 10% random, 10% unchanged), predict originals.
- NSP: Binary classification — does sentence B follow A? (Later removed in RoBERTa.)
- Input: Token + Segment + Position embeddings; [CLS] token for classification.
- Fine-tuning: Add a task head on top; fine-tune entire model end-to-end.
- RoBERTa: No NSP, more data, dynamic masking — consistently outperforms BERT.
- ALBERT: Parameter sharing reduces model size; SOP replaces NSP.
- DistilBERT: Knowledge distillation for 40% smaller, 60% faster model.