Sub topic 3
Translating Text and Working with Long Documents
Prerequisites: This chapter assumes you can write Python, load a Hugging Face model with pipeline, and read a tokenizer's output. You should know that models have a maximum input length measured in tokens.
Translating text and selecting language pairs
A translation model is trained for one direction, such as English to German. Pick the model whose name matches your source and target languages. The MarianMT model Helsinki-NLP/opus-mt-en-de translates English to German, and Helsinki-NLP/opus-mt-de-en translates the reverse. For many languages in one model, use mBART with its language codes.
from transformers import pipeline
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-de")
result = translator("The weather is nice today.", num_beams=4, max_new_tokens=64)
print(result[0]["translation_text"])Summarising documents longer than the context window
Encoder-decoder models read a fixed number of tokens. Text beyond that limit is cut off and never seen. To avoid this, split the document into chunks, summarise each chunk, and join the results.
from transformers import pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
def chunk_sentences(text, max_words=400):
sentences = [s.strip() + "." for s in text.split(".") if s.strip()]
chunks, current, count = [], [], 0
for s in sentences:
n = len(s.split())
if current and count + n > max_words:
chunks.append(" ".join(current))
current, count = [], 0
current.append(s)
count += n
if current:
chunks.append(" ".join(current))
return chunks
def summarise_long(text):
parts = [
summarizer(c, max_length=60, min_length=15, do_sample=False)[0]["summary_text"]
for c in chunk_sentences(text)
]
return " ".join(parts)Fine-tuning a model on your own data
Fine-tuning continues training a pretrained model on your own source and target pairs. Use Seq2SeqTrainer with a dataset of matched texts. Start with a few thousand pairs and a low learning rate, such as 2e-5, so the model keeps its general skills.
Measuring quality with ROUGE, BLEU and chrF
Each metric compares model output with reference text written by people.
| Metric | Typical use | What it counts |
|---|---|---|
| ROUGE | Summaries | Overlapping words and word sequences |
| BLEU | Translation | Matching word n-grams, with a brevity penalty |
| chrF | Translation | Matching character n-grams, which helps with rich morphology |
These scores reward word overlap. A correct paraphrase can score low, and a fluent wrong answer can score high.
Hallucination, repetition and other failure modes
- Hallucination: The model states facts that are not in the source. Check summaries against the original text.
- Repetition: The model repeats phrases. Set
no_repeat_ngram_size=3or arepetition_penaltyabove 1.0. - Mistranslated rare terms: Names, product codes and technical words often break. Protect them or add a glossary.
- Truncation: Long inputs lose their end unless you chunk them.
Exercise
A German-to-English translation model returns output with the names of the source languages mixed in. Which model should you check first, and why?
Show answer
Check that the model name matches the language pair, such as Helsinki-NLP/opus-mt-de-en for German to English. A model trained for another direction produces wrong or confused output.