TL;DR
BERT is a language model that reads text in both directions at once. It is pre-trained on a large unlabelled corpus by hiding about one word in seven and asking the model to fill in the blanks from the words on both sides. It also learns whether two sentences follow one another. After this pre-training, the same model is fine-tuned on each downstream task by adding one small output layer and training everything end to end.
Where you'll see it: search ranking and question answering systems in the late 2010s, and the encoder behind many sentence-embedding and text-classification models that followed.
The problem
By 2018 a standard recipe already existed. Pre-train a language model on a huge amount of text, then reuse it for a specific task. ELMo ran two separate language models, one left-to-right and one right-to-left, and concatenated their outputs. OpenAI's GPT used a left-to-right Transformer that could only look backwards. Both approaches leave something on the table. A word's representation in a left-to-right model never sees the words that come after it, and a shallow concatenation of two one-directional models is weaker than a single model that conditions on both sides at every layer.
The obvious fix, training a bidirectional model with the usual next-word objective, does not work. Each word would be able to see itself indirectly through the context around it, and the task becomes trivial. So the question was how to get deep bidirectional pre-training while keeping a prediction task that is not cheating.
Key idea
Hide some of the words and predict them. This is a masked language model objective, also known as a cloze task. Because the hidden word is replaced in the input, the model has to use context from both sides to recover it, and no word can see itself. A second, cheap task, next sentence prediction, teaches the model how sentence pairs relate. Then the whole pre-trained network is fine-tuned on each task with a small task-specific output layer. The architecture barely changes between pre-training and the downstream task. That is the unifying idea of the paper.
The method
Architecture
BERT is a multi-layer bidirectional Transformer encoder, closely following the original design. Self-attention in every layer looks at all positions, left and right. The paper defines two sizes:
- BERT BASE: layers, hidden size , attention heads, about 110 million parameters.
- BERT LARGE: layers, , heads, about 340 million parameters.
The feed-forward layers inside each block have size . BERT BASE was sized to match OpenAI GPT, so the comparison isolates the attention pattern: BERT attends in both directions, GPT only to the left.
Input representation
The input is a sequence of WordPiece tokens from a 30,000-token vocabulary. Each sequence starts with a special [CLS] token, and a sentence pair is packed into one sequence with a [SEP] token between the two sentences. Every input token's embedding is the sum of three things:
where says whether the token belongs to sentence A or sentence B. The final hidden vector of [CLS], written , is used as a summary of the whole sequence for classification. The hidden vector of token is .
Take the sentence pair "my dog is cute" and "he likes playing", with the second word split into WordPiece pieces "play" and "##ing". The packed sequence is
[CLS] my dog is cute [SEP] he likes play ##ing [SEP]
That is 11 tokens, at positions 0 to 10. The segment labels are 0 for positions 0 to 5 (sentence A, including its [SEP]) and 1 for positions 6 to 10. Each position receives its own position embedding, so the model knows the order even though attention itself is order-free.
Interpretation: a single sequence carries both sentences, and the segment embeddings are the only thing that tells the model where one ends and the other begins.
Pre-training task 1: masked language model
The training generator selects percent of the WordPiece positions in each sequence at random. Only these selected positions contribute to the loss. For each selected position the generator does one of three things:
- Replace the token with
[MASK]with probability . - Replace it with a random token with probability .
- Leave the original token unchanged with probability .
The model must predict the original token at every selected position, from the final hidden vector through a softmax over the vocabulary. With the set of selected positions and the corrupted input,
The 80/10/10 rule exists because [MASK] never appears during fine-tuning. If the model only ever saw [MASK] in pre-training, it would be trained on inputs that differ from the ones it is used on. Keeping some selected words unchanged, or replaced with random words, forces the model to build useful representations for every token, not only for the masked ones.
Take a passage of 40 WordPiece tokens.
- Selected positions: .
- Expected
[MASK]replacements: . - Expected random replacements: .
- Expected unchanged positions: .
- Loss terms: 6, one for each selected position, each a cross-entropy over the vocabulary.
Interpretation: on average the model sees roughly five [MASK] tokens per 40, and it is graded on six positions. Most of the training signal comes from the masked ones, but the other two groups keep the model honest about ordinary words.
Pre-training task 2: next sentence prediction
Many downstream tasks, such as question answering and natural language inference, depend on how two sentences relate. Language modelling does not capture that directly. So for each pre-training example the model receives two spans A and B. Half the time B really follows A in the corpus. Half the time B is a random sentence. The model predicts which case holds from :
The paper reports 97 to 98 percent accuracy on this task at the end of pre-training. Its later ablation shows that dropping it hurts QNLI, MNLI and SQuAD (Section 5.1 of the paper).
Pre-training data
The corpus is BooksCorpus (about 800 million words) and English Wikipedia (about 2,500 million words). Only the text passages of Wikipedia are used, with lists, tables and headers removed. The authors stress that long contiguous documents matter. A shuffled sentence-level corpus would not provide the long spans needed for the sentence-pair inputs.
Fine-tuning
For each task, the inputs are arranged the way the task needs and every parameter is trained end to end. For sentence pairs the two texts become A and B, for paraphrase, entailment and question-answer pairs. For single-text classification, sentence B is empty. The output layer is then:
- For classification, a linear layer on , trained with the usual cross-entropy loss.
- For span tasks such as SQuAD, two new vectors and , one for the start and one for the end of the answer. Each word's start probability is a softmax over the passage:
Suppose the passage has four candidate start positions, and the start scores are , , and .
- Exponentials: , , , .
- Sum: .
- Probabilities: , , , .
The probabilities sum to one, as they should. Interpretation: position 1 is the most likely answer start, with about 64 percent, and the training loss pushes the correct start's probability up. The end vector works the same way, and the predicted answer is the best-scoring span with its end not before its start.
Results
The paper evaluates on eleven NLP tasks in total: eight GLUE tasks (Table 1, with the problematic WNLI set excluded), SQuAD v1.1, SQuAD v2.0 and SWAG. In Table 1 the average test score is for BERT BASE and for BERT LARGE. OpenAI GPT scores , and the best earlier system in the table (labelled "Pre-OpenAI SOTA") scores . On the largest task, MNLI, BERT LARGE reaches on the matched test set.
The paper's text also quotes a different pair of numbers: BERT LARGE at on the official GLUE leaderboard, against for GPT. The two sets of numbers do not conflict. The table averages and are the authors' own average over eight tasks, which excludes WNLI. The leaderboard scores and are the official GLUE scores, which the paper's table caption notes are slightly different. Do not compare a figure from one with a figure from the other.
On SQuAD v1.1 (Table 2), a single BERT LARGE model reaches F1 on the development set, and BERT BASE reaches . The best submitted system, an ensemble also fine-tuned on TriviaQA, reaches F1 on the test set, which the paper says is F1 above the top leaderboard system at the time (). On SQuAD v2.0, which adds questions with no answer in the passage, BERT LARGE reaches test F1, the F1 gain over the previous best system that the paper reports.
The ablations give a clearer view of the design choices. Using BERT BASE for all three:
| Pre-training variant | MNLI | QNLI | MRPC | SST-2 | SQuAD F1 |
|---|---|---|---|---|---|
| Full BERT BASE | 84.4 | 88.4 | 86.7 | 92.7 | 88.5 |
| No next sentence prediction | 83.9 | 84.9 | 86.5 | 92.6 | 87.9 |
| Left-to-right, no NSP | 82.1 | 84.3 | 77.5 | 92.1 | 77.8 |
These are development-set numbers from Table 5, so they differ slightly from the test numbers above (for example, on MNLI-m here against on the test set in Table 1). Dropping NSP costs accuracy on QNLI, MNLI and SQuAD. Replacing the bidirectional model with a left-to-right one is worse on every task, with large drops on MRPC ( to ) and SQuAD ( to ), and only a small drop on SST-2 ( to ).
On model size (Table 6, averages over five fine-tuning restarts), larger models give steady gains on every task shown, even on MRPC, which has only about 3,600 training examples. The paper's text says this holds for "all four datasets", but Table 6 lists only three: MNLI-m, MRPC and SST-2. Going from the 12-layer, 768-wide model to the 24-layer, 1024-wide one lifts them from , , to , , . The -layer row's SST-2 value of also differs from the in Table 5 for the same architecture, because the two tables average different runs.
Why it mattered
BERT made one pre-trained model the default starting point for language understanding. Before it, many systems were built from task-specific architectures. After it, most tasks were approached by fine-tuning a pre-trained encoder with a small head. Its recipe spawned a family of variants that changed the data, the masking rule or the model size, and it became the standard encoder for search ranking and embedding models. Google put BERT into its search ranking in 2019.
The paper also showed that a single bidirectional model could do well across tasks that had previously needed separate designs. The main cost was that BERT is an encoder: it produces representations well but does not generate text one word at a time, which is why the generation models that followed took a different path.
Reading guide
Read the paper in this order. Each section depends on the prerequisites listed beside it.
- Section 1, Introduction. Needs Language Model and Word Embedding to follow the comparison with ELMo and GPT.
- Section 2, Related Work. Needs Transfer Learning for the idea of reusing a pre-trained model, and Bidirectional Recurrent Neural Network for the earlier bidirectional models it contrasts with.
- Section 3, Model architecture. Needs Transformer, Attention Mechanism and Layer Normalization. The paper assumes the Transformer and does not re-derive it.
- Section 3, Input representation. Needs Subword Tokenization for WordPiece and Positional Encoding for the position embeddings.
- Section 3.1, Masked LM. Needs Masked Language Modeling, Softmax and Cross-Entropy Loss.
- Section 3.1, Next sentence prediction. Needs only the idea of a binary classifier on a vector, which the classification part of the softmax lesson covers.
- Section 3.2, Fine-tuning. Needs Fine-Tuning and Transfer Learning.
- Section 4, Experiments. Needs Cross-Entropy Loss for the training objectives in each task and the definition of F1 for span tasks.
- Section 5, Ablations. Needs Language Model to read the left-to-right baseline.
Check yourself
QuestionRecall: why can a left-to-right language model not simply be trained with its usual objective and then made bidirectional at training time?Show answer
Its usual objective predicts each word from the words before it. If the model could see the words after the target, the target would be visible in the input and the task would become trivial. Making the model bidirectional during next-word training lets each word see itself indirectly through its context, so the loss says nothing useful. Masked language modelling avoids this by hiding the target in the input and predicting only the hidden positions.
QuestionComputation: a passage has 60 WordPiece tokens. Under the 15 percent rule, how many positions are selected, and how many of them are expected to show the literal `[MASK]` token?Show answer
Selected positions: . Expected [MASK] replacements: . Expected random replacements: . Expected unchanged: . The loss is computed at all 9 selected positions, so most of the signal comes from the 7.2 masked ones.
QuestionComputation: for SQuAD, a passage has start scores equal to , and at three positions. What are the start probabilities?Show answer
Exponentials: , , and . Sum: . Probabilities: for each of the first two positions and for the third. The probabilities sum to one. The model puts most of its mass on the third position, and the two tied positions split the rest evenly.
QuestionWhy: the paper keeps 10 percent of the selected words unchanged and 10 percent random, instead of always using `[MASK]`. What problem does this solve, and what would go wrong without it?Show answer
[MASK] never appears during fine-tuning, so a model trained only on [MASK] would see a different input distribution at fine-tuning time. Keeping some selected words unchanged or replacing them with random words makes the model build good representations for every token, not only for the ones marked as masked. Without this, the representations of ordinary, unmasked words would receive no training signal in the pre-training task, and the mismatch would hurt downstream accuracy.
QuestionApplied: a team wants to use BERT to classify support tickets into five categories with 2,000 labelled examples. They are deciding between fine-tuning BERT BASE and training a small model from scratch. Which would you recommend, and what would you watch for?Show answer
Fine-tune BERT BASE. The paper's central result is that pre-trained representations transfer well, and that small labelled datasets benefit most from the pre-trained model. Add a linear layer on the [CLS] vector with five outputs, train with cross-entropy, and use the paper's recipe: batch size 32, three epochs, and a learning rate chosen from a small grid such as 2e-5 to 5e-5 on a validation set. Watch for instability on small datasets, which the paper observed with BERT LARGE (and not necessarily with BASE), so run a few random seeds and keep the best one on the validation set.
Sources
- BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding (Devlin et al., 2018)
- Attention Is All You Need (Vaswani et al., 2017)
- GLUE: A Multi-Task Benchmark and Analysis Platform (Wang et al., 2018)
- Official BERT code and pre-trained models (Google Research)
- BERT (language model) (Wikipedia)