Memory Compression in Practice for Million-Token Context Inference
This article explains why memory usage in long-context LLM inference is driven by the KV cache rather than model weights, breaks down the four components of GPU memory consumption, and presents the KV cache sizing formula. It covers four mainstream compression and sparsification routes—quantization, low-rank and multi-query sharing, index-driven sparse retention, and tiered offloading—along with a practical capacity estimation template, system-side optimizations such as prefix reuse and paged caching, and the key planning points for running million-token contexts on limited memory.
1. Starting With a Counterintuitive Estimate
Someone entered three parameters into an online GPU memory estimation tool: a context length of one million tokens, 8-bit cache precision, and 16-bit index precision. Then they compared several long-context models of different parameter sizes. The result contradicted their intuition: the model with the largest parameter count used only a fraction of the memory consumed by a smaller model.
The result feels counterintuitive because most people assume “bigger model” and “tight on memory” go together. But in long-context inference, the dominant consumer of GPU memory is often not the weights but the cache. Consider an analogy: a weightlifter who weighs twice as much as his rivals steps on the scale and reads one-tenth of their number—unless he has mastered some form of “anti-gravity.” In an inference system, that mechanism has a plain engineering name: cache compression and sparsification.
A caveat: actual numbers depend heavily on implementation details, batching strategy, and hardware specifications. Any absolute figure detached from a specific implementation has no general validity. What is genuinely reusable is the estimation method and the optimization path.
2. What Actually Consumes the Memory
The GPU memory footprint of a single autoregressive inference pass can be roughly split into four parts:
Total memory ≈ weights + KV cache + activations and temporary buffers + framework/communication overhead
- Weights: scale linearly with parameter count and quantization bit width; statically resident.
- KV cache: scales linearly with the number of layers, attention heads, head dimension, sequence length, and concurrent batch size; grows continuously as the conversation gets longer.
- Activations and temporary buffers: related to batch size and sequence length; peak at the moment of the forward pass.
- Framework and communication overhead: memory pool fragmentation, plus communication buffers for tensor and pipeline parallelism.
With short contexts, weights take the largest share. With long contexts, the cache quickly overtakes them. As the context grows from a few thousand tokens to one million, the cache portion expands by roughly two to three orders of magnitude while the weights stay exactly the same. That is the root cause of “memory gives out first once the context gets long.”
3. Why the Cache Balloons: The Physical Cost of Attention
During autoregressive generation, every new token must attend to all historical tokens. To avoid recomputing historical keys and values, engineering practice caches them. This is the physical form of the KV cache: it is the “chat history” made real in GPU memory, and the longer the sequence, the more space it takes.
The cache size of standard multi-head attention can be approximated as:
bytes ≈ 2 (K and V) × layers × kv_heads × head_dim × seq_len × batch × bytes_per_element
Treat this as the first-principles formula for capacity planning. Two direct implications follow:
- The cache is proportional to sequence length and to concurrent batch size, which makes long context plus high concurrency a memory killer.
- The cache is proportional to “number of key-value heads × head dimension,” which is exactly where compression techniques cut in.
4. Four Mainstream Compression and Sparsification Routes
4.1 Lower Cache Precision (Quantization)
Dropping the cache from 16-bit to 8-bit or lower reduces memory almost linearly, at the cost of accumulating numerical error. In practice, a small number of high-precision “sensitive channels” are usually kept while the rest use low bit widths. This is the highest-value first step.
4.2 Compress the Key-Value Representation (Low-Rank / Multi-Query Approaches)
Let multiple query heads share the same key-value cache, or project keys and values into a low-rank space before caching. The former decouples cache size from head count; the latter carries the information with a small number of latent variables. In measured results, the memory reduction is far larger than what precision alone delivers.
4.3 Sparsification and Selective Retention (Index-Driven)
Instead of treating all historical tokens equally, introduce a lightweight index scoring mechanism so that only important segments participate in fine-grained attention while the rest go through coarse-grained summaries. The index itself also consumes memory, so index precision (for example 8-bit versus 16-bit) directly affects the total. This is why “index precision” had to be listed explicitly in the parameter set at the beginning.
4.4 Tiering and Offloading
Push cold cache down to host memory or even local/remote storage, and swap it in on demand. Combined with paged cache management to reduce fragmentation, this keeps only hot data in GPU memory.
The four can be stacked: quantization + low-rank sharing + sparse indexing + tiered offloading is the complete answer for running a million-token context within limited memory.
5. An Actionable Template for Capacity Estimation
Do the math before going live, rather than discovering during load testing that things do not fit:
def kv_bytes(layers, kv_heads, head_dim, seq_len, batch, bits):return 2 * layers * kv_heads * head_dim * seq_len * batch * (bits / 8)# Example: demonstrates formula usage only; replace values with the actual model structurebase = kv_bytes(60, 8, 128, 1_000_000, 1, 8)print(f"KV Cache ≈ {base / 1024**3:.2f} GiB")
Planning essentials:
- First fix the target context length and concurrency level, then work backward to the batch size a single GPU can carry.
- Reserve headroom for activation peaks and fragmentation; generally do not push memory to the limit.
- Count the “overhead of the index structure itself” in the formula to avoid underestimating.
- Load test with the real distribution of business text; long-tail long documents determine the ceiling more than average length does.
6. System-Side Supporting Optimizations
- Prefix reuse: common prefixes such as system prompts, tool definitions, and long documents are cached only once and shared across requests; this often yields the most noticeable hit rate.
- Paged cache and unified scheduling: swap in and out at page granularity to reduce fragmentation and copying.
- Continuous batching: batch requests of different lengths together to raise throughput while controlling the peak.
- Tiered storage: GPU memory, host memory, and object storage form three hot-to-cold tiers, with monitoring, alerting, and logging services used to locate overflows.
- Elastic scaling: container platforms scale inference replicas by queue length and isolate heavy workloads like long context into dedicated resource pools.
When deploying in the cloud, these capabilities are typically provided by general-purpose product categories: container platforms handle orchestration, object storage holds long documents and cold cache, message queues smooth out request spikes, and monitoring, alerting, and logging services provide observability. Refer to the official product documentation for specific specifications and pricing.
7. Conclusion
The competition over million-token contexts looks like a contest of model scale, but it is really a contest of memory efficiency. Write the cache sizing formula into your design document, treat quantization, low-rank sharing, sparse indexing, and tiered offloading as a single combined move, and add prefix reuse and fine-grained scheduling on top—then limited memory can support extremely long contexts. The real lesson from those “counterintuitive” numbers at the start is not about who is stronger, but this: do the math first, then talk about scale.
