Saving VRAM in Long-Context Inference: KV Cache and Attention Architecture Selection

    As long-context capabilities transition from a promotional metric into a hard constraint for production LLM deployments, managing VRAM consumption has become critical. Chain-of-thought reasoning and agentic tool calls rapidly extend context length, leading to degraded throughput and latency. This article examines the cost origins of the KV cache, evaluates the roles and limitations of Grouped-Query Attention (GQA), cross-layer KV sharing, and Mixture-of-Experts (MoE) architectures, and provides practical checkpoints for architectural selection.

    Long-context capability has evolved from a promotional parameter into a hard constraint for production deployments. The chain-of-thought output from reasoning models and the accumulated history from agentic tool calls both cause context length to expand rapidly. Longer contexts require the model to store more intermediate states during inference, which subsequently degrades VRAM usage, throughput, and latency. Starting with the cost origins of the KV cache, this article introduces the roles and limitations of Grouped-Query Attention, cross-layer KV sharing, and Mixture-of-Experts (MoE) with sparse attention, concluding with the conditions to verify during architecture selection.

    1. Why the KV Cache Becomes a Bottleneck

    When a large language model generates text, every Transformer layer must save Key and Value vectors for each processed token. These vectors are collectively referred to as the KV cache. During the decoding phase, for every new token generated, the model must read the entire history of the KV cache to participate in attention calculations. Therefore, the cache consumes both VRAM and memory bandwidth.

    The size of the KV cache can be estimated using a formula: the number of bytes occupied by a single token equals 2 × number of layers × number of KV heads × dimension per head × bytes per value. Multiplying this by the context length and the number of concurrent requests yields the total footprint.

    A hypothetical configuration illustrates the scale of this issue. Suppose a model has 32 layers, 32 KV heads, a dimension of 128 per head, and uses FP16 storage. A single token would occupy approximately 512KB. For a single request with a 4K context, the KV cache is about 2GB; when extended to 128K, it reaches about 64GB. These figures are illustrative values calculated based on the formula and do not represent the measured results of any specific model. Actual values depend on the model structure, numerical precision, and the inference framework’s memory management.

    Online services typically handle many requests simultaneously, causing the total cache to multiply with concurrency. Once VRAM is filled by the cache, the server can only reduce the number of concurrently processed requests. Throughput drops, queuing time increases, and the cost per request rises accordingly.

    The growth patterns of compute and storage also differ. In the prefill phase, the compute volume of full attention grows approximately with the square of the context length. In the decoding phase, the volume of historical KV that needs to be read at each step grows approximately linearly with the context length. Therefore, optimization designs must separately address compute and storage.

    2. Grouped-Query Attention: Reducing KV Heads

    In standard Multi-Head Attention (MHA), each query head is paired with an independent Key head and Value head, meaning the KV cache size is directly correlated with the number of attention heads. Multi-Query Attention (MQA) allows all query heads to share a single set of KV heads, resulting in the smallest cache, but each query head has fewer information patterns available, leading to noticeable quality degradation. Grouped-Query Attention (GQA) sits between the two: it divides the query heads into several groups, with each group sharing a pair of KV heads.

    Scheme Number of KV Heads KV Cache Footprint (Relative to MHA) Representation Diversity Applicable Scenarios & Notes
    MHA Same as query heads 1x Highest Quality baseline, highest VRAM pressure
    GQA Fewer than query heads (e.g., 32 query heads with 8 KV heads) ~1/4 of MHA High, close to MHA Common choice for mainstream models; verify inference engine support
    MQA 1 Varies by heads, ~1/32 for 32 heads Lower Most cache-efficient; requires separate validation for quality-sensitive tasks

    The actual benefits of GQA also depend on whether the inference engine can efficiently execute grouped attention. Once the model structure is defined, the number of KV heads is fixed and cannot be arbitrarily changed via configuration during deployment. When selecting a model, first check the number of KV heads in the model’s configuration file, and then verify the version and kernel implementation of the inference engine being used.

    3. Cross-Layer KV Sharing: Adjacent Layers Share Cache

    The attention representations of adjacent Transformer layers are often quite similar. This provides an intuitive optimization approach: deeper layers do not need to regenerate all KV pairs but can directly reference the results already computed by shallower layers. Cross-layer KV sharing is designed based on this concept; related methods have been studied academically and have begun to be implemented in open-source models in recent years.

    A common approach is to divide the model into several layer groups. Within a group, only a subset of layers generates the KV cache, while the remaining layers directly read from it. The more layers that share, the less KV needs to be stored. Theoretically, if every two layers share a set of KV, the cache is roughly halved; if every four layers share a set, it drops to about a quarter. Since reused layers no longer execute the corresponding KV projection matrix multiplication, the compute volume per decoding step also decreases.

    The boundaries of this method must be clearly understood. First, not all arbitrary adjacent layers are suitable for sharing. Which layers share and how many layers share must be determined through training or post-modification evaluation; one cannot assume all layers can be directly reused. Second, the more sharing, the weaker the model’s ability to express inter-layer details. Tasks like long-text retrieval or multi-hop reasoning may exhibit quality degradation earlier than standard question-answering. Third, the sharing mechanism is typically established during the model training phase, and already published weights may not support modifications. Deployers should treat it as an integral part of the model structure rather than a configurable inference parameter.

    4. Mixture-of-Experts vs. Dense: Separating Compute and Cache

    Mixture-of-Experts (MoE) models split the feed-forward network into multiple experts, with each token only activating a few of them. The total parameter count of the model can be very large, while the number of activated parameters per inference step remains low. Therefore, MoE primarily reduces the compute volume per inference step, thereby improving throughput and unit cost.

    MoE does not directly compress the KV cache. The size of the KV cache is determined by the attention component—specifically, the number of layers, KV heads, dimension per head, and context length. If an MoE model simultaneously employs GQA or other cache optimizations, the two can be stacked. Simply switching to an MoE structure without altering the attention mechanism will leave the VRAM occupied by the KV cache fundamentally unchanged.

    MoE also has its own costs in terms of VRAM. The full parameters of the expert networks usually need to be loaded into VRAM or split across multiple GPUs, so the total parameter count directly impacts the VRAM footprint of the weights. Training and post-tuning are similarly more demanding.