Stage 1: Core Idea
- Why unidirectional context was limiting
- Encoder-only Transformer as a bidirectional reader
- What [CLS], [SEP], and [MASK] represent
How Google built a model that reads both left and right simultaneously — and transformed NLP benchmarks overnight with masked language modeling, transfer learning, and task-specific fine-tuning.
Use this order if you want to build strong intuition quickly: understand BERT's bidirectional objective first, then input construction, then pretraining tasks, and finally efficient adaptation for downstream use.
BERT made transfer learning practical for language: pretrain once on large unlabeled corpora, then adapt quickly to many tasks with minimal architecture changes.
That objective taught contextual token representations which generalized across sentiment, QA, NER, and sentence-level classification workloads.
Before BERT, language models were unidirectional — they either read left-to-right (GPT) or right-to-left (ELMo used both but separately). This fundamentally limits understanding:
In "I went to the bank to deposit money", the word "bank" means a financial institution. But in "I sat by the river bank", it means a riverbank. A unidirectional model reading left-to-right can't use "deposit money" to disambiguate "bank" — BERT can, because it sees both sides simultaneously.
BERT's key insight: use the Transformer encoder's bidirectional self-attention with a clever pre-training objective that doesn't require labeled data.
BERT uses only the encoder portion of the Transformer (no decoder). It comes in two sizes:
| Model | Layers (L) | Hidden (H) | Heads (A) | Parameters |
|---|---|---|---|---|
| BERT-Base | 12 | 768 | 12 | 110M |
| BERT-Large | 24 | 1024 | 16 | 340M |
BERT uses WordPiece tokenization with a vocabulary of 30,522 tokens. Unknown words are split into known subwords prefixed with ##:
This is a balance between word-level tokens (too large vocabulary) and character-level (too long sequences). Common words stay whole; rare words get split into frequent subwords.
BERT's input embedding is the sum of three embeddings:
BERT's main pre-training objective. 15% of input tokens are selected, then:
[MASK]The model must predict the original token at each masked position:
The [MASK] token appears during pre-training but never during fine-tuning. The 10% random + 10% unchanged trick mitigates this mismatch by forcing the model to maintain good representations for all tokens, not just masked ones.
The second pre-training objective. Given two sentences A and B, the model predicts whether B actually follows A in the corpus:
IsNext)NotNext)Later work (RoBERTa, ALBERT) showed that NSP can actually hurt performance compared to just MLM. RoBERTa removes NSP entirely, while ALBERT replaces it with Sentence Order Prediction (SOP).
BERT's magic is in fine-tuning: a pre-trained model can be adapted to many downstream tasks by adding a simple output layer and training for a few epochs:
| Model | Year | Key Change |
|---|---|---|
| RoBERTa | 2019 | More data, no NSP, dynamic masking |
| ALBERT | 2019 | Parameter sharing, SOP instead of NSP |
| DistilBERT | 2019 | Knowledge distillation — 60% size, 97% performance |
| ELECTRA | 2020 | Replaced token detection (more sample-efficient) |
| DeBERTa | 2020 | Disentangled attention — separate content/position |
Before BERT, the standard approach (from the LSTM era) was to train a separate model for each task from scratch. BERT changed everything by introducing pre-train once, fine-tune for any task:
Self-supervised learning is the key. BERT's pre-training objectives (MLM + NSP) generate their own labels from raw text — no human annotation needed. The model reads the entire internet and learns language structure. Fine-tuning then adapts this knowledge to specific tasks with minimal data. This is the fundamental paradigm behind all modern LLMs.
Full fine-tuning updates all parameters — expensive for large models. LoRA (Low-Rank Adaptation) freezes the base model and only trains small adapter matrices:
| Method | Trainable Params | GPU Memory | Quality | Best For |
|---|---|---|---|---|
| Full Fine-Tuning | 100% | High (all grads) | Best | Small models (BERT, GPT-2) |
| LoRA | 0.1-1% | Low | ~98% of full | 7B-70B models |
| QLoRA | 0.1-1% | Very Low | ~97% of full | 70B+ on consumer GPU |
| Adapters | 2-5% | Medium | ~96% of full | Multi-task (add per task) |
| Prefix Tuning | 0.01% | Very Low | ~93% of full | Lightweight tasks |
# LoRA fine-tuning with HuggingFace PEFT from peft import LoraConfig, get_peft_model config = LoraConfig( r=16, # Low rank dimension lora_alpha=32, # Scaling factor target_modules=["q_proj", "v_proj"], # Which layers lora_dropout=0.05, ) model = get_peft_model(base_model, config) model.print_trainable_parameters() # trainable: 4,194,304 (0.06% of 7B)
Between pre-training and alignment (RLHF/DPO), there's a critical step: Supervised Fine-Tuning (SFT) on instruction-following data:
{
"instruction": "Summarize the following article.",
"input": "Scientists at MIT have discovered...",
"output": "MIT researchers found a new method..."
}
Alpaca (52K examples) showed that even small instruction datasets can dramatically improve a model. The key is diversity of tasks: summarization, Q&A, code, math, translation, creative writing. LIMA (2023) proved that just 1,000 carefully curated examples can match models trained on millions.
| Model | Pre-training Use | Fine-tuning Use | Method | Data Needed |
|---|---|---|---|---|
| BERT | Learn language structure (MLM + NSP) | Sentiment, NER, QA, classification | Full FT (small model) | 1K-100K labeled examples |
| GPT-2 | Learn to generate text | Chatbots, story writing, code gen | Full FT or LoRA | 10K-1M examples |
| Qwen | Multilingual language + reasoning | Domain-specific assistant, coding, math | LoRA / QLoRA | 5K-50K instructions |
| DeepSeek | General + reasoning via GRPO | Custom reasoning, code review, research | LoRA on dense layers | 1K-10K high-quality |
Let's trace one complete BERT pre-training step with the sentence pair: "I love deep learning" (Sentence A) + "NLP is fun" (Sentence B).
BERT uses bidirectional attention — no masking, so every token sees every other token. This is the key difference from GPT:
After 12 layers:
Only the masked positions are projected to the vocabulary:
BERT's backprop is unique because gradients flow from two loss heads simultaneously and merge at the encoder output:
Pre-training takes 4 days on 4 TPUs. Fine-tuning takes ~1 hour on 1 GPU. This 100× cost difference is why the pre-train/fine-tune paradigm was so revolutionary.
Because BERT's attention is bidirectional, gradients from a masked position flow to all tokens in the sequence. When the model gets [MASK₂]="fun" wrong, gradients reach "NLP", "is", "I", and even "deep" — the entire context learns to contribute useful information. In GPT, gradients can only flow backwards (right-to-left in the attention), limiting the learning signal.
BERT established the pre-train then fine-tune paradigm that dominates modern NLP. Before BERT, each NLP task required training from scratch. After BERT, a single foundation model could be adapted to dozens of tasks with minimal labeled data.
Devlin, J., Chang, M.W., Lee, K., & Toutanova, K. "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding." NAACL 2019. arxiv.org/abs/1810.04805
class BERT(nn.Module): def __init__(self, vocab=30522, d=768, layers=12, heads=12, max_len=512): super().__init__() # Three embeddings (BERT's unique feature) self.tok_emb = nn.Embedding(vocab, d) self.pos_emb = nn.Embedding(max_len, d) self.seg_emb = nn.Embedding(2, d) # Segment A=0, B=1 self.norm = nn.LayerNorm(d) # 12 bidirectional encoder layers (NO causal mask!) encoder_layer = nn.TransformerEncoderLayer( d, heads, dim_feedforward=3072, activation='gelu' ) self.encoder = nn.TransformerEncoder(encoder_layer, layers) # MLM head: predict masked tokens self.mlm_head = nn.Linear(d, vocab) # NSP head: predict if sentence B follows A self.nsp_head = nn.Linear(d, 2) def forward(self, input_ids, segment_ids): pos = torch.arange(input_ids.size(1), device=input_ids.device) x = self.tok_emb(input_ids) + self.pos_emb(pos) + self.seg_emb(segment_ids) x = self.norm(x) h = self.encoder(x) # (B, T, 768) — bidirectional! mlm_logits = self.mlm_head(h) # (B, T, vocab) nsp_logits = self.nsp_head(h[:, 0]) # [CLS] token → 2 classes return mlm_logits, nsp_logits
# Dual-loss pre-training mlm_logits, nsp_logits = model(input_ids, segment_ids) # MLM loss: only on [MASK] positions mlm_loss = F.cross_entropy( mlm_logits[mask_positions].view(-1, vocab_size), mlm_labels[mask_positions].view(-1) ) # NSP loss: binary classification nsp_loss = F.cross_entropy(nsp_logits, nsp_labels) # Combined loss loss = mlm_loss + nsp_loss loss.backward() optimizer.step()
class BERTClassifier(nn.Module): def __init__(self, bert, n_classes): super().__init__() self.bert = bert # Pre-trained BERT self.head = nn.Linear(768, n_classes) def forward(self, input_ids, segment_ids): h = self.bert.encoder(...) # Get encoder output cls_embedding = h[:, 0] # [CLS] token return self.head(cls_embedding) # Fine-tune with lr=3e-5 for ~3 epochs optimizer = torch.optim.AdamW(model.parameters(), lr=3e-5)