Sub topic 9
Translating text and selecting language pairs
This chapter assumes you can run a Hugging Face generate call, know what an encoder-decoder Transformer does, and have seen beam search. It covers how to pick a translation model, how the model learns which language to produce, and the mistakes that cause bad output without raising an error.
Translation as conditional generation
A translation model reads a source sentence with its encoder and writes the target sentence one token at a time with its decoder. The decoder attends to the encoder output through cross-attention. Nothing in this architecture is specific to translation. The model becomes a translator because of its training data: pairs of sentences in two languages.
The practical question is how the model knows which target language to write. There are three common answers, and each gives a different API.
| Family | How the target language is chosen | Example checkpoint | Typical use |
|---|---|---|---|
| MarianMT (single pair) | Fixed by the checkpoint | `Helsinki-NLP/opus-mt-en-de` | One direction, small and fast |
| MarianMT (multi-target) | A `>>xx<<` token at the start of the input | `Helsinki-NLP/opus-mt-en-ROMANCE` | One source, several related targets |
| mBART-50 | Source language set on the tokenizer, target forced as first decoder token | `facebook/mbart-large-50-many-to-many-mmt` | Many directions in one model |
| T5 | Text prefix such as `translate English to German:` | `t5-small` | Few supported pairs, multi-task use |
Single-pair models: MarianMT
MarianMT checkpoints from the Helsinki-NLP group are named opus-mt-{source}-{target}. Each one is a small encoder-decoder, about 75 million parameters, trained on one direction. The model name carries the whole language specification, so the code has no language argument.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "Helsinki-NLP/opus-mt-en-de"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
sentences = ["The weather is nice today.", "Where is the nearest train station?"]
batch = tokenizer(sentences, return_tensors="pt", padding=True)
outputs = model.generate(**batch, num_beams=4, max_new_tokens=64)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))Three details matter here:
padding=Truepads the shorter sentence so both fit in one tensor. The attention mask inbatchtells the encoder to ignore the padding.num_beams=4keeps four candidate translations at each step. Translation usually benefits from beam search because there is one correct meaning to find, unlike open-ended generation.max_new_tokens=64caps the output. A translation can be longer than its source, so set the cap to at least the source length in tokens, plus some margin.
The tokenizer needs the sentencepiece package. If it is missing, you get an import error when loading Marian tokenizers.
Multi-target Marian models
Some checkpoints cover a group of languages, for example opus-mt-en-ROMANCE. The decoder needs to know which language to write, so you put a target token at the start of each source sentence.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "Helsinki-NLP/opus-mt-en-ROMANCE"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
sources = [
">>fr<< The train leaves at nine.",
">>es<< The train leaves at nine.",
">>it<< The train leaves at nine.",
]
batch = tokenizer(sources, return_tensors="pt", padding=True)
outputs = model.generate(**batch, num_beams=4, max_new_tokens=64)
for text in tokenizer.batch_decode(outputs, skip_special_tokens=True):
print(text)The valid tokens are listed on the model card. If you leave the token out, the model still produces something, usually in an arbitrary language from the group. This is a silent failure, so check the model card before you use a multi-target checkpoint.
Multilingual models: mBART-50
facebook/mbart-large-50-many-to-many-mmt translates between 50 languages with one set of weights. It is about 610 million parameters, so it is much heavier than a Marian model. It needs two language settings:
- Set
tokenizer.src_langso the tokenizer adds the source language token to the input. - Pass
forced_bos_token_idtogenerateso the first decoder token is the target language token.
from transformers import MBartForConditionalGeneration, MBart50TokenizerFast
name = "facebook/mbart-large-50-many-to-many-mmt"
tokenizer = MBart50TokenizerFast.from_pretrained(name)
model = MBartForConditionalGeneration.from_pretrained(name)
tokenizer.src_lang = "en_XX"
texts = ["The meeting has been moved to Thursday.", "Please send me the report."]
encoded = tokenizer(texts, return_tensors="pt", padding=True)
target_id = tokenizer.convert_tokens_to_ids("fr_XX")
generated = model.generate(
**encoded,
forced_bos_token_id=target_id,
num_beams=4,
max_new_tokens=64,
)
print(tokenizer.batch_decode(generated, skip_special_tokens=True))mBART-50 codes follow the pattern en_XX, de_DE, fr_XX, zh_CN. They are not the two-letter ISO codes. A wrong code does not always fail loudly: the tokenizer can map an unknown token to the unknown-token id, and the output quality drops without an exception.
Changing the target needs only a new forced_bos_token_id. To translate the same text into several languages, encode once and call generate once per target.
T5 for translation
The t5-small checkpoint was trained on a text-to-text mixture that includes English to German, French and Romanian. The task prefix is part of the input string.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
prompts = ["translate English to German: The house is wonderful."]
inputs = tokenizer(prompts, return_tensors="pt", padding=True)
outputs = model.generate(**inputs, num_beams=4, max_new_tokens=40)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))T5 only translates the pairs it saw in training. Asking for English to Spanish with the same prefix pattern gives unreliable text, because the model has no Spanish decoder behaviour to call on. Use T5 when you want one model for several tasks. Use Marian or mBART when translation quality is the goal.
Selecting a language pair
The diagram shows the order in which to check your options.
A few rules of thumb:
- Prefer a dedicated pair when one exists. A small single-pair model is faster, cheaper to host and often as good as a large multilingual one on its pair.
- Use a multilingual model when you need many directions. One mBART deployment replaces dozens of Marian checkpoints. The cost is memory and slower generation.
- Check the direction.
opus-mt-en-deandopus-mt-de-enare separate models. Loading the wrong one yields output that looks like gibberish or a copy of the input. - Expect lower quality for low-resource languages. Quality follows how much parallel data the model saw. A pair with a few thousand sentences gives much weaker output than English to German.
Pivoting through English
When no model covers the pair, you can chain two: source to English, then English to target. Errors compound. A mistranslated word in the first step cannot be recovered in the second, and information that English does not mark, such as formal versus informal "you" in German or French, is lost at the pivot.
from transformers import pipeline
to_english = pipeline("translation", model="Helsinki-NLP/opus-mt-fr-en")
from_english = pipeline("translation", model="Helsinki-NLP/opus-mt-en-de")
french = ["Le train part à neuf heures."]
english = [r["translation_text"] for r in to_english(french)]
german = [r["translation_text"] for r in from_english(english)]
print(english, german)Language identification and input handling
Models do not check the source language. If you feed German text to an English-source model, you get a poor translation and no error. When input comes from users, run a language detector first (for example the langdetect or fasttext lid models) and route each text to the right model.
Sentence-level translation
Translation models were trained mostly on single sentences or short segments. Long paragraphs cause two problems: input beyond the model's maximum length (512 tokens for many Marian models) is truncated silently, and the decoder may skip or merge sentences. Split text into sentences, translate in batches and join the results.
import re
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "Helsinki-NLP/opus-mt-en-de"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
def split_sentences(text):
return [s for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s]
def translate(text, batch_size=8):
sentences = split_sentences(text)
translated = []
for i in range(0, len(sentences), batch_size):
chunk = sentences[i : i + batch_size]
batch = tokenizer(chunk, return_tensors="pt", padding=True,
truncation=True, max_length=256)
out = model.generate(**batch, num_beams=4, max_new_tokens=256)
translated.extend(tokenizer.batch_decode(out, skip_special_tokens=True))
return " ".join(translated)
print(translate("The weather is nice today. We will walk to the station. Bring an umbrella anyway."))The regular expression splitter is naive. It breaks on abbreviations such as "Dr. Smith". For real text use a proper sentence segmenter such as nltk.sent_tokenize or pysbd.
Common errors
- Wrong or missing target signal. Missing
>>fr<<on a multi-target Marian model, or missingforced_bos_token_idon mBART, gives output in the wrong language, often a copy of the source. - Untranslated rare terms. Names, product codes and technical terms are split into many subword pieces and are often copied, garbled or "translated" literally. If specific terms must stay fixed, protect them with placeholders before translation and restore them after.
- Silent truncation. Without
truncation=Trueand a sensiblemax_length, behaviour on long input depends on the tokenizer. Check token counts on a few real inputs. - Output cut short. A low
max_new_tokensends the sentence in the middle. Check whether the last token of an output is the end-of-sequence token. - Skipped content. Under beam search, models sometimes drop a clause, because shorter hypotheses score well. Sentence-level splitting reduces this.
Measuring translation quality
Score translations against human references with SacreBLEU and chrF. SacreBLEU takes a list of reference lists, one inner list per prediction, so you can supply several references for each sentence.
import evaluate
sacrebleu = evaluate.load("sacrebleu")
chrf = evaluate.load("chrf")
predictions = ["Das Haus ist wunderbar."]
references = [["Das Haus ist wunderbar.", "Das Haus ist großartig."]]
print(sacrebleu.compute(predictions=predictions, references=references)["score"])
print(chrf.compute(predictions=predictions, references=references)["score"])chrF compares character n-grams, so it is more forgiving of inflection and compounding, which makes it a better fit for morphologically rich languages such as German, Finnish or Turkish. Always report the SacreBLEU signature string with your score, since BLEU values from different tokenisation settings are not comparable.
Exercises
Exercise
You load facebook/mbart-large-50-many-to-many-mmt, set tokenizer.src_lang = "en_XX", and call model.generate(**encoded, num_beams=4) without any other language argument. The output is mostly the English input repeated. What is missing, and how do you fix it?
Show answer
The decoder was never told which language to produce. Pass forced_bos_token_id=tokenizer.convert_tokens_to_ids("de_DE") (or the code for the wanted target) to generate so the first decoder token is the target language token.
Exercise
You need Czech to Portuguese translation, and no opus-mt-cs-pt checkpoint exists. Name two options and one risk of each.
Show answer
Option 1: use mBART-50 with src_lang="cs_CZ" and a forced target of pt_XX. The risk is higher memory use and slower generation than a small model. Option 2: pivot through English with a cs-en model followed by an en-pt model. The risk is that errors compound and information English does not mark, such as formality, is lost at the pivot.