AI Logic

Architectures

mT5

Updated:

mT5 architecture. Left: the overall pretraining flow (an encoder reading input with spans replaced by sentinels, a decoder outputting only the masked spans, and the connection from the encoder output to the decoder layers), plus how mC4 languages are sampled and the vocabulary. Right: inside the encoder and decoder layers (pre-normalized self-attention, attention to the encoder output, and feed-forward), and the inside of GeGLU

Background and overview

mT5 is a multilingual model that follows the recipe of the English language model T5 almost exactly, but is pretrained on web text in 101 languages. It was proposed by Xue et al. at Google in 2020 and presented at NAACL 2021. It handles every task, including translation, summarization, classification, and question answering, in a "string in, string out" (text-to-text) format.

T5 (Text-to-Text Transfer Transformer) has the encoder and decoder of the Transformer, and even for classification it generates the label as a string such as "positive". Its advantage is that every task can be learned with the same training objective (maximum likelihood of the target string), but it was pretrained only on English text. About 80% of the world's population does not speak English, so a model usable across languages was needed.

With the goal of staying as close as possible to the T5 recipe, mT5 changes the following.

  • Data: It builds mC4, which extends T5's English dataset C4 to 101 languages
  • Language sampling: It adjusts how often each language is sampled so that low-resource languages are also learned well
  • Vocabulary: It enlarges the SentencePiece vocabulary to 250,000 tokens

In the paper, mT5 achieved state-of-the-art results at the time on the classification and question answering tasks of the multilingual benchmark XTREME. The largest model, mT5-XXL (13 billion parameters), reached 85.0% accuracy on the entailment task XNLI in the setting where it is fine-tuned only on English and evaluated on other languages. The paper also showed the problem of "accidental translation", where a model fine-tuned only on English translates part of its answer into English, along with a simple way to prevent it.

Architecture

mT5 has the same architecture as T5: stacked Transformer encoder and decoder layers. In the figure at the top of this article, the left side shows the overall pretraining flow, and the right side shows the inside of the encoder and decoder layers.

It differs from the original Transformer in the following ways inherited from T5.

  1. Normalization before each sublayer: The input of each sublayer (attention and feed-forward) is normalized before computation, and the residual is added afterward (Pre-LN). The normalization is a simplified layer normalization that only rescales values and adds no bias.
  2. Position is represented with relative position biases: No position is added to the input embeddings; instead, a scalar that depends on the distance between two positions is added to the attention logits (T5 relative position bias). Distances are grouped into 32 buckets, and all distances beyond 128 share the same bucket. These values are shared across all layers, with a separate value learned for each head.

In addition, mT5 follows the "T5.1.1" recipe, an improved version of T5.

  • The feed-forward block is changed from a two-layer ReLU MLP to GeGLU (one of the outputs of two fully connected layers is passed through GELU and multiplied element-wise with the other)
  • In larger models, the vector size dmodeld_{model} is also increased, not just the feed-forward hidden size dffd_{ff}
  • No dropout is used during pretraining
  • The input embedding and the output linear layer do not share weights

As with T5, the paper provides five model sizes.

ModelParameters
mT5-SmallAbout 300M
mT5-Base580M
mT5-Large1.2B
mT5-XL3.7B
mT5-XXL13B

They have more parameters than T5 models of the same size because of the larger vocabulary.

Because it has both an encoder and a decoder, mT5 at the same "Large" size has about twice as many parameters (1.2B, as in the table above) as the encoder-only XLM-R (550M). Classification compute, however, is nearly the same. XLM-R processes T+1T+1 tokens (an input of length TT plus CLS), while mT5's decoder only outputs 2 tokens (the label and an end-of-sequence token), so it needs compute for just T+2T+2 tokens.

Training: mC4 and span corruption

mC4 extends T5's C4 to many languages.

  1. All 71 monthly web crawls released by Common Crawl are used (to gather low-resource languages).
  2. Language identification uses cld3, and pages with a confidence below 70% are removed.
  3. C4's rule of "removing lines that do not end in an English terminal punctuation mark" does not suit many languages, so a different rule is used instead: "keep only pages with at least 3 lines of 200 or more characters".
  4. As in C4, lines duplicated across documents are removed and pages containing inappropriate words are excluded.
  5. Only languages with at least 10,000 pages are kept.

The resulting mC4 contains 6.6 billion pages and 6.3 trillion tokens in total.

Language sampling: With ∣L∣|L| the number of examples in language LL, the probability of sampling text in language LL during pretraining is set as follows.

p(L)∝∣L∣αp(L) \propto |L|^{\alpha}

With α=1\alpha = 1, sampling is proportional to data size; the smaller α\alpha is, the more often low-resource languages are chosen. There is a trade-off: sampling low-resource languages too often leads to overfitting, while sampling high-resource languages too rarely leads to undertraining. The paper tried 0.7 (mBERT), 0.3 (XLM-R), and 0.2 (multilingual translation research) and chose α=0.3\alpha = 0.3.

The vocabulary is a 250,000-token SentencePiece model trained with the same language proportions as pretraining. To suit languages with many characters such as Chinese, character coverage is set to 0.99999, and byte fallback (decomposing characters not in the vocabulary into bytes) allows any string to be represented.

The pretraining objective is "span corruption", the same as in T5.

  1. 15% of the input tokens are selected as spans with an average length of 3.
  2. Each selected span is replaced with a single sentinel token unique to that span (<X>, <Y>, and so on), and the result is fed to the encoder.
  3. The decoder outputs only the masked spans in order, delimited by the sentinels used to replace them, and appends a final sentinel (<Z>).

For example, if "for inviting" and "last" are selected in "Thank you for inviting me to your party last week", the input and output are as follows.

String
Encoder inputThank you <X> me to your party <Y> week
Decoder output<X> for inviting <Y> last <Z>

Because the output contains only the masked parts, decoder computation is lighter than in BART, which rewrites the whole document.

The paper's pretraining settings are as follows.

ItemValue
Batch and steps1024 sequences of length 1024 × 1 million steps (about 1 trillion tokens; the same as T5 and about 1/6 of XLM-R)
Learning rate1/max⁡(n,k)1 / \sqrt{\max(n, k)} (nn is the step number, and k=104k = 10^4 is the number of warmup steps)
DropoutNone

For fine-tuning, every task uses a constant learning rate of 0.001 and dropout of 0.1, and the checkpoint (saved every 200 steps) that performs best on validation data is selected.

Why a single model can handle more than 100 languages

mT5 does not prepare a separate model for each language; it learns 101 languages with one vocabulary and one set of weights. Because languages can share part of their vocabulary and sentence structure, what is learned in one language carries over to others. This sharing is thought to be why a model fine-tuned only on English can also answer questions in other languages (cross-lingual zero-shot transfer).

This resembles how a person who has learned several languages can reuse concepts such as "subject" and "tense" in a new language. By learning text in many languages with the same weights, mT5 is thought to hold structures common to languages in its internal representations.

However, a multilingual model shares its capacity among many languages, so it can perform worse than a model devoted to a single language. When the paper compared it with T5 on English SQuAD, mT5 fell behind at small sizes, but the gap narrowed as models grew, and the two were nearly even from Large upward (table below). The paper suggests that with enough capacity there may be a turning point beyond which interference between languages becomes negligible, even when learning 101 languages.

Because it is a generative model, the form of its answers is unconstrained. When fine-tuned only on English and used on other languages, it exhibits "accidental translation", outputting part or all of its answer translated into English (for example, turning the Russian "хлоропласт" partly into English as "chlorопласт"). The paper attributes this to the probabilities of non-English tokens dropping while the model sees only English targets.

To prevent this, the paper proposes mixing a small amount of the multilingual pretraining task into the fine-tuning data.

  • The mixing ratio is 1 part pretraining data to 100 parts fine-tuning data
  • The language sampling α\alpha is lowered to 0.1, making language proportions nearly uniform
  • Sentinels corresponding to unmasked spans are removed from the output (to keep sentinels from leaking into real predictions)

This alone reduced the rate of answers not found in the input (illegal predictions) by more than 70% (relative) for mT5-Small and mT5-Base, which had suffered most from accidental translation.

Experimental results

XTREME (zero-shot setting: fine-tuned only on English data and evaluated on other languages; accuracy for XNLI and PAWS-X, F1 for the rest)

ModelXNLIPAWS-XWikiAnn (named entities)XQuADMLQATyDi QA
mBERT65.481.962.264.561.459.7
XLM-R79.286.465.476.671.665.1
mT5-Small67.582.450.558.154.635.2
mT5-Base75.486.455.767.064.657.2
mT5-Large81.188.958.577.871.269.9
mT5-XL82.989.665.579.573.575.9
mT5-XXL85.090.069.282.576.080.8

mT5-XXL surpassed the previous state of the art on all classification and question answering tasks, and came close to the best result (70.1) on named entity recognition. Unlike other methods that use parallel data or labeled data from similar tasks, mT5 reaches these results simply by scaling up straightforward pretraining. As models grew, the gap between training on English only (zero-shot) and using data in each language also narrowed.

Comparison with T5 on English SQuAD (F1 / EM)

SizeT5mT5
Small87.2 / 79.184.7 / 76.4
Base92.1 / 85.489.6 / 83.8
Large93.8 / 86.793.0 / 87.0
XL95.0 / 88.594.5 / 88.9
XXL96.2 / 91.395.6 / 90.4

Ablations (mT5-Large, average zero-shot XNLI accuracy)

SettingAccuracy
Baseline (paper's setting)81.1
Dropout 0.1 in pretraining77.6
Sequence length 51280.5
Mean span length 1078.6
α=0.7\alpha = 0.780.7
α=0.2\alpha = 0.280.7
No line-length filter79.1
Add Wikipedia data80.3

Every change fell below the baseline. The line-length filter accounts for about 2 points, showing the importance of removing low-quality pages. With α=0.7\alpha = 0.7, high-resource Russian rose from 81.5% to 82.8%, while low-resource Swahili dropped from 75.4% to 70.6%.

Practical considerations

Keep the following points in mind when using mT5.

  • It cannot solve tasks out of the box: The released mT5 was pretrained only with span corruption on mC4 and has not learned supervised tasks such as translation or summarization. It must be fine-tuned on the target task before use.
  • Turn dropout back on for fine-tuning: Pretraining used no dropout, but the paper uses dropout of 0.1 for fine-tuning.
  • Small models tend to lose per-language performance: Since capacity is shared across 101 languages, Small and Base fell behind T5 on English SQuAD.
  • Results can vary: In zero-shot TyDi QA, results varied widely from one fine-tuning run to the next, so the paper reports the median of 5 runs.
  • Check the output format: Because it is a generative model, even in extractive question answering it can output strings not present in the input (Unicode variants, inflected forms, accidental translation). Decide in advance whether evaluation and post-processing should apply normalization (such as NFKC).

With a large vocabulary of 250,000 tokens, mT5 has more parameters than English T5 of the same nominal size. The smallest T5 model has about 60 million parameters, whereas mT5-Small has about 300 million; the increase comes from the large vocabulary. When memory is limited, include the vocabulary when estimating model size.

Comparison with other models

Comparing multilingual pretrained models from the same angles gives the following (based on Table 1 of the paper).

ModelArchitectureParametersLanguagesData
mBERTEncoder only (multilingual BERT)180M104Wikipedia
XLM-REncoder only (multilingual RoBERTa)270M–550M100Common Crawl (CCNet)
mBARTEncoder + decoder (multilingual BART)680M25Common Crawl (CC25)
mT5Encoder + decoder (multilingual T5)300M–13B101Common Crawl (mC4)

A rough guide to choosing:

  • Multilingual summarization, translation, or generative question answering: mT5 and mBART, which can generate, are well suited. mT5 supports more languages.
  • Multilingual classification or named entity recognition, small and fast: Encoder-only models such as mBERT and XLM-R are also strong options. For named entity recognition, even mT5-XXL had not reached the best score at the time of the paper.
  • Labeled data exists only in English: A large mT5 works well in other languages even when fine-tuned only on English. If generated output drifts toward English, try mixing in the multilingual pretraining task.
  • You want to handle many languages at the character or byte level: There are also methods that process byte sequences directly without a vocabulary (byte-level tokenization).

PyTorch example

Show code
python
import random
import torch
from transformers import AutoTokenizer, MT5ForConditionalGeneration
from transformers.optimization import Adafactor

"""
1. A small implementation that applies T5/mT5 pretraining "span corruption" to a sequence of words
2. An example of loading mT5 with Hugging Face transformers and fine-tuning it in text-to-text form
   (the released mT5 is only pretrained, so it cannot solve tasks out of the box)
"""


def span_corruption(words, ratio=0.15, mean_span=3, sentinels=None):
    """Build an input with each masked span replaced by one sentinel <extra_id_i>, and an output listing only the masked spans (simplified implementation)"""
    sentinels = sentinels or [f"<extra_id_{i}>" for i in range(100)]
    n = len(words)
    n_mask = max(1, round(n * ratio))
    n_spans = max(1, round(n_mask / mean_span))
    masked = set()
    while len(masked) < n_mask:                      # pick span starts at random and mask spans of average length mean_span
        start = random.randrange(n)
        for i in range(start, min(n, start + mean_span)):
            masked.add(i)
            if len(masked) >= n_mask:
                break
    inp, out, s, i = [], [], 0, 0
    while i < n:
        if i in masked:
            inp.append(sentinels[s]); out.append(sentinels[s])
            while i < n and i in masked:             # consecutive masked words are merged into one sentinel
                out.append(words[i]); i += 1
            s += 1
        else:
            inp.append(words[i]); i += 1
    out.append(sentinels[s])                          # final sentinel at the end
    return " ".join(inp), " ".join(out)


src, tgt = span_corruption("Thank you for inviting me to your party last week .".split())
print(src)   # e.g. Thank you <extra_id_0> me to your party last week .
print(tgt)   # e.g. <extra_id_0> for inviting <extra_id_1>

# --- 2. Fine-tune in text-to-text form ---
name = "google/mt5-small"
tokenizer = AutoTokenizer.from_pretrained(name)          # SentencePiece (250,000 tokens)
model = MT5ForConditionalGeneration.from_pretrained(name)
optimizer = Adafactor(model.parameters(), lr=1e-3,             # the paper fine-tunes with a constant learning rate of 0.001
                      scale_parameter=False, relative_step=False, warmup_init=False)

# classification is also learned as a task of generating the label string
inputs = tokenizer(["premise: A man is playing a guitar. hypothesis: A person is playing an instrument.",
                    "premise: A dog is running in the park. hypothesis: A cat is sleeping."],
                   padding=True, return_tensors="pt")
labels = tokenizer(["entailment", "contradiction"], padding=True, return_tensors="pt").input_ids
labels[labels == tokenizer.pad_token_id] = -100         # exclude padding positions from the loss

model.train()                                           # enable dropout (0.1) for fine-tuning
loss = model(**inputs, labels=labels).loss              # decoder inputs are created automatically from labels
loss.backward()
optimizer.step()
optimizer.zero_grad()

model.eval()
with torch.no_grad():
    out = model.generate(**inputs, max_new_tokens=5)
print(tokenizer.batch_decode(out, skip_special_tokens=True))

FAQ

Q. What is the difference between mT5 and T5?
A.

The architecture and training objective are almost the same; the differences are mainly data and vocabulary. T5 was pretrained on the English-only C4, whereas mT5 is pretrained on mC4 in 101 languages, has a vocabulary enlarged to 250,000 tokens, and adjusts language sampling with p(L)∝∣L∣0.3p(L) \propto |L|^{0.3} so that low-resource languages are also learned. It also follows the T5.1.1 recipe, an improved version of T5 (GeGLU, no dropout during pretraining, and so on).

Q. Can the released mT5 be used for translation or summarization as is?
A.

Not as is. The released mT5 was pretrained only with span corruption on mC4 (a task of predicting masked spans) and has not learned supervised tasks such as translation or summarization. It must be fine-tuned on data for the target task before use.

Q. What is "accidental translation", and how can it be prevented?
A.

It is the phenomenon where mT5 fine-tuned only on English data, when given a question in another language, outputs part or all of its answer translated into English. The paper mixes the multilingual pretraining task into the fine-tuning data at a ratio of 1 to 100 and makes language proportions nearly uniform (α=0.1\alpha = 0.1), which reduced illegal predictions of mT5-Small and Base by more than 70%.

References

  1. Xue, L., Constant, N., Roberts, A., Kale, M., Al-Rfou, R., Siddhant, A., Barua, A., & Raffel, C. (2021). mT5: A Massively Multilingual Pre-trained Text-to-Text Transformer. NAACL-HLT 2021. arXiv:2010.11934.
  2. Raffel, C., Shazeer, N., Roberts, A., Lee, K., Narang, S., Matena, M., Zhou, Y., Li, W., & Liu, P. J. (2020). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. JMLR 21(140). arXiv:1910.10683.
  3. Shazeer, N. (2020). GLU Variants Improve Transformer. arXiv:2002.05202.
  4. Google Research. text-to-text-transfer-transformer: Released model checkpoints (changes in T5.1.1). GitHub.
  5. Hugging Face. Transformers documentation: mT5.