AI Notes
Master BERT architecture for AI. Learn bidirectional transformers, pretraining, fine-tuning, token embeddings, attention. Interview preparation 2024.
What Makes BERT Revolutionary
BERT (Bidirectional Encoder Representations from Transformers), introduced by Google in 2018, fundamentally changed how we approach NLP. Before BERT, language models like GPT processed text left-to-right (or right-to-left), building context from only one direction. BERT's key innovation is bidirectional attention—every token attends to every other token simultaneously, building rich contextualized representations that capture meaning from both preceding and following context.
Consider the word "bank" in these sentences: "I went to the bank to deposit money" versus "I sat on the river bank." A left-to-right model processing "bank" hasn't yet seen "deposit" or "river," making disambiguation difficult. BERT sees the entire sentence at once, making contextual understanding natural.
BERT achieved state-of-the-art results on 11 NLP benchmarks simultaneously upon release, establishing the pretrain-then-finetune paradigm that dominates modern NLP.
Architecture Deep Dive
Model Variants
Input Representation
BERT's input is the sum of three embedding types:
| Input | "[CLS] The cat sat on the mat [SEP] It was tired [SEP]" |
| Token Embeddings | [CLS] The cat sat on the mat [SEP] It was tired [SEP] |
| Segment Embeddings | A A A A A A A A B B B B |
| Position Embeddings | 0 1 2 3 4 5 6 7 8 9 10 11 |
[CLS] token: Its final hidden state serves as the aggregate sequence representation for classification tasks.
[SEP] token: Separates sentence pairs and marks sentence boundaries.
WordPiece Tokenization
BERT uses WordPiece with a 30,000 token vocabulary:
This handles rare words by breaking them into known subwords, eliminating out-of-vocabulary issues.
Pre-training Objectives
1. Masked Language Modeling (MLM)
MLM is BERT's primary training signal. Randomly mask 15% of input tokens and predict them:
| Original | "The cat sat on the mat" |
| Masked | "The cat [MASK] on the mat" |
| Predict | "sat" |
| 80% | replaced with [MASK] |
| 10% | replaced with random token |
| 10% | kept unchanged |
| - [MASK] never appears in fine-tuning | distribution mismatch |
Training Example Walkthrough
| Input | "The [MASK] sat on the [MASK]" |
| Labels | "cat" (position 1), "mat" (position 5) |
| Embedding | 12 Transformer layers → hidden states H |
2. Next Sentence Prediction (NSP)
Binary classification: does sentence B follow sentence A in the original corpus?
Positive example (IsNext)
A: "The cat sat on the mat"
B: "It was a fluffy Persian cat"
Negative example (NotNext)
A: "The cat sat on the mat"
B: "Stock prices rose sharply yesterday"
Input: [CLS] A [SEP] B [SEP]
Output: CLS hidden state → linear → sigmoid → IsNext/NotNext
NSP was later shown to be less important than MLM (RoBERTa removed it entirely with no performance loss), but it helps with tasks like question answering and natural language inference.
Fine-tuning BERT for Downstream Tasks
The pretrain-finetune paradigm:
- Pre-train on massive unlabeled corpus (BookCorpus + Wikipedia, ~3.3B words)
- Fine-tune on small task-specific labeled data (often just thousands of examples)
Task-Specific Architectures
| Input | [CLS] text [SEP] |
| Use: CLS token | Dense → softmax |
| Input | [CLS] question [SEP] context [SEP] |
| Use: Each token | start/end score → span extraction |
| Input | [CLS] token1 token2 ... [SEP] |
| Use: Each token | entity label (B-PER, I-PER, O, ...) |
| Input | [CLS] sentence1 [SEP] sentence2 [SEP] |
| Use: CLS token | Dense → {entailment, contradiction, neutral} |
Fine-tuning Hyperparameters
| Learning rate | 2e-5 to 5e-5 (much smaller than pre-training) |
| Batch size | 16 or 32 |
| Epochs | 2-4 (overfitting risk with small data) |
| Warmup | 10% of training steps |
| Max sequence length | 128 or 512 tokens |
Attention Mechanism in BERT
Each transformer layer has multi-head self-attention:
With 12 heads in BERT-Base, each head learns different relationship patterns: some capture syntax, others semantics, coreference, or positional patterns.
BERT Variants and Successors
| Model | Key Change | Improvement |
|---|---|---|
| RoBERTa | Remove NSP, more data, longer training | +2-5% on benchmarks |
| ALBERT | Parameter sharing, factorized embeddings | 18x fewer params, similar performance |
| DistilBERT | Knowledge distillation | 60% size, 97% performance |
| ELECTRA | Replaced token detection instead of MLM | More sample-efficient |
| DeBERTa | Disentangled attention (content + position) | State-of-art on SuperGLUE |
Practical Considerations
Computational Requirements
| BERT-Base pre-training | 4 days on 16 TPUs (~$50,000 equivalent) |
| BERT-Base fine-tuning | 1-2 hours on single GPU |
| BERT-Base inference | ~10ms per sentence (GPU) |
Limitations
- Max 512 tokens: Cannot process long documents directly
- Slow inference: Full transformer computation for every input
- No generation: Encoder-only; cannot generate text autoregressively
- Static after fine-tuning: Cannot learn from new data without retraining
Interview Questions
Q: Why bidirectional? What's the trade-off vs. autoregressive? A: Bidirectional context gives richer representations (sees full sentence). The trade-off: BERT cannot generate text token-by-token since it needs the full input. For generation tasks, autoregressive models (GPT) are necessary.
Q: Why does BERT mask only 15% of tokens? A: Masking too many tokens (say 50%) would make the context too sparse—predictions become unreliable. Masking too few (say 1%) makes training extremely slow. 15% balances training signal quality with efficiency.
Q: How does BERT handle words not in its vocabulary? A: WordPiece tokenization splits unknown words into known subword units. "Transformers" might become ["Transform", "##ers"]. The model learns subword compositions through pre-training.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for BERT - Bidirectional Encoder Representations.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Artificial Intelligence topic.
Search Terms
artificial-intelligence, artificial intelligence, artificial, intelligence, deep, learning, bert, model
Related Artificial Intelligence Topics