AI Logic

Architectures

BERT

Updated:

Structure of BERT. Left: the overall flow of pre-training (input of [CLS], sentence A, [SEP], sentence B; the sum of three embeddings; repeated encoder layers; the two outputs for next sentence prediction and the masked language model) and the range of bidirectional attention, which can see every position. Right: the inside of an encoder layer (self-attention and feed-forward)

Background and overview

BERT (Bidirectional Encoder Representations from Transformers) is a language model that stacks only the encoder of the Transformer and learns word representations using the context on both sides of a sentence. It was proposed by Devlin et al. at Google in 2018. It is "pre-trained" on large amounts of unlabeled text and then "fine-tuned" on a small amount of labeled data for tasks such as sentence classification and question answering.

Earlier pre-trained models had the following limitations.

  • GPT: as a language model that predicts the next word from left to right, each word can only see the words to its left.
  • ELMo: it trains left-to-right and right-to-left language models separately and only concatenates their outputs, so the context in both directions cannot be used at the same time inside the layers.

BERT is pre-trained on a task called the masked language model, which hides some of the input words and predicts the original words, so that every layer can use the context on both sides at once. It is also trained on next sentence prediction, which predicts whether two sentences are consecutive.

In the paper, simply adding one output layer to the pre-trained model and fine-tuning it produced state-of-the-art results on 11 natural language processing tasks at the time.

  • A GLUE score of 80.5 (7.7 points above the previous best)
  • MultiNLI accuracy of 86.7% (4.6 points higher)
  • SQuAD v1.1 test F1 of 93.2 (1.5 points higher) and v2.0 F1 of 83.1 (5.1 points higher)

Architecture

BERT is a stack of LL Transformer encoder layers. The paper states that its implementation is almost identical to the original Transformer. The left side of the figure at the top of the article shows the overall flow of pre-training and which positions self-attention can see, and the right side shows the inside of one encoder layer.

The two sizes in the paper are as follows.

ModelLayers LLHidden size HHHeads AAFeed-forward inner sizeParameters
BERT-Base12768123072110M
BERT-Large241024164096340M

BERT-Base was given the same size as GPT for comparison. The only difference between the two is the range that attention can see.

  • BERT: each token sees all tokens before and after it in the sentence (bidirectional self-attention).
  • GPT: each token sees only the tokens to its left (self-attention with a mask that hides future tokens).

The input is built as follows.

  1. The text is split into tokens with WordPiece (vocabulary of 30,000).
  2. A special classification token [CLS] is placed at the beginning, and when two sentences are given, a separator [SEP] is placed between them and at the end. One input is at most 512 tokens.
  3. For each token, three embeddings are summed to form the input vector.
    • Token embedding: which word it is
    • Segment embedding: whether it belongs to the first sentence (A) or the second sentence (B)
    • Position embedding: its position (learned positional embedding)

Of the last layer's outputs, the vector at the [CLS] position, C∈RHC \in \mathbb{R}^H, is used for classification as a representation that summarizes the whole input, and the vector at the ii-th token position, Ti∈RHT_i \in \mathbb{R}^H, is used for per-token predictions (such as the answer position in question answering).

As in the original Transformer, each encoder layer consists of two sublayers, multi-head attention and a feed-forward network, each with a residual connection and layer normalization. Following GPT, the activation function is GELU rather than ReLU.

Training: pre-training and fine-tuning

BERT is trained in two stages: pre-training and fine-tuning.

In pre-training, the model learns the following two tasks simultaneously from unlabeled text. The loss is the sum of the mean losses (cross-entropy) of the two tasks.

  1. Masked language model (MLM): 15% of the input tokens are chosen at random, and the original token at each chosen position is predicted from the last layer's output TiT_i with a softmax over the whole vocabulary. The chosen tokens are replaced as follows.
    • 80% are replaced with the [MASK] symbol
    • 10% are replaced with a different random token
    • 10% are left unchanged
  2. Next sentence prediction (NSP): two sentences A and B are input, and the model predicts from the [CLS] output CC whether B is actually the sentence that follows A (50%) or a sentence chosen at random from the corpus (50%). This is meant to help with tasks that require understanding the relation between two sentences, such as question answering and natural language inference.

The pre-training settings in the paper are as follows.

ItemValue
DataBooksCorpus (800M words) and English Wikipedia (2,500M words)
Batch256 sequences × 512 tokens (about 128,000 tokens)
Steps1,000,000 (about 40 epochs)
OptimizationAdam (learning rate 10−410^{-4}, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999), L2 weight decay of 0.01
Learning rateWarmup over the first 10,000 steps, then linear decay
Dropout0.1 in all layers

Because the cost of attention grows with the square of the sequence length, 90% of the steps are trained on sequences of length 128, and the remaining 10% on sequences of length 512 to learn the positional embeddings for longer positions. BERT-Base took 4 days on 16 TPU chips, and BERT-Large took 4 days on 64 TPU chips.

In fine-tuning, training starts from the pre-trained weights, a small task-specific output layer is added, and all weights are trained again.

  • Sentence classification (sentiment analysis, natural language inference, etc.): a linear layer with weights W∈RK×HW \in \mathbb{R}^{K \times H} is applied to CC, and softmax(CW⊤)\mathrm{softmax}(CW^\top) gives the probabilities of the KK labels.
  • Question answering (SQuAD): the question is input as sentence A and the passage as sentence B. Only a start vector SS and an end vector EE for the answer are newly learned, and the probability that each token is the start of the answer is computed with the following formula (and likewise for the end).
Pi=eS⋅Ti∑jeS⋅TjP_i = \frac{e^{S \cdot T_i}}{\sum_j e^{S \cdot T_j}}

The fine-tuning settings recommended in the paper are to choose the best combination on the validation data from batch sizes 16 and 32, learning rates 5×10−55 \times 10^{-5}, 3×10−53 \times 10^{-5}, and 2×10−52 \times 10^{-5}, and 2 to 4 epochs. All results in the paper require only enough computation to be reproduced within an hour on a single Cloud TPU, or in a few hours on a GPU.

Why bidirectional training is possible

An ordinary language model is trained on the task of "predicting the next word from the previous words," so it can only learn in one direction. If it were made bidirectional, each word would indirectly "see itself" inside the multi-layer network, making the answer trivial.

The masked language model avoids this problem by hiding the very word to be predicted from the input. Since the information about the hidden word is not in the input, the model has no choice but to infer the original word from the surrounding context alone. This is the same idea as a fill-in-the-blank (cloze) test.

It is easier to understand by thinking of an English fill-in-the-blank question. In "I went to the ___ to buy bread.", the blank is hard to fill from "went to the" on the left alone, but reading "to buy bread" on the right suggests "bakery" or "store". BERT acquires this ability to read both sides through pre-training.

Only 80% of the chosen tokens are replaced with [MASK] because [MASK] never appears in the input during fine-tuning. If the input looks too different between pre-training and fine-tuning, the learned representations are hard to use. By also mixing in random words and unchanged words, the model comes to assume that "any word might be wrong" and builds context-based representations at every position.

The masked language model predicts only 15% of the tokens in each batch. Pre-training therefore converges somewhat more slowly than with a left-to-right language model that predicts every token. However, in the paper's experiments, the masked language model outperformed it in accuracy after fine-tuning from early in training.

Experimental results

GLUE (test data. F1 for QQP and MRPC, Spearman correlation for STS-B, accuracy for the others. The average excludes WNLI)

ModelMNLI (matched / mismatched)QNLISST-2CoLARTEAverage
BiLSTM + ELMo + Attn76.4 / 76.179.890.436.056.871.0
OpenAI GPT82.1 / 81.487.491.345.456.075.1
BERT-Base84.6 / 83.490.593.552.166.479.6
BERT-Large86.7 / 85.992.794.960.570.182.1

BERT-Base and GPT have almost the same architecture apart from the attention mask, yet they differ by 4.5 points on average. BERT-Large greatly outperformed BERT-Base, especially on tasks with little training data.

SQuAD v1.1 (validation data. EM is the exact match rate)

ModelEMF1
BERT-Base (single)80.888.5
BERT-Large (single)84.190.9
BERT-Large (ensemble of 7)85.891.8

Comparison of pre-training tasks (BERT-Base, validation data)

Pre-trainingMNLI-mQNLIMRPCSST-2SQuAD (F1)
MLM + NSP (BERT-Base)84.488.486.792.788.5
MLM only83.984.986.592.687.9
Left-to-right language model only82.184.377.592.177.8
Left-to-right + BiLSTM82.184.175.791.684.9

Removing NSP lowered the scores on QNLI, MNLI, and SQuAD, and switching further to a left-to-right language model lowered the scores on every task. The drops are especially large on SQuAD (more than 10 points in F1), which needs the right-hand context, and on MRPC. Adding a bidirectional LSTM on top did not reach the level of bidirectional pre-training.

Model size (validation accuracy, averaged over 5 fine-tuning runs)

LayersHHHeadsMNLI-mMRPCSST-2
37681277.979.888.4
67681281.984.891.3
127681284.486.792.9
2410241686.687.893.7

Even on MRPC, which has only 3,600 training examples, accuracy rose as the model got larger. The paper describes this as the first work to show that, given sufficient pre-training, scaling up the model helps even on small tasks.

Caveats when using it

When using BERT, keep the following points in mind.

  • It is not suited to text generation: BERT is an encoder trained for filling in blanks and classification, so for generating text from left to right, use a decoder-only model such as GPT.
  • The input is limited to 512 tokens: position embeddings are learned only up to position 512. Long documents need workarounds such as splitting them into chunks.
  • Results vary on small data: the paper reports that fine-tuning BERT-Large can be unstable on small datasets, so it was trained several times with different random initializations and the best run on the validation data was chosen.
  • Use a small learning rate for fine-tuning: to avoid destroying the pre-trained weights, use a learning rate of around 10−510^{-5} and train for only 2 to 4 epochs.
  • Use the same tokenizer as the model: the vocabulary and the IDs of [CLS], [SEP], and [MASK] must match those used in pre-training.

The [CLS] output CC of a BERT model that has not been fine-tuned cannot be used as a vector representing the meaning of a sentence. As the paper notes, CC is trained during pre-training only for next sentence prediction. To use it for computing sentence similarity or similar tasks, fine-tune it on the target task first.

BERT can also be used with frozen weights, feeding the outputs of its intermediate layers as features into another model. In the paper's named entity recognition (CoNLL-2003) experiment, concatenating the outputs of the last four layers gave a validation F1 of 96.1, only 0.3 below fine-tuning the whole model (96.4).

Comparison with other models

Comparing pre-trained language models from the same viewpoints gives the following.

ModelArchitectureDirection of contextPre-training taskUse on downstream tasks
ELMoBidirectional LSTMLearns left-to-right and right-to-left separately and concatenates the outputsLanguage model (next-word prediction)Outputs are fed as features into a task-specific model
GPTTransformer decoder onlyLeft to rightLanguage model (next-word prediction)Fine-tune the whole model
BERTTransformer encoder onlyBoth sides at once, in every layerMasked language model + next sentence predictionFine-tune the whole model

After BERT, many improved versions were proposed, such as RoBERTa, which revisited the pre-training procedure; ALBERT, which reduced the number of parameters; DistilBERT, which was made smaller with knowledge distillation; and ELECTRA, which changed the pre-training task.

Rough guidelines for choosing are as follows.

  • Sentence classification, search, named entity recognition, question answering (extracting answers from a passage): encoder-only models like BERT are a good fit. They can use the context on both sides and can be smaller than generative models.
  • Text generation, dialogue, writing summaries: use a decoder-only model such as GPT or GPT-2, or a model with both an encoder and a decoder such as BART.

PyTorch example

Show code
python
import torch
from transformers import AutoTokenizer, BertForMaskedLM, BertForSequenceClassification

"""
Example of loading and using pre-trained BERT-Base (English, uncased) with Hugging Face transformers
1. Masked language model: predict the word at the [MASK] position (the pre-training task itself)
2. Sentence classification: add a classification layer on top of the [CLS] output and fine-tune
"""

name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(name)   # WordPiece. Adds [CLS] and [SEP] automatically

# --- 1. Fill in the blank with the masked language model ---
mlm = BertForMaskedLM.from_pretrained(name)
mlm.eval()                                         # Disable dropout
inputs = tokenizer("The capital of France is [MASK].", return_tensors="pt")
# inputs: input_ids (token IDs), token_type_ids (sentence A=0 / sentence B=1), attention_mask (padding=0)
with torch.no_grad():
  logits = mlm(**inputs).logits                    # [1, sequence length, vocabulary size]
mask_index = (inputs["input_ids"][0] == tokenizer.mask_token_id).nonzero(as_tuple=True)[0]
top5 = logits[0, mask_index].topk(5, dim=-1).indices[0]
print(tokenizer.convert_ids_to_tokens(top5.tolist()))  # Candidate words (most probable first)

# --- 2. Classify the relation between two sentences (one fine-tuning step) ---
clf = BertForSequenceClassification.from_pretrained(name, num_labels=2)  # The classification layer is newly initialized
optimizer = torch.optim.AdamW(clf.parameters(), lr=2e-5)                 # Candidates in the paper: 5e-5, 3e-5, 2e-5

batch = tokenizer(
  ["A man is playing a guitar.", "A dog runs in the park."],    # Sentence A
  ["A person plays an instrument.", "The cat is sleeping."],    # Sentence B
  padding=True, truncation=True, max_length=128, return_tensors="pt")
labels = torch.tensor([1, 0])                                   # 1: related, 0: unrelated

clf.train()                                         # Enable dropout
out = clf(**batch, labels=labels)                   # [CLS] output → linear layer → cross-entropy
out.loss.backward()
optimizer.step()
optimizer.zero_grad()

clf.eval()
with torch.no_grad():
  probs = clf(**batch).logits.softmax(dim=-1)       # [2, 2]
print(probs)

FAQ

Q. What is the difference between BERT and GPT?
A.

BERT uses only the Transformer encoder, and each word sees all the words before and after it. It is pre-trained with the masked language model, which predicts hidden words. GPT uses only the decoder, and each word sees only the words to its left and predicts the next word. As a result, BERT is suited to understanding text (classification, question answering), and GPT is suited to generating text.

Q. Why are not all hidden words replaced with [MASK]?
A.

Because [MASK] does not appear in the input during fine-tuning or actual use, and this reduces the mismatch with pre-training. In the paper's experiments, the fine-tuning results did not change much with any replacement strategy, but when the weights were frozen and used as features, replacing everything with [MASK] lowered the named entity recognition F1 from 94.9 to 94.0.

Q. Can BERT generate text?
A.

It is not suited to it as is. BERT is not trained to produce words one by one from left to right, so it is poor at naturally writing a continuation of a text. For generation, use a decoder-only model such as GPT or a model with an encoder and a decoder such as BART.

References

  1. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. Proceedings of NAACL-HLT 2019, 4171–4186. arXiv:1810.04805.
  2. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. NIPS 2017.
  3. Radford, A., Narasimhan, K., Salimans, T., & Sutskever, I. (2018). Improving Language Understanding by Generative Pre-Training. OpenAI.
  4. Hugging Face. Transformers documentation: BERT.