Sub topic 10
Summarising Documents Longer Than the Context Window
This chapter assumes you can run a Hugging Face pipeline, know what a tokeniser does, and have read the earlier chapters on encoder-decoder models, decoding settings and ROUGE. The goal is to summarise a document that does not fit in the model's input, and to know what you lose when you do.
Why long inputs are a problem
Every encoder-decoder model has a maximum input length, counted in tokens, not words. For facebook/bart-large-cnn it is 1024 tokens, about 700 to 800 English words. The limit comes from two things:
- Position information. BART uses learned position embeddings with exactly 1024 slots. There is no embedding for token 1025.
- Cost. Self-attention in the encoder compares every token with every other token, so memory and time grow with the square of the input length.
T5 uses relative position biases, so it can technically accept longer inputs than it was trained on. In practice quality drops and memory still grows quadratically, so a longer input is not a fix.
The dangerous part is what happens by default. If you tokenise with truncation=True, everything past the limit is silently dropped. The summary then describes only the start of the document.
Measuring the input
Count tokens with the same tokeniser the model uses:
from transformers import AutoTokenizer
name = "facebook/bart-large-cnn"
tokenizer = AutoTokenizer.from_pretrained(name)
text = open("report.txt", encoding="utf-8").read()
n_tokens = len(tokenizer.encode(text, add_special_tokens=False))
print("model limit:", tokenizer.model_max_length)
print("document tokens:", n_tokens)
print("fits:", n_tokens + 2 <= tokenizer.model_max_length)The + 2 leaves room for the start and end special tokens that the tokeniser adds.
Strategies at a glance
| Strategy | Idea | Strength | Weakness |
|---|---|---|---|
| Truncate | Keep the first N tokens | Trivial, fast | Ignores the rest of the document |
| Chunk and merge | Summarise pieces, then summarise the summaries | Works with any model | Context is lost at chunk edges |
| Extract, then abstract | Select key sentences, then summarise them | Cheap, fits a fixed budget | Selection errors cannot be recovered |
| Long-context model | Use a model built for 4k to 16k tokens | One pass over the whole text | Larger, slower, fewer checkpoints |
Truncation is acceptable only when the important content sits at the start, as in news articles. Many documents do not follow that pattern.
Chunk and merge (map-reduce)
The most common approach has two phases:
- Map. Split the document into chunks that each fit the model. Summarise each chunk independently.
- Reduce. Join the chunk summaries and summarise that text. If the joined text is still too long, repeat the whole procedure on it.
Splitting on sentence boundaries
Cutting at a fixed token offset can slice a sentence in half, and the model then summarises a fragment. Packing whole sentences into chunks avoids most of that. A single sentence longer than the limit is rare, but it needs a fallback, so the code below hard-splits it by tokens.
import re
from transformers import AutoTokenizer, pipeline
name = "facebook/bart-large-cnn"
tokenizer = AutoTokenizer.from_pretrained(name)
summarizer = pipeline("summarization", model=name, tokenizer=tokenizer)
MAX_TOKENS = 900 # below the 1024 limit, leaving a safety margin
def count_tokens(text):
return len(tokenizer.encode(text, add_special_tokens=False))
def split_sentences(text):
parts = re.split(r"(?<=[.!?])\s+", text)
return [p.strip() for p in parts if p.strip()]
def hard_split(sentence, max_tokens):
ids = tokenizer.encode(sentence, add_special_tokens=False)
return [
tokenizer.decode(ids[i : i + max_tokens])
for i in range(0, len(ids), max_tokens)
]
def chunk_text(text, max_tokens=MAX_TOKENS):
chunks, current, current_len = [], [], 0
for sentence in split_sentences(text):
pieces = [sentence]
if count_tokens(sentence) > max_tokens:
pieces = hard_split(sentence, max_tokens)
for piece in pieces:
n = count_tokens(piece)
if current and current_len + n > max_tokens:
chunks.append(" ".join(current))
current, current_len = [], 0
current.append(piece)
current_len += n
if current:
chunks.append(" ".join(current))
return chunks
def summarise_chunk(chunk):
out = summarizer(
chunk, max_length=120, min_length=30, do_sample=False, truncation=True
)
return out[0]["summary_text"]
def summarise_long(text, max_rounds=4):
for _ in range(max_rounds):
chunks = chunk_text(text)
if len(chunks) == 1:
return summarise_chunk(chunks[0])
text = " ".join(summarise_chunk(c) for c in chunks)
# Rounds exhausted: summarise what is left, truncating if necessary.
return summarise_chunk(text)
document = open("report.txt", encoding="utf-8").read()
print(summarise_long(document))A few details in this code matter:
MAX_TOKENS = 900leaves headroom. Re-encoding a decoded string can differ slightly from the original token IDs, and special tokens take two slots.truncation=Trueis passed to the pipeline as a last safety net. Without it the pipeline does not truncate, and an oversize chunk fails with an indexing error.max_roundsstops the loop if summaries stop shrinking, for example when the model echoes its input.- The summariser runs with
do_sample=False, so the same document gives the same summary.
Overlap
If a chunk boundary falls between a claim and its supporting detail, neither half summarises well. You can repeat the last sentence or two of each chunk at the start of the next. Overlap costs extra compute and can make the same fact appear in two partial summaries. Check whether it helps on your own documents before adding it.
Controlling length across rounds
Each round compresses the text, and each round can introduce errors. Two rules of thumb apply:
- Set the per-chunk
max_lengthso the joined partial summaries are well under the original size. If a chunk of 900 tokens becomes 120 tokens, one round shrinks the text by about 7 times. - Use fewer rounds when possible. A document of 20 chunks usually reduces in two rounds, and a third round mostly adds paraphrase error.
Extract, then abstract
An extractive step picks the most informative sentences, and an abstractive model then rewrites them. A simple selector scores each sentence by similarity to the document's centroid, for instance with TF-IDF or sentence embeddings, and keeps the top-scoring ones in their original order until the token budget is full. Then you run the normal single-pass model.
This is cheaper than chunk and merge, because it makes one model call instead of many. It also works well for documents with a lot of redundancy. Its weakness is that a sentence that was never selected cannot be recovered. It also tends to miss content that is spread across many short sentences.
Long-context models
Some checkpoints are built for longer inputs. The Longformer Encoder-Decoder (LED) replaces full encoder attention with local windowed attention plus a few global tokens, which makes cost grow linearly with length. allenai/led-large-16384-arxiv accepts 16,384 tokens and was fine-tuned for summarising scientific papers.
import torch
from transformers import AutoTokenizer, LEDForConditionalGeneration
name = "allenai/led-large-16384-arxiv"
tokenizer = AutoTokenizer.from_pretrained(name)
model = LEDForConditionalGeneration.from_pretrained(name)
text = open("paper.txt", encoding="utf-8").read()
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=16384)
# LED needs to know which tokens attend globally. The first token is the usual choice.
global_attention_mask = torch.zeros_like(inputs["input_ids"])
global_attention_mask[:, 0] = 1
summary_ids = model.generate(
inputs["input_ids"],
attention_mask=inputs["attention_mask"],
global_attention_mask=global_attention_mask,
num_beams=4,
max_length=256,
no_repeat_ngram_size=3,
)
print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])Using a long-context model has costs:
- The checkpoints are domain-specific. This one writes in the style of an abstract, which may not suit meeting notes or legal contracts.
- Memory use is high, even though it is linear in length.
- Models can attend to the start and end of a very long input better than the middle, so a longer window does not guarantee that every section is covered.
Failure modes specific to long inputs
- Coverage bias. With truncation, only the beginning is represented. With chunking, sections that happen to be dense in numbers or names can dominate the final text.
- Compounding hallucination. In the reduce step, the model summarises text that is already a model output. An unsupported detail from round one is treated as fact in round two. Keep numbers, names and dates checkable against the source.
- Lost cross-chunk context. A pronoun or abbreviation defined in chunk 1 may be unresolved in chunk 5, so the partial summary refers to "the company" or "the Act" without naming it.
- Repetition. Partial summaries often restate the same background. Use
no_repeat_ngram_sizeorrepetition_penaltyin the final call, and consider removing duplicate sentences before the reduce step. - Uneven chunk sizes. A final chunk of 20 tokens is summarised into something longer than itself. Merge tiny trailing chunks into the previous one, or set
min_lengthrelative to the chunk size.
Evaluation is also harder here. ROUGE compares the summary with a reference, and a long document may have several valid summaries that emphasise different parts. A low score may reflect a different emphasis, not an error. For long documents, spot-check a sample by reading the source sections that each summary sentence came from.
Choosing an approach
- If the document fits (token count below the limit minus special tokens), do one pass and skip everything above.
- If the content you need is at the start, truncate on purpose and say so in your documentation.
- If the document is moderately long (a few thousand tokens) and a suitable long-context checkpoint exists for your domain, try it first.
- Otherwise use chunk and merge on sentence boundaries, with a capped number of rounds.
- If cost matters more than completeness, add an extractive pre-selection step.
Exercise
A 6,000-token report is summarised with facebook/bart-large-cnn using chunk and merge, with chunks of at most 900 tokens and a 120-token summary per chunk. Roughly how many chunks are produced, how long is the joined text after the first round, and does a second round of summarising run? Name one risk of the second round.
Show answer
About 7 chunks (6,000 / 900 is 6.7, so 7 when whole sentences are packed). Seven summaries of up to 120 tokens give up to 840 tokens, which is under the 900-token chunk limit, so chunk_text returns a single chunk and the next loop iteration produces the final summary. This is a second model call but not a second split. The risk is compounding hallucination: any unsupported detail in a first-round summary is now treated as source text, and the final model can repeat or reinforce it.
Exercise
Your pipeline summarises long contracts. Users report that the summaries never mention clauses near the end of the document. You are using tokenizer(text, truncation=True) followed by model.generate. What is the cause, and what are two changes that address it?
Show answer
The tokeniser truncates the input to the model's maximum length (1024 tokens for BART), so the end of the contract is never seen by the model. Two fixes: split the contract into sentence-aligned chunks and use map-reduce summarisation, or switch to a long-context checkpoint such as LED with a suitable fine-tune. Also add a token-count check that logs or raises an error when the input exceeds the limit.