Sub topic 13
Cost and latency trade-offs
This chapter assumes you can write basic Python, have sent prompts to an LLM through an API, and know that models read and write tokens. It also assumes you have met the three strategies from earlier chapters: single-pass, map-reduce and refine. Here you will put numbers on each strategy so you can choose between them before you build anything.
What you pay for
Most hosted models bill per token, and they charge different rates for input tokens (what you send) and output tokens (what the model writes). Output tokens usually cost several times more than input tokens. Check your provider's current price list, because prices change often.
Latency is the wall-clock time from sending the request to receiving the answer. For a single call it has two parts:
- Time to process the input. This grows with prompt length, but modern models handle input quickly.
- Time to generate the output. The model writes one token at a time, so this grows roughly in step with the number of output tokens.
Two consequences follow. A long input with a short summary is cheap and fast compared with a short input and a long answer. And many small calls add overhead, because each call has its own network round trip and queueing delay.
A rough cost model for one call is:
cost = input_tokens * input_price + output_tokens * output_priceA rough latency model for one call is:
latency = overhead + input_tokens / read_speed + output_tokens / write_speedYou do not need exact values for read_speed or write_speed. Measure a few real calls and use the averages.
Counting the calls in each strategy
Let a document have D tokens. Let the chunk size be C tokens, so the number of chunks is N = ceil(D / C). Let each partial summary be S tokens long.
Single-pass
One call. The input is D tokens plus the prompt, and the output is one summary. This is the cheapest and fastest strategy when the document fits in the context window. It is also the easiest to keep consistent, since the model sees everything at once.
The limits are the context window and the quality problems of very long inputs, such as the lost-in-the-middle effect. If the document does not fit, this strategy is not available.
Map-reduce
The map step makes N calls. Together they read about D input tokens and write N * S output tokens. The reduce step reads the N * S tokens of partial summaries and writes the final summary. If the combined partials are still too long, the reduce step repeats, as in the recursive summarise function from the earlier chapter.
Total input is about D + N*S (plus a little for each repeated prompt). Total output is N*S plus the final summary. So map-reduce costs a little more than single-pass on the same text, because the partial summaries are read a second time.
The important property is that the map calls are independent. You can run them in parallel. Wall-clock latency is then about one map call plus one reduce call, not N map calls plus the reduce.
Refine
Refine also makes N calls, but each call reads one chunk plus the running summary. Input is about D + N*S, where S is the running summary size, and each call writes a new summary of about S tokens. Token cost is close to map-reduce.
The difference is latency. Each call needs the previous call's output, so the calls cannot run in parallel. Wall-clock time is about N times the latency of one call.
Hierarchical
Hierarchical summarisation is map-reduce with several levels. It adds calls at each level, but each level shrinks the text sharply. For a very long document the extra cost is small compared with the first map level, because later levels read only summaries.
Comparing the strategies
| Strategy | Calls | Approximate input tokens | Can run in parallel? | Latency (rough) |
|---|---|---|---|---|
| Single-pass | 1 | D | Not applicable | 1 long call |
| Map-reduce | N + 1 (or more) | D + N*S | Map step: yes | Slowest map call + reduce |
| Refine | N | D + N*S | No | N sequential calls |
| Hierarchical | N + several | D + N*S + upper levels | Within each level | One call per level, plus waits |
A worked estimate
Take a 120,000-token report. Assume a model with a 32,000-token usable window, chunks of 3,000 tokens, partial summaries of 300 tokens, and a final summary of 400 tokens. These numbers are made up for illustration. Use your own prices.
- Chunks:
N = 120000 / 3000 = 40. - Map step: 40 calls, 120,000 input tokens, 12,000 output tokens.
- Reduce step: 12,000 tokens of partials fit in one call, so 1 call, 12,000 input tokens, 400 output tokens.
- Totals: 41 calls, about 132,000 input tokens, about 12,400 output tokens.
Now suppose the input price is 1 unit per million tokens and the output price is 4 units per million. The cost is roughly 0.132 + 0.0496 = 0.18 units. For refine with the same sizes, the input is about the same, 120,000 + 40 * 300 = 132,000, and the output is 40 * 300 = 12,000. The cost is nearly identical. The strategies differ in time, not money.
If one call takes 6 seconds and you run 10 map calls at once, the map step takes about 4 rounds, so roughly 24 seconds, plus 6 seconds to reduce. Refine takes 40 × 6 = 240 seconds, about 8 times longer, for a similar bill.
You can put this into a small function and compare strategies before you commit:
import math
def estimate(doc_tokens, chunk_tokens, partial_tokens, final_tokens,
input_price, output_price, call_seconds, parallel=10):
n = math.ceil(doc_tokens / chunk_tokens)
partials = n * partial_tokens
map_in, map_out = doc_tokens, partials
reduce_in, reduce_out = partials, final_tokens
mr_cost = ((map_in + reduce_in) * input_price
+ (map_out + reduce_out) * output_price) / 1_000_000
mr_time = math.ceil(n / parallel) * call_seconds + call_seconds
refine_in = doc_tokens + n * partial_tokens
refine_out = n * partial_tokens
refine_cost = (refine_in * input_price
+ refine_out * output_price) / 1_000_000
refine_time = n * call_seconds
return {
'chunks': n,
'map_reduce': {'cost': round(mr_cost, 4), 'seconds': mr_time},
'refine': {'cost': round(refine_cost, 4), 'seconds': refine_time},
}
print(estimate(120_000, 3_000, 300, 400,
input_price=1.0, output_price=4.0, call_seconds=6))The function ignores the prompt text added to each call and assumes every call takes the same time. That is fine for a first estimate.
Levers that change the numbers
Chunk size
Larger chunks mean fewer calls and less per-call overhead. They also mean each call sees more text, which can lower quality if the chunk is long enough to trigger the middle-of-context problems. Smaller chunks give finer detail in the partial summaries, but they produce more partials, so the reduce step has more to read and may need another level.
A common starting point is a chunk well below the context window, often a few thousand tokens, then adjust after reading the outputs.
Partial summary length
Partial summary length S controls how much text the reduce step must read. Doubling S doubles the output cost of the map step and the input cost of the reduce step. It also raises the chance that the reduce step needs another round. Ask for the shortest partial that keeps the facts you need, such as the 5 bullets used in the earlier example.
Parallelism and rate limits
Parallel map calls reduce wall-clock time but not tokens. Providers limit requests per minute and tokens per minute. If you send 40 calls at once and exceed a limit, some will fail with a rate-limit error. Use a bounded worker pool, and retry failed calls with a short, growing delay. A pool of 5 to 10 workers is a sensible start.
from concurrent.futures import ThreadPoolExecutor
def map_parallel(chunks, call_llm, workers=8):
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 input order, so the partial summaries stay in document order for the reduce step.
Model choice
You can use different models for different steps. A smaller, cheaper model often does the map step well, since it only compresses a short passage. A stronger model can handle the reduce step, where combining and resolving overlaps matters more. Test this on your own documents, because the gain depends on how hard the content is.
Caching and reuse
If you summarise the same document many times with different prompts (for example, one summary for executives and one for engineers), cache the partial summaries. The map step is the expensive part, and it can often be reused if the map prompt does not change. Some providers also discount repeated prompt prefixes. Check whether yours does, and put the unchanging text at the start of the prompt.
Retries and failures
Every call can fail or return something unusable. Budget for retries. In map-reduce, a failed map call can be retried alone. In refine, a failure in call 30 blocks calls 31 to 40, so store the running summary after each step and resume from there.
Edge cases
- The reduce step is bigger than the window. With many chunks and long partials,
N*Scan exceed the window. Recurse, as the earliersummarisefunction does, and accept the extra calls. - Summaries that do not shrink. If partials are not shorter than their inputs, recursion never ends. The guard in
summariseraises an error for this case. Treat it as a prompt problem and tighten the length instruction. - Short documents. Do not use map-reduce on a document that fits in one call. It costs more and loses cross-section context for no gain.
- Output limits. Models cap output tokens per call. A long requested summary can be cut off. Keep partials short.
- Pricing changes. Hard-code prices in a config, not in logic, so estimates stay current.
Choosing a strategy
- If the document fits in the window with room for the prompt and the output, and quality is acceptable, use single-pass.
- If it does not fit and speed matters, use map-reduce with parallel map calls.
- If document order and a continuous narrative matter more than speed, and the document is not huge, use refine.
- If the partial summaries themselves exceed the window, use hierarchical summarisation.
Exercise
A 90,000-token document is split into 30 chunks of 3,000 tokens. Each partial summary is 250 tokens, and one call takes 5 seconds. Estimate the wall-clock time for map-reduce with 10 parallel workers, and for refine. Which is faster, and does the token cost differ much?
Show answer
Map-reduce: 30 chunks with 10 workers is 3 rounds of 5 seconds, which is 15 seconds. The partials total 30 × 250 = 7,500 tokens, which fit in one reduce call of about 5 seconds. Total is about 20 seconds. Refine: 30 sequential calls × 5 seconds = 150 seconds. Map-reduce is about 7 times faster. Token cost is nearly the same: both read about 90,000 chunk tokens plus about 7,500 tokens of summaries, and both write about 7,500 tokens of summaries, plus a final summary for map-reduce.
Exercise
Your map-reduce job fails often with rate-limit errors when you send all 60 map calls at once. Name two changes that fix this without changing the summaries.
Show answer
Run the map calls through a bounded worker pool (for example 5 to 10 workers) instead of all at once, and retry failed calls with a growing delay between attempts. Both leave the prompts and chunks unchanged, so the summaries stay the same.