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.
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:
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
| Model | Layers L | Dimensions H | Heads A | Parameters |
|---|---|---|---|---|
| BERT-Base | 12 | 768 | 12 | 110 million |
| BERT-Large | 24 | 1024 | 16 | 340 million |
Both were trained on BooksCorpus (800 million words) and English Wikipedia (2,500 million words).
Fine-tuning by task type
| Task type | Input | What we take from BERT | Example |
|---|---|---|---|
| Sentence classification | [CLS] sentence [SEP] | The [CLS] representation → linear layer | Sentiment, dialect |
| Pair classification | [CLS] A [SEP] B [SEP] | The [CLS] representation | Inference, similarity |
| Token tagging | Sentence | Each token's representation → tag | Entities, parts of speech |
| Extractive question answering | [CLS] question [SEP] passage [SEP] | Start and end probabilities for each token | SQuAD, 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:
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.
