BERT: pre-training a bidirectional Transformer by filling in masked words, then one thin output layer per task
BERT pre-trains a deep bidirectional Transformer encoder by restoring masked words, then adds one output layer per task and fine-tunes everything, setting records on 11 NLP tasks. It rechecks the paper's tables, parameter counts and training budget, and probes bert-base-uncased three ways.
On this page
- Why this paper is worth reading
- Background: why one-directional pre-trained representations fall short
- Method
- Model and input
- Pre-training task 1: masked language modeling
- Pre-training task 2: next sentence prediction
- Pre-training setup
- Fine-tuning: swap the output layer
- The paper’s experiments and conclusions
- Main results
- Ablations: what each removal costs
- Things to keep in mind when reading the results
- Hands-on recheck: recomputing the paper’s numbers
- Hands-on experiment: three probes of bert-base-uncased
- Limitations and what came after
- What to take away from this paper
- Further reading
- FAQ
BERT (Bidirectional Encoder Representations from Transformers) comes from “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” (Devlin, Chang, Lee and Toutanova of Google AI Language; arXiv 1810.04805; NAACL 2019). The paper pre-trains a deep, bidirectional Transformer encoder with masked language modeling (MLM): hide 15% of the input tokens at random and ask the model to restore them from the context on both sides. A second task, next sentence prediction (NSP), teaches the relation between two pieces of text. After pre-training, a small output layer is added on top, all parameters are fine-tuned on the downstream task, and the result set new records on 11 natural language processing tasks: a GLUE leaderboard score of 80.5 (7.7 points above OpenAI GPT’s 72.8), MNLI accuracy of 86.7%, SQuAD v1.1 test F1 of 93.2 and SQuAD v2.0 test F1 of 83.1. The model comes in two sizes: BERT-BASE (12 layers, about 110 million parameters) and BERT-LARGE (24 layers, about 340 million).
This post does two things. Recheck: it recomputes the paper’s tables and statements, including the Average column of Table 1, the gains quoted in the abstract, the ablations in Tables 5 to 8, the number of epochs and the parameter counts. Most numbers hold, with a few exceptions worth knowing. The Average column of Table 1 counts MNLI twice (matched and mismatched), nine numbers in all. “About 40 epochs” holds only if every step uses 512-token sequences, while the paper also says 90% of the steps use 128. The baseline row of Table 8 (the 80/10/10 mix) disagrees with BERT-BASE elsewhere in the paper by 1.0 and 1.2 F1 on NER, more than the spread among the rows of that table. Small-scale replication: three probes on the released bert-base-uncased. Hiding one side of the context cuts top-1 recovery of a masked whole word from 64.7% with both sides to 11.5% and 20.1%. At the positions where 80/10/10 swapped in a random token, the original word is still restored 44.2% of the time. The NSP head separates the real next sentence from a random sentence of another answer (82.2% right) but is almost never right on a later sentence of the same answer or on a swapped pair (1.2% and 0.1%).
Why this paper is worth reading
- It made pre-train-then-fine-tune the default in NLP. The authors call BERT the first fine-tuning-based representation model to reach state-of-the-art results on a large suite of sentence-level and token-level tasks, beating many task-specific architectures: one pre-trained model plus one new output layer covers classification, tagging and question answering.
- It gave “bidirectional” a trainable definition. A standard language model can only be trained left to right (or right to left), because conditioning on both sides would let each word indirectly see itself. MLM gets around that by hiding the word and restoring it.
- It is the flagship of the encoder branch. Today’s large models are mostly decoder-only, but both branches share the same Transformer block (see Transformer Block), and encoders in the BERT family still power retrieval embeddings, reranking and classification.
- It gives enough detail to be checked. The paper lists the full configuration of both sizes, the training hyperparameters and eight tables, and later work (RoBERTa, ALBERT, ELECTRA) corrected some of its conclusions, so it is a good paper to read with a recheck and a few probes.
- Neighbors on this site. The Transformer itself is in the Attention Is All You Need explainer; the decoder-only line is in the GPT series note; T5 puts BERT-style denoising into an encoder-decoder; ViT borrows the [CLS] token; WordPiece tokenization is covered in Tokenizers and Embeddings.
Background: why one-directional pre-trained representations fall short
Before BERT there were two ways to use a pre-trained language representation downstream. The feature-based approach, represented by ELMo, keeps a task-specific architecture and feeds the pre-trained representations in as extra features. The fine-tuning approach, represented by OpenAI GPT, adds a minimal set of task parameters and fine-tunes all pre-trained parameters on the downstream task. Both used the same kind of objective during pre-training: a unidirectional language model.
The paper’s argument is that unidirectionality limits the pre-trained representations. GPT is a left-to-right Transformer in which every token can attend only to the tokens on its left. That is sub-optimal for sentence-level tasks and could be very harmful for token-level tasks such as question answering, where context from both sides matters. ELMo trains two independent unidirectional LSTMs and concatenates their features, which is only a shallow kind of bidirectionality. BERT wants deep bidirectionality: every layer conditions on both sides at once.
| ELMo | OpenAI GPT | BERT | |
|---|---|---|---|
| Pre-training architecture | Two independent unidirectional LSTMs | Left-to-right Transformer | Bidirectional Transformer encoder |
| Conditioning | Each direction trained alone, features concatenated | Each token sees only its left | Every layer sees both sides |
| Use | Feature-based, task-specific architecture on top | Fine-tune all parameters | Fine-tune all parameters (features also work) |
The difference between BERT and GPT is not only the direction. Appendix A.4 of the paper lists the other differences itself:
- Data: GPT is trained on BooksCorpus (800 million words); BERT adds English Wikipedia (2,500 million words), 3.3 billion words in all.
- Special tokens: GPT introduces [SEP], [CLS] and the sentence A/B embeddings only at fine-tuning time; BERT learns them during pre-training.
- Batch size: both train for 1 million steps, but GPT uses a batch of 32,000 words and BERT 128,000 words, four times more.
- Learning rate: GPT uses the same 5e-5 for every fine-tuning experiment; BERT picks the best one per task.
So the edge of BERT-BASE over GPT in Table 1 does not come from bidirectionality alone. The paper’s own conclusion is that most of the gain comes from the two pre-training tasks and the bidirectionality they enable, and the evidence is the “LTR & No NSP” row of Table 5 below: it is the one comparison that controls the direction with the same data, input representation and fine-tuning scheme.
Method
The paper splits the method into pre-training and fine-tuning, and stresses that the architecture used in pre-training and the final downstream architecture differ only slightly. The figure puts the input representation, the two pre-training objectives and the four fine-tuning interfaces side by side.
Model and input
BERT is a Transformer encoder, and the paper says its implementation is almost identical to the original, so it does not repeat the background (see the Attention Is All You Need explainer). Write for the number of layers, for the hidden size and for the number of attention heads; the feed-forward width is always . The paper reports two sizes:
| Layers L | Hidden H | Heads A | Feed-forward width | Parameters in the paper | Computed from the config | |
|---|---|---|---|---|---|---|
| BERT-BASE | 12 | 768 | 12 | 3,072 | 110M | 110.1M |
| BERT-LARGE | 24 | 1,024 | 16 | 4,096 | 340M | 336.2M |
BASE was chosen to match GPT in size. The last column was counted here from the Transformers library configuration (both the MLM and NSP heads included, output matrix tied to the word embeddings, released vocabulary of 30,522); see “Recheck” below.
The input is always one token sequence, which can hold one “sentence” or a pair of sentences packed together (a “sentence” here is any span of contiguous text, not necessarily a linguistic sentence). The vocabulary is WordPiece with 30,000 tokens as the paper states it (the released uncased model has 30,522). The first token is always [CLS], and its final hidden state is the representation of the whole sequence. Two pieces of text are separated by [SEP] and each token receives a segment embedding that says whether it belongs to A or B. The input at each position is the sum of the token, segment and position embeddings.
Pre-training task 1: masked language modeling
A standard language model can only be trained in one direction, because conditioning on both sides would let each word indirectly see itself through the layers and make the prediction trivial. BERT’s way out: pick 15% of the token positions at random and predict only the original tokens there, with cross-entropy:
Here is the set of chosen positions and is the corrupted input; the final hidden vector at each chosen position goes through a softmax over the vocabulary. Unlike a denoising autoencoder, BERT predicts only the chosen words and does not reconstruct the whole input.
This has a side effect: [MASK] appears only in pre-training and never at fine-tuning time. To soften the mismatch, a chosen position is not always replaced by [MASK]; it follows an 80/10/10 rule:
| What happens to a chosen position | Share of chosen positions | Share of all tokens |
|---|---|---|
| Replaced by [MASK] | 80% | 12.0% |
| Replaced by a random token | 10% | 1.5% |
| Left unchanged | 10% | 1.5% |
The model therefore cannot tell whether the word in front of it is correct or was swapped, and has to build a context-dependent representation for every position. The price is a weak learning signal: only 15% of positions carry a loss (about 19.2 positions per 128-token sequence, 76.8 per 512-token sequence). Appendix C.1 admits that MLM converges slightly slower than a left-to-right model, but says it overtakes it in accuracy almost immediately. ELECTRA later took exactly this point as its starting point: learning from only 15% of the tokens is not an efficient use of compute.
Pre-training task 2: next sentence prediction
Question answering (QA) and natural language inference (NLI) depend on the relation between two sentences, which language modeling does not capture directly. So BERT adds a binary task. For each pre-training example, 50% of the time B really is the sentence that follows A (labeled IsNext) and 50% of the time B is a random sentence from the corpus (labeled NotNext); the output at [CLS] makes the call. A footnote reports that the final model reaches 97% to 98% accuracy on NSP, and another warns that without fine-tuning is not a meaningful sentence representation, because it was trained for NSP. The training loss is the sum of the mean MLM likelihood and the mean NSP likelihood:
Pre-training setup
| Item | The paper’s setting |
|---|---|
| Corpus | BooksCorpus (800M words) plus English Wikipedia (2,500M words; text passages only, no lists, tables or headers), 3.3 billion words in all. The paper stresses that a document-level corpus is needed to get long contiguous spans, not a shuffled sentence-level corpus such as the Billion Word Benchmark |
| Sequence | Two spans packed into one sequence, at most 512 tokens in all; masking is applied after WordPiece, with no special care for split words |
| Batch and steps | 256 sequences per batch (256 x 512 = 128,000 tokens, as the paper puts it), 1,000,000 steps |
| Optimizer | Adam with learning rate 1e-4, , , L2 weight decay 0.01, linear warmup over the first 10,000 steps and linear decay afterwards |
| Other | Dropout 0.1 on all layers; GELU activation, following GPT |
| Length schedule | 90% of the steps at length 128 and the last 10% at 512, so the position embeddings learn long positions |
| Hardware | BASE: 4 Cloud TPUs in Pod configuration (16 chips); LARGE: 16 Cloud TPUs (64 chips); 4 days each |
Fine-tuning: swap the output layer
At fine-tuning time the task input is put into the same “sentence A, sentence B” format, the output is attached to the matching positions of BERT, and all parameters are updated end to end (the lower half of the figure). The paper says fine-tuning is relatively cheap: every result can be replicated from the same pre-trained model in at most one hour on a single Cloud TPU, or a few hours on a GPU.
- GLUE: a classification layer ( is the number of labels) on , with loss . Batch size 32, 3 epochs, and the learning rate is chosen per task on the Dev set from 5e-5, 4e-5, 3e-5 and 2e-5. Fine-tuning BERT-LARGE was sometimes unstable on small datasets, so the authors ran several random restarts and kept the best on the Dev set; the test set was submitted once per model.
- SQuAD v1.1: introduce a start vector and an end vector . The probability that token starts the answer is a softmax of over the passage, and a candidate span is scored by the start score plus the end score, taking the best :
3 epochs, learning rate 5e-5, batch size 32. The paper also fine-tunes on TriviaQA first and then on SQuAD, as “modest data augmentation”.
- SQuAD v2.0: questions with no answer get a span that starts and ends at [CLS]. At prediction time the no-answer score is compared with the best non-null span, and the model predicts an answer only if it beats the null score by a threshold chosen on the Dev set. 2 epochs, learning rate 5e-5, batch size 48.
- SWAG: each of the four candidates becomes one input; a vector is dotted with the [CLS] representation to get a score, followed by a softmax. 3 epochs, learning rate 2e-5, batch size 16.
The paper’s experiments and conclusions
Main results
GLUE test results (scored by the evaluation server). QQP and MRPC report F1, STS-B reports Spearman correlation and the rest report accuracy; the Average column excludes WNLI, which the paper calls problematic.
| System | MNLI (m/mm) | QQP | QNLI | SST-2 | CoLA | STS-B | MRPC | RTE | Average |
|---|---|---|---|---|---|---|---|---|---|
| Training examples | 392k | 363k | 108k | 67k | 8.5k | 5.7k | 3.5k | 2.5k | |
| Pre-OpenAI SOTA | 80.6/80.1 | 66.1 | 82.3 | 93.2 | 35.0 | 81.0 | 86.0 | 61.7 | 74.0 |
| BiLSTM+ELMo+Attn | 76.4/76.1 | 64.8 | 79.8 | 90.4 | 36.0 | 73.3 | 84.9 | 56.8 | 71.0 |
| OpenAI GPT | 82.1/81.4 | 70.3 | 87.4 | 91.3 | 45.4 | 80.0 | 82.3 | 56.0 | 75.1 |
| BERT-BASE | 84.6/83.4 | 71.2 | 90.5 | 93.5 | 52.1 | 85.8 | 88.9 | 66.4 | 79.6 |
| BERT-LARGE | 86.7/85.9 | 72.1 | 92.7 | 94.9 | 60.5 | 86.5 | 89.3 | 70.1 | 82.1 |
Question answering and commonsense inference (test sets):
| Task | Metric | Previous best or baseline | BERT-LARGE |
|---|---|---|---|
| SQuAD v1.1 | F1 | 91.7 (leaderboard #1, nlnet ensemble) | 93.2 (ensemble, with TriviaQA); single model (with TriviaQA) 91.8 |
| SQuAD v2.0 | F1 | 78.0 (leaderboard #1, single model) | 83.1 |
| SWAG | Accuracy | 59.2 (ESIM+ELMo); 78.0 (OpenAI GPT) | 86.3 |
| GLUE leaderboard | Score | 72.8 (OpenAI GPT) | 80.5 |
Ablations: what each removal costs
Section 5 uses the BERT-BASE architecture with the same data and fine-tuning settings and compares three pre-training variants (Dev sets):
| Pre-training setup | MNLI-m | QNLI | MRPC | SST-2 | SQuAD |
|---|---|---|---|---|---|
| BERT-BASE (MLM + NSP) | 84.4 | 88.4 | 86.7 | 92.7 | 88.5 |
| No NSP | 83.9 | 84.9 | 86.5 | 92.6 | 87.9 |
| Left-to-right, no NSP (LTR) | 82.1 | 84.3 | 77.5 | 92.1 | 77.8 |
| LTR plus a BiLSTM on top | 82.1 | 84.1 | 75.7 | 91.6 | 84.9 |
The paper’s reading: removing NSP hurts QNLI, MNLI and SQuAD noticeably; the left-to-right model is worse than the MLM model on every task, with the largest drops on MRPC and SQuAD; adding a randomly initialized BiLSTM recovers much of SQuAD but stays far below the bidirectional model and hurts the GLUE tasks. Three more sets of results:
- Model size (Table 6): from 3 layers of 768 dimensions to 24 layers of 1,024, MNLI-m rises from 77.9 to 86.6, MRPC from 79.8 to 87.8 and SST-2 from 88.4 to 93.7, and every column improves monotonically with size. The paper calls this the first work to demonstrate convincingly that scaling to extreme model sizes also helps very small tasks, provided the model is pre-trained enough.
- Feature-based use (Table 7): on CoNLL-2003 named entity recognition, concatenating the last four layers of BERT-BASE as features, with a two-layer BiLSTM on top, gives a Dev F1 of 96.1, only 0.3 below fine-tuning the whole model (96.4), so BERT works both ways.
- Masking strategy (Table 8): on MNLI and NER, fine-tuning is quite robust to departures from 80/10/10; using only [MASK] hurts the feature-based NER result and using only random tokens is clearly worse.
Things to keep in mind when reading the results
- Most ”%” in the paper are percentage points. The abstract’s “GLUE score to 80.5% (7.7% point absolute improvement)” and “MultiNLI accuracy to 86.7% (4.6% absolute improvement)”, and the text’s “4.5% and 7.0% respective average accuracy improvement”, are differences between two scores, not relative gains.
- Test scores are the best of several runs chosen on the Dev set. LARGE was unstable on small datasets, so the authors ran random restarts and selected the best model on the Dev set before submitting it, once per model. The LARGE numbers in Table 1 are therefore not averages over runs.
- The gap to GPT is not only direction (previous section): about four times as much data, four times the batch size and a per-task learning rate. The controlled direction comparison is the LTR row of Table 5.
- Each ablation cell is one pre-training run. The BERT-BASE of Table 5 and the 12-layer, 768-dimension row of Table 6 are the same configuration; MNLI-m and MRPC agree, but SST-2 is 92.7 against 92.9, a 0.2-point gap the paper does not explain. Of the NSP removals, SST-2 (-0.1) and MRPC (-0.2) are no larger than that gap, MNLI (-0.5) and SQuAD (-0.6) are only two or three times as large, and only QNLI (-3.5) is clearly larger.
- The claim about NSP was not tested in isolation. The paper says removing NSP “hurts performance significantly”, but RoBERTa later found in a stricter comparison that removing the NSP loss matches or slightly improves downstream results, and suspected that the original BERT experiment removed only the loss term while keeping the paired-segment input format.
Hands-on recheck: recomputing the paper’s numbers
No training is needed: the paper’s tables are copied into code, recomputed by the paper’s own recipe, and the parameter counts come from the Transformers library configuration. The output has seven parts: how the Average column of Table 1 is computed, the gains quoted in the abstract and text, whether LARGE’s gain over BASE depends on the training-set size, the internal consistency of Tables 5 to 7, the baseline row of Table 8 against the other tables, the masking rate with the pre-training data and compute, and the parameter counts. Environment: Python 3.14.3, PyTorch 2.10.0, Transformers 5.3.0 (used only to build models from configs and count parameters; no weights are loaded).
Full code (about 185 lines)
"""Checking BERT: its tables, parameter counts and pre-training budget"""
import torch
from transformers import BertConfig, BertForPreTraining
from transformers import OpenAIGPTConfig, OpenAIGPTLMHeadModel
from transformers import logging as hf_logging
hf_logging.set_verbosity_error()
# Table 1 (GLUE test): MNLI in two columns, one per other task
COLS = ("MNLI-m", "MNLI-mm", "QQP", "QNLI", "SST-2", "CoLA", "STS-B",
"MRPC", "RTE")
TRAIN_K = (392, 392, 363, 108, 67, 8.5, 5.7, 3.5, 2.5) # train size (thousands)
ROWS = {
"Pre-OpenAI SOTA": ((80.6, 80.1, 66.1, 82.3, 93.2, 35.0, 81.0, 86.0,
61.7), 74.0),
"BiLSTM+ELMo+Attn": ((76.4, 76.1, 64.8, 79.8, 90.4, 36.0, 73.3, 84.9,
56.8), 71.0),
"OpenAI GPT": ((82.1, 81.4, 70.3, 87.4, 91.3, 45.4, 80.0, 82.3, 56.0),
75.1),
"BERT-BASE": ((84.6, 83.4, 71.2, 90.5, 93.5, 52.1, 85.8, 88.9, 66.4),
79.6),
"BERT-LARGE": ((86.7, 85.9, 72.1, 92.7, 94.9, 60.5, 86.5, 89.3, 70.1),
82.1),
}
# --- 1. How the Average column is computed ---
print("1. The Average column of Table 1")
print(f" {'system':<18}{'paper':>6}{'9 nums':>8}{'8 tasks, MNLI=mean':>20}"
f"{'8 tasks, MNLI=m':>17}")
for name, (v, printed) in ROWS.items():
nine = sum(v) / 9
eight = (sum(v) - v[0] - v[1] + (v[0] + v[1]) / 2) / 8
only_m = (sum(v) - v[1]) / 8
print(f" {name:<18}{printed:>6.1f}{nine:>8.2f}{eight:>20.2f}"
f"{only_m:>17.2f}")
def avg9(name):
return sum(ROWS[name][0]) / 9
def avg8(name):
v = ROWS[name][0]
return (sum(v) - v[0] - v[1] + (v[0] + v[1]) / 2) / 8
for name in ("BERT-BASE", "BERT-LARGE"):
print(f" {name} minus OpenAI GPT: "
f"9 numbers {avg9(name) - avg9('OpenAI GPT'):.2f}, "
f"8 tasks {avg8(name) - avg8('OpenAI GPT'):.2f}")
# --- 2. Headline gains in the abstract and text ---
print("\n2. Headline gains in the abstract and text (percentage points)")
claims = (
("GLUE leaderboard 80.5 - 72.8", 80.5 - 72.8, 7.7),
("MNLI 86.7 - 82.1", 86.7 - 82.1, 4.6),
("SQuAD 1.1 test F1 93.2 - 91.7", 93.2 - 91.7, 1.5),
("SQuAD 2.0 test F1 83.1 - 78.0", 83.1 - 78.0, 5.1),
("SWAG 86.3 - 59.2 (ESIM+ELMo)", 86.3 - 59.2, 27.1),
("SWAG 86.3 - 78.0 (OpenAI GPT)", 86.3 - 78.0, 8.3),
("Table 1 BASE 79.6 - 75.1 (GPT)", 79.6 - 75.1, 4.5),
("Table 1 LARGE 82.1 - 75.1 (GPT)", 82.1 - 75.1, 7.0),
)
for text, got, paper in claims:
print(f" {text:<34}{got:5.1f}", f"(paper {paper})")
print(" Against the Pre-OpenAI SOTA row (74.0) instead:",
f"BASE +{79.6 - 74.0:.1f}, LARGE +{82.1 - 74.0:.1f}")
# --- 3. Does the LARGE-over-BASE gain depend on training-set size ---
print("\n3. LARGE minus BASE, sorted by training-set size")
base, large = ROWS["BERT-BASE"][0], ROWS["BERT-LARGE"][0]
gain = [round(b - a, 1) for a, b in zip(base, large)]
order = sorted(range(9), key=lambda i: TRAIN_K[i])
for i in order:
print(f" {COLS[i]:<8}{TRAIN_K[i]:>6g}k {gain[i]:+5.1f}")
def ranks(xs):
s = sorted(range(len(xs)), key=lambda i: xs[i])
r = [0.0] * len(xs)
for k, i in enumerate(s):
r[i] = k + 1.0
return r
# MNLI m/mm merged into one task, 8 tasks; Spearman, no ties
idx = [0, 2, 3, 4, 5, 6, 7, 8]
sz = [TRAIN_K[i] for i in idx]
gn = [(gain[0] + gain[1]) / 2 if i == 0 else gain[i] for i in idx]
rs, rg = ranks(sz), ranks(gn)
n = len(idx)
rho = 1 - 6 * sum((a - b) ** 2 for a, b in zip(rs, rg)) / (n * (n * n - 1))
print(f" Spearman correlation of size and gain: {rho:+.2f} ({n} tasks)")
# --- 4. Tables 5, 6, 7 internal consistency ---
print("\n4. Table 5: Dev-set change for each thing removed")
T5 = {"BERT-BASE": (84.4, 88.4, 86.7, 92.7, 88.5),
"No NSP": (83.9, 84.9, 86.5, 92.6, 87.9),
"LTR & No NSP": (82.1, 84.3, 77.5, 92.1, 77.8),
"+ BiLSTM": (82.1, 84.1, 75.7, 91.6, 84.9)}
T5_COLS = ("MNLI-m", "QNLI", "MRPC", "SST-2", "SQuAD")
print(" " + " " * 22 + "".join(f"{c:>8}" for c in T5_COLS))
for new, old in (("No NSP", "BERT-BASE"), ("LTR & No NSP", "No NSP"),
("+ BiLSTM", "LTR & No NSP")):
label = f"{new} - {old}"
print(f" {label:<22}" + "".join(
f"{b - a:>+8.1f}" for a, b in zip(T5[old], T5[new])))
T6 = ( # L, H, A, LM ppl, MNLI-m, MRPC, SST-2
(3, 768, 12, 5.84, 77.9, 79.8, 88.4),
(6, 768, 3, 5.24, 80.6, 82.2, 90.7),
(6, 768, 12, 4.68, 81.9, 84.8, 91.3),
(12, 768, 12, 3.99, 84.4, 86.7, 92.9),
(12, 1024, 16, 3.54, 85.7, 86.9, 93.3),
(24, 1024, 16, 3.23, 86.6, 87.8, 93.7),
)
print("\n Table 6: does every column improve strictly with model size")
for j, name in ((3, "LM ppl"), (4, "MNLI-m"), (5, "MRPC"), (6, "SST-2")):
col = [r[j] for r in T6]
ok = all(a > b for a, b in zip(col, col[1:])) if j == 3 else all(
a < b for a, b in zip(col, col[1:]))
print(f" {name:<8}{' -> '.join(str(x) for x in col)} ", ok)
print(" The same BERT-BASE: SST-2 is 92.7 in Table 5 and 92.9 in Table 6")
# --- 5. Table 8 baseline row against the other tables ---
print("\n5. Table 8's baseline row (80/10/10) against Tables 5 and 7")
rows8 = {"80/10/10": (84.2, 95.4, 94.9), "100/0/0": (84.3, 94.9, 94.0),
"80/0/20": (84.1, 95.2, 94.6), "80/20/0": (84.4, 95.2, 94.7),
"0/20/80": (83.7, 94.8, 94.6), "0/0/100": (83.6, 94.9, 94.6)}
other = (84.4, 96.4, 96.1) # Table 5 MNLI-m; Table 7 BASE, two rows
for j, name in enumerate(("MNLI", "NER fine-tune", "NER feature-based")):
col = [v[j] for v in rows8.values()]
print(f" {name:<18}", "baseline row", f"{col[0]}",
"elsewhere", f"{other[j]}", "gap",
f"{col[0] - other[j]:+.1f}", "range over the rows",
f"{max(col) - min(col):.1f}")
# --- 6. Pre-training data and compute ---
print("\n6. Masking rates, pre-training data and compute")
print(f" Of the 15%: [MASK] {0.15 * 0.8:.1%}, "
f"random {0.15 * 0.1:.1%}, unchanged {0.15 * 0.1:.1%}")
for length in (128, 512):
print(f" {length} tokens per sequence: {0.15 * length:.1f} predicted")
WORDS = 0.8e9 + 2.5e9 # BooksCorpus + Wikipedia
STEPS, BATCH = 1_000_000, 256
all512 = STEPS * BATCH * 512
mixed = 0.9 * STEPS * BATCH * 128 + 0.1 * STEPS * BATCH * 512
print(f" Corpus: {WORDS / 1e9:.1f}B words; the paper says ~40 epochs")
print(f" Reading 1 (all 512): {all512 / 1e9:.1f}B tokens, "
f"{all512 / WORDS:.1f} epochs")
print(f" Reading 2, 90% of steps at 128 and 10% at 512, batch 256 sequences:"
f" {mixed / 1e9:.1f}B", "tokens ->", f"{mixed / WORDS:.1f}", "epochs")
print(f" BASE: 16 chips x 4 days = {16 * 4 * 24:,} chip-hours; "
f"LARGE: 64 x 4 days = {64 * 4 * 24:,}")
# --- 7. Parameter counts, counted on the meta device ---
def count(model):
return sum(p.numel() for p in model.parameters())
def bert(layers, hidden, heads, vocab=30_522):
cfg = BertConfig(vocab_size=vocab, hidden_size=hidden,
num_hidden_layers=layers, num_attention_heads=heads,
intermediate_size=4 * hidden)
with torch.device("meta"):
return BertForPreTraining(cfg)
print("\n7. Parameters (both heads, output matrix tied to embeddings)")
for name, (l, h, a) in (("BASE", (12, 768, 12)), ("LARGE", (24, 1024, 16))):
m = bert(l, h, a)
emb = count(m.bert.embeddings)
print(f" BERT-{name}: {count(m) / 1e6:.1f}M", ", embeddings",
f"{emb / 1e6:.1f}M", ", the paper says",
"110M" if name == "BASE" else "340M")
base30 = count(bert(12, 768, 12, vocab=30_000))
print(f" BASE with a 30,000-token vocabulary: {base30 / 1e6:.1f}M "
f"(released: 30,522)")
with torch.device("meta"):
gpt1 = OpenAIGPTLMHeadModel(OpenAIGPTConfig())
print(f" OpenAI GPT (12 layers, 768, 12 heads, 40,478 tokens): "
f"{count(gpt1) / 1e6:.1f}M")
print(" Table 6 rows (with both heads):",
" ".join(f"{count(bert(l, h, a)) / 1e6:.0f}M" for l, h, a, *_ in T6))
Output:
1. The Average column of Table 1
system paper 9 nums 8 tasks, MNLI=mean 8 tasks, MNLI=m
Pre-OpenAI SOTA 74.0 74.00 73.21 73.24
BiLSTM+ELMo+Attn 71.0 70.94 70.28 70.30
OpenAI GPT 75.1 75.13 74.31 74.35
BERT-BASE 79.6 79.60 79.05 79.12
BERT-LARGE 82.1 82.08 81.55 81.60
BERT-BASE minus OpenAI GPT: 9 numbers 4.47, 8 tasks 4.74
BERT-LARGE minus OpenAI GPT: 9 numbers 6.94, 8 tasks 7.24
2. Headline gains in the abstract and text (percentage points)
GLUE leaderboard 80.5 - 72.8 7.7 (paper 7.7)
MNLI 86.7 - 82.1 4.6 (paper 4.6)
SQuAD 1.1 test F1 93.2 - 91.7 1.5 (paper 1.5)
SQuAD 2.0 test F1 83.1 - 78.0 5.1 (paper 5.1)
SWAG 86.3 - 59.2 (ESIM+ELMo) 27.1 (paper 27.1)
SWAG 86.3 - 78.0 (OpenAI GPT) 8.3 (paper 8.3)
Table 1 BASE 79.6 - 75.1 (GPT) 4.5 (paper 4.5)
Table 1 LARGE 82.1 - 75.1 (GPT) 7.0 (paper 7.0)
Against the Pre-OpenAI SOTA row (74.0) instead: BASE +5.6, LARGE +8.1
3. LARGE minus BASE, sorted by training-set size
RTE 2.5k +3.7
MRPC 3.5k +0.4
STS-B 5.7k +0.7
CoLA 8.5k +8.4
SST-2 67k +1.4
QNLI 108k +2.2
QQP 363k +0.9
MNLI-m 392k +2.1
MNLI-mm 392k +2.5
Spearman correlation of size and gain: +0.10 (8 tasks)
4. Table 5: Dev-set change for each thing removed
MNLI-m QNLI MRPC SST-2 SQuAD
No NSP - BERT-BASE -0.5 -3.5 -0.2 -0.1 -0.6
LTR & No NSP - No NSP -1.8 -0.6 -9.0 -0.5 -10.1
+ BiLSTM - LTR & No NSP +0.0 -0.2 -1.8 -0.5 +7.1
Table 6: does every column improve strictly with model size
LM ppl 5.84 -> 5.24 -> 4.68 -> 3.99 -> 3.54 -> 3.23 True
MNLI-m 77.9 -> 80.6 -> 81.9 -> 84.4 -> 85.7 -> 86.6 True
MRPC 79.8 -> 82.2 -> 84.8 -> 86.7 -> 86.9 -> 87.8 True
SST-2 88.4 -> 90.7 -> 91.3 -> 92.9 -> 93.3 -> 93.7 True
The same BERT-BASE: SST-2 is 92.7 in Table 5 and 92.9 in Table 6
5. Table 8's baseline row (80/10/10) against Tables 5 and 7
MNLI baseline row 84.2 elsewhere 84.4 gap -0.2 range over the rows 0.8
NER fine-tune baseline row 95.4 elsewhere 96.4 gap -1.0 range over the rows 0.6
NER feature-based baseline row 94.9 elsewhere 96.1 gap -1.2 range over the rows 0.9
6. Masking rates, pre-training data and compute
Of the 15%: [MASK] 12.0%, random 1.5%, unchanged 1.5%
128 tokens per sequence: 19.2 predicted
512 tokens per sequence: 76.8 predicted
Corpus: 3.3B words; the paper says ~40 epochs
Reading 1 (all 512): 131.1B tokens, 39.7 epochs
Reading 2, 90% of steps at 128 and 10% at 512, batch 256 sequences: 42.6B tokens -> 12.9 epochs
BASE: 16 chips x 4 days = 1,536 chip-hours; LARGE: 64 x 4 days = 6,144
7. Parameters (both heads, output matrix tied to embeddings)
BERT-BASE: 110.1M , embeddings 23.8M , the paper says 110M
BERT-LARGE: 336.2M , embeddings 31.8M , the paper says 340M
BASE with a 30,000-token vocabulary: 109.7M (released: 30,522)
OpenAI GPT (12 layers, 768, 12 heads, 40,478 tokens): 116.5M
Table 6 rows (with both heads): 46M 68M 68M 110M 185M 336M
Reading these numbers.
- The Average column is the arithmetic mean of nine numbers. Counting MNLI’s m and mm separately plus the other seven tasks gives nine numbers, and four of the five rows match the printed average to rounding (BERT-BASE 79.60, BERT-LARGE 82.08, OpenAI GPT 75.13, Pre-OpenAI SOTA 74.00); the BiLSTM+ELMo+Attn row is slightly off (70.94 computed, 71.0 printed). Treating MNLI as one task and averaging eight gives 79.05 for BASE and 81.55 for LARGE, which do not match the paper. MNLI therefore carries two shares of the weight in the average.
- Every quoted gain recomputes, and the unit is percentage points. The eight gains in the abstract and text (7.7, 4.6, 1.5, 5.1, 27.1, 8.3, 4.5 and 7.0) all agree with the paper. “4.5% and 7.0% average improvement over the prior state of the art” is in fact the difference to OpenAI GPT’s average (79.6 - 75.1, 82.1 - 75.1); against the Pre-OpenAI SOTA row (74.0) of the table it would be +5.6 and +8.1.
- “Small datasets gain more” holds for only half of the tasks. LARGE over BASE gains +3.7 on RTE (2.5k training examples) and +8.4 on CoLA (8.5k), but only +0.4 on MRPC (3.5k) and +0.7 on STS-B (5.7k), while QNLI (108k) and the two MNLI sets gain +2.1 to +2.5. The Spearman correlation between training-set size and gain is only +0.10 (8 tasks, the two MNLI gains averaged into one). The “bigger gain on small data” story rests mostly on CoLA and RTE.
- Tables 5 and 6: the trend is clear, the magnitudes deserve a discount. In Table 6 the three Dev metrics and the language-model perplexity improve strictly row by row. In Table 5, removing NSP costs MNLI-m -0.5, QNLI -3.5, MRPC -0.2, SST-2 -0.1 and SQuAD -0.6; going from MLM to LTR costs MRPC -9.0 and SQuAD -10.1, and -0.5 to -1.8 elsewhere. The same BERT-BASE has SST-2 92.7 in Table 5 and 92.9 in Table 6.
- The baseline row of Table 8 disagrees with the other tables. The 80/10/10 row (the setting BERT actually uses) gives 84.2 on MNLI, where Table 5 has 84.4 for the same model; NER fine-tuning gives 95.4, where Table 7 has 96.4 for BERT-BASE; NER feature-based gives 94.9, where Table 7 has 96.1 for the concatenation of the last four layers. The last two gaps (-1.0 and -1.2) are larger than the spread among the rows of Table 8 (0.6 and 0.9), so the rows of Table 8 are only good for comparison within the table and should not be mixed with other tables. Oddly, the feature-based baseline 94.9 equals the “last hidden layer only” entry of Table 7, although the paper says Table 8’s feature-based setting concatenates the last four layers; I cannot tell which side is wrong, or whether it is a separate run.
- “About 40 epochs” needs a question mark. The paper says 1 million steps of 256 sequences of 512 tokens over a 3.3-billion-word corpus come to “approximately 40 epochs”. With all steps at 512 that is 131.1B tokens and 39.7 epochs, which agrees; but the paper also says 90% of the steps use length 128, and if those steps also use 256 sequences the total is 42.6B tokens, about 12.9 epochs. To agree with “about 40 epochs”, the length-128 steps would need about 130 thousand tokens per batch as well (1,024 sequences), which the paper does not say. The count also treats words and WordPiece tokens as the same thing, although a word is usually more than one token.
- Parameters: BASE agrees, LARGE’s “340M” is a rounded-up figure. From the configuration, BASE has 110.1M (both heads included, output matrix tied to the word embeddings) and LARGE 336.2M, of which the embeddings are 23.8M and 31.8M. With the paper’s 30,000-token vocabulary, BASE would be 109.7M (the released vocabulary has 30,522). “BASE matches GPT in size” holds roughly: counted from 12 layers, 768 dimensions and a vocabulary of 40,478, OpenAI GPT has 116.5M. The rows of Table 6 (both heads included) come to 46M, 68M, 68M, 110M, 185M and 336M.
- Pre-training budget. BASE trained for 4 days on 16 TPU chips, about 1,536 chip-hours; LARGE on 64 chips for 4 days, about 6,144 chip-hours. The paper gives no FLOPs and none are converted here.
Hands-on experiment: three probes of bert-base-uncased
Replicating BERT means pre-training it again (BASE took 4 days on 16 TPU chips), which this laptop cannot do. So instead of replicating the paper’s pre-training ablations, this section runs three probes on the released bert-base-uncased to see how three mechanisms from the paper look in that model. It is a “small-scale replication” with large differences from the paper:
| The paper | These probes | |
|---|---|---|
| Model | Self-pre-trained BASE, plus a separately pre-trained LTR model | The released bert-base-uncased; no retraining, no LTR control |
| Text | Downstream task datasets | Answers written by text-davinci-003 in the Alpaca dataset (not in BERT’s corpus): 1,500 answers with at least 4 sentences each |
| One-directional control | A separately trained LTR model | An attention mask hides one side, measuring what each side contributes |
| Metric | Downstream accuracy | Restoring a masked word (top-1, top-5) and the verdict of the NSP head |
The three probes:
- How much does one side of the context matter? From each answer pick a random sentence, choose a whole word made of a single WordPiece, replace it by one [MASK] and let the MLM head predict it. Five conditions: both sides; left only (an attention mask hides everything to the right, including the final [SEP], with position ids unchanged); right only; no context (both sides hidden, only [CLS] and [MASK] itself left); and “left only, cut off” (the sequence is truncated to [CLS] left-context [MASK] [SEP], which was my first version and is kept as a cautionary example).
- After 80/10/10, can the model still restore the word? In each sentence every token is chosen with probability 15% and corrupted by 80/10/10; report top-1 recovery at the three kinds of positions. The three kinds are drawn from the same sentences, so their difficulty is the same and the three numbers can be compared directly.
- What is the NSP head looking at? From the same answers build four kinds of sentence pairs: the real next sentence; a random sentence from another answer; a later sentence of the same answer (at least one sentence further); and the real next sentence with the order swapped. Report how often the NSP head says “next sentence”.
Environment: CPU (Apple M2 Max, 6 threads), Python 3.14.3, PyTorch 2.10.0, Transformers 5.3.0, datasets 4.6.1; bert-base-uncased is Apache-2.0 licensed according to its model card, and the Alpaca dataset (tatsu-lab/alpaca) is CC BY-NC 4.0 according to its dataset card. Sampling, masking, corruption and pair construction use four independent random seeds; there is no training, so another environment should reproduce the numbers exactly. The intervals are 95% normal approximations.
Full code (about 216 lines)
"""Three probes of bert-base-uncased: context, 80/10/10, NSP head
Usage: python exp_bert_probe.py
"""
import math
import random
import re
from collections import Counter
import datasets
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, BertForPreTraining
from transformers import logging as hf_logging
hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
datasets.logging.set_verbosity_error()
datasets.disable_progress_bars()
torch.set_num_threads(6)
NAME, N_DOC = "bert-base-uncased", 1500
# Independent seeds for sampling, masking, corruption, NSP pairs
SEED_DOC, SEED_MASK, SEED_NOISE, SEED_NSP = 0, 1, 2, 3
def pad(s, width): # CJK characters take two columns
wide = sum(1 for c in s if ord(c) > 0x2E80)
return s + " " * (width - len(s) - wide)
tok = AutoTokenizer.from_pretrained(NAME)
model, info = BertForPreTraining.from_pretrained(
NAME, output_loading_info=True)
model.eval()
CLS, SEP, MASK = tok.cls_token_id, tok.sep_token_id, tok.mask_token_id
FIRST_REAL = 999 # ids 0-998 are special tokens and [unused*]
n_par = sum(p.numel() for p in model.parameters())
miss, extra = len(info["missing_keys"]), len(info["unexpected_keys"])
print(f"{NAME}: {n_par / 1e6:.1f}M parameters; at load, "
f"{miss} weights missing and {extra} unexpected; CPU")
# Data: Alpaca outputs (text-davinci-003, 2023), not in BERT's corpus
raw = load_dataset("tatsu-lab/alpaca", split="train")["output"]
docs = []
for text in raw:
if "\n" in text or not text.isascii():
continue
sents = [s for s in re.split(r"(?<=[.!?])\s+", text.strip())
if s[:1].isupper() and 8 <= len(s.split()) <= 40]
if len(sents) >= 4:
docs.append(sents)
random.Random(SEED_DOC).shuffle(docs)
docs = docs[:N_DOC]
print(f"Data: {len(docs):,} Alpaca outputs with at least 4 sentences each")
def predict(seqs, positions, hidden=None):
"""Top-5 token ids at each requested position of each sequence.
hidden[i] lists indices of sequence i that no token may attend to.
"""
out = [None] * len(seqs)
order = sorted(range(len(seqs)), key=lambda i: len(seqs[i]))
for b in range(0, len(order), 64):
idx = order[b:b + 64]
width = max(len(seqs[i]) for i in idx)
ids = torch.zeros(len(idx), width, dtype=torch.long)
att = torch.zeros(len(idx), width, dtype=torch.long)
for r, i in enumerate(idx):
ids[r, :len(seqs[i])] = torch.tensor(seqs[i])
att[r, :len(seqs[i])] = 1
if hidden:
att[r, hidden[i]] = 0
with torch.inference_mode():
logits = model(input_ids=ids, attention_mask=att).prediction_logits
for r, i in enumerate(idx):
out[i] = [logits[r, p].topk(5).indices.tolist()
for p in positions[i]]
return out
def pm(k, n): # half-width of the 95% interval (normal approximation)
p = k / n
return 1.96 * math.sqrt(p * (1 - p) / n)
# --- 1. Mask one whole word: what does each side of the context add ---
rng = random.Random(SEED_MASK)
items = [] # (token ids of a sentence, masked position)
for sents in docs:
toks = tok.tokenize(rng.choice(sents))
if not 6 <= len(toks) <= 64:
continue
whole = [i for i, t in enumerate(toks)
if t.isalpha() and not t.startswith("##")
and not (i + 1 < len(toks) and toks[i + 1].startswith("##"))]
if whole:
items.append((tok.convert_tokens_to_ids(toks), rng.choice(whole)))
CONDS = (("both", "both sides"),
("left", "left only"),
("right", "right only"),
("none", "no context"),
("cut", "left only, cut off"))
hits, tops = {}, {}
for key, _ in CONDS:
seqs, pos, hidden = [], [], []
for ids, p in items:
if key == "cut": # ends at the mask, then [SEP]
seqs.append([CLS] + ids[:p] + [MASK] + [SEP])
hidden.append([])
else:
seqs.append([CLS] + ids[:p] + [MASK] + ids[p + 1:] + [SEP])
hide = []
if key in ("right", "none"): # hide the left side
hide += range(1, 1 + p)
if key in ("left", "none"): # hide the right and [SEP]
hide += range(2 + p, len(ids) + 2)
hidden.append(hide)
pos.append([1 + p])
top = predict(seqs, pos, hidden)
tops[key] = tok.convert_ids_to_tokens([t[0][0] for t in top])
gold = [ids[p] for ids, p in items]
hits[key] = (sum(g == t[0][0] for g, t in zip(gold, top)),
sum(g in t[0] for g, t in zip(gold, top)))
n = len(items)
print(f"\n1. Mask one whole word ({n:,} words, one per output) and predict it")
print(f" {pad('condition', 22)}top-1 top-5")
for key, label in CONDS:
k1, k5 = hits[key]
print(f" {pad(label, 22)}{k1 / n:5.1%} ±{pm(k1, n):.1%} "
f"{k5 / n:5.1%} ±{pm(k5, n):.1%}")
def punct(key): # share of top-1 predictions that are punctuation
return sum(not w.isalnum() for w in tops[key]) / n
print(f" top-1 is punctuation: left only {punct('left'):.1%}, "
f"cut off {punct('cut'):.1%}")
print(" most common top-1 when cut off: "
+ "; ".join(f"{w!r}: {c:,}"
for w, c in Counter(tops["cut"]).most_common(3)))
# --- 2. 80/10/10 can the model restore the chosen positions ---
rng = random.Random(SEED_NOISE)
seqs, pos, gold, kind = [], [], [], []
for sents in docs:
ids = tok.convert_tokens_to_ids(tok.tokenize(rng.choice(sents)))
if not 6 <= len(ids) <= 64:
continue
chosen = [i for i in range(len(ids)) if rng.random() < 0.15]
chosen = chosen or [rng.randrange(len(ids))]
x, kinds = list(ids), []
for i in chosen:
u = rng.random()
kinds.append("mask" if u < 0.8 else "random" if u < 0.9 else "same")
if kinds[-1] == "mask":
x[i] = MASK
elif kinds[-1] == "random":
x[i] = rng.randrange(FIRST_REAL, tok.vocab_size)
seqs.append([CLS] + x + [SEP])
pos.append([1 + i for i in chosen])
gold.append([ids[i] for i in chosen])
kind.append(kinds)
top = predict(seqs, pos)
tally = {"mask": [0, 0], "random": [0, 0], "same": [0, 0]}
for g, t, k in zip(gold, top, kind):
for gi, ti, ki in zip(g, t, k):
tally[ki][0] += ti[0] == gi
tally[ki][1] += 1
total = sum(v[1] for v in tally.values())
print(f"\n2. Choose 15% of positions, corrupt 80/10/10 "
f"({len(seqs):,} sentences, {total:,} positions)")
print(f" {pad('what the position holds', 24)}{'n':>6} top-1")
for k, label in (("mask", "[MASK]"), ("random", "a random token"),
("same", "the original token")):
hit, cnt = tally[k]
rate = f"{hit / cnt:5.1%} ±{pm(hit, cnt):.1%}"
print(f" {pad(label, 24)}{cnt:>6,} {rate}")
# --- 3. NSP head ---
rng = random.Random(SEED_NSP)
pairs = {"next": [], "other": [], "same": [], "swap": []}
for d, sents in enumerate(docs):
i = rng.randrange(0, len(sents) - 2)
j = rng.randrange(i + 2, len(sents))
elsewhere = docs[(d + 1 + rng.randrange(len(docs) - 1)) % len(docs)]
pairs["next"].append((sents[i], sents[i + 1]))
pairs["other"].append((sents[i], rng.choice(elsewhere)))
pairs["same"].append((sents[i], sents[j]))
pairs["swap"].append((sents[i + 1], sents[i]))
KINDS = (("next", 0, "the next sentence (IsNext)"),
("other", 1, "a random sentence, other output"),
("same", 1, "a later sentence, same output"),
("swap", 1, "the next sentence, order swapped"))
stat = {}
for key, want, _ in KINDS:
right, p_next = 0, 0.0
for b in range(0, len(pairs[key]), 64):
a, c = zip(*pairs[key][b:b + 64])
enc = tok(list(a), list(c), truncation=True, max_length=128,
padding=True, return_tensors="pt")
with torch.inference_mode():
lg = model(**enc).seq_relationship_logits
right += (lg.argmax(-1) == want).sum().item()
p_next += lg.softmax(-1)[:, 0].sum().item()
stat[key] = (right, p_next / len(pairs[key]))
n = len(docs)
print(f"\n3. NSP head: is sentence two the next one? ({n:,} pairs per type)")
print(f" {pad('pair', 34)}right mean P(IsNext)")
for key, _, label in KINDS:
right, p_next = stat[key]
print(f" {pad(label, 34)}{right / n:5.1%} {p_next:.2f}")
mix = (stat["next"][0] + stat["other"][0]) / (2 * n)
print(f" Pre-training mix (half IsNext, half random elsewhere): {mix:.1%}")
Output (python exp_bert_probe.py, CPU, one complete run, about 4 minutes):
bert-base-uncased: 110.1M parameters; at load, 0 weights missing and 0 unexpected; CPU
Data: 1,500 Alpaca outputs with at least 4 sentences each
1. Mask one whole word (1,500 words, one per output) and predict it
condition top-1 top-5
both sides 64.7% ±2.4% 83.4% ±1.9%
left only 11.5% ±1.6% 30.1% ±2.3%
right only 20.1% ±2.0% 35.7% ±2.4%
no context 7.6% ±1.3% 16.3% ±1.9%
left only, cut off 0.1% ±0.1% 3.1% ±0.9%
top-1 is punctuation: left only 39.1%, cut off 99.8%
most common top-1 when cut off: '.': 1,405; ';': 86; '?': 4
2. Choose 15% of positions, corrupt 80/10/10 (1,500 sentences, 5,077 positions)
what the position holds n top-1
[MASK] 4,130 58.9% ±1.5%
a random token 455 44.2% ±4.6%
the original token 492 97.6% ±1.4%
3. NSP head: is sentence two the next one? (1,500 pairs per type)
pair right mean P(IsNext)
the next sentence (IsNext) 99.9% 1.00
a random sentence, other output 82.2% 0.18
a later sentence, same output 1.2% 0.99
the next sentence, order swapped 0.1% 1.00
Pre-training mix (half IsNext, half random elsewhere): 91.1%
Reading these numbers.
- Both sides of the context are needed. With both sides, top-1 is 64.7% and top-5 is 83.4%; with the left side only it falls to 11.5%, with the right side only to 20.1%; with both sides hidden, only the position and [CLS] remain and top-1 is still 7.6%, a guess from position and word-frequency priors. That agrees in direction with Table 5 of the paper, where the one-directional model (LTR) loses the most on MRPC and SQuAD. The two one-sided conditions are not symmetric: with the right side only the final [SEP] stays visible and with the left side only it does not, so do not read the result as “the right side matters more than the left in general”.
- Cutting the sequence off is a trap. After truncating to [CLS] left-context [MASK] [SEP], top-1 is only 0.1%. The predictions show why: 99.8% of the top-1 predictions are punctuation, and the period alone accounts for 1,405 of the 1,500 words. The masked words all sit in the middle of a sentence, but with [SEP] right behind the [MASK] the model takes it for the end of the sentence. Even with the right side merely hidden by an attention mask (nothing truncated), 39.1% of the top-1 predictions are punctuation. Using the cut-off version to “measure a one-directional model” would give a far more dramatic conclusion.
- A random token is still restored almost half the time. At the positions holding a random token, the model restores the original word 44.2% of the time (58.9% at [MASK] positions), and 97.6% where the word was left unchanged. A model that believed whatever it saw would score near 0 at the random positions; a model that ignored the input word would score the same at all three. The result lies in between, which is what the 10% random and 10% unchanged cases are meant to teach: the word in front of you may be wrong, so judge it against the context. This group cannot be compared directly with the 64.7% of probe 1: here about 15% of the positions of every sentence are chosen, neighbouring words can be hidden too, and subwords and punctuation are included.
- The NSP head mostly reads the topic. The real next sentence is right 99.9% of the time and a random sentence of another answer 82.2% (mean P(IsNext) 0.18); but a later sentence of the same answer is almost always labeled as the next sentence (right only 1.2% of the time, mean P(IsNext) 0.99), and so is the swapped pair (right only 0.1%). The head tells “same topic” from “different topic” but ignores order and adjacency. That is consistent with ALBERT’s argument that NSP mixes topic prediction with coherence prediction and the former is easier, here measured directly on the released BERT.
- The NSP accuracy is lower than the paper’s. On the pre-training mix (half IsNext, half random elsewhere) it is 91.1%, below the 97% to 98% of the paper’s footnote. A possible reason is that the text is not from its corpus: the Alpaca answers were all written by one model, different answers often share a topic, and random sentences are harder to tell from real next sentences. I did not check this on Wikipedia text.
What these probes do not show. They are not the paper’s pre-training ablations: nothing is retrained and there is no LTR control, so they can neither confirm nor refute Table 5. The text has a different style from BERT’s corpus, each answer contributes one sentence or one word, and there are 1,500 answers; top-1 is strict word-level matching, so a synonym counts as wrong; the intervals come from sampling only and do not include the effect of drawing a different set of texts.
Limitations and what came after
- Understanding only, no generation. Bidirectional attention has no causal mask; BERT outputs a representation per position and cannot write text one word at a time. Generation needs a decoder, or an encoder-decoder such as T5.
- The [MASK] mismatch and the ignored dependencies. 80/10/10 softens but does not remove the mismatch between pre-training and fine-tuning. The abstract of XLNet (arXiv 1906.08237) adds that BERT corrupts the input with masks, neglects the dependency between the masked positions and suffers from a pretrain-finetune discrepancy.
- The value of NSP was later disputed. RoBERTa (arXiv 1907.11692) found that removing the NSP loss matches or slightly improves downstream results; ALBERT (arXiv 1909.11942) replaced it with sentence-order prediction (SOP), which looks only at order.
- BERT was under-trained. The RoBERTa abstract says BERT was significantly undertrained: it trains longer with bigger batches over more data, drops NSP, uses longer sequences and changes the masking pattern dynamically, and the result matches or exceeds every model published after BERT.
- Too little signal per example. ELECTRA (arXiv 2003.10555) points out that MLM learns from only 15% of the tokens in each example and instead trains a discriminator to say whether each token was replaced, which beats BERT at the same model size, data and compute.
- One model per task. In the paper every downstream task has its own fine-tuned copy, so the parameters grow with the number of tasks, which motivated Adapters and parameter-efficient methods such as LoRA.
- The split from LLMs. The mainstream moved to decoder-only models and in-context learning, while encoders in the BERT family are still used for retrieval embeddings, reranking and classification, for example the BGE small model used in this site’s RAG experiment (see RAG).
What to take away from this paper
- MLM turns “bidirectional” into a trainable objective by hiding and restoring tokens; the 80/10/10 rule softens the fact that [MASK] never appears at fine-tuning time, and only 15% of the positions of each sequence produce a learning signal.
- One pre-trained encoder plus a different output layer covers classification, tagging and question answering: the inputs are unified as “[CLS] sentence A [SEP] sentence B [SEP]” and all parameters are fine-tuned together.
- The gap to GPT is not only direction. Data, batch size, special tokens and the learning-rate search all differ; the LTR row of Table 5 is the controlled comparison, and each cell is a single pre-training run.
- The paper’s numbers are mostly self-consistent, with a few discounts: the Average column counts nine numbers, “about 40 epochs” depends on the all-512 reading, the baseline row of Table 8 disagrees with other tables, and the benefit of NSP was later overturned.
- Measuring it yourself is the best way to read it: on bert-base-uncased one side of the context restores only 11.5% to 20.1% of a masked word, random-token positions are still restored 44.2% of the time, and the NSP head mostly reads the topic.
Further reading
- Paper: BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding; code and weights: google-research/bert.
- Predecessors: Deep contextualized word representations (ELMo); GPT-1: Improving Language Understanding by Generative Pre-Training; WordPiece comes from Google’s Neural Machine Translation System; the activation is Gaussian Error Linear Units.
- Benchmarks: GLUE, SQuAD, SWAG.
- Follow-ups: RoBERTa, ALBERT, ELECTRA, XLNet.
- On this site: Transformer Block, Tokenizers and Embeddings, Training Pipeline, Attention Is All You Need explainer, T5 explainer.
FAQ
- What is BERT and why did it matter?
- BERT (Bidirectional Encoder Representations from Transformers) is a pre-trained language representation model published by Google AI Language in October 2018 (arXiv 1810.04805). It is a bidirectional Transformer encoder, pre-trained on BooksCorpus (800 million words) and English Wikipedia (2,500 million words) with masked language modeling and next sentence prediction, then fine-tuned with one thin output layer per task. At the time it set new records on 11 NLP tasks (GLUE leaderboard 80.5, MNLI accuracy 86.7%, SQuAD v1.1 test F1 93.2, SQuAD v2.0 test F1 83.1) and made pre-train-then-fine-tune the default recipe in NLP.
- How is BERT different from GPT?
- The difference is the direction of attention and what the model is trained to do. BERT is a Transformer encoder: every position sees both sides, it is trained to restore masked tokens (MLM), and it outputs one representation per position, which suits classification, tagging and retrieval but cannot generate text on its own. GPT is a Transformer decoder with a causal mask: it sees only the left side and is trained to predict the next token, which makes it a natural generator. The closest controlled comparison in the BERT paper is the LTR & No NSP row of Table 5: with the same data and fine-tuning, the left-to-right model is 9.0 points lower on MRPC and 10.1 points lower on SQuAD than the bidirectional model without NSP.
- Why does BERT mask 80% of the chosen tokens, replace 10% with random words and keep 10%?
- Because [MASK] appears only in pre-training and never at fine-tuning time, which creates a mismatch. Of the 15% of positions chosen, 80% become [MASK], 10% become a random token and 10% stay unchanged, so the model cannot tell whether the word in front of it is correct or was swapped and has to build a context-dependent representation for every position. Table 8 of the paper shows fine-tuning is robust to the mix, while using only [MASK] hurts the feature-based NER result and using only random tokens is much worse. On bert-base-uncased, the original word is still restored at 44.2% of the positions that hold a random token, against 58.9% at [MASK] positions.
- Is next sentence prediction useful? Why do later models drop it?
- The BERT paper reports that removing NSP lowers QNLI by 3.5 points, MNLI by 0.5 and SQuAD by 0.6, but each cell comes from a single pre-training run. RoBERTa (arXiv 1907.11692) found in a stricter comparison that removing the NSP loss matches or slightly improves downstream results, and ALBERT (arXiv 1909.11942) argued that NSP mixes topic prediction with coherence prediction, topic prediction being the easier one, and switched to sentence-order prediction (SOP). A probe of the released NSP head shows the same pattern: it separates the real next sentence from a random sentence of another answer (82.2% right) but labels almost every later sentence of the same answer as the next sentence (only 1.2% right).
- Is BERT still relevant, and how does it relate to today's LLMs?
- Encoder models are still common in retrieval embeddings, reranking and classification: the BGE small model (BAAI/bge-small-en-v1.5) used in this site's RAG page has the BERT architecture and takes the hidden state at the [CLS] position as the vector. Generation and chat are dominated by decoder-only LLMs, which share the same Transformer block and differ mainly in the attention mask and the pre-training objective. What BERT left behind is the pre-train-then-fine-tune paradigm, the masked-language-modeling objective and the idea of one backbone for many tasks.