Sub topic 10
Hierarchical summarisation for very long documents
This chapter assumes you can read basic Python, have sent prompts to an LLM through an API, and know what a token is. It also assumes you have seen the chunk_paragraphs and summarise functions from the chunking and map-reduce chapters. Here we extend them to documents so long that one reduce step is not enough.
What hierarchical summarisation is
Hierarchical summarisation builds a tree of summaries. The leaves are chunks of the source. Each level above summarises groups of nodes from the level below. The root is the final summary.
Map-reduce already does this in a limited way. It summarises every chunk, then joins the partial summaries and summarises again. If the joined partial summaries still do not fit in the context window, it repeats. The recursive summarise function from the map-reduce chapter therefore produces a tree implicitly. A hierarchical design makes that tree explicit. You choose the fan-in (how many children feed one parent), you can group children by document structure, and you keep every level.
Keeping every level is the main practical benefit. You can inspect the intermediate summaries, regenerate one branch without redoing the others, and let readers drill down from the overall summary to a chapter summary to a section summary.
When you need it
Plain map-reduce works when the partial summaries fit in one call. Take a 3,000-token budget and 5 bullet points per chunk of roughly 120 tokens each. One reduce call can then take about 25 partials, which is roughly 25 chunks or 75,000 tokens of source. Past that point you need more than two levels.
Typical cases are:
- A book, a long legal record, or a year of meeting transcripts.
- A set of many documents, such as hundreds of support tickets or research papers.
- Any job where readers want summaries at several zoom levels.
For documents under that threshold, a flat map-reduce is simpler and has fewer places to lose information. Add levels only when the arithmetic forces you to, or when the multi-level output is the product you want.
The arithmetic of levels
Let N be the number of chunks and f the fan-in. Level 1 has N summaries, level 2 has about N/f, level 3 has about N/f², and so on. The number of levels above the leaves is about log base f of N.
The total number of calls is a geometric sum: N + N/f + N/f² + … + 1. For large f this is close to N, so the extra levels add little cost. With 400 chunks and a fan-in of 8:
| Level | Inputs per call | Calls |
|---|---|---|
| 1 (chunks) | 1 chunk | 400 |
| 2 | 8 summaries | 50 |
| 3 | 8 summaries | 7 |
| 4 (root) | 7 summaries | 1 |
| Total | 458 |
Latency is different. Calls within a level are independent, so you can run them in parallel. Levels depend on each other, so they run in sequence. Wall-clock time is therefore roughly the number of levels times the slowest call per level, plus any rate-limit waiting. It is not the total number of calls.
Choosing the fan-in
You can fix the fan-in as a number, such as 8. A better rule for intermediate use is to group by token budget, the same way chunk_paragraphs groups paragraphs. Fill each group until the next summary would push it past the budget. This adapts to summaries of uneven length and cannot overflow the context window.
Leave headroom. The budget applies to the text you pass in, but the prompt instructions and the model's output also use the window. If your window is 8,000 tokens, a 3,000-token input budget is comfortable. A 7,900-token one is not.
Implementation
The code below reuses chunk_paragraphs from the chunking chapter. It adds group_by_budget and hierarchical_summary, which returns the final summary and every level of the tree. The prompts end with a TEXT: marker so the stub model in the demo can find the input.
LEAF_PROMPT = (
'Summarise this section in 5 bullet points. '
'Use only information in the text.\n\nTEXT:\n'
)
MERGE_PROMPT = (
'The following are summaries of consecutive parts of one document. '
'Merge them into one summary of 5 bullet points. '
'Keep names, numbers and dates exactly as written. '
'Use only information in the text.\n\nTEXT:\n'
)
FINAL_PROMPT = (
'The following are summaries of consecutive parts of one document. '
'Write a short paragraph that summarises the whole document. '
'Use only information in the text.\n\nTEXT:\n'
)
def chunk_paragraphs(text, max_tokens, count_tokens):
chunks, current, size = [], [], 0
for para in text.split('\n\n'):
n = count_tokens(para)
if current and size + n > max_tokens:
chunks.append('\n\n'.join(current))
current, size = [], 0
current.append(para)
size += n
if current:
chunks.append('\n\n'.join(current))
return chunks
def group_by_budget(items, max_tokens, count_tokens):
groups, current, size = [], [], 0
for item in items:
n = count_tokens(item)
if current and size + n > max_tokens:
groups.append(current)
current, size = [], 0
current.append(item)
size += n
if current:
groups.append(current)
return groups
def hierarchical_summary(chunks, call_llm, count_tokens, max_tokens=3000):
levels = [chunks]
current = [call_llm(LEAF_PROMPT + c) for c in chunks]
levels.append(current)
while count_tokens('\n\n'.join(current)) > max_tokens:
groups = group_by_budget(current, max_tokens, count_tokens)
if len(groups) >= len(current):
raise ValueError('Level did not shrink; summaries are too long for the budget')
current = [call_llm(MERGE_PROMPT + '\n\n'.join(g)) for g in groups]
levels.append(current)
final = call_llm(FINAL_PROMPT + '\n\n'.join(current))
return final, levels
if __name__ == '__main__':
def count_tokens(text):
return len(text.split())
def call_llm(prompt):
body = prompt.split('TEXT:\n', 1)[1]
return ' '.join(body.split()[:25])
paragraphs = ['Paragraph %d ' % i + 'word ' * 58 for i in range(60)]
text = '\n\n'.join(p.strip() for p in paragraphs)
chunks = chunk_paragraphs(text, 200, count_tokens)
final, levels = hierarchical_summary(chunks, call_llm, count_tokens, max_tokens=200)
print([len(level) for level in levels])
print(len(final.split()))Running it prints [20, 20, 3] and then 25. The 60 paragraphs become 20 chunks. Each chunk becomes one summary. Those 20 summaries are 500 words, which exceeds the 200-word budget, so they are merged in groups of 8 into 3 summaries. The 3 summaries total 75 words, which fits, so the final call runs.
To use a real model, replace call_llm with a function that sends the prompt to your API and returns the text. Replace count_tokens with your model's tokenizer. Since the leaf and merge calls inside one level are independent, you can wrap those list comprehensions in a thread pool to run them in parallel. Respect your provider's rate limits when you do.
The progress guard
The len(groups) >= len(current) check prevents an infinite loop. It fires when each summary is so large that no two fit in one group. The usual cause is a model that ignores the length instruction. The fix is a firmer length limit in the prompt, a lower max_tokens for chunks, or a hard cap on output tokens in the API call.
Grouping by structure instead of by size
group_by_budget groups neighbours purely by size, so a group can straddle a chapter boundary. If the document has structure, such as chapters, headings, or one file per meeting, build the tree along that structure:
- Split the document at top-level headings.
- Chunk and summarise each section on its own, merging inside the section until it has one summary.
- Merge the section summaries into the final summary.
Each summary then describes a real unit of the document. Readers can also find "the summary of chapter 3" directly. The cost is uneven branches, because a short section produces a shallow subtree and a long one a deep subtree. That is fine as long as every merge call stays within the budget.
Failure modes
Information loss compounds. Each level discards detail. A fact that is minor inside its chunk may be dropped at level 2 even if it matters for the whole document. Deep trees lose more than shallow ones, so prefer a larger fan-in and fewer levels when the model can handle it.
Errors propagate upward. A hallucinated claim in a leaf summary looks like source text to the next level. The merge step cannot check it, because it never sees the original chunk. Keep every level (the function above does) so you can trace a suspicious claim downward. The faithfulness chapter covers checks.
Uneven weight. A merge prompt treats all inputs as equal. If one section has the decisive finding in two lines and another has ten pages of routine detail, the routine section may dominate. Ask leaf summaries to flag the single most important point, and tell the merge step to preserve those.
Chunk boundaries cut context. A leaf summary sees only its own chunk. A pronoun or a running case name defined in the previous chunk may be unclear. Put the document title and section heading in each leaf prompt, or let consecutive chunks overlap slightly.
Loss of order. Merge prompts say "consecutive parts", and the code keeps the original order. Do not shuffle summaries between levels, or the final text may reverse the order of events.
Hierarchical, map-reduce and refine compared
| Strategy | Calls run in parallel | Order preserved | Handles unlimited length | Intermediate views |
|---|---|---|---|---|
| Single pass | Not applicable | Yes | No | No |
| Flat map-reduce | Yes | Yes | Only up to one reduce call | No |
| Refine | No | Yes | Yes, but early detail fades | No |
| Hierarchical | Yes, within a level | Yes | Yes | Yes |
Choose hierarchical when the document is too long for one reduce call, when you want parallel speed, or when users need multiple zoom levels. Choose refine when strict narrative order matters more than speed and the document is moderate in length. Choose flat map-reduce or single pass for anything that fits.
Exercise
You have 1,200 chunks and a fan-in of 10. How many levels of merge calls do you need above the chunk summaries, and roughly how many LLM calls does the whole job take, counting the leaf calls and the final call? Why does the guard len(groups) >= len(current) matter?
Show answer
Level 1 is 1,200 chunk summaries. Merging by 10 gives 120, then 12, then 2, then 1 final summary. That is 3 merge levels (1,200 to 120 to 12 to 2) plus the final call that produces the root from the 2 remaining summaries. Total calls: 1,200 + 120 + 12 + 2 + 1 = 1,335. The guard stops the loop when a merge level produces as many summaries as it received. That happens when each summary is so long that no two fit in one group, and without the guard the loop would never end.
Exercise
A reader complains that a deadline mentioned once in chapter 7 of a 400-page report is missing from the final summary. Give two changes to the hierarchical pipeline that make this less likely, and one way to find out at which level the deadline was lost.
Show answer
Changes: (1) tell every leaf and merge prompt to keep dates, names and numbers exactly as written, and state the reader's goal (for example "track deadlines") in every prompt, not only the last one; (2) use a larger fan-in or group by chapter so the tree has fewer levels. To locate the loss, search the saved levels for the deadline text, starting from the chunk, then the level-1 summary, then each merge level. The first level where it is missing is where it was dropped.