Local Long-Context Deployment: Measuring and Compressing the KV Cache
This guide explains how the key-value (KV) cache grows with context length during local large language model inference. It shows how to estimate the cache size from model parameters, describes KV cache compression methods and their limits, and covers how to enable compression, measure peak memory, speed, output quality, and stability, and troubleshoot common problems.
1. Why Long Context Consumes Memory
Memory use during model inference has two parts: the model weights and the KV cache. Once loaded, the weights have a fixed size, and quantization can reduce it. The KV cache grows with context length. When the model generates each new token, it stores the Key and Value vectors of every previous token at every layer. It reads these vectors repeatedly when computing attention. Increasing the context from 4K to 128K increases the cache by about 32 times.
With short conversations, the cache is small and barely noticeable. It grows quickly when you read long documents, run multi-turn conversations, or analyze codebases. On unified memory devices, the CPU and GPU share the same memory. The operating system, model weights, KV cache, and other programs compete for that memory. When memory runs short, programs often crash or report an OOM (out-of-memory) error.
2. Estimate Your KV Cache Size First
Use this formula:
KV cache bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element
The factor of 2 accounts for storing both Key and Value. In models that use grouped-query attention (GQA), the number of KV heads is usually smaller than the number of attention heads. Use the value from the model’s configuration file. Each element takes 2 bytes at FP16 and 1 byte at 8-bit precision.
Here is a hypothetical example. A model has 60 layers, 8 KV heads, and a head dimension of 128, and it stores the cache in FP16. Each token uses 2 × 60 × 8 × 128 × 2 = 245,760 bytes, or about 240 KiB. At a 128K context (131,072 tokens), the total cache is about 240 KiB × 131,072 ≈ 30 GiB. This figure excludes the weights and runtime overhead. It only demonstrates the calculation, so substitute the actual parameters of your own model.
3. Compression Approaches: Principles and Limits
The traditional approach uses block-wise quantization, with formats such as Q4_0 and Q8_0. Each data block stores its own scaling parameters. These formats usually compress the cache by 2 to 4 times, and the error varies with block size and data distribution.
A newer approach aims to store the KV cache at a lower bit-width while keeping attention computation accurate. In general, it first applies a random orthogonal rotation to the vectors, which spreads values more evenly across dimensions. Then it quantizes the values to a low bit-width. These methods do not need to store extra scaling parameters for each small block, so the metadata overhead is small.
Keep these points in mind:
- The names, implementation details, and source papers of specific algorithms should be checked against the official framework documentation or the original papers. This article does not expand on unverified details.
- Going from 16-bit to 3-bit gives a theoretical compression ratio of about 5.3 times. The actual ratio is lower because of metadata, layers that keep higher precision, and the implementation.
- Compression and decompression require extra computation, so generation speed may drop. The amount depends on hardware and context length.
- At short context lengths, the cache is small, so savings are limited. The savings become clear beyond 32K.
4. Enable Compression: Configuration
Inference frameworks enable this feature in different ways, and parameter names may change between versions. The following illustrative configuration shows which settings to adjust. Check your framework’s documentation for the exact parameter names:
[context]max_length = 131072 # Target maximum context lengthkv_cache_quant = true # Enable KV cache quantizationkv_cache_bitwidth = 3 # Quantization bit-width, common values are 4, 3, and 2
After you enable compression, check three things. First, look in the startup logs for messages showing that the KV cache compression module loaded. If no such messages appear, the feature may not be active. Second, check whether the log reports the estimated memory use after compression, and compare it with your estimate from Section 2. Third, run inference on a real long document and observe peak memory. Do not rely only on the number reported at startup.
5. Verify the Results
Memory use alone does not show whether compression works. After compression, measure at least these four metrics:
- Peak memory: the highest memory use during inference, not the usage at startup.
- Generation speed: output tokens per second and time to first token. The change in first-token latency is especially visible with long contexts.
- Output quality: compare results before and after compression on the same tasks. You can calculate perplexity (PPL) or spot-check accuracy on summarization, question answering, and code modification.
- Stability: during long multi-turn conversations or long runs, check for abnormal output, crashes, or memory use that keeps growing.
During testing, keep the model, quantization method, prompts, and hardware the same. Repeat each test group at least a few times. Record the results in the following format, using your own measured values rather than impressions:
- Context length:
- Peak memory without compression:
- Peak memory with compression:
- Change in generation speed:
- Quality spot-check results:
6. Common Problems and Troubleshooting
- Unsupported version: Older framework versions may not include this feature. Upgrade to the latest stable release, or check the changelog.
- Changed parameter names: If the configuration has no effect, check the parameter names against the documentation for your current version.
- No compression module in the logs: Confirm that the switch is actually enabled. Some frameworks require a service restart after configuration changes.
- Still running out of memory: First check whether the weights take up too much memory. Then consider shortening the context or reducing concurrency. Weight quantization also lowers memory use, but it affects model quality, so evaluate it separately.
- Lower output quality: First raise the bit-width, for example from 3-bit to 4-bit, and test again. If the problem persists, disable compression.
7. Rollback and Usage Recommendations
If your daily context stays within 16K, enabling compression is usually unnecessary. Enable it and test it when you work with documents or conversations longer than 64K. After each framework upgrade or model change, rerun the quality and memory tests.
Rollback is simple. Turn off the compression switch to restore the original behavior. Before you enable compression, save a baseline of results without compression so you can compare against it if problems appear.
8. Summary
The KV cache grows linearly with context length, and that growth is the main bottleneck for long-context inference. First estimate your model’s cache size with the formula, then decide whether compression is needed. The benefit of compression depends on the model architecture, framework version, bit-width, and hardware, so do not rely on a single number. Following the estimation and testing steps in this article helps you find the maximum usable context length within your available memory.
