BERT and the encoder family: pretraining and fine-tuning

BERT and Encoder Models: Pre-training and Fine-tuning

How BERT was trained with masked language modeling and next sentence prediction, input representation ([CLS], [SEP] and segments), fine-tuning methods for each task type, then what RoBERTa, ALBERT, DistilBERT, ELECTRA and DeBERTa changed, and the Arabic models AraBERT, CAMeLBERT and MARBERT, with code examples.

Lesson 23 of 38Intermediate50 minutes

Lesson objectives

  • Explain the MLM task and the 80/10/10 rule.
  • Know how BERT is fine-tuned for classification, tagging and extractive question answering.
  • Compare BERT variants and choose a suitable Arabic model.
Page contents
  1. The idea
  2. Why not use an ordinary language model?
  3. The two pretraining tasks
  4. Input representation
  5. The two original sizes
  6. Fine-tuning by task type
  7. Beyond BERT
  8. BERT and Arabic

The idea

Devlin et al. (2019) introduced BERT (Bidirectional Encoder Representations from Transformers): a transformer encoder only, pretrained on unlabeled text, then fine-tuned for any understanding task by adding a small layer. On release it achieved the best results on 11 tasks, including the GLUE benchmark and SQuAD, and became the foundation for hundreds of models.

Encoder-only model (BERT family) Encoder-only (BERT family)
[CLS]T0ذهبT1[MASK]T2إلىT3المدرسةT4[SEP]T5Token + Segment + Position embeddingsN× encoder blocksbidirectional self-attention: every token sees every tokenMLM: the student?classifier

Every token sees the whole context in both directions. In pre-training some tokens are masked and the model predicts them (MLM); in fine-tuning the [CLS] representation or the token representations are used.

Why not use an ordinary language model?

A left-to-right language model sees only the past. If we trained a bidirectional transformer to predict the next word, each word could "see itself" through the layers. The solution: hide some words and ask for them to be predicted.

The two pretraining tasks

1. Masked language modeling (MLM)

We randomly select 15% of the tokens. Of the selected ones:

  • 80% are replaced with [MASK].
  • 10% are replaced with a random token.
  • 10% stay as they are.

Then we ask for the original token to be predicted at the selected positions only:

\mathcal{L}_{\text{MLM}} = - \sum_{i \in \mathcal{M}} \log P(x_i \mid \tilde{\mathbf{x}})

The reason for the 80/10/10 rule: the [MASK] token never appears during fine-tuning, so if the model learned that prediction is only needed at [MASK], it would not build good representations for ordinary words.

2. Next sentence prediction (NSP)

A pair of sentences (A, B): in 50% of cases B really is the next sentence, and in 50% it is a random sentence. The goal is to teach relations between sentences for tasks such as question answering and inference. (RoBERTa would later show that this task is unnecessary.)

Input representation

[CLS] ذهب الطالب إلى المكتبة [SEP] واستعار كتاباً [SEP]

Each token's representation = token embedding (WordPiece, about 30 thousand in English BERT) + segment embedding (A or B) + position embedding (learned, up to 512).

  • [CLS]: a token at the start whose final representation is used as a summary of the sequence in classification tasks.
  • [SEP]: a separator between segments.

The two original sizes

ModelLayers LDimensions HHeads AParameters
BERT-Base1276812110 million
BERT-Large24102416340 million

Both were trained on BooksCorpus (800 million words) and English Wikipedia (2,500 million words).

Fine-tuning by task type

Task typeInputWhat we take from BERTExample
Sentence classification[CLS] sentence [SEP]The [CLS] representation → linear layerSentiment, dialect
Pair classification[CLS] A [SEP] B [SEP]The [CLS] representationInference, similarity
Token taggingSentenceEach token's representation → tagEntities, parts of speech
Extractive question answering[CLS] question [SEP] passage [SEP]Start and end probabilities for each tokenSQuAD, ARCD

In extractive question answering we learn two vectors \mathbf{s} and \mathbf{e}, and the probability that the answer starts at token i is:

P_{\text{start}}(i) = \frac{\exp(\mathbf{s} \cdot \mathbf{h}_i)}{\sum_j \exp(\mathbf{s} \cdot \mathbf{h}_j)}

and likewise for the end, and we choose the span (i, j) with j \ge i that maximizes the sum of the two scores.

Code example for fine-tuning on classification

from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer

name = "aubmindlab/bert-base-arabertv02"   # example; choose the model that suits your data
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=3)

def encode(batch):
    return tok(batch["text"], truncation=True, max_length=128)

args = TrainingArguments(output_dir="out", learning_rate=2e-5, per_device_train_batch_size=16,
                         num_train_epochs=3, weight_decay=0.01, eval_strategy="epoch", seed=42)
trainer = Trainer(model=model, args=args, train_dataset=train.map(encode, batched=True),
                  eval_dataset=dev.map(encode, batched=True), tokenizer=tok)
trainer.train()

Small learning rates (2e-5 to 5e-5) and 2–4 epochs are usually enough. With small data, performance fluctuates a lot between random seeds, so report the mean and standard deviation over several seeds.

Beyond BERT

  • RoBERTa (Liu et al., 2019): the same architecture, but much longer training, more data (160 GB), larger batches, dynamic masks that change every epoch, and removing NSP. It clearly outperformed BERT and showed that BERT had been "undertrained".
  • ALBERT (2019): fewer parameters through factorizing the embedding matrix and sharing parameters across layers, and replacing NSP with a sentence order prediction (SOP) task.
  • DistilBERT (Sanh et al., 2019): knowledge distillation from BERT into a model with half the layers, about 40% smaller and about 60% faster while keeping most of the performance.
  • ELECTRA (Clark et al., 2020): instead of predicting only 15% of the tokens, a small generator produces replacements for some tokens, and a discriminator learns to detect, for each token, whether it is original or replaced (replaced token detection). Learning from all tokens makes it far more compute-efficient.
  • DeBERTa (2020): disentangled attention (Disentangled) that represents content and relative position with two separate vectors, with an enhanced mask decoder.

BERT and Arabic

  • mBERT: Google's multilingual version (104 languages), in which Arabic's share is limited.
  • AraBERT (Antoun et al., 2020): the first widely used Arabic BERT, trained on Arabic Wikipedia and news corpora (such as OSIAN and the El-Khair corpus), and some of its versions used pre-segmentation with Farasa.
  • ARBERT and MARBERT (Abdul-Mageed et al., 2021): ARBERT for MSA, and MARBERT trained on about a billion tweets, so it excels on dialects and social media.
  • CAMeLBERT (Inoue et al., 2021): a set of models for MSA, dialects, Classical Arabic and a mix of them, with smaller MSA versions to study the effect of size. The most important finding: how close the pretraining data is in variant to the task data matters more than its size.

The practical selection rule: tweets and dialects → MARBERT, CAMeLBERT-DA or CAMeLBERT-Mix; news and MSA → AraBERT, ARBERT or CAMeLBERT-MSA; Classical texts → CAMeLBERT-CA. Then compare two or three models on the validation set instead of relying on the rule alone.

You will find detailed cards for all these models, with their diagrams and references, in the Models tab.

Lesson summary

  • BERT is a bidirectional transformer encoder trained to predict masked tokens.
  • Fine-tuning adds a small layer on top of the representations and updates all the weights.
  • RoBERTa showed that the training recipe matters as much as the architecture.
  • Choosing an Arabic model depends on the type of text: MSA, dialects or Classical.

Check what you understood

Choose an answer for each question to see the correction and the reasoning. Your answers are not sent anywhere.

  1. In MLM, what happens to the 15% of selected tokens?

  2. What did RoBERTa find about next sentence prediction (NSP)?

  3. For sentiment analysis of tweets in different dialects, which Arabic model is the best starting choice?

References

  1. Devlin, J., Chang, M.-W., Lee, K. & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL arxiv.org/abs/1810.04805
  2. Liu, Y. et al. (2019). RoBERTa: A Robustly Optimized BERT Pretraining Approach arxiv.org/abs/1907.11692
  3. Clark, K. et al. (2020). ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators. ICLR arxiv.org/abs/2003.10555
  4. Antoun, W., Baly, F. & Hajj, H. (2020). AraBERT: Transformer-based Model for Arabic Language Understanding. OSACT Workshop arxiv.org/abs/2003.00104
  5. Inoue, G. et al. (2021). The Interplay of Variant, Size, and Task Type in Arabic Pre-trained Language Models. WANLP arxiv.org/abs/2103.06678
  6. Rogers, A., Kovaleva, O. & Rumshisky, A. (2020). A Primer in BERTology: What We Know About How BERT Works. TACL 8 arxiv.org/abs/2002.12327