KV Cache Optimization: The Key to Cutting LLM Inference Costs
This article explains why large language model inference costs are not fixed, breaking down the prefill and decode phases and showing how KV Cache reduces repeated computation in autoregressive generation. It covers how to estimate KV Cache memory usage, why high prefix cache hit rates lower unit costs, and a practical list of general optimization techniques including prefix caching, paged cache management, quantization, batching, and observability, along with engineering recommendations for capacity planning.
1. What Price Cuts Reveal About the Real Cost of Inference
A recent trend of sustained price reductions for some large model services has sparked wide discussion. Setting aside the marketing angle, the point developers should focus on is that the unit cost of LLM inference is not fixed. It is determined jointly by compute, GPU memory, memory bandwidth, and cache reuse rate. Understanding these variables is what enables sound decisions about architecture selection, prompt design, and capacity planning.
The cost of a single text generation request can be roughly split into two parts: the prefill phase (processing the input prompt, compute-intensive) and the decode phase (generating tokens one by one, memory-bandwidth-intensive). In the decode phase, every generated token requires re-reading the key and value tensors of all prior context from GPU memory. The longer the context and the higher the concurrency, the greater the memory bandwidth pressure. Whoever turns “repeated reads” into “compute once, reuse many times” can significantly reduce the cost per token.
2. KV Cache: The Memory Optimization Foundation of Autoregressive Generation
When a Transformer generates text, it does so autoregressively: it produces one token at a time, appends it to the sequence, and then generates the next. In the attention mechanism, each token produces three vectors: Q (query), K (key), and V (value). Without caching, when the second step processes “today the weather is”, the K and V of the first three tokens are recomputed in full, even though they are identical to the first step. This is purely redundant computation.
The idea behind KV Cache is that after each new token is computed, its K and V are written to GPU memory. Subsequent inference reads the cached history directly, computes Q, K, and V only for the newest token, scores attention between the new Q and all cached K, and then weights the cached V. The per-step computation drops from “processing the entire sequence” to “processing a single token,” which is the root of improved inference throughput.
Illustrative pseudocode:
# Without cache: recompute the full sequence at every stepfor step in range(max_len):q, k, v = model(tokens) # tokens keeps growing in lengthnext_token = sample(q[:, -1], k, v)# With cache: reuse historical K/Vcache = empty_kv_cache()for step in range(max_len):q, k, v = model(last_token, cache) # compute only the new tokencache.append(k, v) # append to the cachelast_token = sample(q, k, v)
3. Quantifying Memory Usage: Making the Bottleneck Measurable
KV Cache size ≈ 2 × number of layers × number of heads × dimension per head × sequence length × bytes per value of precision. Take 32 layers, 32 heads, a per-head dimension of 128, and FP16 (2 bytes) as an example: per token per layer is 2 × 32 × 128 × 2 = 16384 bytes, or 16 KB. At a sequence length of 4096, that is roughly 16 KB × 32 × 4096 ≈ 2 GB. With 10 concurrent requests, it is about 20 GB. As this shows, in long-context, high-concurrency scenarios the cache can consume more GPU memory than the weights themselves, directly determining the maximum concurrency the system can support.
4. Why a High Cache Hit Rate Cuts Costs Substantially
When a large number of requests share the same prefix (system prompts, templates, long documents, code context), the K and V of that prefix need to be computed only once and can be reused across requests, pushing the hit rate close to saturation. At that point, the marginal cost of a new request is mainly the memory access overhead of the decode phase, so the unit cost drops significantly. It is worth emphasizing that this is a benefit of a general industry technique, not an exclusive metric of any particular service.
5. A Checklist of General Optimization Techniques
- Prefix Caching: content-addressed reuse of common prefixes. The hit rate depends on prefix stability, so place variable fields as late as possible in the prompt.
- Paged cache management: split the cache into fixed-size blocks to reduce fragmentation and reserved waste, improving GPU memory utilization.
- Cache quantization and sparsification: store K and V at lower precision, or prune by attention importance, trading a small amount of precision for capacity.
- Batching and scheduling: continuous batching interleaves long and short requests to improve compute utilization in the decode phase.
- Architecture-level optimization: designs such as multi-query and grouped-query attention compress the cache size at the source.
- Observability: use monitoring, alerting, and logging services to track hit rate, memory watermark, and time to first token, forming a capacity feedback loop.
6. Engineering Recommendations
Start by measuring the share of common prefixes and the average context length on the business side, then use these to estimate cache size and the concurrency ceiling. Place stable content first and dynamic content last to improve reuse rate. For long-document scenarios, evaluate the precision loss of quantization approaches. Finally, use load testing to validate the real curves of throughput and cost. With the general-purpose container platforms, object storage, and monitoring and alerting capabilities offered by platforms such as Baidu AI Cloud, the optimizations above are easier to turn into reusable engineering standards.
