KV Cache Explained: The Core of Reducing LLM Inference Costs

    This article breaks down how KV Cache works and why it is central to lowering large language model inference costs. It explains the cost structure of inference, why autoregressive generation repeats computation, how caching Key and Value vectors turns quadratic complexity into linear, how to estimate KV Cache memory usage, and what drives a high cache hit rate. Developers will find practical guidance on measuring effective token costs and organizing prompts to maximize cache reuse.

    1. What Price Cuts Reveal About Inference Cost Structure

    A cloud provider recently made a permanent price cut to one quarter of the previous rate for its large model inference service, sparking broad discussion in the developer community. What often delivers the real sense of “drastically lower cost” is not the list price alone, but a large improvement in cache hit rate during actual calls. When repeated prefixes are reused efficiently, the number of billable effective tokens drops significantly, and the experienced cost can be far below the nominal unit price.

    To understand this, you first need to see how inference cost is composed. The cost of a single request comes mainly from two parts: the floating-point operations of matrix multiplications, and memory usage plus data movement. Both are directly tied to whether historical tokens need to be recomputed. So the key lever for reducing inference cost largely comes down to the design of KV Cache and the efficiency of cache hits.

    2. Why Autoregressive Generation Repeats Computation

    Text generation is an autoregressive process: the model produces one token at a time, appends it to the end of the sequence, and then generates the next.

    1. Step 1: input [Today weather] -> output is
    2. Step 2: input [Today weather is] -> output good
    3. Step 3: input [Today weather is good] -> output ...

    In the attention mechanism, every token produces three vectors: Q (Query), K (Key), and V (Value). The problem is that in Step 2, the K and V of the first three tokens were already computed in Step 1 and are exactly the same, yet they are computed again. The longer the sequence, the worse this repeated waste becomes, and the overall complexity grows quadratically.

    3. How KV Cache Works

    The core idea is straightforward: each time a new token is generated, write its K and V into a memory cache. In later inference, the K and V of historical tokens are read directly from the cache; only the newest token has its Q, K, and V fully computed. The new Q is then used with all cached K to compute attention scores, which weight the cached V.

    This reduces the per-step computation from “processing the entire sequence” to “processing a single token,” lowering complexity from quadratic to linear. This is also the fundamental reason why long-text inference has seen a qualitative leap in speed.

    It is important to stress that cache correctness depends on an “exact prefix match.” Once any change occurs in the request prefix, the cache at the corresponding position becomes invalid and must be recomputed. This directly raises the issue of hit rate.

    4. How to Estimate Memory Usage

    The size of KV Cache can be estimated with a general formula:

    1. KV Cache = 2 × num_layers × num_heads × head_dim × seq_len × bytes_per_value

    For 32 layers, 32 heads, a head dimension of 128, a sequence length of 4096, and FP16 (2 bytes):

    1. Per layer per token: 2 × 32 × 128 × 2 = 16384 bytes = 16 KB
    2. Total: 16 KB × 32 layers × 4096 tokens ≈ 2 GB
    3. With a batch size of 10, about 20 GB

    As this shows, in long-text, high-concurrency scenarios, KV Cache can consume more memory than the model parameters themselves and become a throughput bottleneck. In engineering practice, this is usually mitigated by quantizing cache precision, paged memory management, and prefix sharing.

    5. Where a High Hit Rate Comes From

    A high hit rate is not accidental but the combined result of system design. Common practices include:

    • Prefix stabilization: place and fix invariant content such as system prompts, examples, and documents at the front so the shared prefix can be reused;
    • Cache paging and sharing: manage the cache in page blocks and let multiple requests share the same prefix;
    • Request scheduling affinity: route requests with the same prefix to the same instance to reduce cache invalidation;
    • Context structure optimization: place volatile content at the end to avoid polluting the shared prefix.

    For developers, the actionable advice is to fix prompt templates, reduce meaningless dynamic concatenation, and organize long documents in a sensible order.

    6. Practical Advice and Summary

    In response to price changes, the rational approach is to evaluate real cost from the perspective of “effective tokens”: first measure the cache hit rate of your own workload, then optimize the architecture with memory estimation and batching strategies. In general-purpose inference services on platforms such as Baidu AI Cloud, general capabilities like log services, monitoring and alerting, and container platforms can help locate hit-rate and memory bottlenecks. Ultimately, only by understanding KV Cache can you turn the benefits of a cost-reduction cycle into real business gains.