Search

Search papers and lessons

RoBERTa: A Robustly Optimized BERT Pretraining Approach

Yinhan Liu, Myle Ott, Naman Goyal et al. · 2019

RoBERTa re-runs BERT's pretraining with a few changes (more data, longer training, bigger batches, dynamic masking, no next-sentence loss) and shows that the gains came from training recipe, not a new architecture.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Neural network basics
  • Linear algebra
  • Probability
  • Optimizers
  • ReadReady to readNot yet

TL;DR

BERT was a landmark: pretrain a Transformer to fill in masked words, then fine-tune it on a task. RoBERTa asks how much of the result depended on how BERT was trained rather than on its design. Its authors kept the BERT architecture and objective, changed the training recipe, and got better results on the standard language-understanding benchmarks. The changes were: more data, longer training, larger batches, masks that change every time a sentence is seen, and no next-sentence loss.

Builds on: BERT: Pre-training of Deep Bidirectional Transformers, Masked Language Modeling, Subword Tokenization, Adam Optimizer · Leads to: the view that recipe and data often matter as much as architecture, which shaped how later encoder models were trained

Why it mattered

By 2019 BERT-style models had become the default way to get strong results on language understanding tasks such as question answering, sentence classification and textual entailment. The standard test suites were GLUE, a set of nine language-understanding tasks, and SQuAD, questions answered from a passage of text. Each new paper claimed a new model, often with a new objective or architecture. Training was expensive, many groups used private data of different sizes, and so the comparisons were hard to trust.

RoBERTa was a replication study. It showed that a plain BERT, trained longer on more text with better settings, was far better than the published numbers suggested. The paper's headline is that a simple recipe matched or beat the models published after BERT. It also released its models and code in fairseq, which let other groups build on the same baseline.

The problem

BERT takes two segments of text, x1,…,xNx_1, \ldots, x_N and y1,…,yMy_1, \ldots, y_M, joined with special tokens. Two objectives are trained together. Masked language modeling (MLM) picks a random subset of tokens, replaces them, and asks the model to predict the originals with cross-entropy. Next sentence prediction (NSP) asks whether the second segment really follows the first in the source text.

The authors found that BERT, as published, was undertrained, and that several choices were fixed by accident. The masks were generated once and saved. The NSP loss was assumed to help, but other work questioned it. The batch size, the learning rate schedule and the amount of data were not tuned together. Because so many things changed at once across papers, no one could say which change had done the work. The question for RoBERTa was: which choices really matter?

How it works

Think of RoBERTa as BERT with a set of adjustments to the training pipeline. The adjustments form a path from the data to the final model.

flowchart LR
  A["Text corpus: 160GB from five sources"] --> B["Pack full sentences, no NSP pair"]
  B --> C["Mask tokens fresh each time a sequence is fed"]
  C --> D["Byte-level BPE, 50K vocabulary"]
  D --> E["Large batches of 8K sequences, 500K steps"]
  E --> F["Pretrained encoder"]
  F --> G["Fine-tune on GLUE, SQuAD, RACE"]
  1. Start with the data. The original BERT used 16GB of books and Wikipedia. RoBERTa adds CC-News (76GB after filtering), OpenWebText (38GB) and Stories (31GB), for over 160GB in total.

  2. Pack the input. BERT's inputs were two segments, each possibly spanning several sentences, with NSP as a side task. RoBERTa tested four formats and kept full sentences: each input is packed with contiguous sentences up to 512 tokens, may cross document boundaries, and has no NSP loss.

  3. Mask the tokens. BERT chose 15% of tokens and replaced 80% with a mask token, 10% with a random token, and 10% left them unchanged. RoBERTa keeps the 15% and the 80/10/10 rule but creates the mask pattern every time a sequence is fed to the model. This is dynamic masking.

  4. Tokenize. BERT used a character-level byte-pair vocabulary of 30K. RoBERTa uses a byte-level byte-pair encoding with 50K units. Any text can then be encoded without an unknown-token case.

  5. Set the optimizer and batch. The authors use Adam with β2=0.98\beta_2 = 0.98, which they found more stable with large batches. They use batches of 8K sequences instead of 256, and tune the peak learning rate for each setting.

  6. Train longer. The large model is trained for 100K, then 300K, then 500K steps. Each stage adds data or steps and the downstream results rise at each stage.

  7. Fine-tune on each task. The pretrained encoder is then fine-tuned with BERT's procedure on each task. The paper uses single-task fine-tuning, which means no multi-task training and no ensembling for the dev-set results.

Worked examples

Example
1. Tiny: masking 1000 tokens

Setting: a corpus contains 1000 tokens chosen for prediction, following BERT's rule.

  1. Of the 1000 chosen tokens, 80% are replaced by the mask token: 0.80×1000=8000.80 \times 1000 = 800.
  2. Of the 1000, 10% get a random vocabulary token: 0.10×1000=1000.10 \times 1000 = 100.
  3. The remaining 10%, or 100 tokens, keep their original word.
  4. Check: 800+100+100=1000800 + 100 + 100 = 1000. Every chosen token is accounted for.
  5. Interpretation: the model cannot tell which of the 1000 positions are masked, so it must predict the right word at every chosen position, even when the input already shows it.

Answer: 800 masked, 100 random, 100 unchanged.

Example
2. Standard: static versus dynamic masks

Setting: BERT duplicated its data 10 times and trained for 40 epochs. Each duplicate got its own static mask, made once in preprocessing.

  1. Each sequence has 10 different masks, one per copy.
  2. Over 40 epochs, each copy is seen 4 times, so each of the 10 masks is seen 40/10=440 / 10 = 4 times.
  3. With dynamic masking, a new mask is drawn each time, so the number of distinct masks grows with the number of epochs: 40 patterns instead of 10.
  4. Interpretation: the model sees more variety in its prediction task with the same compute.

Answer: static masks give 10 patterns, each seen 4 times; dynamic masks give 40 distinct patterns over the same 40 epochs.

Example
3. Realistic: matching the cost of different batch sizes

Setting: BERT trained for 1M steps with 256 sequences per step, so 1,000,000×256=2561{,}000{,}000 \times 256 = 256 million sequences in total.

  1. With 2K sequences per step, the same number of sequences takes 256,000,000/2,048=125,000256{,}000{,}000 / 2{,}048 = 125{,}000 steps.
  2. With 8K sequences per step, it takes 256,000,000/8,192≈31,250256{,}000{,}000 / 8{,}192 \approx 31{,}250 steps, which the paper rounds to 31K.
  3. The paper's Table 3 reports, for the same number of passes over the data, held-out Perplexity (the model's average surprise at unseen text, where lower is better) of 3.99 at batch 256, 3.68 at 2K and 3.77 at 8K. MNLI accuracy is 84.7, 85.2 and 84.6.
  4. Interpretation: the 2K setting gave the best held-out perplexity and the best MNLI accuracy, and the 8K setting was close. Fewer, larger steps can be as good as many small ones when the learning rate is tuned.

Try it: a run uses 4K sequences per step for 500K steps. How many sequences does it see in total? Answer: 4,096×500,000=2,048,000,0004{,}096 \times 500{,}000 = 2{,}048{,}000{,}000, about 2 billion sequences.

The math

BERT's MLM objective is a cross-entropy loss on the masked positions. Let M\mathcal{M} be the set of masked positions in a sequence x\mathbf{x} and let x^\hat{\mathbf{x}} be the corrupted input. Then

LMLM=−∑i∈Mlog⁡pθ ⁣(xi∣x^),\mathcal{L}_{\text{MLM}} = -\sum_{i \in \mathcal{M}} \log p_\theta\!\left(x_i \mid \hat{\mathbf{x}}\right),

where pθp_\theta is the model's distribution over the vocabulary at position ii, and xix_i is the original token. The sum runs only over masked positions; the rest of the sentence contributes nothing directly.

Definition: Dynamic masking

A masking scheme that draws a new set Mt\mathcal{M}_t each time sequence x\mathbf{x} is fed at step tt, instead of drawing one set M\mathcal{M} once and reusing it. Dynamic masking exposes the model to more distinct corruptions over training.

Step 2 in symbols: the sampling rule

For each position ii, draw uiu_i uniformly from [0,1)[0, 1). Select position ii if ui<0.15u_i < 0.15. For selected positions, replace the token by the mask token if vi<0.8v_i < 0.8, by a random token if 0.8≤vi<0.90.8 \leq v_i < 0.9, and keep it otherwise, with viv_i another uniform draw. These rules give the 80/10/10 split of Masked Language Modeling in expectation.

Step 3 in symbols: the batch and the step count

Let BB be the batch size in sequences and SS the number of steps. The total number of sequences seen is B×SB \times S. For a fixed budget B×S=CB \times S = C, the step count is S=C/BS = C / B. This gives the equal-cost comparisons in the realistic example, and it is why the authors could compare 256 with 8K at the same cost.

Step 4 in symbols: the optimizer

Adam keeps running averages of the gradient gt\mathbf{g}_t and its square, with decay rates β1\beta_1 and β2\beta_2. The update is

θt+1=θt−ηtm^tv^t+ϵ,\theta_{t+1} = \theta_t - \eta_t \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon},

where m^t\hat{\mathbf{m}}_t and v^t\hat{\mathbf{v}}_t are the bias-corrected averages and ηt\eta_t is the learning rate. RoBERTa changes β2\beta_2 from 0.999 to 0.98, and tunes ηt\eta_t and the warmup length for each batch size, which is why the peak rate in the tables is 1e-4 for batch 256, 7e-4 for batch 2K and 1e-3 for batch 8K.

Results

Masking and NSP (Tables 1 and 2). On SQuAD 2.0, static masking gave F1 78.3 and dynamic masking 78.7 for BERT-base. On MNLI, the two were 84.3 and 84.0, and on SST-2 92.5 and 92.9. The authors conclude that dynamic masking is comparable or slightly better and is cheaper to run.

For the input format, the segment-pair format with NSP gave SQuAD 1.1/2.0 of 90.4/78.7 and RACE 64.2. Removing NSP and packing full sentences gave 90.4/79.1 and RACE 64.8. Restricting each input to one document gave 90.6/79.7 and RACE 65.6. Sentence-pair inputs with NSP were the weakest, which the authors attribute to the model not learning long-range dependencies. The paper also suggests the original BERT may have removed only the loss term while still keeping the segment structure.

Batch size (Table 3). At equal cost, batch 2K with a learning rate of 7e-4 gave the lowest held-out perplexity, 3.68 against 3.99 at batch 256, and MNLI accuracy 85.2 against 84.7.

Full RoBERTa-large (Table 4). With 16GB of text and 100K steps, the model gets SQuAD 1.1/2.0 F1 of 93.6/87.3, MNLI 89.0 and SST-2 95.3. Adding the 160GB corpus gives 94.0/87.7, 89.3 and 95.6. Training to 300K steps gives 94.4/88.7, 90.0 and 96.1, and 500K steps gives 94.6/89.4, 90.2 and 96.4. The BERT-large numbers on the same settings are 90.9/81.8 and 86.6 on MNLI.

Benchmarks. On the GLUE development sets with single-task fine-tuning, RoBERTa reports state of the art on all nine tasks, with the same architecture and objective as BERT-large. On the GLUE test leaderboard, the submission reaches an average of 88.5 with single-task models, and state of the art on four of nine tasks. On SQuAD 2.0 dev it reaches F1 89.4, improving on XLNet by 0.6 points, using only the provided SQuAD data. On RACE test, accuracy is 83.2, state of the art at the time.

Limits. Only the encoder recipe was studied; the architecture was kept fixed. The data mix and the training steps were changed together, so the paper cannot fully separate their effects. The large model used 1024 V100 GPUs for roughly a day per 100K steps, so the replication is expensive to reproduce. The results are medians over several seeds on dev sets, and the test results use ensembles and task-specific tricks for QNLI and WNLI.

Misreadings to avoid

It is tempting to think that RoBERTa is a new model. In fact it is the same architecture and objective as BERT, trained differently. The gains come from the recipe and the data.

It is tempting to think that more data always helps on its own. In fact the paper adds data and steps in stages (Table 4), and each stage helps, so the gains come from the whole recipe rather than from one change.

It is tempting to think that removing NSP always hurts. In fact, in this study, dropping NSP and packing full sentences matched or improved downstream results, though the original BERT paper had reported the opposite.

Use the RoBERTa recipe when you pretrain an encoder yourself and have the compute to tune the batch size and learning rate. Do not use it as a recipe for decoder models, which the paper does not study. A cheaper alternative, when the budget is small, is to start from a released RoBERTa checkpoint and fine-tune it.

Reading guide

Read the paper in this order, with the lessons it needs at each step:

Chain of ideas in this lesson: BERT is a masked language model pretrained then fine-tuned; the paper holds the architecture fixed and varies the recipe; dynamic masking, full-sentence inputs without NSP, large batches and longer training each help; with more data and steps, RoBERTa beats the published BERT and matches or beats the post-BERT models on several benchmarks.

Check yourself

QuestionIn BERT's masking rule, 15% of tokens are chosen. Of the chosen tokens, 80% become the mask token, 10% a random token and 10% stay the same. How many of 2000 tokens are masked with the mask token?Show answer

Chosen tokens: 0.15×2000=3000.15 \times 2000 = 300. Mask token: 0.80×300=2400.80 \times 300 = 240.

QuestionBERT trained for 1M steps with 256 sequences per step. How many steps would the same number of sequences take with 8K sequences per step, to the nearest whole step?Show answer

The total is 1,000,000×256=256,000,0001{,}000{,}000 \times 256 = 256{,}000{,}000 sequences. Dividing by 8192 gives 31,250.031{,}250.0 steps, so 31,250 steps.

QuestionWhy does dynamic masking matter more when a model is trained for many more steps?Show answer

With static masking, each sequence has a fixed set of masks, so the number of distinct corruptions is the number of stored copies. Over many epochs or steps, the model sees the same few masked versions repeatedly. Dynamic masking draws a fresh mask each time, so the number of distinct corruptions grows with the number of steps, and the model cannot memorise one pattern per sequence.

QuestionApplied scenario: a team pretrains a small encoder on 2 GB of domain text, and their validation loss stops improving after a few epochs. Which RoBERTa change is most likely to help, and what is the risk?Show answer

Dynamic masking is cheap and gives more variety without new data, so it is a low-risk first change. Longer training would also help, but on 2 GB of text the model may overfit, and the paper's gains came from adding data along with steps. The risk is that more steps on a small corpus can memorise it, so the team should watch a held-out loss and stop when it rises.

Sources

Read the full paper

Yinhan Liu, Myle Ott, Naman Goyal et al., 2019. arXiv:1907.11692