Sub topic 10
Summising Documents Longer Than the Context Window
This chapter assumes that you know Python, basic PyTorch tensors, and the main parts of a Transformer. You should also understand tokenisation, sequence-to-sequence models, and autoregressive decoding.
An encoder-decoder model cannot read unlimited input. Its encoder has a fixed context window, measured in tokens. If a document contains more tokens than this limit, the tokenizer may truncate the end, or the model may reject the input. Truncation can silently remove the document's conclusion, so it is unsafe for summarisation unless you explicitly accept information loss.
Check the token budget
The model's tokenizer determines how many tokens a document uses. Words, punctuation, and subwords can each become separate tokens. Reserve some capacity for special tokens and use a limit supported by the model.
from transformers import AutoTokenizer
name = "facebook/bart-large-cnn"
tokenizer = AutoTokenizer.from_pretrained(name)
document = "A long document goes here."
tokens = tokenizer(document, add_special_tokens=True)["input_ids"]
print("tokens:", len(tokens))
print("model limit:", tokenizer.model_max_length)Some tokenizers report an extremely large placeholder for an unknown limit. In that case, use the limit documented for the specific model. Do not assume that every encoder-decoder model supports the same length.
Chunk, summarise, and combine
A practical solution is hierarchical summarisation:
- Split the document into chunks that fit the encoder.
- Summarise each chunk independently.
- Join the intermediate summaries.
- Summarise the joined text again.
The first pass compresses the document. The second pass produces one coherent summary from the compressed material.
Chunk boundaries matter. Splitting at an arbitrary token position can separate a sentence or an important explanation. Prefer paragraph or sentence boundaries, then enforce the token limit. A small overlap between neighbouring chunks can preserve context that crosses a boundary. Overlap also repeats information, so excessive overlap wastes the token budget and can cause repeated facts in the final result.
from transformers import pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
tokenizer = summarizer.tokenizer
def paragraph_chunks(text, max_input_tokens=900):
chunks = []
current = []
for paragraph in text.split("\n\n"):
candidate = "\n\n".join(current + [paragraph])
size = len(tokenizer(candidate, add_special_tokens=True)["input_ids"])
if current and size > max_input_tokens:
chunks.append("\n\n".join(current))
current = [paragraph]
else:
current.append(paragraph)
if current:
chunks.append("\n\n".join(current))
return chunks
def summarize_long(text):
chunks = paragraph_chunks(text)
partial = [
summarizer(chunk, max_length=80, min_length=20, do_sample=False)[0]["summary_text"]
for chunk in chunks
]
combined = " ".join(partial)
return summarizer(
combined, max_length=120, min_length=30, do_sample=False
)[0]["summary_text"]The max_input_tokens value leaves room below the model's maximum. That margin protects against special tokens and unusually long paragraphs. A production splitter should also handle a single paragraph that is itself too long by splitting it into sentences or token windows.
Choose a strategy for the document
| Strategy | Strength | Main risk |
|---|---|---|
| Truncate | Simple and fast | Loses unseen content |
| Independent chunks | Preserves broad coverage | Repeated or disconnected points |
| Overlapping chunks | Preserves boundary context | Uses more tokens and compute |
| Hierarchical summary | Produces one coherent result | Important details may disappear during the first pass |
| Retrieval before summarising | Focuses on a question or topic | Omits information that was not retrieved |
A hierarchical summary is not guaranteed to preserve every important detail. If the document contains tables, legal conditions, or rare names, intermediate summaries may omit them. For high-stakes work, retain chunk summaries, cite their source locations, and ask a verifier to compare the final summary with the original.
Other approaches and failure modes
Long-context models can accept larger inputs, but they still have finite limits and may attend less reliably to information far from the beginning or end. A larger window also increases memory use and inference time.
Map-reduce summarisation is another name for the chunk-and-combine pattern: map summarisation over chunks, then reduce the results. For documents with a clear structure, summarise sections separately and combine them using section headings. For question-focused work, retrieve relevant passages first instead of summarising the entire document.
Test with documents whose key fact appears at the beginning, middle, and end. Check whether the output repeats chunk boundaries, invents connections, or changes a number. These tests reveal more than a single fluent example.
Exercise
A 12,000-token report must be summarised by a model with a 1,024-token input limit. What basic pipeline should you use, and what risk must you check?
Show answer
Split the report into sentence- or paragraph-aligned chunks below the limit, summarise each chunk, then summarise the joined intermediate summaries. Check for omitted facts, repeated content, hallucinated connections, and changed numbers.