Chapter 03 — Encoder Models

BERT: Bidirectional Encoder Representations

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.

Guided Track: Pretrain to Fine-tune

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.

Stage 1: Core Idea

  • Why unidirectional context was limiting
  • Encoder-only Transformer as a bidirectional reader
  • What [CLS], [SEP], and [MASK] represent

Stage 2: Pretraining

  • Masked Language Modeling objective
  • Next Sentence Prediction and its alternatives
  • Scaling pretraining corpus and compute

Stage 3: Adaptation

  • Sequence-level and token-level fine-tuning
  • LoRA and PEFT for efficient adaptation
  • SFT-style downstream workflows

Why BERT Changed NLP

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.

Why Bidirectional?

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:

🔑 The "Bank" Example

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.

Architecture

BERT uses only the encoder portion of the Transformer (no decoder). It comes in two sizes:

ModelLayers (L)Hidden (H)Heads (A)Parameters
BERT-Base1276812110M
BERT-Large24102416340M
T₁
T₂
T₃
···
T_n
↑ × 12 (or 24) Transformer Encoder Layers
Bidirectional Self-Attention
↑
[CLS]
I
love
[MASK]
learning
[SEP]
Fig 1. BERT processes the full input with bidirectional attention. [CLS] is used for classification tasks, [MASK] tokens are predicted during pre-training, and [SEP] separates sentence pairs.

WordPiece Tokenization

BERT uses WordPiece tokenization with a vocabulary of 30,522 tokens. Unknown words are split into known subwords prefixed with ##:

Input: "unbelievable transformers"
un
##bel
##iev
##able
transform
##ers

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.

Input Representation

BERT's input embedding is the sum of three embeddings:

Token Emb.
[CLS]
I
love
[SEP]
NLP
[SEP]
Segment Emb.
A
A
A
A
B
B
Position Emb.
0
1
2
3
4
5
Fig 2. BERT input = Token + Segment + Position embeddings. Segment A/B distinguish between the two sentences in a pair.

Masked Language Modeling (MLM)

BERT's main pre-training objective. 15% of input tokens are selected, then:

The model must predict the original token at each masked position:

The
cat
[MASK]
on
the
mat
↓ BERT Encoder (12 layers of bidirectional attention)
sat ✓
⚠️ Train-Test Mismatch

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.

Next Sentence Prediction (NSP)

The second pre-training objective. Given two sentences A and B, the model predicts whether B actually follows A in the corpus:

⚡ Modern Verdict

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).

Pre-training Details

Fine-tuning

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:

Classification
Use [CLS] hidden state → linear layer → softmax
Sentiment, Topic, NLI
Token Classification
Each token hidden state → linear → softmax
NER, POS tagging
Question Answering
Predict start & end token positions in context
SQuAD

BERT Variants & Successors

ModelYearKey Change
RoBERTa2019More data, no NSP, dynamic masking
ALBERT2019Parameter sharing, SOP instead of NSP
DistilBERT2019Knowledge distillation — 60% size, 97% performance
ELECTRA2020Replaced token detection (more sample-efficient)
DeBERTa2020Disentangled attention — separate content/position

The Pre-training Revolution

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:

Old: LSTM-Era Approach
✗ Train sentiment LSTM from scratch
✗ Train NER LSTM from scratch
✗ Train QA LSTM from scratch
✗ Each needs ~100K labeled examples
✗ Each takes days of training
✗ No knowledge sharing between tasks
New: BERT Pre-train + Fine-tune
✓ Pre-train ONCE on unlabeled text
✓ Fine-tune for sentiment (~1hr, 5K examples)
✓ Fine-tune for NER (~1hr, 5K examples)
✓ Fine-tune for QA (~1hr, 5K examples)
✓ 10× less labeled data needed
✓ Knowledge transfers across tasks
💡 Why This Works

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.

LoRA & Parameter-Efficient Fine-Tuning (PEFT)

Full fine-tuning updates all parameters — expensive for large models. LoRA (Low-Rank Adaptation) freezes the base model and only trains small adapter matrices:

LoRA: add low-rank update BA instead of modifying the full weight matrix
MethodTrainable ParamsGPU MemoryQualityBest 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 Example: Fine-tuning LLaMA-7B
Full FT: 7B params × 4 bytes × 3 (weights+grads+optimizer) = 84 GB
LoRA (r=16): 7B frozen + 4.2M trainable = 14 GB

QLoRA: Even less!
Base model in 4-bit (NF4): 7B × 0.5 bytes = 3.5 GB
+ LoRA adapters in FP16: 4.2M × 2 bytes = 8 MB
Total: ~6 GB ← fits on a single RTX 3060!

Where to add LoRA:
Typically on Q, K, V, O projections in attention
Rank r=8-64 (sweet spot: r=16 for most tasks)
Python
# 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)

SFT & Instruction Tuning

Between pre-training and alignment (RLHF/DPO), there's a critical step: Supervised Fine-Tuning (SFT) on instruction-following data:

Pre-train
Next-token on internet text
→
SFT
Instruction→Response pairs
→
RLHF / DPO
Human preferences
→
ChatBot
ChatGPT, Claude
JSON — Alpaca-style instruction format
{
  "instruction": "Summarize the following article.",
  "input": "Scientists at MIT have discovered...",
  "output": "MIT researchers found a new method..."
}
⚡ Quality over Quantity

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.

Fine-tuning vs Pre-training: When to Use What

ModelPre-training UseFine-tuning UseMethodData 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

When to Pre-train vs Fine-tune vs Prompt

Pre-train from scratch when:
✗ You need a completely new language (rare script)
✗ Your domain is radically different (e.g., DNA sequences)
✗ Cost: $1M-$100M, months of GPU time

Fine-tune when:
✓ Your task needs specific behavior/format
✓ You have labeled data (even 1K examples)
✓ You need consistent, reliable output
✓ Cost: $10-$10K, hours to days

Just prompt when:
✓ The base model already does it well
✓ You need flexibility (many task types)
✓ Cost: $0, instant
🔥 Full MLM Training Pipeline

Full Pre-training Pipeline: End-to-End Example

Let's trace one complete BERT pre-training step with the sentence pair: "I love deep learning" (Sentence A) + "NLP is fun" (Sentence B).

Full BERT Architecture: Data Flow

"[CLS] I [MASK] deep learning [SEP] NLP is [MASK] [SEP]"
↓ ① WordPiece + Masking
Token Emb
30522×768
+
Segment Emb
2×768
+
Pos Emb
512×768
② h⁰ ∈ ℝ10×768
× 12 Encoder Layers
③ Bidirectional Self-Attention
12 heads × dk=64, NO mask
↓ Add & Norm + residual
FFN: 768 → 3072 → 768
GELU activation
↓ Add & Norm + residual
H ∈ ℝ10×768
④ MLM Head
H[MASK] → 30522
−log P(love), −log P(fun)
④ NSP Head
H[CLS] → 2
−log P(IsNext)
↓ ⑤ Backprop + Adam
BERT: Encoder-only with two output heads. Bidirectional attention (no mask) lets every token see every other. Steps ①-⑤ map to pipeline below.

Step 1: WordPiece Tokenize → Apply Masking

Original: "I love deep learning" [SEP] "NLP is fun"
[CLS]→1
I→15
[MASK]←love
deep→4912
learning→3776
[SEP]→2
NLP→18223
is→18
[MASK]←fun
[SEP]→2
"love" and "fun" are masked (15% ≈ 2 of 10 tokens). 80% chance → [MASK]

Step 2: Construct Three Embeddings

Token ID = [1, 15, 103, 4912, 3776, 2, 18223, 18, 103, 2]
Segment = [A, A, A, A, A, A, B, B, B, B]
Position = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

h⁰ = Token Emb + Segment Emb + Position Emb
Shape: 10 × 768

Step 3: Encoder Forward (×12 layers, NO causal mask)

BERT uses bidirectional attention — no masking, so every token sees every other token. This is the key difference from GPT:

[MASK₂]: [0.08, 0.06, 0.01, 0.12, 0.15, 0.08, 0.10, 0.25, 0.01, 0.14]

← Even though "fun" is masked, it attends to "NLP" and "is" (weight 0.25 + 0.14), gathering bidirectional context to predict itself!

After 12 layers:

Step 4: Dual Loss (MLM + NSP)

MLM Head

Only the masked positions are projected to the vocabulary:

[MASK₁] → ?
Target: love
P(love)=0.12
−log = 2.12
[MASK₂] → ?
Target: fun
P(fun)=0.08
−log = 2.53

NSP Head

h[CLS] → Linear(768, 2) → Softmax
P(IsNext) = 0.72, P(NotNext) = 0.28
This IS a real pair → −log(0.72) = 0.33
Total Loss = LMLM + LNSP = (2.12+2.53)/2 + 0.33 = 2.66

Step 5: Backpropagation Through BERT

BERT's backprop is unique because gradients flow from two loss heads simultaneously and merge at the encoder output:

∂LMLM/∂H[MASK]
gradient at masked positions only
∂LNSP/∂H[CLS]
gradient at [CLS] only
↓ merge: ∂L/∂H = ∂L_MLM/∂H + ∂L_NSP/∂H
Through 12 × (Self-Attention + FFN) layers
↓ through attention: ∂L/∂WQ, ∂L/∂WK, ∂L/∂WV
∂L/∂Etoken, ∂L/∂Esegment, ∂L/∂Eposition

Gradient Through GELU (FFN Backprop)

FFN: hout = GELU(hin × W₁) × W₂

GELU derivative at x=0.85:
GELU'(x) = Φ(x) + x·φ(x)
GELU'(0.85) = 0.802 + 0.85×0.278 = 1.038

For W₁[42, 7] with upstream gradient δ = 0.0156:
∂L/∂W₁[42,7] = hin[42] × GELU'(z[7]) × δ
= 0.65 × 1.038 × 0.0156 = 0.01052

Adam Weight Update

g = 0.01052, η = 1e-4, β₁=0.9, β₂=0.999
m₁ = 0.1 × 0.01052 = 0.001052
v₁ = 0.001 × 0.01052² = 1.107e-7
m̂ = 0.001052/0.1 = 0.01052
v̂ = 1.107e-7/0.001 = 1.107e-4
Δw = −1e-4 × 0.01052/(√1.107e-4+1e-8) = −1.0e-4
w_new = w_old − 0.0001 ← tiny step, 110M params updated simultaneously!

Fine-tuning Pipeline (e.g., SQuAD QA)

Pre-trained BERT (110M params)
↓ Add 2 linear heads (start + end)
Input: [CLS] Question [SEP] Passage
↓ 12 encoder layers (fine-tuned)
P(start), P(end) for each token in passage
↓ 3 epochs, LR=3e-5
SQuAD F1 = 93.2% 🎉
⚡ Fine-tuning is Cheap

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.

💡 Why BERT's Bidirectional Backprop Matters

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.

Impact & Legacy

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.

📄 Citation

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

💻 PyTorch Code

Code: BERT from Scratch

BERT Encoder

Python
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

Pre-training Step

Python
# 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()

Fine-tuning for Classification

Python
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)