Sub topic 13
Hallucination, repetition and other failure modes
Encoder-decoder models usually produce fluent text. Fluency hides errors, because a wrong summary reads as smoothly as a right one. This chapter covers how these models fail, why each failure happens, and which settings or checks help.
This chapter assumes you can run pretrained models with Hugging Face Transformers. It also assumes you know how generate works (greedy search, beam search, length limits) and what ROUGE and BLEU measure.
A map of failure modes
Each failure has a different cause, so each needs a different fix.
| Failure | What you see | Usual cause | First thing to try |
|---|---|---|---|
| Hallucination | Facts, names or numbers that are not in the source | The decoder falls back on patterns learned in pretraining | Constrain the task, add checks, fine-tune on clean data |
| Repetition | The same phrase or sentence repeats until the length limit | Likelihood-driven decoding loops on high-probability tokens | `no_repeat_ngram_size`, `repetition_penalty` |
| Truncated input | The summary ignores the end of the document | The tokenizer cut the input at the model's maximum length | Check token counts, chunk the input |
| Omission | Part of the source is missing from the output | Short length limits, early stopping, or weak coverage | Raise `min_length`, change `length_penalty` |
| Mistranslated rare terms | Names, product terms and numbers are wrong | Rare words are split into many subword pieces | Glossary post-checks, domain fine-tuning |
| Wrong output language | The translation is in the wrong language, or the source is copied | A multilingual model was not told the target language | Set the target language token explicitly |
Hallucination
A hallucination is output that the source does not support. Researchers separate two kinds:
- Intrinsic hallucination contradicts the source. The source says the council approved 40 km, and the summary says 14 km.
- Extrinsic hallucination adds information the source never mentions, even if it happens to be true. The summary says the lanes will cost 12 million euros, and the article gave no cost.
Why it happens
An abstractive decoder is a language model conditioned on the source. At every step it chooses the next token from a distribution that mixes two signals: the cross-attention evidence from the encoder, and the language prior learned in pretraining. When the evidence is weak or ambiguous, the prior fills the gap with something plausible.
Training data makes this worse. Many news summarisation datasets contain reference summaries with details that are not in the article, because the reference writer had extra context. A model fine-tuned on such pairs learns that adding unsupported detail is normal.
Beam search does not remove the problem. It finds sequences with high model probability, and a fluent invented sentence can have a higher probability than a clumsy accurate one.
A cheap grounding check
You cannot prove a summary is faithful with a few lines of code. You can catch the most common errors: numbers and capitalised names that appear in the output but not in the source. The same function also reports how much of the output is repeated trigrams.
import re
from collections import Counter
NUMBER = r"\d+(?:[.,]\d+)?"
def repeated_ngram_rate(text, n=3):
tokens = text.lower().split()
grams = [tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1)]
if not grams:
return 0.0
counts = Counter(grams)
repeats = sum(c - 1 for c in counts.values())
return repeats / len(grams)
def grounding_report(source, summary):
source_words = set(re.findall(r"[a-z0-9]+", source.lower()))
source_numbers = set(re.findall(NUMBER, source))
new_numbers = sorted(set(re.findall(NUMBER, summary)) - source_numbers)
capitalised = set(re.findall(r"\b[A-Z][a-z]+\b", summary))
new_names = sorted(w for w in capitalised if w.lower() not in source_words)
return {
"repeat_rate": round(repeated_ngram_rate(summary), 3),
"new_numbers": new_numbers,
"new_names": new_names,
}
source = (
"The city council voted on Tuesday to expand the bike lane network by 40 "
"kilometres over the next three years."
)
summary = "The city council approved 50 kilometres of bike lanes in Berlin."
print(grounding_report(source, summary))This prints {'repeat_rate': 0.0, 'new_numbers': ['50'], 'new_names': ['Berlin']}. Both flags are real errors: the number changed and a city appeared from nowhere.
The check has clear limits:
- It misses spelled-out numbers, such as "forty" versus "40".
- It misses paraphrased contradictions, such as "rejected" versus "approved".
- It flags correct paraphrases that use new capitalised words.
Treat it as a filter that sends suspicious outputs to review, not as a verdict. Stronger checks use a natural language inference model or a question-answering model to test whether the source entails each summary sentence.
Reducing hallucination
- Prefer extractive or hybrid output when exact wording matters, for example legal or medical text. Extractive methods copy source sentences, so they cannot invent facts.
- Fine-tune on clean pairs. Filter training examples whose reference summary contains numbers or names absent from the article.
- Keep summaries short. Each extra generated token is another chance to drift from the source.
- Keep sampling off for factual tasks (
do_sample=False). Sampling adds randomness on top of the prior.
Repetition
Greedy and beam search both maximise probability. Once a phrase has appeared, the same phrase becomes likely again, because the decoder sees it in its own previous output. The result is loops such as "The council approved the plan. The council approved the plan. The council approved the plan." The loop ends only when generation hits max_length.
Two controls address this:
no_repeat_ngram_size=nforbids any n-gram from appearing twice. It is a hard rule.repetition_penalty(for example1.2) lowers the score of tokens that already appeared. It is a soft rule.
from transformers import pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
article = (
"The city council voted on Tuesday to expand the bike lane network by 40 kilometres "
"over the next three years. Supporters said the plan would reduce traffic and emissions, "
"while some shop owners worried about losing parking spaces near their stores. "
"The first new lanes are expected to open next spring."
)
guarded = summarizer(
article,
max_length=60,
min_length=15,
num_beams=4,
do_sample=False,
no_repeat_ngram_size=3,
repetition_penalty=1.2,
)
print(guarded[0]["summary_text"])Both controls have side effects:
- A hard n-gram ban applies to every n-gram, including ones that must repeat. A summary may need to say "bike lanes" twice, and with
no_repeat_ngram_size=2it cannot. In translation, a name that must be repeated may be blocked or mangled. Use a size of 3 or more for prose, and be careful when you translate. - A strong
repetition_penaltyalso penalises words that have to repeat, such as "the". Values above about 1.5 tend to produce odd synonyms. - The checkpoint
facebook/bart-large-cnnalready ships withnum_beams=4,length_penalty=2.0andno_repeat_ngram_size=3in its generation config. Checkmodel.generation_configbefore you assume a loop comes from the defaults.
Repetition is a decoding problem. If a model loops on one input and not on others, look at that input first: very short, noisy or list-like inputs often trigger it.
Truncated input and omission
Every model has a maximum input length, and the tokenizer cuts anything beyond it silently when truncation=True. A summary that covers the first third of a long report and nothing else is the typical sign.
Check token counts before you trust a result:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
text = "word " * 5000
n_tokens = len(tokenizer(text)["input_ids"])
limit = tokenizer.model_max_length
print(n_tokens, limit, n_tokens > limit)The summariser reads at most limit tokens, 1024 for BART. Anything past that never reaches the encoder. The fix is chunking, covered in the long-inputs chapter.
Omission has other causes too:
- A small
max_lengthforces the model to stop before it covers everything. - A low
length_penaltywith beam search favours short outputs. In Transformers, the final beam score is divided bylength ** length_penalty. Values above 1.0 reward longer sequences and values below 1.0 reward shorter ones. - In translation, the model may drop a clause, especially in long sentences. Translate one sentence at a time and compare the length ratio of source and output.
Translation-specific failures
Rare terms, names and numbers
A subword tokenizer splits a rare word into several pieces. The model then has to reassemble a word it rarely saw, and it often picks a similar common word instead. Typical results:
- Product names get translated literally ("Apple Store" becomes a phrase about fruit).
- Proper nouns are respelled.
- Domain terms receive the everyday sense of the word. "Bank" in a river-engineering text becomes a financial institution.
The same grounding idea works here. Extract numbers, URLs and glossary terms from the source and check that the translation contains the agreed target forms. Where a glossary term is mandatory, the safest option is fine-tuning on in-domain parallel data, with a post-check as a backstop.
Wrong output language
MarianMT models such as Helsinki-NLP/opus-mt-en-de are single-direction, so the target language is fixed by the checkpoint. Multilingual models like mBART-50 are different. They need the target language token forced as the first generated token. If you omit it, the model may copy the source or answer in a different language.
from transformers import MBart50TokenizerFast, MBartForConditionalGeneration
name = "facebook/mbart-large-50-many-to-many-mmt"
tokenizer = MBart50TokenizerFast.from_pretrained(name)
model = MBartForConditionalGeneration.from_pretrained(name)
tokenizer.src_lang = "en_XX"
batch = tokenizer("The bank approved the loan.", return_tensors="pt")
outputs = model.generate(
**batch,
forced_bos_token_id=tokenizer.convert_tokens_to_ids("de_DE"),
num_beams=4,
max_new_tokens=40,
)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))A language-identification check on the output catches the remaining cases cheaply.
Low-resource pairs
Quality falls sharply for language pairs with little parallel data. Failures there look different: more hallucinated fluent text unrelated to the source, and more repetition. Do not carry quality expectations from English-German to a pair with a fraction of the training data.
Why metrics do not warn you
ROUGE counts overlapping n-grams with a reference. BLEU and chrF compare n-grams or characters. None of them checks whether a fact is true.
- A summary that changes "40" to "14" loses one token of overlap, so its ROUGE barely moves.
- An extrinsic hallucination that is added at the end barely lowers precision-based scores.
- A fluent but unfaithful summary can outscore a faithful one that is phrased differently from the reference.
Report a faithfulness check next to ROUGE, even a simple one like the grounding report above. Add a human review of a sample, with extra attention to numbers, names and negations.
Exercises
Exercise
A summariser run with beam search produces the same sentence five times in a row, and the output stops only at max_length. Name two generation arguments that address this, and say what risk each one carries.
Show answer
Use norepeatngramsize (for example 3) and repetitionpenalty (for example 1.2). The n-gram ban is a hard rule that also blocks phrases that legitimately need to repeat, such as a repeated name or term, and a small n makes this worse. The penalty is soft but also lowers the score of necessary repeated words like "the", and large values produce awkward synonyms.
Exercise
The groundingreport function returns {'repeatrate': 0.0, 'newnumbers': [], 'newnames': []} for a summary that says the council "rejected" a plan the source says it "approved". Why does the check pass, and what kind of tool would catch this error?
Show answer
The check compares only numbers and capitalised words, and the wrong verb is a lowercase word that appears in neither list. This is an intrinsic hallucination (a contradiction), which needs semantic comparison. A natural language inference model or a question-answering model that tests whether the source entails each summary sentence would catch it, as would human review.
Exercise
A multilingual mBART-50 model is asked to translate English into German, but the output is mostly the English source. What is the most likely missing setting, and how do you set it?
Show answer
The target language token was not forced. Pass forcedbostokenid=tokenizer.converttokenstoids("deDE") to generate, and set tokenizer.srclang = "en_XX" before tokenising the source.