AI Logic

Architectures

RoBERTa

Updated:

Pretraining of RoBERTa. The left side shows the overall flow (input packed up to 512 tokens with contiguous sentences sampled from documents, byte-level BPE, dynamic masking, embeddings, repeated encoder layers identical to BERT, and a masked language model output only). The right side is a table of changes from BERT (masking strategy, input format, next sentence prediction, sequence length, batch size and steps, data, tokenization)

Background and overview

RoBERTa (Robustly optimized BERT approach) is a language model that revisits only the pretraining procedure of BERT without changing its architecture. It was proposed in 2019 by Liu et al. at Facebook AI and the University of Washington.

After BERT, models with new pretraining objectives such as XLNet outperformed BERT one after another. However, because each used different amounts of training data and training lengths, it was difficult to isolate which ideas were responsible for the gains. Liu et al. rebuilt BERT's pretraining and measured the effect of changing one setting at a time. Their conclusion was that "BERT was significantly undertrained".

RoBERTa makes the following four changes.

  • Train longer, with larger batches, on more data (data 16GB → 160GB)
  • Remove next sentence prediction (NSP)
  • Train only on long sequences (512 tokens)
  • Re-select the masked positions every time a sequence is fed in (dynamic masking)

With the architecture and the training objective (masked language modeling) kept the same as BERT-Large, it achieved the following results at the time of the paper.

  • An average of 88.5 on the GLUE leaderboard (the previous best, XLNet, scored 88.4), with the best result on 4 of the 9 tasks
  • F1 of 89.4 on the SQuAD v2.0 dev set (0.6 points higher than XLNet)
  • 83.2% accuracy on the test set of the reading comprehension task RACE

Architecture

The RoBERTa network is the same stack of Transformer encoder layers as BERT. The paper deliberately leaves the architecture unchanged so that the effects can be compared purely by training procedure. In the figure at the top of the article, the left side shows the pretraining flow and the right side lists the changes from BERT.

ModelLayers LLHidden size HHHeads AAFeed-forward inner sizeParameters
RoBERTa-Base12768123072About 15M more than BERT-Base
RoBERTa-Large241024164096355M

The only change outside the architecture is the input tokenization. BERT uses WordPiece with a 30K vocabulary, whereas RoBERTa uses the same byte-level BPE as GPT-2 (50K vocabulary). Because the smallest unit is a byte rather than a character, any text can be split into tokens without producing "unknown words". The larger vocabulary adds about 15M embedding parameters for Base and about 20M for Large.

Because RoBERTa does not use next sentence prediction, its input is not "a pair of two sentences". The Hugging Face implementation likewise does not use token_type_ids to distinguish sentence A from sentence B; two sentences are fed in with only separator tokens between them.

Training: four changes from BERT

RoBERTa's pretraining uses the same masked language modeling as BERT (select 15% of the input tokens, replace 80% of them with [MASK], 10% with a random token, leave 10% unchanged, and predict the original tokens). The differences are the following four points.

  1. Dynamic masking: BERT decided the masked positions only once during preprocessing. To avoid always using the same mask, it duplicated the data 10 times with 10 different masks, but over 40 epochs of training each mask is still seen 4 times. RoBERTa re-selects the masked positions every time a sequence is fed to the model.
  2. Remove next sentence prediction and pack sentences: each input is packed with contiguous sentences sampled from one or more documents, up to a total of 512 tokens. When the end of a document is reached, sentences from the next document follow, with a separator token at the boundary (the format called FULL-SENTENCES in the paper). The next sentence prediction loss is not used.
  3. Train with large batches: BERT's batch of 256 sequences is increased to 8,000 sequences. To match the larger batch, the learning rate is raised (up to 4×10−44 \times 10^{-4} for Large), and the β2\beta_2 of Adam is lowered from 0.999 to 0.98 to stabilize training.
  4. More data, longer training: training runs for 500K steps on 160GB of text in total, adding the news corpus CC-News (76GB), OpenWebText (38GB), and Stories (31GB) to BERT's BooksCorpus and English Wikipedia (16GB).

In addition, RoBERTa drops the short sequences of length 128 that BERT used for 90% of training and trains only on sequences of length 512 from start to finish.

The pretraining settings for RoBERTa-Large in the paper are as follows.

ItemValue
Data5 corpora, 160GB in total
Batch8,000 sequences × up to 512 tokens
Steps500K
OptimizationAdam (β1=0.9\beta_1 = 0.9, β2=0.98\beta_2 = 0.98, ϵ=10−6\epsilon = 10^{-6}), weight decay 0.01
Learning rateWarmup to a peak of 4×10−44 \times 10^{-4} over the first 30K steps, then linear decay
Dropout0.1 (also 0.1 on attention weights)
Hardware1,024 V100 GPUs, about 1 day per 100K steps

Compared with BERT (256 sequences × 1M steps), RoBERTa (8,000 sequences × 500K steps) sees about 16 times as many sequences during training.

Fine-tuning works as in BERT: an output layer is added and the whole model is retrained. The paper's GLUE setting selects a batch size from 16 and 32 and a learning rate from 1×10−51 \times 10^{-5}, 2×10−52 \times 10^{-5}, and 3×10−53 \times 10^{-5}, warms up for the first 6% of steps and then decays linearly to 0, trains for 10 epochs, and uses early stopping on the dev set.

Why it works

All four changes push in the same direction: "give the same model more, and more diverse, training".

  • Dynamic masking: because a different position is hidden each time even in the same sentence, the model can learn many fill-in-the-blank problems from one sentence. The longer the training or the more data, the larger this difference becomes. It also removes the need to duplicate and store the data.
  • Removing next sentence prediction: in the paper's experiments, the format that packs sentences without the prediction gave equal or slightly better results than the format that splits the input into two segments and predicts the next sentence. On the other hand, using pairs of single sentences lowered the results. The paper attributes this to short inputs preventing the model from learning long-range dependencies.
  • Large batches: when comparing with the number of passes over the data (epochs) and the amount of computation held fixed, a batch of 2,000 sequences improved both the masked language model perplexity and the accuracy on downstream tasks. Large batches also have the advantage of being easy to split across multiple GPUs (data parallelism).
  • Data and training length: increasing the data from 16GB to 160GB improved results on all tasks, and training longer, from 100K → 300K → 500K steps, improved them further. Even at 500K steps there was no sign of overfitting, and the paper states that further training might bring more gains.

As an analogy with exam preparation, BERT was like "repeating the same workbook until the positions of the answers were memorized". RoBERTa is like "making the workbook 10 times larger, turning it into different fill-in-the-blank problems every time, and studying for much longer". The study method (the model's architecture and objective) is the same, yet simply raising the quantity and quality of study boosted the scores substantially.

RoBERTa's results come from compute and data, not from the architecture. The paper's final model sees about 16 times as many sequences on about 10 times as much data as BERT. Under the same budget, the gap with other models may be smaller. The paper itself notes that other methods such as XLNet might also improve if retuned.

Experimental results

Masking strategy (BERT-Base size, dev sets. SQuAD is F1, others are accuracy. Median of 5 runs)

MaskingSQuAD 2.0MNLI-mSST-2
Static (reimplementation of BERT)78.384.392.5
Dynamic78.784.092.9

Although the differences are small, dynamic masking is equal or slightly better and does not require duplicating the data, so all subsequent experiments used dynamic masking.

Input format and next sentence prediction (BERT-Base size, BooksCorpus and Wikipedia, 1M steps)

Input formatNSPSQuAD 1.1 / 2.0MNLI-mSST-2RACE
Segment pairs (same as BERT)Yes90.4 / 78.784.092.964.2
Sentence pairsYes88.7 / 76.282.992.163.0
Packed sentences (across documents)No90.4 / 79.184.792.564.8
Packed sentences (within a document)No90.6 / 79.784.792.765.6

The within-document format is slightly better, but because it makes the batch size vary, RoBERTa uses the cross-document format.

Batch size (BERT-Base size, with the number of passes over the data and the computation held fixed)

BatchStepsLearning ratePerplexityMNLI-mSST-2
2561M1×10−41 \times 10^{-4}3.9984.792.7
2,000125K7×10−47 \times 10^{-4}3.6885.292.9
8,00031K1×10−31 \times 10^{-3}3.7784.692.8

Data size and training length (Large size, dev sets. Each row adds to the changes of the rows above)

ModelDataBatchStepsSQuAD 1.1 / 2.0MNLI-mSST-2
RoBERTa16GB8,000100K93.6 / 87.389.095.3
+ more data160GB8,000100K94.0 / 87.789.395.6
+ train longer160GB8,000300K94.4 / 88.790.096.1
+ train even longer160GB8,000500K94.6 / 89.490.296.4
BERT-Large13GB (*)2561M90.9 / 81.886.693.7
XLNet-Large126GB2,000500K94.5 / 88.889.895.6

(*) The same BooksCorpus and Wikipedia as BERT, but 13GB as counted in the XLNet paper.

Even with the same 16GB of data, RoBERTa clearly outperformed BERT-Large. Each time the data was increased and training was lengthened, results improved on all tasks.

GLUE (a single model fine-tuned for each task, dev sets. MNLI is matched/mismatched; the others use each task's metric such as accuracy)

ModelMNLIQNLIQQPRTESST-2MRPCCoLASTS-B
BERT-Large86.6 / -92.391.370.493.288.060.690.0
XLNet-Large89.8 / -93.991.883.895.689.263.691.8
RoBERTa90.2 / 90.294.792.286.696.490.968.092.4

On the dev sets, RoBERTa achieved the best results at the time on all 9 GLUE tasks. On the test sets (leaderboard, ensembles) it averaged 88.5, slightly above XLNet's 88.4.

SQuAD and RACE (a single model without additional data)

ModelSQuAD 1.1 (dev, EM / F1)SQuAD 2.0 (dev, EM / F1)RACE (test, accuracy)
BERT-Large84.1 / 90.979.0 / 81.872.0
XLNet-Large89.0 / 94.586.1 / 88.881.7
RoBERTa88.9 / 94.686.5 / 89.483.2

Practical notes

Keep the following points in mind when using RoBERTa.

  • Not compatible with the BERT tokenizer: both the vocabulary (byte-level BPE, 50K) and the special tokens (<s>, </s>, <mask>) differ from BERT. Always use the tokenizer for RoBERTa.
  • Input is limited to 512 tokens: as with BERT, long documents need to be split before being fed in.
  • Sentence pairs are distinguished only by separators: since there is no embedding to distinguish sentence A from sentence B, the two sentences are fed in separated by separator tokens.
  • Fine-tune with a small learning rate: the paper's GLUE setting uses a learning rate of 1∼3×10−51 \sim 3 \times 10^{-5} with warmup over 6% of the total steps. For its leaderboard submissions, the paper reports that small tasks (RTE, STS-B, MRPC) worked better when starting from a model fine-tuned on MNLI.
  • Mind the compute if pretraining yourself: the paper's setting is 8,000 sequences × 500K steps. In the paper, 100K steps took about 1 day on 1,024 V100 GPUs. Even on smaller hardware, accumulating gradients over several steps before updating gives the same computation as a large batch, but it takes correspondingly longer.

The paper reports that training with large batches was very sensitive to Adam's ϵ\epsilon and β2\beta_2. Reverting RoBERTa's settings (β2=0.98\beta_2 = 0.98, ϵ=10−6\epsilon = 10^{-6}) to BERT's (β2=0.999\beta_2 = 0.999) can make training unstable with large batches.

Comparison with other models

Comparing BERT and later models from the same viewpoints gives the following.

ModelArchitecturePretraining objectivePretraining dataWhat changed
BERTTransformer encoderMasked language model + next sentence prediction16GB(baseline)
XLNetIts own architecture modified from BERTAutoregressive language model with permuted prediction order126GBPretraining objective and architecture
RoBERTaSame as BERTMasked language model only160GBTraining procedure and amount of data

RoBERTa caught up with XLNet, which introduced a new pretraining objective, without changing the objective, and surpassed it on many tasks. The paper points out the need to carefully distinguish whether the improvements of new models come from "the architecture or objective" or from "the amount of data and training".

Other improvements on BERT include ALBERT, which reduces parameters; DistilBERT, which is made smaller through knowledge distillation; and ELECTRA, which changes the pretraining objective.

Rough guidelines for choosing:

  • To improve accuracy while using it the same way as BERT: replacing BERT with RoBERTa is the easy option. The architecture and usage are the same, and it outperforms BERT on many tasks.
  • When compute is limited or fast inference is needed: consider smaller models such as DistilBERT or ALBERT.
  • To generate text: like BERT, RoBERTa is encoder-only and is not suited to this. Use a decoder model such as GPT-2.

PyTorch example

Show code
python
import torch
from transformers import (AutoTokenizer, RobertaForMaskedLM,
                          RobertaForSequenceClassification, DataCollatorForLanguageModeling)

"""
Example of using pretrained RoBERTa-Base with Hugging Face transformers
1. Dynamic masking: re-select the masked positions every time a batch is built (when continuing pretraining)
2. Fill in the blank with the masked language model
3. Classify the relation between two sentences (one fine-tuning step)
"""

name = "roberta-base"
tokenizer = AutoTokenizer.from_pretrained(name)   # byte-level BPE (50K vocabulary). Adds <s> and </s> automatically

# --- 1. Dynamic masking ---
# DataCollatorForLanguageModeling re-selects 15% of the tokens on every call (80% <mask>, 10% random, 10% unchanged)
collator = DataCollatorForLanguageModeling(tokenizer, mlm=True, mlm_probability=0.15)
examples = [tokenizer("RoBERTa removes the next sentence prediction objective.")]
batch_1 = collator(examples)
batch_2 = collator(examples)                       # the hidden positions change even for the same sentence
print(batch_1["input_ids"])
print(batch_2["input_ids"])                        # labels hold the original ids only at hidden positions, -100 elsewhere

# --- 2. Fill in the blank with the masked language model ---
mlm = RobertaForMaskedLM.from_pretrained(name)
mlm.eval()                                         # disable dropout
inputs = tokenizer("The capital of France is <mask>.", return_tensors="pt")  # <mask>, not BERT's [MASK]
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()))  # a leading space of a word is shown as Ġ

# --- 3. Classify the relation between two sentences ---
clf = RobertaForSequenceClassification.from_pretrained(name, num_labels=2)  # the classification layer is newly initialized
optimizer = torch.optim.AdamW(clf.parameters(), lr=2e-5, weight_decay=0.1)  # the paper's GLUE candidates are 1e-5, 2e-5, 3e-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 (separated by </s></s>; token_type_ids are not used)
  padding=True, truncation=True, max_length=128, return_tensors="pt")
labels = torch.tensor([1, 0])

clf.train()                                        # enable dropout
out = clf(**batch, labels=labels)                  # output at the leading <s> -> classification 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 RoBERTa and BERT?
A.

The network architecture and the masked language modeling objective are the same; only the pretraining procedure differs. RoBERTa increases the data from 16GB to 160GB, raises the batch from 256 to 8,000 sequences and trains longer, removes next sentence prediction, and re-selects the masked positions every time an input is fed in. It also switches the tokenization from WordPiece to byte-level BPE with a 50K vocabulary.

Q. Is it really fine to remove next sentence prediction (NSP)?
A.

In the paper's experiments, removing NSP and packing sentences up to 512 tokens gave equal or slightly better results than the BERT format with NSP (e.g. SQuAD 2.0 F1 from 78.7 to 79.1). The RoBERTa paper speculates that results dropped when NSP was removed in the BERT paper perhaps because only the loss was removed while the input format remained pairs of two segments.

Q. Can RoBERTa be used with the BERT tokenizer?
A.

No. RoBERTa is trained with byte-level BPE with a 50K vocabulary, so both the token ids and the special tokens such as <s>, </s>, and <mask> differ from BERT. Use the tokenizer with the same name as the pretrained model (e.g. roberta-base).

References

  1. Liu, Y., Ott, M., Goyal, N., Du, J., Joshi, M., Chen, D., Levy, O., Lewis, M., Zettlemoyer, L., & Stoyanov, V. (2019). RoBERTa: A Robustly Optimized BERT Pretraining Approach. arXiv:1907.11692.
  2. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT 2019. arXiv:1810.04805.
  3. Yang, Z., Dai, Z., Yang, Y., Carbonell, J., Salakhutdinov, R., & Le, Q. V. (2019). XLNet: Generalized Autoregressive Pretraining for Language Understanding. NeurIPS 2019. arXiv:1906.08237.
  4. Hugging Face. Transformers documentation: RoBERTa.