Sub topic 8
Map-reduce: summarise the parts, then combine
This chapter assumes you can write 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 function from the previous chapter, which splits text into pieces under a token budget.
The idea
A document that does not fit in one prompt can be handled in two stages:
- Map. Summarise each chunk on its own.
- Reduce. Combine the partial summaries into one final summary.
The names come from distributed computing, where a "map" step runs the same function over many pieces of data and a "reduce" step merges the results. Here the function is "summarise this chunk", and the merge is another summarisation call.
The map calls do not depend on each other. You can send them in parallel, so total latency is closer to one call plus the reduce step than to the sum of all calls. This is the main practical advantage over the refine strategy, covered in the next chapter.
A working implementation
The function below uses the chunker from the previous chapter. It summarises each chunk, joins the partial summaries, and repeats if the joined text is still too long.
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 summarise(text, call_llm, count_tokens, max_tokens=3000):
if count_tokens(text) <= max_tokens:
return call_llm('Summarise the following text in a short paragraph. Use only information in the text.\n\n' + text)
chunks = chunk_paragraphs(text, max_tokens, count_tokens)
partials = [
call_llm('Summarise this section in 5 bullet points. Use only information in the text.\n\n' + c)
for c in chunks
]
combined = '\n\n'.join(partials)
if count_tokens(combined) >= count_tokens(text):
raise ValueError('Partial summaries are not shorter than the input')
return summarise(combined, call_llm, count_tokens, max_tokens)call_llm is any function that takes a prompt string and returns the model's text. count_tokens is any function that returns a token count for a string. Both are passed in, so the code does not depend on one provider.
How the code behaves
- Base case. If the text fits within
max_tokens, one call produces the final summary. This is the single-pass path. - Map. Otherwise the text is chunked, and each chunk gets a prompt asking for five bullets. The list comprehension runs the calls one after another.
- Reduce. The bullets from all chunks are joined and passed back to
summarise. If they fit, the base case produces the final paragraph. If they do not fit, the function chunks the joined text and maps again. - Guard. If the combined partial summaries are not shorter than the input, the function raises an error. Without this check, a model that returns long or verbose output could make the recursion run forever.
Notice that the same function handles both the map and the reduce stage. The recursion makes the reduce step repeat until the text fits, which is what makes this approach work on documents of any length.
Running the map calls in parallel
The list comprehension is sequential. Because the map calls are independent, you can run them with a thread pool. API calls spend most of their time waiting on the network, so threads work well here.
from concurrent.futures import ThreadPoolExecutor
def map_chunks(chunks, call_llm, workers=4):
prompts = [
'Summarise this section in 5 bullet points. Use only information in the text.\n\n' + c
for c in chunks
]
with ThreadPoolExecutor(max_workers=workers) as pool:
return list(pool.map(call_llm, prompts))pool.map returns results in the same order as the inputs, so the partial summaries stay in document order. This matters because the reduce step often relies on order to build a coherent narrative.
You can swap this into summarise by replacing the list comprehension with partials = map_chunks(chunks, call_llm). Keep workers small enough to stay under your provider's rate limit. A burst of parallel calls can trigger rate-limit errors, so real code should also retry failed calls with a delay.
Designing the two prompts
The map and reduce steps do different jobs, and they work better with different prompts.
The map prompt should extract what matters from one section. It sees only that section, so it cannot know what the rest of the document says. Give it the same purpose and audience you chose at the start of the project. If the final summary is for a lawyer who needs obligations and deadlines, tell the map prompt to keep obligations and deadlines. Otherwise each map call decides for itself what is important, and details the reduce step needs may be dropped.
The reduce prompt sees only the partial summaries, not the source. It should merge, remove duplicates, and organise. A reasonable reduce prompt is:
REDUCE_PROMPT = (
'Below are summaries of consecutive sections of one document. '
'Combine them into a single summary of about 150 words for a busy manager. '
'Remove repetition, keep the order of events, and use only information '
'in the summaries. If two summaries disagree, say so.\n\n'
)The recursive summarise function reuses one prompt per path, which is fine for a first version. In production you would pass the map and reduce prompts as parameters, so the final call uses a prompt tuned for the final output format.
What goes wrong
Map-reduce is simple and parallel, but it has failure modes that follow from its design.
Context is lost between chunks
Each map call sees one chunk. A pronoun such as "she" or a phrase such as "the agreement" may refer to something defined in an earlier chunk. The map call cannot resolve it, so the partial summary may be vague or wrong. Chunking along section or paragraph boundaries reduces this, and so does prefixing every chunk with the document title and a one-line description.
Cross-chunk reasoning is weak
If the answer depends on combining facts from chunks 2 and 9, such as a figure that is reported in one place and revised in another, neither map call sees both. The reduce step sees only the compressed versions, and the relevant detail may have been dropped. Map-reduce suits documents where each part can be summarised alone, such as a collection of reports or meeting notes. It is less suited to a tightly argued text where later sections revise earlier ones.
Details are lost at every level
Each stage compresses. A fact that survives the map step with probability 0.9 and the reduce step with probability 0.9 survives the whole pipeline with probability 0.81. With a recursive reduce, there are more stages, so more loss. A long document therefore gets a summary that favours themes repeated in many chunks and under-represents one-off details.
Errors compound
If a map call invents a detail, the reduce step has no source text to check it against. It treats the partial summary as true. The "use only information in the text" instruction lowers this risk but does not remove it. Faithfulness checks are covered in a later chapter.
Inconsistent style and duplicates
Because the map calls run independently, they may use different terms for the same thing, or repeat the same point from different angles. The reduce prompt should say to merge duplicates and use one term per concept.
Edge cases to handle
| Situation | What happens | Fix |
|---|---|---|
| One paragraph larger than the budget | `chunk_paragraphs` makes an oversized chunk that may exceed the context window | Split oversized paragraphs by sentence before chunking |
| Partial summaries not shorter than input | The guard raises `ValueError` | Ask for fewer bullets or a word limit in the map prompt |
| One map call fails | The whole run fails | Retry with a delay, then fall back to an error or a placeholder for that chunk |
| Chunks with no useful content, such as a page of boilerplate | The model summarises the boilerplate | Filter these chunks or allow the model to answer "nothing relevant" |
| Very many chunks | The joined partial summaries exceed the budget, so the reduce step needs several rounds | Accept the recursion, or use the hierarchical strategy in a later chapter |
Cost and latency
For a document of N tokens, the map step reads all N tokens once and produces partial summaries. The reduce step reads only the partial summaries, so its cost is small if the compression is good. Total input cost is therefore a bit more than N tokens, plus the prompt text repeated in every call.
Latency with parallel map calls is roughly the time of the slowest map call plus the time of each reduce round. Sequential map calls take the sum of all of them. This is why parallelism is worth the extra code.
When to choose map-reduce
Choose it when:
- The document is too long for one call, or long enough that single-pass quality suffers.
- Sections can be understood alone.
- Speed matters and you can run calls in parallel.
Prefer another strategy when:
- The document is a story or argument where order and earlier context matter. Refine keeps a running summary, so it fits better.
- The document fits in the context window and quality is acceptable. Single-pass is simpler and has no compounding loss.
Exercise
A 40-page contract is summarised with map-reduce. The final summary says "the supplier must deliver within 30 days", but the contract's last section changes this to 45 days. Explain why map-reduce can produce this error, and name two changes that would reduce it.
Show answer
Each map call sees only one chunk. The chunk with the original 30-day term and the chunk with the later amendment are summarised separately, and the reduce step sees only compressed bullets. If the amendment bullet is dropped or is phrased without context, the reduce step keeps the 30-day claim. Two possible changes: (1) tell the map prompt to always keep numbers, deadlines and changes to earlier terms, and use a fixed structure so those fields appear in every partial summary; (2) tell the reduce prompt to flag conflicting values rather than choose one, or switch to the refine strategy so that later chunks can update an earlier running summary. Prefixing each chunk with a short description of the contract would also help.
Exercise
In summarise, why does the function raise an error when count_tokens(combined) >= count_tokens(text), and what would happen without that check?
Show answer
The recursion only terminates if each round makes the text shorter. If the model returns partial summaries as long as or longer than their chunks, the combined text never drops below max_tokens, so the function would call itself again forever and keep spending money on API calls. The check stops this by failing early. You can then shorten the map prompt's output limit, for example by asking for fewer bullets or a word limit.