Sub topic 8
Summarising text with an encoder-decoder model
This chapter assumes you know basic Python, how a Transformer uses self-attention, and how to load a model with Hugging Face Transformers. Earlier chapters covered the encoder, cross-attention and teacher forcing. Here you apply them to summarisation: what the task is, how to run a pretrained model, which settings matter, and which errors to expect.
Extractive and abstractive summaries
A summary can be built in two ways.
- Extractive summarisation selects existing sentences or phrases from the source and joins them. The output is always made of the source's own words, so it rarely states something the source does not say. It can read awkwardly, and it cannot merge two sentences into one.
- Abstractive summarisation writes new text. The model can paraphrase, compress several sentences into one and change word order. Encoder-decoder models such as BART and T5 work this way.
The abstractive approach reads fluently. Its cost is that the decoder generates freely, so it can write something the source does not support. That error is called hallucination, and it is the main risk in this chapter.
| Property | Extractive | Abstractive |
|---|---|---|
| Output wording | Copied from the source | Newly generated |
| Fluency | Can be choppy | Usually smooth |
| Faithfulness | High by construction | Needs checking |
| Typical model | Sentence ranking | BART, T5, PEGASUS |
How the pieces fit together
The encoder reads the whole article once and produces one vector per input token. The decoder then writes the summary one token at a time. At each step it attends to its own previous output through self-attention. It also attends to the encoder's vectors through cross-attention, so it can look back at the relevant part of the article.
The loop between the decoder and the next token is autoregressive generation. The decoder stops when it emits the end-of-sequence token or reaches the length limit.
Running a pretrained summariser
The pipeline helper bundles tokenisation, generation and decoding. facebook/bart-large-cnn is BART fine-tuned on CNN/DailyMail news articles, so it works best on news-style text.
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."
)
result = summarizer(article, max_length=60, min_length=15, do_sample=False)
print(result[0]["summary_text"])Setting do_sample=False makes decoding deterministic. Running the script twice gives the same summary.
What the length arguments mean
max_length and min_length count output tokens, not words and not characters. A subword tokeniser splits rare words into several pieces, so 60 tokens is roughly 40 to 45 English words. Two consequences follow:
- If
min_lengthis larger than the useful content, the model pads the summary with filler or repeats itself. - If
max_lengthis too small, the model is cut off mid-sentence. Cutting off is a hard stop, so the model does not plan to finish within the limit.
A short input with a large min_length is a common source of odd output. Choose limits from the length you want, not from the model's defaults.
Using the model directly
The pipeline hides the individual steps. When you need control over batching or generation arguments, call the tokenizer and generate yourself. This example uses t5-small, which selects the task through a text prefix.
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.",
"summarize: The city council approved a plan to add 40 kilometres of bike lanes over three years.",
]
inputs = tokenizer(prompts, return_tensors="pt", padding=True)
outputs = model.generate(**inputs, num_beams=4, max_new_tokens=40)
for text in tokenizer.batch_decode(outputs, skip_special_tokens=True):
print(text)T5 was trained with prefixes such as summarize: and translate English to German:. Leaving the prefix off usually degrades the output, because the model has no signal about which task to perform. BART does not use prefixes. Its fine-tuned checkpoint has one task built in.
max_new_tokens limits only the generated tokens. This is usually clearer than max_length, which in encoder-decoder models counts the decoder sequence, including its start token.
Decoding settings for summaries
Decoding was covered in detail earlier. For summarisation, these settings matter most.
- Beam search (
num_beams=4) keeps several candidate summaries and returns the best. It tends to give more fluent and more faithful output than greedy search, at higher compute cost. length_penaltyadjusts how beam search scores length. Values above 1.0 favour longer outputs, and values below 1.0 favour shorter ones.no_repeat_ngram_size(for example 3) forbids repeating any 3-token sequence. It cures looping output but can also block a legitimate repeat, such as a name that must appear twice.early_stopping=Trueends beam search once enough finished candidates exist.- Sampling (
do_sample=True, withtop_portemperature) gives varied output. For summaries, deterministic beam search is the usual choice, because variety raises the chance of unsupported claims.
Documents longer than the context window
Each model has a maximum input length. BART accepts 1024 tokens, and t5-small was pretrained on 512-token inputs. If a document is longer, the tokenizer truncates it when truncation=True, and the model never sees the rest. With the pipeline, long inputs can instead raise an error or be silently cut, depending on the version and settings. Check this on your own data.
The standard remedy is map-reduce summarisation:
- Split the document into chunks that fit the window, preferably on paragraph or sentence boundaries.
- Summarise each chunk.
- Join the chunk summaries and summarise again. Repeat if the joined text is still too long.
from transformers import AutoTokenizer, pipeline
name = "facebook/bart-large-cnn"
tokenizer = AutoTokenizer.from_pretrained(name)
summarizer = pipeline("summarization", model=name, tokenizer=tokenizer)
def chunk_by_tokens(text, limit=900):
sentences = text.replace("\n", " ").split(". ")
chunks, current, count = [], [], 0
for sentence in sentences:
n = len(tokenizer.tokenize(sentence))
if current and count + n > limit:
chunks.append(". ".join(current))
current, count = [], 0
current.append(sentence)
count += n
if current:
chunks.append(". ".join(current))
return chunks
def summarise_long(text):
partial = [
summarizer(c, max_length=120, min_length=30, do_sample=False)[0]["summary_text"]
for c in chunk_by_tokens(text)
]
joined = " ".join(partial)
if len(tokenizer.tokenize(joined)) > 900:
return summarise_long(joined)
return summarizer(joined, max_length=120, min_length=30, do_sample=False)[0]["summary_text"]The limit of 900 leaves room under BART's 1024 tokens for special tokens. A single sentence longer than the limit still becomes its own oversized chunk and gets truncated. Handle that case if your data contains it.
Map-reduce has costs. Each chunk is summarised without knowledge of the others, so facts that depend on context across chunks can be lost or misattributed. Models built for long inputs, such as LED (Longformer Encoder-Decoder), avoid chunking by using sparse attention, though they are more demanding to run.
Failure modes specific to summarisation
- Hallucination. The summary contains a name, number or claim that is absent from the source. Models fine-tuned on news often add plausible details from their training data. Compare numbers and named entities in the summary against the source.
- Repetition. The decoder repeats a phrase or sentence. Use
no_repeat_ngram_sizeor a repetition penalty, and avoid amin_lengththat exceeds the real content. - Lead bias. News-trained models favour the first sentences of the article, because news places key facts there. On a report or a transcript, the summary may overweight the opening.
- Domain mismatch. A news model applied to legal text or dialogue can produce fluent but shallow output. Fine-tuning on in-domain data is the fix, covered in a later chapter.
- Truncation. Text beyond the input limit is ignored without any warning in the output.
Checking your results
For a quick sanity check, compute the compression ratio and confirm that each number in the summary appears in the source. Automatic scoring with ROUGE is covered in the evaluation chapter. ROUGE measures word overlap with a reference summary, so it can rate a faithful paraphrase low and an unfaithful but overlapping summary high.
Exercise
You summarise a 3,000-word report with facebook/bart-large-cnn, calling the tokenizer with truncation=True. The summary covers only the first third of the report. Why, and what two changes would fix it?
Show answer
BART accepts at most 1,024 tokens, so truncation discards everything after that point and the decoder never sees the rest. Fix it by splitting the report into chunks under the limit, summarising each, then summarising the joined chunk summaries (map-reduce). Alternatively, use a long-input model such as LED, which accepts far more tokens.
Exercise
A summary keeps repeating the same clause three times. You raise min_length from 30 to 100 and the problem gets worse. Explain why, and name one setting that helps.
Show answer
The article only supports a short summary. A high minlength stops the decoder from emitting the end-of-sequence token, so it fills the extra tokens by repeating content. Lower minlength to match the real content, and set norepeatngram_size=3 (or add a repetition penalty) to block repeated phrases.