4.3.2Pretraining & Fine-Tuning LLMs

BERT and encoder models

2,097 words10 min readdifficulty · medium

What is an encoder model?

WHAT is the contrast?

Family Attention Trained for Example
Encoder-only bidirectional understanding BERT
Decoder-only causal (left→right) next-token generation GPT
Encoder-decoder both seq-to-seq (translate) T5

Pretraining objective 1: Masked Language Modelling (MLM)

HOW the 15% are handled (the 80/10/10 rule):

  • 80% → replaced with a special [MASK] token
  • 10% → replaced with a random token
  • 10% → left unchanged

Deriving the MLM loss from first principles. Let MM be the set of masked positions. For a masked position ii, the model outputs contextual vector hih_i, projects it to vocab logits zi=Whi+bz_i = W h_i + b, and forms a probability over the vocabulary VV:

p(wcontext)=softmax(zi)w=ezi,wvVezi,vp(w \mid \text{context}) = \operatorname{softmax}(z_i)_w = \frac{e^{z_{i,w}}}{\sum_{v\in V} e^{z_{i,v}}}

We want to maximize the probability of the true token yiy_i. Maximizing a probability = minimizing its negative log. Summing over all masked positions:


Pretraining objective 2: Next Sentence Prediction (NSP)

WHY: many downstream tasks (QA, entailment) need relationships between two sentences, which single-sentence MLM doesn't teach.

LNSP=[ylogp^+(1y)log(1p^)],p^=σ(wh[CLS])\mathcal{L}_{\text{NSP}} = -\big[y\log \hat p + (1-y)\log(1-\hat p)\big],\qquad \hat p = \sigma(w^\top h_{\texttt{[CLS]}})

The total pretraining loss is L=LMLM+LNSP\mathcal{L} = \mathcal{L}_{\text{MLM}} + \mathcal{L}_{\text{NSP}}.


Special tokens & the input format

Every BERT input looks like: [CLS]  A1Am  [SEP]  B1Bk  [SEP]\texttt{[CLS]}\; A_1 \dots A_m \;\texttt{[SEP]}\; B_1 \dots B_k \;\texttt{[SEP]}

  • ==[CLS]== — a token whose final vector h[CLS]h_{\texttt{[CLS]}} is used as the sentence-level summary for classification.
  • [SEP] — separates sentence A from sentence B.
  • Three embeddings summed per token: token + position + segment (A vs B).
Figure — BERT and encoder models

Fine-tuning: WHY one model → many tasks

  • Sentence classification (sentiment): feed h[CLS]h_{\texttt{[CLS]}} → linear → softmax.
  • Token classification (NER, POS): feed each hih_i → linear → per-token label.
  • Span extraction (SQuAD QA): predict start/end positions over tokens.

Worked examples


Common mistakes


Active recall

Recall Test yourself (hidden — answer first!)
  • Why can't BERT use next-token prediction? → bidirectional attention would let it see the answer.
  • What is the 80/10/10 rule for? → prevent [MASK]-only train/test mismatch.
  • Which objective did RoBERTa drop? → NSP.
  • Which token gives the sentence summary? → [CLS].
Recall Feynman: explain to a 12-year-old

Imagine a sentence with some words hidden by stickers. A really smart kid reads everything around each sticker — words before AND after — and guesses the hidden word. To make sure the kid actually reads instead of memorizing where stickers go, sometimes we swap in a wrong word instead of a sticker, and sometimes leave the real word. After lots of practice guessing, the kid understands sentences so well that you can quickly teach them small new jobs — like "is this review happy or sad?" — with just a few examples. That smart reader is BERT.


Flashcards

What kind of Transformer is BERT (encoder/decoder)?
Encoder-only, bidirectional attention.
Why can't BERT be trained with next-token prediction?
Bidirectional attention would let each token attend to the future token it must predict — trivial cheating.
What fraction of tokens are selected in MLM?
15%.
Describe the 80/10/10 rule.
Of selected tokens: 80% → [MASK], 10% → random token, 10% → unchanged.
Why keep 10% unchanged / 10% random instead of always [MASK]?
[MASK] never appears at inference; forcing uncertainty about every token gives good representations for all tokens (avoids train/test mismatch).
Write the MLM loss.
1MiMlogp(yicontext)-\frac{1}{|M|}\sum_{i\in M}\log p(y_i\mid\text{context}), cross-entropy over masked positions only.
What is NSP and is it necessary?
Binary "is B the next sentence after A"; RoBERTa showed it's often unnecessary/harmful.
What are the three summed input embeddings in BERT?
Token + position + segment embeddings.
Why are position embeddings needed?
Self-attention is permutation-invariant; positions inject word order.
What is the [CLS] token used for?
Aggregated sentence-level representation for classification (used in NSP and fine-tuning).
How do you fine-tune BERT for sentiment?
Add a linear+softmax head on h[CLS]h_{[CLS]} and train on labelled data.
How is token classification (NER) done?
Apply a shared linear layer to each token's hih_i.

Connections

  • Transformer Architecture — BERT stacks its encoder blocks.
  • Self-Attention — bidirectional (unmasked) version powers BERT.
  • GPT and decoder models — the generative, causal-masked counterpart.
  • T5 and encoder-decoder models — text-to-text unifier.
  • Cross-Entropy Loss — MLM and NSP objectives.
  • Fine-Tuning vs Pretraining — the two-stage paradigm.
  • WordPiece Tokenization — how BERT splits text into sub-word tokens.
  • RoBERTa — BERT trained better, drops NSP.

Concept Map

motivates

is a

uses

no

enables cheating on

forces need for

masks

split by

prevents

projects h_i to

minimizes

contrasts with

Language is bidirectional

BERT encoder-only model

Encoder-only Transformer

Bidirectional attention

Causal mask

Next-word prediction

Masked Language Modelling

15% of tokens

80/10/10 rule

Train/test mismatch

Vocab logits and softmax

Cross-entropy loss

Decoder-only GPT causal

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, BERT ka core idea simple hai: kisi word ka matlab samajhne ke liye tumhe uske dono taraf ka context chahiye — left bhi aur right bhi. "Main bank gaya paise nikalne" me bank ka matlab aage ke words se clear hota hai. GPT jaise decoder models sirf left-to-right dekhte hain, lekin BERT ek encoder-only model hai jisme attention bidirectional hoti hai — har token poore sentence ko dekh sakta hai.

Problem yeh hai: agar model poora sentence dekh sakta hai aur usse next word predict karne ko bolo, to woh cheat karega (answer to saamne hai!). Isliye BERT Masked Language Modelling use karta hai — 15% tokens ko chhupa deta hai aur unhe predict karwata hai. Ek trick hai 80/10/10: 80% ko [MASK] se replace, 10% random word, 10% same rehne do. Yeh isliye ki [MASK] token real use me kabhi aata nahi, to model har token ka accha representation banana seekhe, sirf [MASK] ka nahi.

Ek doosra objective NSP (Next Sentence Prediction) tha, par baad me RoBERTa ne dikhaya ki yeh zaroori nahi — asli kaam MLM karta hai. Loss dono me cross-entropy hi hai, bas MLM me sirf masked positions par grade karte hain.

Kaam ka matlab: ek baar mehnga pretraining karo, phir chhota sa linear head laga ke kisi bhi task (sentiment, NER, QA) par thodi si training se fine-tune kar lo. [CLS] token poore sentence ka summary deta hai — usse classification kar lo. Yaad rakho: BERT samajhne ke liye hai, text generate karne ke liye nahi.

Go deeper — visual, from zero

Test yourself — Pretraining & Fine-Tuning LLMs

Connections