Sub topic 9
Translating Text and Selecting Language Pairs
The translation workflow
This chapter assumes basic Python, neural-network training, Transformer self-attention, and PyTorch or Hugging Face Transformers. You will use an encoder-decoder model to translate a source sequence into a target sequence.
A translation model has a defined language pair. A model named en-de expects English input and produces German output. The tokenizer must match the model because it converts text into the token IDs used during training.
The main steps are:
- Choose a model trained for the required source and target languages.
- Tokenize one or more source sentences.
- Pass the tokens to the encoder-decoder model.
- Generate target tokens with a decoding strategy.
- Decode the target tokens back into text.
Selecting a language pair
A language-pair model is usually the simplest choice when you know both languages. MarianMT models from Helsinki-NLP commonly use names such as Helsinki-NLP/opus-mt-en-de, where en means English and de means German.
| Model type | Best use | Language selection |
|---|---|---|
| MarianMT | One specific language pair | Encoded in the model name |
| mBART | Several languages and multilingual fine-tuning | Language codes in the tokenizer and generation settings |
| NLLB | Many language pairs, including lower-resource languages | Explicit source and target language codes |
The pair direction matters. An English-to-German model is not automatically a German-to-English model. Look for a separate reverse-direction model unless the model documentation says that it supports both directions.
Language codes also require care. Different model families may use different codes, such as en_XX, de_DE, or eng_Latn. Read the model card before setting them. A model can produce poor output when the code is valid but does not represent the intended language variant.
A multilingual model can reduce the need to manage many separate checkpoints, but it may use more memory and may perform differently across language pairs. A dedicated model often gives more predictable results for a frequently used pair.
Running batched translation
The following example translates two English sentences into German. Padding makes the sentences in a batch the same length. The attention mask tells the model which positions are real tokens rather than padding.
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,
truncation=True,
)
outputs = model.generate(
**batch,
num_beams=4,
max_new_tokens=64,
)
translations = tokenizer.batch_decode(
outputs,
skip_special_tokens=True,
)
for source, target in zip(sentences, translations):
print(f"{source} -> {target}")generate runs the decoder one token at a time. At each step, the decoder uses its previous output tokens and cross-attention over the encoded source. num_beams=4 keeps four likely partial translations and usually improves fluency over choosing only the most likely next token.
max_new_tokens limits the number of generated target tokens. It is safer than setting only a large total length because it directly limits output growth. truncation=True prevents an oversized input from causing an error, but it can silently remove source content. For important documents, check the model's context limit and split the input deliberately.
Language handling and common errors
Translation is more than replacing words. The model must reorder phrases, select grammatical forms, and preserve names, numbers, units, and formatting. Rare names and technical terms are common weak points because the model may have seen few similar examples.
Check these details before deploying a translation pipeline:
- Confirm the source and target language direction.
- Use the tokenizer belonging to the selected model.
- Preserve the attention mask when batching padded inputs.
- Avoid truncation unless losing the end of the source is acceptable.
- Test dates, numbers, names, negation, and domain-specific terms.
- Compare outputs with a qualified human for high-impact content.
For multilingual models, set the source language during tokenization when required. Set the target language through the model's documented forced beginning-of-sentence token or generation parameter. These settings differ between model families, so copy the model card's pattern rather than guessing.
Exercise
You need to translate French text into English, but the checkpoint is named opus-mt-en-fr. What should you do?
Show answer
Find a checkpoint trained for French-to-English, such as a documented fr-en model. Do not assume that the en-fr checkpoint can translate in the reverse direction.