# BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding

Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova · arXiv · 2018-10-11

- **Problem** Pre-trained language models that are fine-tuned on each task are limited when each token can only attend to one side of its context.
- **Method** BERT pre-trains a bidirectional Transformer encoder with a masked LM objective and next sentence prediction, then fine-tunes all parameters with one added output layer per task.
- **Results** BERTLARGE reached an average GLUE Test score of 82.1, against 75.1 for OpenAI GPT.

## Why unidirectional pre-training limits fine-tuning

Pre-trained language representations reached downstream tasks in two ways before BERT. The feature-based route feeds pre-trained representations into a task-specific architecture as extra inputs, while the fine-tuning route adds a small output layer and updates all pre-trained parameters on the target task.

The fine-tuning route depends on the pre-training objective. Standard language models are unidirectional, and in OpenAI GPT every token can attend only to earlier tokens in the self-attention layers. That restriction suits sentence-level tasks reasonably well, but it can be harmful for token-level tasks such as question answering, where a token needs context from both directions.

The paper therefore asks whether a pre-training objective that conditions on both sides of each position can be trained and then fine-tuned with only a small change to the architecture.

## Model architecture and input encoding

BERT is a multi-layer bidirectional Transformer encoder based on the original Transformer implementation, and the paper counts layers as L, the hidden size as H and the self-attention heads as A. BERTBASE was sized to match OpenAI GPT, so that the comparison isolates the attention pattern and the pre-training choices.

The architectural difference from GPT is the direction of self-attention: the BERT encoder attends in both directions, while the GPT Transformer restricts each token to its left context. The figure comparing BERT, OpenAI GPT and ELMo summarises where this difference sits and which of the three models are fine-tuned rather than used as frozen features.

Inputs use WordPiece embeddings with a 30,000 token vocabulary, and each sequence starts with a special classification token. A sequence holds either one span or two spans packed together, separated by a \[SEP\] token and tagged with a learned embedding that marks sentence A or sentence B. The input vector for each token is the sum of its token, segment and position embeddings, and the final hidden vector of the \[CLS\] token serves as the sequence representation C for classification.

## Masked language model pre-training

A standard conditional language model cannot be bidirectional, because a word that can see both neighbours can also see itself through the layers and predict itself trivially. The masked LM sidesteps this by hiding some input tokens and training the model to predict only those hidden tokens from the surrounding context, which is the Cloze procedure applied to a Transformer.

In each sequence 15% of WordPiece tokens are chosen at random, and the final hidden vectors at the chosen positions go into a softmax over the vocabulary. Of the chosen positions, 80% are replaced with \[MASK\], 10% with a random token and 10% are left unchanged, and the loss is the cross entropy of predicting the original token from Ti. The replacement mix addresses the mismatch between pre-training and fine-tuning, because the \[MASK\] symbol never appears in fine-tuning inputs.

Unlike a denoising auto-encoder, the model predicts only the masked words and does not reconstruct the full input. Random replacement touches only about 1.5% of all tokens, and the worked example in the appendix shows how the 80, 10 and 10 split applies to a single sentence. Because only 15% of tokens give a prediction signal per batch, the authors expect more pre-training steps to be needed, and Appendix C.1 compares convergence with a left-to-right model.

## Next sentence prediction and pre-training data

The second pre-training task is a binarized next sentence prediction. For each example, B is the true next sentence after A in half the cases and a random sentence from the corpus in the other half. The vector C is used to make this prediction, and the final model reaches 97%-98% accuracy on it. The two losses are summed during pre-training, so the masked LM and next sentence prediction are trained jointly.

Sampled text spans are capped so that the combined length is 512 tokens or less, and the pre-training text is drawn from BooksCorpus (800M words) and English Wikipedia (2,500M words). Only the text passages of Wikipedia are used, and the authors argue that a document-level corpus is needed so that long contiguous sequences can be drawn. Each pre-training run uses batches of 256 sequences of up to 512 tokens for 1,000,000 steps, and the paper reports that each pre-training took 4 days.

## Adapting one encoder to each task

Fine-tuning starts from the pre-trained parameters, and every parameter is updated with labelled data from the downstream task, with one separate fine-tuned model per task. Sentence pairs in paraphrasing, entailment and question answering map onto the sentence A and sentence B slots, while single-text tasks use an empty second span. Token-level outputs come from the token representations, and classification outputs come from the \[CLS\] representation.

For GLUE, the only new parameters are a classification weight matrix W in R^(K x H), where K is the number of labels, and the loss is computed from C and W. The formula is written as \\(\\log(\\mathrm{softmax}(CW^{T}))\\) in the paper.

For SQuAD, only a start vector S and an end vector E are added, and the probability that word i starts the answer is a softmax over dot products between S and each token vector. The probability is \\(P\_i = \\frac{e^{S\\cdot T\_i}}{\\sum\_j e^{S\\cdot T\_j}}\\), and the end position uses the analogous formula with E. A candidate span from position i to position j scores S\\cdot T\_i + E\\cdot T\_j, and the prediction is the highest scoring span with j at or after i.

Fine-tuning is comparatively cheap: the paper states that every result can be replicated in at most one hour on a single Cloud TPU, or a few hours on a GPU, from the same pre-trained model.

## GLUE results

On the GLUE Test set, BERTLARGE reached an average score of 82.1, and BERTBASE reached 79.6, while OpenAI GPT reached 75.1 and the pre-OpenAI state of the art reached 74.0. The average excludes the WNLI set, and BERTLARGE scores 4.5 and 7.0 points above the prior state of the art on the two model sizes as averages.

Hyperparameters were set with a batch size of 32 and 3 fine-tuning epochs, with the learning rate chosen on the Dev set from 5e-5, 4e-5, 3e-5 and 2e-5. Because BERTLARGE fine-tuning was sometimes unstable on small datasets, several random restarts were run and the best Dev model was selected.

On MNLI, BERTLARGE reached 86.7 on the matched set and 85.9 on the mismatched set, against 82.1 and 81.4 for OpenAI GPT. BERTBASE and OpenAI GPT share nearly the same architecture apart from the attention masking, so the gap between them is most directly tied to the bidirectional pre-training. BERTLARGE improves on BERTBASE on every task, with the largest gains on tasks that have the least training data.

## SQuAD v1.1 and v2.0 results

The best SQuAD v1.1 system fine-tunes on TriviaQA before SQuAD, and it reached a Test F1 of 93.2 as an ensemble, which the paper reports as 1.5 F1 above the top leaderboard entry. A single BERTLARGE model reached 91.8 Test F1 with TriviaQA fine-tuning and 91.1 Dev F1 in the same setting.

For SQuAD v2.0, questions without an answer are given a span that starts and ends at the \[CLS\] token, so the no-answer case is scored in the same softmax as the answer spans. At prediction time, a no-answer score S·C + E·C is compared with the best non-null span score, and a non-null answer is predicted when the difference exceeds a threshold tau chosen on the Dev set to maximize F1.

A single BERTLARGE model reached 83.1 Test F1 on SQuAD v2.0, which the paper reports as 5.1 F1 above the previous best system.

## SWAG results

For SWAG, the model builds four input sequences, each pairing the given sentence with one candidate continuation, and a single vector dotted with the \[CLS\] representation scores each candidate before a softmax.

On the Test set, BERTLARGE reached 86.3 accuracy, against 78.0 for OpenAI GPT and 85.0 for expert human performance reported in the SWAG paper. The paper also reports BERTLARGE above the ESIM plus ELMo baseline by 27.1% and above OpenAI GPT by 8.3%.

## Which pre-training task matters

The ablation keeps the BERTBASE architecture, data, fine-tuning scheme and hyperparameters fixed, and varies only the pre-training objective. The No NSP variant is a bidirectional masked LM without next sentence prediction, while LTR and No NSP is a left-to-right LM without next sentence prediction, close to OpenAI GPT but trained on the larger corpus.

Removing next sentence prediction lowers MNLI-m accuracy from 84.4 to 83.9 and SQuAD F1 from 88.5 to 87.9 on the Dev set. Replacing the masked LM with the left-to-right objective and dropping NSP lowers SQuAD F1 from 88.5 to 77.8 and MRPC accuracy from 86.7 to 77.5. Adding a randomly initialised BiLSTM on top of the left-to-right model recovers SQuAD F1 to 84.9, but it still falls short of the bidirectional models, and it hurts performance on the GLUE tasks.

## Effect of model size

The model size study varies layers, hidden units and attention heads with the same hyperparameters and training procedure, and reports Dev accuracy averaged over 5 random restarts. Going from 12 layers, 768 hidden units and 12 heads to 24 layers, 1024 hidden units and 16 heads raises Dev MNLI-m accuracy from 84.4 to 86.6 and Dev MRPC accuracy from 86.7 to 87.8.

The authors report strict accuracy gains across all four datasets they test, including MRPC, which has 3,600 labelled training examples. The paper also contrasts BERT sizes with prior Transformers, noting that the largest Transformer in Vaswani et al. (2017) has 100M encoder parameters, while BERTLARGE has 340M. Prior feature-based work reported only mixed gains from scaling, and the authors hypothesise that fine-tuning lets small task data benefit from larger pre-trained models, though this is not tested beyond the settings given.

## Masking strategy ablation

The masking ablation varies the probabilities of replacing a target token with \[MASK\], keeping it unchanged or replacing it with a random token, and reports MNLI and NER results. The default 80, 10 and 10 mix gives 84.2 on MNLI and 95.4 NER fine-tuning F1 and 94.9 NER feature-based F1.

Fine-tuning is robust to the choice of masking mix, but using only the \[MASK\] replacement is problematic for the feature-based NER setting. Using only random replacement performs much worse than the default mix in the feature-based NER setting, according to the paper.

## Feature-based use on NER

In the feature-based setting, activations are extracted from one or more layers without tuning any BERT parameters, and they feed a randomly initialised two-layer 768-dimensional BiLSTM before the classification layer. The case-preserving WordPiece model and document context follow the paper's NER setup, and the representation of the first sub-token is passed to the token classifier.

The fine-tuning BERTLARGE reached 96.6 Dev F1 and 92.8 Test F1, and BERTBASE reached 96.4 Dev F1 and 92.4 Test F1. The best feature-based setting concatenates the top four hidden layers of BERTBASE and reached 96.1 Dev F1, which is 0.3 F1 below fine-tuning the entire model.

## Limitations

In the authors' ablation, the masked LM converges slightly more slowly than a left-to-right model, measured on MNLI after fine-tuning from checkpoints at different pre-training steps. The masked LM still outperforms the left-to-right model in absolute accuracy almost immediately, and the authors judge the training cost worthwhile.

The reported fine-tuning results are single-task, and the paper notes that multitask fine-tuning could push performance further, with RTE gains seen from multitask training with MNLI. The SQuAD v1.1 ensemble result and the TriviaQA-augmented results use additional fine-tuning data, while the single-model SQuAD v2.0 result does not use TriviaQA.

## Paper info

- **Authors**: Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova
- **Venue**: arXiv · Preprint
- **First published**: 2018-10-11
- **Added**: 2026-10-20
- **Updated**: 2019-5-24
- **Version**: v2
- **arXiv**: 1810.04805
- **Category**: cs.CL
- **Original paper terms**: [arXiv non-exclusive 1.0](https://arxiv.org/licenses/nonexclusive-distrib/1.0/)
- **What we show**: Paper info and commentary

[Original paper ↗](https://arxiv.org/abs/1810.04805v2) · [PDF ↗](https://arxiv.org/pdf/1810.04805v2)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Quote from the paper

Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. arXiv:1810.04805v2. https://arxiv.org/abs/1810.04805v2

**BibTeX**

```
@misc{devlin2018bert,
  title = {{BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding}},
  author = {Jacob Devlin and Ming-Wei Chang and Kenton Lee and Kristina Toutanova},
  year = {2018},
  eprint = {1810.04805},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1810.04805v2}
}
```

## Other paper commentary

- [Looped Models are Fast Multi-Token Predictors](https://refivu.com/en/papers/753aee4a-f281-45ed-9e03-84eb93c47b6d-looped-models-are-fast-multi-token-predictors.md)
- [FIDEL: Abugida-Aware Pre-tokenization for Ethiopic Languages](https://refivu.com/en/papers/ddcebe56-3d04-41f8-b252-f5f305a78bc1-fidel-abugida-aware-pre-tokenization-for-ethiopic-languages.md)
- [Meaning Reaches Object Choice but Not Completion: Where Is a VLA Vulnerable to Landmark Synonyms?](https://refivu.com/en/papers/defc7d50-8eb3-4076-bf41-f9d85534ab4c-meaning-reaches-object-choice-but-not-completion-where.md)
- [Quantifying the added value of human forecaster discussions for tropical cyclone intensity prediction](https://refivu.com/en/papers/ebc948f3-4b88-46c9-989e-efcb0d97c1eb-quantifying-the-added-value-of-human-forecaster-discussions.md)
- [AuXSpec: Learning to Autoformalize Program Specifications via Executable Postconditions](https://refivu.com/en/papers/d6ae6e57-c73c-4909-b2a8-0a7a84033d1f-auxspec-learning-to-autoformalize-program-specifications-via.md)
- [Centered Ablation: Why Last-Layer Directional Ablation Under-Fires or Collapses, and a Closed-Form Fix](https://refivu.com/en/papers/e522068b-b9e0-411d-8146-73a3b153eaba-centered-ablation-why-last-layer-directional-ablation-under.md)
- [Attention Is All You Need](https://refivu.com/en/papers/9645c9a1-cc92-404a-bc65-1ec437b1deab-attention-is-all-you-need.md)
- [FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning](https://refivu.com/en/papers/177a3817-56f7-448e-964a-a2e688dc7c81-flashattention-2-faster-attention-with-better-parallelism.md)
- [Instance Normalization: The Missing Ingredient for Fast Stylization](https://refivu.com/en/papers/d30fae5e-d1ad-4ef1-9b41-da9a7a9f25cf-instance-normalization-the-missing-ingredient-for-fast.md)
- [Group Normalization](https://refivu.com/en/papers/73ea525c-b90c-43b2-b656-bb21666ab914-group-normalization.md)
- [Layer Normalization](https://refivu.com/en/papers/2f67f179-7720-4b69-8cac-e7157bee38ae-layer-normalization.md)
- [Root Mean Square Layer Normalization](https://refivu.com/en/papers/97c61522-5940-4a28-ad7d-4126a3ce8c01-root-mean-square-layer-normalization.md)

## Terms in this paper

- [Accuracy](https://refivu.com/en/terms/1995c0cd6282-accuracy)
- [self-attention](https://refivu.com/en/terms/426589b81077-self-attention)
- [BERT](https://refivu.com/en/terms/45b639a1d317-bert)
- [TriviaQA](https://refivu.com/en/terms/d04d9611868e-triviaqa)
- [GLUE](https://refivu.com/en/terms/9305114e7947-glue)
- [Question Answering](https://refivu.com/en/terms/b3a98bd42a6e-question-answering)
- [ELMo](https://refivu.com/en/terms/a4cbe56494c9-elmo)
- [next sentence prediction](https://refivu.com/en/terms/1f8e569cac6a-next-sentence-prediction)
- [English Wikipedia](https://refivu.com/en/terms/34ae8aa404c0-english-wikipedia)
- [MultiNLI](https://refivu.com/en/terms/0cdc2fd76008-multinli)
- [BooksCorpus](https://refivu.com/en/terms/d1538bb49762-bookscorpus)
- [WordPiece](https://refivu.com/en/terms/1c3e6af9e9ca-wordpiece)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/037751cf-a504-48c3-b08a-868e3ab40b26-bert-pre-training-of-deep-bidirectional-transformers-for)
