AI Logic

Architectures

BART

Updated:

Architecture of BART. On the left, the overall pretraining flow (a bidirectional encoder that reads the corrupted document, a decoder that rewrites the original document from left to right, and lines from the encoder output to the decoder layers) and examples of the five noising methods. On the right, the inside of the encoder and decoder layers (self-attention, attention over the encoder output found only in decoder layers, and a GELU feed-forward network)

Background and overview

BART is a language model that pretrains an encoder-decoder Transformer on the task of restoring an original document from a deliberately corrupted one. It was proposed in 2019 by Lewis et al. at Facebook AI and presented at ACL 2020. The name comes from a Transformer that combines a Bidirectional encoder with an Auto-Regressive decoder.

The leading pretraining methods before it had the following limitations.

  • BERT: It predicts masked words from the surrounding context, which makes it strong at understanding text, but because it predicts words independently, it is hard to use for text generation.
  • GPT: It predicts the next word from left to right, so it can generate text, but each word can only see the context to its left.

BART reads the corrupted document with a bidirectional encoder and rewrites the original document one word at a time with a left-to-right decoder. Because the encoder input and the decoder output need not have the same length, any kind of corruption (noise) can be used, not just masking words but also deleting or reordering them. The paper states that BART can be viewed as a generalization of both BERT (bidirectional encoder) and GPT (left-to-right decoder).

The paper compared many noising schemes and found that the combination of "text infilling," which replaces spans with a single mask, and "sentence permutation," which shuffles sentence order, worked best. BART-Large, trained at the same scale as RoBERTa, performed on par with RoBERTa on GLUE and SQuAD while achieving state-of-the-art results at the time on summarization, dialogue, and abstractive question answering. On the XSum summarization task, ROUGE improved by about 6 points over the previous best.

Architecture

BART's architecture is exactly the standard Transformer sequence-to-sequence model (encoder and decoder) used in machine translation. In the figure at the top of the article, the left shows the overall pretraining flow and the noising methods, and the right shows the inside of the encoder and decoder layers.

ModelEncoder layersDecoder layersHidden size
BART-Base66768
BART-Large12121024

The only changes from the original Transformer are the following two, following GPT:

  • The activation function is changed from ReLU to GELU
  • Parameters are initialized from a normal distribution with mean 0 and standard deviation 0.02

Compared with BERT, it differs in these respects:

  1. It has a decoder: Each decoder layer looks at the words to its left with masked self-attention and also attends to the output of the final encoder layer (Q from the decoder, K and V from the encoder output).
  2. No feed-forward layer before word prediction: BERT passes through an additional feed-forward layer before predicting words, but BART does not.

In total, it has about 10% more parameters than a BERT of the same size. For tokenization, it uses the same byte-level BPE as GPT-2.

Training: add noise, then restore

BART pretraining proceeds as follows.

  1. Corrupt the document by adding noise (combining the methods in the table below).
  2. Feed the corrupted document to the encoder, which builds representations by looking at all words before and after.
  3. Feed the decoder the original document shifted one position to the right, and have it predict the words of the original document from left to right while attending to the encoder output.
  4. Minimize the cross-entropy between the decoder output and the original document (the negative log-likelihood of the original document).

The paper tried the following five noising methods (examples with the original document A B C . D E .).

MethodWhat it doesExample
Token maskingAs in BERT, replaces randomly selected tokens with [MASK]A _ C . _ E .
Token deletionDeletes randomly selected tokens; the model must also decide which positions are missingA . C . E .
Text infillingReplaces spans whose lengths are drawn from a Poisson distribution (λ=3\lambda = 3) with a single [MASK]; a span of length 0 corresponds to inserting a [MASK]A _ . D _ E .
Sentence permutationSplits the document into sentences at full stops and shuffles their order randomlyD E . A B C .
Document rotationRotates the document so that it begins with a randomly chosen token; this trains the model to find the start of the documentC . D E . A B

Text infilling is inspired by SpanBERT, but whereas SpanBERT replaces a span with the same number of [MASK] tokens, BART collapses the span into a single [MASK]. The model therefore has to predict how many tokens are missing from the span as well.

The pretraining setup for the large-scale BART-Large is as follows.

ItemValue
NoiseText infilling (masking 30% of the tokens in each document) + sentence permutation (all sentences)
DataThe same 160GB as RoBERTa (news, books, stories, and web text)
Batch × steps8,000 × 500k steps (same as RoBERTa)
DropoutDisabled for the final 10% of training steps

For fine-tuning, BART is used as follows depending on the task.

  • Sequence classification: The same input is fed to both the encoder and the decoder, and the decoder output at the final token is passed to a classification layer. This corresponds to BERT's [CLS], but placing it at the end lets the decoder attend to the entire input at that position.
  • Token classification (such as answer spans in SQuAD): The whole document is fed to the encoder and decoder, and the outputs of the final decoder layer are used as the representation of each token.
  • Sequence generation (summarization, abstractive question answering, etc.): The input is fed to the encoder, and the decoder generates the output one word at a time. In the paper, training uses cross-entropy with label smoothing (0.1), and generation uses beam search with a beam size of 5, blocking repeated trigrams.
  • Machine translation: BART's embedding layer is replaced with a small, randomly initialized encoder. This encoder learns to map the foreign language into "noisy input that BART can turn into English," and the whole of BART is used as a pretrained English-side decoder. Training has two stages: first only some parts, such as the new encoder, are trained, and then the whole model is trained for a small number of steps.

Why is it strong at generation tasks such as summarization?

BART's pretraining task is "read a corrupted input and rewrite clean text from left to right." Summarization and abstractive question answering are also tasks of "copying information from the input while rewriting it in a different form," so pretraining and fine-tuning take similar forms. The paper also cites this similarity as the reason for its strength on generation tasks.

Picture being handed a manuscript full of holes, with its paragraphs out of order, and asked to produce a clean copy. To do that you need both the ability to read the whole manuscript and grasp its meaning (the encoder) and the ability to write natural text while filling in the missing parts (the decoder). Both abilities carry over directly to summarization.

In addition, the decoder is always trained with the uncorrupted original document as its context. It practices writing without relying on symbols like BERT's [MASK], which never appear in real inputs, so the mismatch between pretraining and generation is small.

The paper's comparisons (in the experiments section below) also showed the following.

  • Noise that masks or deletes words is essential: Sentence permutation or document rotation alone led to large drops in performance.
  • Left-to-right pretraining helps generation: The masked language model and permuted language model, which do not include left-to-right prediction, were weaker than the others on generation tasks.
  • A bidirectional encoder helps on SQuAD: A model with only a left-to-right decoder dropped sharply on SQuAD.

BART's advantage is less pronounced for generation that is only loosely constrained by the input. In the paper's comparison, ELI5, which requires writing long free-form answers to questions, was the one task where a plain language model achieved better perplexity than BART. The paper attributes this to the pretraining format of "rewriting the input" fitting poorly with tasks where the answer is only loosely determined by the question.

Experimental results

Comparison of noising methods (Base size, 1M steps on books and Wikipedia. SQuAD is F1, MNLI is accuracy, and the rest are perplexities, where lower is better)

PretrainingSQuAD 1.1MNLIELI5XSumConvAI2CNN/DM
BERT-Base88.584.3----
Masked language model90.083.524.777.8712.597.06
Language model (left to right)76.780.121.407.0011.516.56
Permuted language model89.183.724.037.6912.236.96
BART: token masking90.484.125.057.0811.736.10
BART: token deletion90.484.124.616.9011.465.87
BART: text infilling90.884.024.266.6111.055.83
BART: document rotation77.275.353.6917.1419.8710.59
BART: sentence permutation85.481.541.8710.9316.677.89
BART: infilling + permutation90.883.824.176.6211.125.41

On every task except ELI5, BART with text infilling gave consistently strong results.

Understanding tasks (BART-Large; GLUE and SQuAD validation data)

ModelSQuAD 1.1 (EM/F1)SQuAD 2.0 (EM/F1)MNLI (matched)SST-2RTECoLA
BERT84.1 / 90.979.0 / 81.886.693.270.460.6
XLNet89.0 / 94.586.1 / 88.889.895.683.863.6
RoBERTa88.9 / 94.686.5 / 89.490.296.486.668.0
BART88.8 / 94.686.1 / 89.289.996.687.062.8

Its performance is nearly the same as RoBERTa trained with the same resources, showing that the improvements for generation do not hurt classification performance.

Summarization (ROUGE-1 / ROUGE-2 / ROUGE-L)

ModelCNN/DailyMailXSum
First three sentences (Lead-3)40.42 / 17.62 / 36.6716.30 / 1.60 / 11.95
BERTSUMEXTABS42.13 / 19.60 / 39.1838.81 / 16.50 / 31.27
BART44.16 / 21.28 / 40.9045.14 / 22.27 / 37.25

It outperformed prior work on every metric, both on CNN/DailyMail, where summaries tend to stay close to the source sentences, and on XSum, where they involve much rephrasing. On XSum the margin is about 6 points. It also achieved the best results on the ConvAI2 dialogue task (validation F1 from 19.09 to 20.72) and on ELI5 abstractive question answering (ROUGE-L up 1.2 points), and on Romanian-to-English translation (WMT16, with back-translation data added), BLEU rose from the baseline's 36.80 to 37.96.

Practical considerations

Keep the following in mind when using BART.

  • Generation settings affect results: The paper tunes the beam size (5), trigram-repetition blocking, minimum and maximum lengths, and length penalty on validation data. For summarization and similar tasks, set the generation parameters as carefully as the training ones.
  • For classification, feed the same input to both sides: When using BART for classification, feed the input to both the encoder and the decoder and use the decoder output at the final token. This is not the same as BERT, which uses only the encoder output.
  • Its use for translation is limited: The translation approach in the paper uses BART only on the English (output) side. It was reported to be less effective and prone to overfitting without back-translation data. Translation into languages other than English requires a multilingually pretrained model.
  • Use the tokenizer that matches the model: Match the byte-level BPE vocabulary shared with GPT-2.

BART's summaries are fluent but can include content that is not in the input. Even in the paper's summarization examples, the output contained the claim that "the study was published in Science," which was not in the original article. Do not use summaries as is without fact-checking.

Which noise works depends heavily on the task. In the paper's comparison, document rotation or sentence permutation alone hurt performance, and including noise that masks or deletes words was important. When doing BART-style pretraining on your own data, building around text infilling is a safe choice.

Comparison with other models

Comparing pretrained language models from the same viewpoints gives the following.

ModelArchitecturePretraining taskInput and outputStrengths
BERTEncoder onlyPredict masked words independentlySame length (prediction per position)Classification, extractive question answering
GPTDecoder onlyPredict the next wordContinue from the left contextText generation
BARTEncoder + decoderRewrite the original document from a corrupted oneLengths may differSummarization, dialogue, abstractive question answering; classification on par with RoBERTa
mT5Encoder + decoderReplace spans with sentinel tokens and output only the masked partsLengths may differMultilingual generation and understanding

Rough guidelines for choosing:

  • Generation that rewrites the input, such as English summarization, paraphrasing, or dialogue responses: BART is a good fit. Its pretraining format is close to these tasks, and this is where the paper found the largest gains.
  • Classification only: BART reaches RoBERTa-level performance, but encoder-only BERT-family models are smaller and faster.
  • Writing long text that is only loosely constrained by the input: As the ELI5 results in the paper show, a decoder-only language model such as GPT-2 may be a better fit.
  • Languages other than English: BART is pretrained on English data. For multilingual use, consider mT5 or similar models.

PyTorch example

Show code
python
import random
import torch
from transformers import BartTokenizer, BartForConditionalGeneration

"""
1. A small implementation that applies the paper's noise (text infilling + sentence permutation) to a token sequence
2. An example of using BART-Large fine-tuned for summarization with Hugging Face transformers
"""


def text_infilling(tokens, mask_token, ratio=0.3, lam=3.0):
    """Replace spans whose lengths are drawn from a Poisson distribution (λ = 3) with a single mask_token.
    Repeat until the masked tokens reach the fraction ratio of the whole (30% for BART-Large) (simplified implementation)."""
    out = list(tokens)
    budget = round(len(tokens) * ratio)
    for _ in range(10 * len(tokens)):                     # cap the number of attempts
        if budget <= 0 or len(out) == 0:
            break
        length = min(int(torch.poisson(torch.tensor(lam)).item()), budget)
        start = random.randrange(len(out))
        if out[start] == mask_token:
            continue                                      # skip spots already replaced
        out[start:start + length] = [mask_token]          # length 0 means inserting a mask
        budget -= max(length, 1)
    return out


def sentence_permutation(tokens, end="."):
    """Split into sentences at full stops and shuffle the sentence order randomly"""
    sents, cur = [], []
    for t in tokens:
        cur.append(t)
        if t == end:
            sents.append(cur)
            cur = []
    if cur:
        sents.append(cur)
    random.shuffle(sents)
    return [t for s in sents for t in s]


doc = "A B C . D E .".split()
noisy = text_infilling(sentence_permutation(doc), "<mask>")
print(noisy)            # e.g. ['D', '<mask>', '.', 'A', '<mask>', '.']. The decoder learns to rewrite the original doc

# --- 2. Generating a summary ---
name = "facebook/bart-large-cnn"                   # BART-Large fine-tuned for summarization on CNN/DailyMail
tokenizer = BartTokenizer.from_pretrained(name)    # same byte-level BPE as GPT-2
model = BartForConditionalGeneration.from_pretrained(name)
model.eval()                                        # disable dropout

article = ("The researchers tested the new battery for two years. It kept 90 percent of its capacity "
           "after 5,000 charging cycles, about twice as many as current batteries.")
inputs = tokenizer(article, return_tensors="pt", truncation=True, max_length=1024)
with torch.no_grad():
    summary_ids = model.generate(
        **inputs,
        num_beams=5,               # beam size 5, as in the paper
        no_repeat_ngram_size=3,    # do not repeat the same trigram
        min_length=10, max_length=60, length_penalty=2.0)  # tune the length settings on validation data
print(tokenizer.decode(summary_ids[0], skip_special_tokens=True))

# For training, passing the reference summary as labels automatically builds the decoder input (shifted one to the right)
model.train()
labels = tokenizer("A new battery kept 90 percent of its capacity after 5,000 cycles.",
                   return_tensors="pt").input_ids
loss = model(**inputs, labels=labels).loss         # cross-entropy (the paper trains generation with label smoothing 0.1)
loss.backward()

FAQ

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

BERT is an encoder-only model that predicts each masked word independently at its position. BART has both an encoder and a decoder: it reads the corrupted document with the encoder and rewrites the original document from left to right with the decoder. As a result, BART can be used directly for text generation such as summarization, and it also performs nearly as well as RoBERTa of the same scale on classification.

Q. How does text infilling differ from BERT's masking?
A.

BERT replaces one token with one [MASK]. BART's text infilling collapses a span, whose length is drawn from a Poisson distribution (λ=3\lambda = 3), into a single [MASK] regardless of its length. A span of length 0 simply inserts a [MASK]. The model must infer not only the missing words but also how many words are missing.

Q. Can BART be used for translation?
A.

In the paper, BART's embedding layer was replaced with a new small encoder and used for translation from a foreign language into English. Using the whole of BART as a pretrained English-side decoder improved BLEU by 1.1 on WMT16 Romanian-to-English. However, BART is pretrained only on English, so translation into other languages requires a multilingual model.

References

  1. Lewis, M., Liu, Y., Goyal, N., Ghazvininejad, M., Mohamed, A., Levy, O., Stoyanov, V., & Zettlemoyer, L. (2020). BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension. ACL 2020. arXiv:1910.13461.
  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. arXiv:1706.03762.
  3. 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.
  4. Hugging Face. Transformers documentation: BART.