Reducing LLM Inference Costs: KV Cache and Architecture Optimization

    This article explores practical approaches to reducing Large Language Model (LLM) inference costs in production environments. It breaks down inference costs between the prefill and decode phases, examines the role of sparse activation and asymmetric computation in Mixture of Experts (MoE) architectures, and details effective KV cache compression techniques. Understanding these optimization strategies helps teams manage memory bandwidth, improve resource utilization, and lower the cost per request.

    1. Background: Why Inference Cost is a Key Metric

    Once large models move from experimentation to production, training costs become a one-time expense, while inference costs grow continuously with request volume. Every conversation, every tool call, and every document analysis consumes compute resources, memory, and storage. For long-running services, inference costs typically account for the majority of the total cost of ownership. Therefore, reducing the cost per request has become a shared priority for both model serving and business teams.

    Cost reduction generally focuses on three directions: reducing the computation required per request, minimizing the memory and cache usage per request, and improving resource utilization. These three factors are interdependent. For example, if cache usage decreases, a single accelerator card can handle more concurrent requests, which in turn lowers the unit cost.

    2. Composition of Inference Costs

    An LLM request generally consists of two phases:

    Prefill phase: The model processes all input tokens at once and generates Keys and Values for the attention calculation in each layer. This phase is computationally intensive but can be highly parallelized.

    Decode phase: The model generates output tokens one by one. For every token generated, it must read the previously accumulated KV cache. This phase is typically constrained by memory bandwidth rather than compute power.

    Therefore, the input length primarily affects the prefill duration, while the output length and concurrency level primarily affect memory usage and latency during the decode phase. Understanding this distinction is crucial for identifying which part of the process requires optimization.

    3. Sparse Activation and Asymmetric Computation

    3.1 Basic Concept of Sparse Activation

    The Mixture of Experts (MoE) architecture splits the feed-forward network into multiple expert subnetworks, with a routing module selecting only a few experts for each token to participate in the computation. The total parameter count of the model can be very large, but the parameters actually involved in the computation for a single token represent only a small fraction. This approach preserves the expressive capacity of a large model while reducing the computational overhead of a single inference.

    When using sparse activation, three metrics require attention. The total parameter count determines storage and loading costs. The activated parameter count per token determines the compute cost. The degree of expert load balancing determines the efficiency of multi-card parallelism. If routing is overly concentrated on a few experts, some devices will become bottlenecks, and actual throughput will fall below the theoretical value.

    3.2 Asymmetric Allocation for Input and Output

    During inference, the computational characteristics of the input side and the output side differ. Input tokens can be processed in parallel batches, whereas output tokens must be generated one by one. Consequently, some architectures adopt different computational allocation strategies for both sides, making input processing more lightweight while reserving more compute budget for output generation. The core of this design is allocating resources by phase rather than using a uniform compute budget for all tokens.

    When evaluating such designs, input activation volume and output activation volume should be measured separately, and the average cost should be calculated based on the actual input-output ratio of the business. Tasks with long inputs and short outputs (e.g., document retrieval Q&A) and tasks with short inputs and long outputs (e.g., code generation) have very different cost structures and cannot be estimated using the same coefficient.

    4. KV Cache Compression

    4.1 Why KV Cache is a Memory Bottleneck

    The attention mechanism requires saving the Keys and Values of historical tokens during decoding. The cache size is proportional to the number of layers, the number of KV heads, the dimension per head, the context length, and the concurrency level. The longer the context and the higher the concurrency, the faster the cache footprint grows.

    The following example estimates the KV cache size under a set of hypothetical parameters to illustrate the scale:

    1. def kv_cache_bytes(num_layers, num_kv_heads, head_dim,
    2. seq_len, batch_size, dtype_bytes=2):
    3. """Estimate the number of bytes occupied by the KV cache. The coefficient 2 indicates that Key and Value are stored separately."""
    4. return (2 * num_layers * num_kv_heads * head_dim
    5. * seq_len * batch_size * dtype_bytes)
    6. if __name__ == "__main__":
    7. # Assumed parameters: 60 layers, 8 KV heads, head dimension 128, context 32K, concurrency 4, FP16 storage
    8. size = kv_cache_bytes(num_layers=60, num_kv_heads=8, head_dim=128,
    9. seq_len=32768, batch_size=4, dtype_bytes=2)
    10. print(f"KV cache is approximately {size / 1024**3:.2f} GiB")

    The result is approximately 30 GiB. The cache for just a single group of requests consumes a significant amount of memory, which explains why long-context services often require multi-card deployment or rely on tiered storage to offload part of the cache.

    4.2 Common Compression Methods

    Common KV cache optimization techniques in the industry include the following categories:

    • Reducing the number of KV heads: Such as Grouped-Query Attention (GQA) or Multi-Query Attention (MQA), where multiple query heads share fewer key-value heads.
    • Cache quantization: Storing KV values from FP16 to INT8 or FP8. This can theoretically halve the footprint or more, but the impact on accuracy must be evaluated.
    • Cache eviction and sliding window: Retaining only the cache of the most recent or most important tokens, suitable for tasks with weak dependencies on distant information.
    • Tiered storage: Migrating cold data from high-bandwidth memory to host RAM or local solid-state drives and loading it on demand.

    Each method has its trade-offs. Quantization may introduce accuracy loss, sliding windows may lose long-distance information, and tiered storage increases loading latency. When choosing a method, business metrics (accuracy, time-to-first-token, throughput) should be the primary criteria, rather than just the memory saving ratio.

    4.3 Estimating the Benefits

    The benefits of compression can be estimated using a simple formula:

    Effective concurrency ≈ Available cache memory ÷ Cache usage per request

    If the cache footprint is reduced to a quarter of its original size, the theoretical concurrency under the same memory capacity increases by about four times. The actual improvement will be lower than the theoretical value because model weights, activation values, and runtime overhead also consume memory, and scheduling efficiency does not scale linearly. Pre-launch decisions should be based on stress-test data.

    5. Cache Hits in Agent Scenarios

    Agent applications typically invoke the model over multiple rounds, with each round carrying system instructions, tool definitions, historical conversations, and intermediate results. These contents contain significant overlap, making efficient cache management particularly relevant for optimizing performance and reducing costs in such scenarios.