Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
BERT,
explained.
One year after the Transformer, a Google team asked a stubborn question: why should a model only read a sentence left to right? BERT let it read both directions at once — and by teaching a model to fill in the blanks across more than three billion words, it made "pre-train once, fine-tune anywhere" the default recipe for modern NLP.
Contents 17 sections
The delta The one-way problem The big idea: read both ways at once Masked language modeling: fill in the blank Next-sentence prediction Tokens, [CLS], and [SEP] The recipe: pre-train once, fine-tune anywhere 110M and 340M, derived by hand How it works The math The evidence Since then Solve it yourself Why it still matters Questions Check yourself Where this sitsWhat changes here: the direction text is read in
This is rung 1 of the pre-training ladder, so there is no rung below it to measure against — the comparison is against the practice it replaced. Before BERT, the strong recipe for a language representation was to read a sentence left to right and predict the next word, because that is what a language model is. Every word's representation could therefore only see the words before it.
BERT's change is small to describe and large in consequence: stop predicting the next word, and instead hide about 15% of the tokens and predict those. Once the target is a hidden token rather than the next one, there is no reason to withhold the right-hand context, so every token's representation is conditioned on the whole sentence in both directions at once.
The units to carry up the ladder: 110M parameters for the base model and 340M for the large one — the largest a language-understanding model had usefully been at the time, and a figure worth remembering when rung 3 arrives at 175B. Note also what BERT is for: it produces representations that you then fine-tune, with a task-specific head, on labelled data for each task. Both halves of that sentence are things later rungs remove.
The one-way problem
The Transformer had already shown that attention could replace recurrence. But the language models built on it still read like someone with a piece of paper covering the rest of the page: strictly left to right, one word at a time, predicting the next word from everything before it.
That one-way habit throws away half the clues. Take the word "bank" in "I went to the bank to deposit my" — you can't be sure it's a riverbank or a money bank until you read the word that comes after it. A left-to-right model, by design, never gets to peek forward. The meaning it builds is always half-blind.
The big idea: read both ways at once
BERT's bet was simple to state and awkward to pull off: let every word see the words on both sides of it, simultaneously. That's what the "B" stands for — Bidirectional Encoder Representations from Transformers.
The catch is a chicken-and-egg problem. If you train a model to predict the next word while also letting it look ahead, it can just read the answer — the future word it's supposed to guess is sitting right there. True bidirectional context and next-word prediction can't coexist. So BERT threw out next-word prediction entirely and invented a different game.
Masked language modeling: fill in the blank
Instead of predicting the next word, BERT plays fill-in-the-blank. Take a sentence, randomly hide about 15% of its words behind a [MASK] token, and train the model to recover what was hidden — using every other word, on both sides, as evidence. This is masked language modeling (MLM).
Because the answer is now hidden rather than sitting one step ahead, the model is free to use the future as well as the past. To guess "mat," it leans on "cat," "sat," and "on" all at once. Do this across billions of words and the model is forced to learn deep, two-sided representations of meaning.
A subtlety: the [MASK] token never appears at fine-tuning or inference time, which would create a mismatch. BERT hedges — of the 15% chosen words, 80% become [MASK], 10% are swapped for a random word, and 10% are left unchanged — so the model can't assume a masked slot is always literally [MASK].
Next-sentence prediction
Filling in words teaches BERT about individual sentences. But many real tasks — question answering, natural-language inference — hinge on the relationship between two sentences. So BERT added a second pre-training task: next-sentence prediction (NSP). Show the model two sentences and ask a yes/no question — did B actually follow A in the original text, or is it a random impostor pulled from somewhere else?
Half the training pairs are genuine neighbors, half are random. Learning to tell them apart nudges BERT toward understanding discourse and coherence, not just word-level patterns. (Later work — RoBERTa — showed NSP was largely unnecessary, but it was part of the original recipe.)
Tokens, [CLS], and [SEP]
BERT wraps its input in a few special tokens. Every sequence starts with [CLS] — a slot whose final vector becomes a summary of the whole input, perfect to hang a classifier on. Two sentences are divided by a [SEP] separator, and each token also carries a segment embedding marking whether it belongs to sentence A or B.
Words themselves are split into WordPiece sub-word units, so rare words like "tokenization" become "token" + "##ization" — a fixed 30,000-token vocabulary that never hits an unknown word. Each token's final embedding is the sum of three signals: what the word is, which segment it's in, and where it sits.
The recipe: pre-train once, fine-tune anywhere
This is BERT's real gift to the field. Pre-training — the expensive part — happens once: MLM plus NSP over BooksCorpus and English Wikipedia, days of compute on a big cluster. The result is a model that already understands language in general.
Then, for any specific task, you fine-tune: bolt a tiny task-specific layer onto the [CLS] output (or every token, for tagging), and train briefly on a small labeled dataset. Sentiment, question answering, named-entity recognition — same pre-trained body, different lightweight head, a few hours each. Teams that couldn't dream of training a language model from scratch could now reach state-of-the-art by fine-tuning BERT.
Before BERT, most NLP models were trained from scratch per task. After BERT, "download a pre-trained model and fine-tune it" became the default. That transfer-learning mindset is the through-line from BERT to every large model since.
110M and 340M, derived by hand
The two model sizes aren't arbitrary — they fall straight out of the architecture with the same napkin formula that sizes every Transformer (≈12·d² weights per layer, plus the embedding matrix):
BERT-large: 12·24·1024² + 30522·1024 + 512·1024 ≈ 333.8M ≈ 340M ✓
(30,522 is the WordPiece vocabulary; 512 the max positions.) The masking recipe is just as concrete. For every training sequence, 15% of tokens are selected for prediction — but only 80% of those become [MASK]; 10% are swapped for a random word and 10% left untouched:
| Per 1,000 tokens | Count | Why |
|---|---|---|
| Selected for prediction (15%) | 150 | enough signal per pass without destroying context |
| → replaced with [MASK] (80%) | 120 | the core fill-in-the-blank task |
| → swapped for a random token (10%) | 15 | model can't trust that visible words are real — must model everything |
| → left unchanged (10%) | 15 | [MASK] never appears at fine-tune time; this closes the mismatch |
That 80/10/10 hedge looks fussy until you see the failure it prevents: a model trained only on literal [MASK] slots learns "the interesting positions are the masked ones" — and at fine-tune time there are no masks, so the signal vanishes. The hedge forces every position to carry a real representation.
How BERT was pre-trained and fine-tuned, step by step
BERT's method has two phases that share one network. Pre-training runs once, on unlabeled text, and is the expensive part. Fine-tuning runs once per task, on labeled data, and is cheap. This is the procedure the paper describes.
- Build a document-level corpus. BooksCorpus (about 800M words) plus English Wikipedia (about 2,500M words), roughly 3.3B words in all. From Wikipedia only text passages are kept; lists, tables and headers are dropped. The authors chose whole documents over a shuffled sentence-level corpus such as the Billion Word Benchmark, because the model is trained on long contiguous spans.
- Sample a pair and pack it. Each example is two spans of text, A and B, with a combined length of at most 512 tokens. Half the time B is the span that really follows A; half the time it is a random span from elsewhere in the corpus. The pair is packed as [CLS] A [SEP] B [SEP], and segment embeddings mark which tokens belong to which span.
- Corrupt 15% of positions. WordPiece positions are chosen at random and each chosen one is replaced by [MASK], by a random token, or left alone, in the 80/10/10 proportions. The network only ever sees the corrupted sequence.
- Encode. A Transformer encoder with no causal mask. BERT-BASE has 12 layers, hidden size 768 and 12 attention heads; BERT-LARGE has 24 layers, hidden size 1,024 and 16 heads. The feed-forward inner size is four times the hidden size, and the activation is GELU.
- Score two losses. Final vectors at the chosen positions go through a softmax over the whole vocabulary and are scored by cross-entropy against the original tokens; every other position contributes nothing. The final [CLS] vector feeds a binary IsNext / NotNext classifier. The training loss is the sum of the two mean losses.
- Optimize. Adam with learning rate 1e-4, β1 = 0.9, β2 = 0.999 and L2 weight decay 0.01; linear warmup over the first 10,000 steps, then linear decay; dropout 0.1 on every layer. Each batch is 256 sequences of up to 512 tokens, about 128,000 tokens, for 1,000,000 steps, which the paper puts at roughly 40 epochs over the corpus. Attention cost grows with the square of length, so 90% of the steps use 128-token sequences and only the last 10% use 512, mainly so the later position embeddings get trained.
- Use modest hardware by later standards. BERT-BASE trained on 16 TPU chips and BERT-LARGE on 64, about four days each.
- Fine-tune end to end. Add a task head and train every weight, body included, on the labeled data.
The three kinds of head
For classification, one weight matrix W, sized labels × hidden, reads the final [CLS] vector C, and the label probabilities are softmax(C·W). For tagging, as in named-entity recognition, a classifier reads every token's final vector; the paper uses the first sub-token of each word. For SQuAD, the question is segment A, the passage is segment B, and the only new parameters are a start vector S and an end vector E.
The suggested search is small: batch size 16 or 32, learning rate 5e-5, 3e-5 or 2e-5, and 2 to 4 epochs. The paper notes that every result it reports can be reproduced in at most an hour on one Cloud TPU, or a few hours on a GPU, from the same checkpoint. BERT-LARGE sometimes failed to fine-tune on small datasets, so the authors ran several random restarts and kept the best model on the dev set.
The pre-training loss and the SQuAD span score
M— the positions chosen for prediction, about 15% of the sequence;x̃is the corrupted input andxithe original token at position i.p(xi | x̃)— a softmax over the WordPiece vocabulary computed from the final vector at position i, which has seen the whole corrupted sequence in both directions.LNSP— binary cross-entropy of the IsNext classifier on the final [CLS] vector.Ti— final vector of passage token i;SandE— the only new SQuAD parameters, each the size of a hidden state. Training maximizes log Pstart of the true start plus log Pend of the true end.
At the extremes: if M covered every position there would be nothing left to condition on, and if M were empty there would be no signal, which is why a modest fraction is chosen. The constraint j ≥ i rules out an end before its start. For SQuAD v2.0 the paper scores "no answer" as a span at [CLS], snull = S·C + E·C, and answers only when the best span beats snull + τ, with τ tuned on the dev set.
What BERT was tested on, and what the ablations showed
Each model was fine-tuned separately on each task. BERT-BASE was sized to match OpenAI GPT, a left-to-right Transformer, so the two could be compared directly; BERT-LARGE shows what size adds. BERT set a new state of the art on eleven tasks.
| Benchmark | Reference point | BERT |
|---|---|---|
| GLUE, official leaderboard score | OpenAI GPT: 72.8 | BERT-LARGE: 80.5 (+7.7) |
| GLUE average in the paper's own comparison (WNLI excluded) | OpenAI GPT: 75.1 | BASE 79.6 · LARGE 82.1 |
| MultiNLI-matched accuracy | OpenAI GPT: 82.1 | 86.7 (+4.6) |
| SQuAD v1.1 test F1 | Human: 91.2 | 93.2, ensemble with extra TriviaQA data (+1.5 over the top system) |
| SQuAD v2.0 test F1 | Previous best: 78.0 | 83.1 (+5.1) |
| SWAG accuracy | OpenAI GPT: 78.0 | 86.3 (+8.3) |
BERT-LARGE beat BERT-BASE on every GLUE task, most clearly on the small datasets.
Ablations, all on BERT-BASE dev sets
Dropping next-sentence prediction hurt QNLI, MNLI and SQuAD, with QNLI falling from 88.4 to 84.9. Training left to right without it hurt far more: MRPC fell from 86.7 to 77.5 and SQuAD F1 from 88.5 to 77.8. Adding a randomly initialized BiLSTM on top of that left-to-right model recovered SQuAD partway, to 84.9, but made GLUE worse. Scaling from 3 layers up to BERT-LARGE improved every task tried, even MRPC with only a few thousand training examples, and training for 1M rather than 500k steps added about a point on MNLI.
A feature-based variant, with BERT frozen and its top four hidden layers concatenated as input to a BiLSTM tagger on CoNLL-2003 named entities, reached 96.1 dev F1, only 0.3 behind fine-tuning the whole model. The masking-mix ablation found fine-tuning robust to the 80/10/10 choice, while the feature-based setting suffered most when every chosen token became [MASK].
What the authors admit, and what happened next
The paper is candid that masked language modelling creates a
mismatch between pre-training and fine-tuning: the
[MASK] token appears constantly during pre-training and never
at inference. That is the whole reason for the 80/10/10 split the exercise
above implements — of the tokens selected for prediction, most are masked,
some are replaced with a random token, and some are left alone. It is a
patch on a known defect, not an elegance.
The authors also note the obvious cost: because only the selected fraction of tokens is predicted, each batch teaches the model less than left-to-right prediction would, and pre-training converges more slowly per token seen.
How it held up: the bidirectional-encoder recipe was the dominant approach to language understanding for roughly three years and remains the right tool for retrieval and classification — rung 3 of the retrieval ladder is a direct descendant. What did not hold up is the assumption underneath it, that you need a task-specific fine-tune per task at all. Rung 2 makes every task the same shape, and rung 3 removes the fine-tune. Later work also showed BERT-sized models were badly under-trained on data relative to their parameter count, which is exactly the axis rung 5 formalises.
The masking recipe & the napkin math
BERT's exact 15% / 80-10-10 masking procedure on real text, plus the parameter derivation for both model sizes — running in your browser through WebAssembly. Run it, check the proportions land where the paper says, then change MASK_RATE to 30% and think about what that does to the training signal (this exact question produced several follow-up papers).
Write the body of mlm_mask. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 5 assertions below — they start red.
- Derives BERT-base near 110M
- Derives BERT-large near 340M
- Masking selects ~15 percent
- BERT-base has fewer parameters than BERT-large
- About 12% of all tokens become [MASK] (0.15 selected x 0.8)
Why it still matters
BERT is the encoder half of the family tree. Where GPT took the Transformer's decoder and ran toward generation, BERT took the encoder and ran toward understanding — and for years, if you were classifying, retrieving, or extracting, you reached for BERT or one of its descendants (RoBERTa, DistilBERT, ELECTRA, DeBERTa). Its sentence embeddings still power a huge share of search and retrieval systems today.
More than any single benchmark, BERT's legacy is the recipe it normalized: pre-train a Transformer on oceans of unlabeled text, then fine-tune. That idea — not the specific masking trick — is what every model after it inherited.
When you build semantic search or a RAG retriever, the embedding model turning your text into vectors is very often a BERT descendant. Understanding BERT is understanding the retrieval side of modern AI.
Questions people ask about BERT
How does BERT answer SQuAD questions?
BERT reads the question as segment A and the passage as segment B, packed as [CLS] question [SEP] passage [SEP]. Fine-tuning adds only two new vectors, a start vector S and an end vector E, each the size of a hidden state. The probability that passage token i starts the answer is a softmax of S·Ti over all passage tokens, and the end works the same way with E. A candidate span from i to j scores S·Ti + E·Tj, and the highest-scoring span whose end is not before its start is the answer. Training maximizes the log-likelihood of the correct start and end. For SQuAD v2.0, unanswerable questions are treated as a span at the [CLS] token, and the model only answers when its best span beats that null score by a threshold tuned on the dev set.
What hyperparameters was BERT pre-trained with?
The paper used batches of 256 sequences of up to 512 tokens, about 128,000 tokens per batch, for 1,000,000 steps, which it describes as roughly 40 epochs over a 3.3-billion-word corpus. The optimizer was Adam with learning rate 1e-4, beta1 0.9, beta2 0.999 and L2 weight decay 0.01, with linear warmup over the first 10,000 steps and linear decay after that. Dropout was 0.1 on all layers and the activation was GELU. To save compute, 90% of the steps used 128-token sequences and the last 10% used 512 tokens. BERT-BASE trained on 16 TPU chips and BERT-LARGE on 64, each for about four days.
What fine-tuning settings does the BERT paper recommend?
Most pre-training settings carry over unchanged; only batch size, learning rate and number of epochs are tuned. The paper suggests searching batch sizes of 16 and 32, Adam learning rates of 5e-5, 3e-5 and 2e-5, and 2 to 4 epochs, with dropout kept at 0.1. It reports that large datasets, with 100,000 or more labeled examples, are far less sensitive to these choices than small ones. Every result in the paper can be reproduced in at most an hour on a single Cloud TPU, or a few hours on a GPU, starting from the same pre-trained checkpoint. BERT-LARGE sometimes failed to fine-tune on small datasets, so the authors ran several random restarts and kept the best dev-set model.
Does removing next-sentence prediction hurt BERT?
In the BERT paper's own ablation, yes: a BERT-BASE model trained without the next-sentence objective did worse on QNLI, MNLI and SQuAD, with the largest drop on QNLI. RoBERTa (Liu and colleagues, 2019) later reached the opposite conclusion, finding that removing the objective matched or slightly improved downstream results. The two findings are less contradictory than they look, because the input format changed too: RoBERTa suggests BERT's ablation removed only the loss while still training on pairs of short segments, whereas RoBERTa packed full sentences from contiguous text up to 512 tokens. Most later encoders dropped next-sentence prediction or replaced it with a harder sentence-order task, as ALBERT did.
How much text was BERT pre-trained on?
About 3.3 billion words: BooksCorpus, roughly 800 million words of unpublished books, plus English Wikipedia, roughly 2,500 million words. From Wikipedia only the text passages were kept, with lists, tables and headers removed. The authors stress using a document-level corpus rather than a shuffled sentence-level one such as the Billion Word Benchmark, because the model is trained on long contiguous sequences and on pairs of consecutive spans. Over 1,000,000 steps of 256 sequences the model passed over the corpus roughly 40 times. Later work, RoBERTa among it, found that much more data and longer training kept improving models of the same size.
Can BERT be used without fine-tuning, as fixed features?
Yes, and the paper tested it on CoNLL-2003 named-entity recognition. Instead of fine-tuning, it froze BERT-BASE and fed activations from one or more layers into a two-layer bidirectional LSTM tagger. Concatenating the top four hidden layers gave 96.1 F1 on the dev set, only 0.3 behind fine-tuning the whole model at 96.4. The embedding layer alone was far worse, and the second-to-last layer did better than the last one. The practical point is that you can compute BERT features once and reuse them across many experiments, which is cheaper than fine-tuning a separate copy for every model you try.
5 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
BERT trains on 256 sequences of up to 512 tokens for 1,000,000 steps. Roughly how many passes is that over 3.3 billion words, and why is it an upper bound?
Show answer
256 × 512 ≈ 131,000 tokens per step, times 10^6 steps ≈ 1.3 × 10^11 tokens; divided by 3.3 × 10^9 that is about 40 passes, the paper's own figure. It is an upper bound because 90% of the steps used 128-token sequences, and because WordPiece splits many words into several tokens, so the same token budget covers fewer words.
For a SQuAD question, start scores S·Ti peak at token 40 and end scores E·Tj peak at token 35. What does BERT output?
Show answer
Not 40 to 35: a span needs j ≥ i. BERT searches the valid pairs and returns the one with the highest S·Ti + E·Tj — perhaps a start at 40 with a weaker end after it, or an end at 35 with a weaker start before it, whichever pair sums higher.
On SQuAD v2.0 the best span scores 7.2, the null score S·C + E·C is 6.5, and the tuned threshold is 1.0. Does BERT answer?
Show answer
No. It answers only when the best span beats snull + τ = 6.5 + 1.0 = 7.5, and 7.2 < 7.5, so it predicts that the question has no answer. A larger τ makes the model abstain more often; τ is picked to maximize F1 on the dev set.
Why did a BiLSTM on top of the left-to-right model recover part of the SQuAD gap but hurt GLUE?
Show answer
A span head needs each token's right-hand context to judge where an answer ends, and a left-to-right model has none. The BiLSTM supplies some, so SQuAD F1 rose from 77.8 to 84.9. But it is shallow and trained only on task data, not pre-trained, so it adds parameters without adding knowledge; on GLUE that cost more than it gave.
About how many positions in a 512-token sequence produce a masked-LM training signal, and what does that predict about convergence compared with a left-to-right model?
Show answer
15% of 512 ≈ 77 positions, against all 512 for a left-to-right model, so each batch carries roughly a seventh of the targets. The paper confirms the prediction: masked-LM training converges slightly more slowly, but it overtakes the left-to-right model's accuracy almost immediately.
Pre-training, and the scaling laws
The ladder where rung 5 overturns rung 4. Read `scaling-laws` before `chinchilla` — the second measures the same axis in the same units and gets a different answer.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- Chain-of-Thought PromptingShow a model a few worked examples with their reasoning and it starts solving problems it used to fail. Why reasoning emerges only at scale, the GSM8K jump, zero-shot "Let's think step by step", and how CoT seeded modern reasoning models.Read →
- LoRAThe paper that made fine-tuning affordable. Freeze the giant pretrained model and train two tiny low-rank matrices instead — up to 10,000x fewer trainable parameters, no extra inference latency, and swappable per-task adapters. The road to QLoRA and PEFT.Read →
- Direct Preference OptimizationRLHF without the RL. Align a model to human preference pairs with one simple classification-style loss — no separate reward model, no unstable reinforcement learning. Why "your LM is secretly a reward model", and how DPO became the default alignment method.Read →
- ChinchillaThe compute-optimal scaling law that said models were too big. Parameters and training tokens should scale together — ~20 tokens per parameter — so a 70B model trained on 1.4T tokens beat the 280B giants. Why every model since trains on trillions of tokens.Read →
- FlashAttentionAttention was slow for the wrong reason. By treating it as a memory-movement problem — tiling, online softmax, keeping work in fast SRAM instead of slow HBM — FlashAttention makes exact attention several times faster and cuts its memory from quadratic to linear, unlocking long context windows.Read →