Million-Token Context: Compute Costs and KV Cache Practicality
A million-token context window is useful only if inference costs, KV cache memory, and long-range retrieval remain manageable. This article examines the compute and cache bottlenecks, architectural approaches to reducing them, and application-level practices for retrieval, prompt caching, request budgeting, and evaluation. It also explains how to assess long-context systems through latency, memory, and quality curves rather than maximum window size alone.
Why Fitting a Million Tokens Is Not Enough
As models rely on longer reasoning sequences, cross-document retrieval, and multi-step decisions, inference compute requirements rise quickly. Standard self-attention has approximately quadratic computational complexity over a full sequence. During autoregressive decoding, each new token must access a large set of historical keys and values. Expanding context from tens of thousands to a million tokens increases both per-token computation and memory-bandwidth demands, making latency and cost harder to manage.
KV cache growth creates a less visible constraint. Autoregressive decoding stores the keys and values of previous tokens at every layer. As sequences grow, this cache can exhaust GPU memory before model parameters do. It also complicates scheduling, increases cache swapping, and contributes to memory fragmentation.
The engineering question is therefore not simply how large a context window a model advertises. It is whether computation remains affordable, the cache can stay resident in memory, and long-range dependencies remain reliable at that length.
Two Hard Bottlenecks
Compute. In standard attention, each query is compared with all historical keys, then used to compute a weighted combination of their values. A tenfold increase in sequence length produces roughly a tenfold increase in historical access per decoding step. Longer reasoning sequences, tool responses, and concatenated documents can make the effective context much larger than the user’s visible question. Adding more GPU capacity alone offers diminishing returns against the quadratic cost of processing the full sequence.
Cache. KV data is stored by layer, attention head, and token. At a million tokens, the cache can reach tens to hundreds of gigabytes, depending on model dimensions, numerical precision, and parallel partitioning. It competes with activations and communication buffers, reducing concurrency. Prefix-cache reuse also becomes sensitive to prompt changes: modifying an early part of the prompt can invalidate the cached prefix from that point onward.
Practical usability comes down to three measurements:
- How quickly incremental cost per token rises with context length.
- How much concurrency and context length a given amount of GPU memory can support.
- Whether retrieval of information from the middle and later portions of long documents remains reliable.
Maximum context length alone can substantially overstate real serving throughput.
Architectural Approaches to Reducing the Pressure
Long-context architectures do not simply extend the same attention mechanism indefinitely. Instead, they assign different densities of historical access to different layers and positions. The following approaches can be combined and do not depend on proprietary model terminology.
Hybrid Attention
Most layers use compressed or sparse historical access, while a smaller number retain denser global or sliding-window attention to preserve important dependencies.
The principle is that not every token needs an equally precise view of the entire history. Compressed layers condense distant information into retrievable summary states, while dense layers provide fine-grained alignment locally and at important positions.
This can reduce both per-step FLOPs and the KV data that must be materialized, rather than merely truncating the context at serving time.
KV Representation Compression
Lower-precision caches, sharing across attention heads, blockwise merging of adjacent tokens’ keys and values, and retaining only entries likely to be accessed by later queries can all reduce cache size.
The trade-offs include information loss and additional indexing overhead. Evaluation should consider compression ratio, reconstruction error, and quality degradation across retrieval, coding, and long-conversation tasks—not just a single compression figure.
Sparse and Sliding-Window Attention
Local windows work well for tasks with strong locality. Global sparsity works well when a small set of hub tokens connects information across the document.
However, fixed, content-independent sparse patterns can miss unexpected long-distance references. A more robust approach is to use learnable sparsity or block-level routing while keeping a small number of global tokens continuously accessible, such as section headings or system constraints.
Training Stability
Starting training directly with million-token sequences can destabilize gradient variance, loss scaling, and positional-encoding extrapolation.
Common practices include progressively increasing sequence length, stabilizing optimization on short and medium sequences first, and then introducing longer sequences and compression modules. Auxiliary losses on compression paths can help prevent the main objective from rewarding only short-range patterns.
The ability to run inference at a given length does not establish that the model’s representations are well aligned at that length.
These techniques reduce the rate at which costs grow; they do not eliminate costs. More aggressive compression makes high-precision paths especially important for tasks that require exact comparison, such as contract clauses, code diffs, and tables.
Making Long Context Reliable at the Application Layer
A model’s context window is an upper limit. The task should determine what actually enters it.
Retrieve first, then read closely. Keep the knowledge base in object storage or a retrieval engine. Retrieve a small set of highly relevant passages for each question before sending them to the model. A million-token window is useful for cases where retrieval alone is insufficient and reasoning must span many passages. It should not replace an index.
Use layered context. Keep system constraints and the current objective in a retained section. Maintain rolling summaries of conversation history. Assign block identifiers to source documents and expand only the blocks referenced by the current reasoning step. This uses the long window without replaying the entire document every turn.
Structure prompts for cache reuse. Separate stable prefixes—roles, tool descriptions, and fixed rules—from changing suffixes. This improves prefix-cache hit rates. Frequent changes to system prompts can erase much of the benefit of KV reuse.
Set budgets and fallback behavior. Define token budgets and timeouts for individual requests. When a request exceeds its budget, discard low-relevance blocks or shorten the reasoning sequence rather than failing silently. Monitor input length, output length, cache hit rate, and tail latency separately.
Evaluate against the real workload. Needle-in-a-haystack tests demonstrate addressability, not multi-hop reasoning. Include matched tests with information at the beginning, middle, and end; tasks requiring multiple pieces of evidence; and versions containing distracting passages. Measure cost curves at 32K, 128K, and lengths approaching the maximum window. Record both quality and cost per task rather than optimizing scores alone.
The following request-budget pseudocode illustrates the control flow:
budget = max_context - reserve_for_outputprefix = stable_system_and_toolsrecalled = retrieve(query, top_k)body = pack_until(recalled, budget - len(prefix))if overflow(body):body = summarize_or_drop_lowest_score(body)call_model(prefix + body + user_turn)
Cost Modeling: Measure Growth, Not Claims
A rough cost model has three parts:
- Prefill: Processing the long input once.
- Decoding: Accessing the KV cache at each generation step.
- Cache residency: Holding each sequence’s cache in memory, multiplied by the number of concurrent sequences.
Prefill is heavily affected by compute and bandwidth. Decoding with a long cache often becomes bandwidth-bound. Cache residency determines how many requests can run concurrently.
If hybrid attention and KV compression are effective, per-token latency and memory per sequence should grow substantially more slowly with context length than the roughly linear growth expected for standard dense-attention decoding and KV storage.
At the serving layer, long requests should use separate pools from short requests. Otherwise, million-token contexts can dominate batches and increase queueing time for all users.
Logs and alerts should also be grouped by context-length range. Aggregate averages can hide expensive tail behavior. For cloud container platforms and inference services, autoscaling metrics should include KV memory usage and queue wait time, not just GPU utilization. High utilization may simply reflect repeated scanning of very long histories rather than efficient execution.
Deployment Checklist
- Does the task genuinely require nearly a million tokens to be visible at once, or would retrieval and summarization suffice?
- Have context-length curves been measured for latency, memory usage, and task quality?
- Can critical facts still be traced to their original locations when compression or sparse attention is used?
- Is the prompt prefix stable, is output capacity reserved, and is fallback behavior explicit when limits are exceeded?
- If training or fine-tuning uses long sequences, have loss behavior and positional extrapolation been revalidated at the target length?
Million-token context can reduce manual document slicing for cross-document reasoning and long-running tasks. Its cost is that compute, cache capacity, and stability must be designed together.
Treating window size as capability itself risks both excessive bills and unreliable answers. Making retrieval, compression, budgeting, and length-specific evaluation standard practice is what turns a long-context demonstration into a usable system.
