mT5 › Working with mT5
Language AI HandbookAll chapters mT5 › Working with mT5One section · Sections in this chapter7 / 11 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let's implement a practical example using mT5 for multilingual text generation. We'll use the Hugging Face Transformers library to demonstrate fine-tuning on a simple translation-like task.
Working with mT5 in practice follows the same pattern as T5: format your task as a text-to-text problem, tokenize the input and target sequences, and train the model with a cross-entropy loss over the output tokens. The main difference is that your data can now span multiple languages, and you need to be thoughtful about how your task prefix interacts with the model's multilingual representations. For classification or extraction tasks, using the task prefix in the source language of the input text typically works well. For translation tasks, the convention is to specify the source and target languages explicitly in the prefix, similar to how Google's multilingual MT systems format their prompts.
One practical consideration when loading mT5 is that the model is larger than its T5 counterpart of the same nominal size, primarily because of the expanded vocabulary. mT5-Small has 300M parameters compared to T5-Small's approximately 60M, largely due to the 250K token vocabulary. For production deployments where memory is constrained, this vocabulary overhead is worth factoring into your infrastructure planning.
import torch
from transformers import AutoModelForSeq2SeqLM, T5Tokenizer
# Load mT5-small for demonstration
model_name = "google/mt5-small"
tokenizer = T5Tokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
# Move to GPU if available
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)
model_params = sum(p.numel() for p in model.parameters())Model: google/mt5-small Device: cpu Parameters: 300,176,768 Vocabulary size: 250,100 Embedding parameters: 128,051,200
The mT5-Small model loads successfully with its full 250K vocabulary. The embedding layer alone accounts for a significant portion of the total parameters. This reflects the vocabulary expansion needed for multilingual support. Despite being the smallest variant, it still provides strong multilingual capabilities for experimentation and deployment in resource-constrained settings.
Multilingual Span Corruption Example
mT5 uses the same span corruption objective as T5. Let's examine how it works on different languages:
def demonstrate_span_corruption(text, language, tokenizer):
"""
Simulate span corruption for demonstration.
In practice, this happens during pre-training data preparation.
"""
tokens = tokenizer.tokenize(text)
# Select spans to corrupt (simplified: corrupt every 4th-7th token)
corrupted = []
targets = []
sentinel_id = 0
i = 0
while i < len(tokens):
if i > 0 and i % 5 == 0 and i + 2 < len(tokens):
# Corrupt a span of 2-3 tokens
span_len = min(3, len(tokens) - i)
corrupted.append(f"<extra_id_{sentinel_id}>")
targets.extend(
[f"<extra_id_{sentinel_id}>"] + tokens[i : i + span_len]
)
sentinel_id += 1
i += span_len
else:
corrupted.append(tokens[i])
i += 1
if sentinel_id > 0:
targets.append(f"<extra_id_{sentinel_id}>")
return " ".join(corrupted), " ".join(targets)
# Test on multiple languages
test_texts = {
"English": "Natural language processing enables computers to understand human language.",
"Spanish": "El procesamiento del lenguaje natural permite que las computadoras entiendan el idioma humano.",
"German": "Die Verarbeitung natürlicher Sprache ermöglicht es Computern, menschliche Sprache zu verstehen.",
"Japanese": "自然言語処理により、コンピュータは人間の言語を理解できるようになります。",
}Span Corruption Examples: === English === Original: Natural language processing enables computers to understand human language. Corrupted: ▁Natural ▁language ▁processing ▁en ables <extra_id_0> ▁human ▁language . Target: <extra_id_0> ▁computers ▁to ▁understand <extra_id_1> === Spanish === Original: El procesamiento del lenguaje natural permite que las computadoras entiendan el idioma humano. Corrupted: ▁El ▁proces amiento ▁del ▁ <extra_id_0> ▁permit e <extra_id_1> computador as <extra_id_2> ▁el ▁ <extra_id_3> Target: <extra_id_0> lengua je ▁natural <extra_id_1> ▁que ▁las ▁ <extra_id_2> ▁en tienda n <extra_id_3> idioma ▁humano . <extra_id_4> === German === Original: Die Verarbeitung natürlicher Sprache ermöglicht es Computern, menschliche Sprache zu verstehen. Corrupted: ▁Die ▁ Verarbeitung ▁ n <extra_id_0> Sprache ▁er <extra_id_1> ▁Computer n <extra_id_2> ▁ Sprache <extra_id_3> . Target: <extra_id_0> atürlich er ▁ <extra_id_1> möglich t ▁es <extra_id_2> , ▁mens chliche <extra_id_3> ▁zu ▁ver stehen <extra_id_4> === Japanese === Original: 自然言語処理により、コンピュータは人間の言語を理解できるようになります。 Corrupted: ▁ 自然 言語 処理 により <extra_id_0> 人間の 言語 <extra_id_1> ようになります 。 Target: <extra_id_0> 、 コンピュータ は <extra_id_1> を 理解 できる <extra_id_2>
The span corruption examples demonstrate how mT5's pre-training objective works uniformly across languages. Regardless of script or language family, the model learns to predict masked spans given surrounding context. This consistent training signal across all 101 languages encourages the model to develop language-agnostic representations that capture universal patterns in how information is structured in text.
Fine-Tuning for Multilingual Tasks
Fine-tuning mT5 follows the same text-to-text format as T5. Here's an example setup for multilingual question answering:
from torch.utils.data import Dataset
class MultilingualQADataset(Dataset):
"""
Dataset for multilingual question answering.
Formats data as text-to-text for mT5.
"""
def __init__(
self, examples, tokenizer, max_input_length=512, max_target_length=128
):
self.examples = examples
self.tokenizer = tokenizer
self.max_input_length = max_input_length
self.max_target_length = max_target_length
def __len__(self):
return len(self.examples)
def __getitem__(self, idx):
example = self.examples[idx]
# Format input as: "question: {question} context: {context}"
input_text = (
f"question: {example['question']} context: {example['context']}"
)
target_text = example["answer"]
# Tokenize
inputs = self.tokenizer(
input_text,
max_length=self.max_input_length,
truncation=True,
padding="max_length",
return_tensors="pt",
)
targets = self.tokenizer(
target_text,
max_length=self.max_target_length,
truncation=True,
padding="max_length",
return_tensors="pt",
)
return {
"input_ids": inputs["input_ids"].squeeze(),
"attention_mask": inputs["attention_mask"].squeeze(),
"labels": targets["input_ids"].squeeze(),
}
# Example multilingual QA data
multilingual_qa_examples = [
{
"question": "What is machine learning?",
"context": "Machine learning is a subset of artificial intelligence that enables systems to learn from data.",
"answer": "a subset of artificial intelligence",
},
{
"question": "¿Qué es el aprendizaje automático?",
"context": "El aprendizaje automático es un subconjunto de la inteligencia artificial que permite a los sistemas aprender de los datos.",
"answer": "un subconjunto de la inteligencia artificial",
},
{
"question": "Was ist maschinelles Lernen?",
"context": "Maschinelles Lernen ist ein Teilgebiet der künstlichen Intelligenz, das Systemen ermöglicht, aus Daten zu lernen.",
"answer": "ein Teilgebiet der künstlichen Intelligenz",
},
]Multilingual QA Dataset Examples: Example 1: Question: What is machine learning? Input tokens: 512 Target: a subset of artificial intelligence Example 2: Question: ¿Qué es el aprendizaje automático? Input tokens: 512 Target: un subconjunto de la inteligencia artificial Example 3: Question: Was ist maschinelles Lernen? Input tokens: 512 Target: ein Teilgebiet der künstlichen Intelligenz
The examples demonstrate mT5's text-to-text format for question answering: questions and contexts are combined into a single input string, and the model learns to generate the answer span. Using the same format for English and Spanish, and likewise for German, allows the model to learn the task structure and use cross-lingual representations.
Generation Across Languages
Let's examine how mT5 generates text in different languages:
def generate_text(model, tokenizer, prompt, max_length=50):
"""Generate text from a prompt using mT5."""
inputs = tokenizer(prompt, return_tensors="pt").to(device)
outputs = model.generate(
**inputs,
max_length=max_length,
num_beams=4,
early_stopping=True,
no_repeat_ngram_size=2,
)
return tokenizer.decode(outputs[0], skip_special_tokens=True)
# Test prompts in different languages
prompts = [
"translate English to German: Hello, how are you?",
"translate English to Spanish: The weather is nice today.",
"summarize: Machine learning is a branch of artificial intelligence focused on building systems that learn from data.",
]mT5 Generation Examples: (Note: mT5-small is not fine-tuned, results are from pre-training only) Input: translate English to German: Hello, how are you?
model.safetensors: reconstructing file: 0%| | 0.00B / 1.20GB
model.safetensors: downloading bytes: | 0.00B
Output: <extra_id_0> Input: translate English to Spanish: The weather is nice today. Output: <extra_id_0> Input: summarize: Machine learning is a branch of artificial intelligence focused on building systems that learn from data. Output: <extra_id_0>.
Note that the base mT5 model requires fine-tuning on specific tasks to produce high-quality outputs. The pre-trained model has learned multilingual representations through span corruption but hasn't been trained to follow specific task instructions. This is the same pattern we observed with T5: pre-training builds powerful general representations, and fine-tuning teaches the model to apply those representations to a specific task format. For production multilingual applications, you would fine-tune mT5 on task-specific multilingual data, potentially combining English-only labeled data with any available target-language examples to maximize transfer.