KV Cache Compression for Long-Context Inference: From MHA to GQA and MQA

    This article explains why the KV cache becomes a bottleneck in long-context autoregressive inference, quantifies its memory footprint, and compares three attention architectures—multi-head attention (MHA), multi-query attention (MQA), and grouped-query attention (GQA)—in terms of cache size, bandwidth impact, and quality trade-offs. It includes a practical formula for estimating cache memory, a numerical example across context lengths, and a code snippet showing how KV grouping works in GQA.

    1. The Starting Point: Why the KV Cache Becomes a Bottleneck

    During autoregressive text generation, each newly generated token requires the model to compute attention between its query vector and the keys and values of all previous tokens. The keys and values for earlier tokens have already been computed in previous steps, but recomputing them each step would become prohibitively expensive as the context grows. To avoid this, inference frameworks store the keys and values in memory, and that storage is called the KV cache.

    The core decoding loop can be simplified to the following pseudocode:

    1. # Pseudocode: core autoregressive decoding loop
    2. for step in range(max_new_tokens):
    3. q = project_query(current_token) # Q is used once, in this step only
    4. k, v = project_key_value(current_token) # K, V must be kept for future steps
    5. kv_cache.append(k, v) # cache grows linearly with context
    6. out = attention(q, kv_cache.keys(), kv_cache.values())
    7. current_token = sample(out)

    This code illustrates two facts. First, the query is used only in the current step and can be discarded immediately. Second, keys and values must be retained for the entire generation process, so the number of cached rows equals the number of tokens generated so far. Consequently, the KV cache size grows proportionally with the context length.

    1.1 Estimating Cache Size

    The memory footprint of the KV cache can be approximated with the following formula:

    cache bytes = 2 × context length × number of layers × number of KV heads × head dimension × bytes per element

    The factor of 2 accounts for storing both K and V. The bytes per element depend on the precision; FP16 typically uses 2 bytes.

    1. def kv_cache_bytes(n_tokens, n_layers, n_kv_heads, head_dim, dtype_bytes=2):
    2. # 2 accounts for storing both K and V
    3. return 2 * n_tokens * n_layers * n_kv_heads * head_dim * dtype_bytes

    1.2 A Concrete Example

    To illustrate the scale, consider a model with 64 layers, a head dimension of 128, and FP16 precision. The same model is evaluated under three attention schemes with 64, 8, and 1 KV heads, corresponding to multi-head attention (MHA), grouped-query attention (GQA), and multi-query attention (MQA), respectively. The numbers below are computed from the formula and are meant to show the order of magnitude, not to represent any specific model’s measured values.

    Context Length MHA (64 KV heads) GQA (8 KV heads) MQA (1 KV head)
    4K 8 GiB 1 GiB 0.125 GiB
    32K 64 GiB 8 GiB 1 GiB
    128K 256 GiB 32 GiB 4 GiB
    1M 2048 GiB 256 GiB 32 GiB

    Two observations stand out. First, with MHA, a 128K-token context already exceeds the memory capacity of a single 80 GB accelerator. Second, the cache size is directly proportional to the number of KV heads; reducing the number of KV heads to a fraction of the original also reduces the cache by the same fraction.

    Note that the numbers in the table represent a single sequence. During batch inference, each concurrent sequence maintains its own cache, so the memory requirement scales linearly with the batch size.

    1.3 Not Just Capacity: Bandwidth Matters

    The KV cache also affects memory bandwidth. For every token generated, the compute units must read the entire historical cache from memory. The longer the context, the more data is read at each step, and decoding speed becomes increasingly limited by memory bandwidth. Therefore, compressing the cache not only saves memory capacity but also improves decoding throughput.

    2. Multi-Head Attention (MHA): Quality Baseline and Storage Cost

    The Transformer architecture introduced in 2017 uses multi-head attention. The model splits the hidden dimension into H heads, each with its own Q, K, and V projection matrices. Different heads can learn different attention patterns, such as local syntactic relations, long-distance coreferences, or positional alignment.

    1. def multi_head_attention_shapes(x, n_heads, d_head):
    2. # x has shape [seq_len, d_model], and d_model = n_heads * d_head
    3. seq_len = len(x)
    4. q = project(x, "Wq").reshape(seq_len, n_heads, d_head)
    5. k = project(x, "Wk").reshape(seq_len, n_heads, d_head)
    6. v = project(x, "Wv").reshape(seq_len, n_heads, d_head)
    7. return q, k, v

    The advantage of multi-head attention is its high expressive power; it is often used as the quality baseline. Its cost is equally clear: every head stores its own K and V, so the cache size grows linearly with the number of heads H. When the context reaches hundreds of thousands of tokens, this overhead becomes the primary constraint for deployment.

    3. Multi-Query Attention (MQA): One Shared K and V for All Query Heads

    Multi-query attention keeps H query heads but lets all query heads share a single set of K and V. Thus the number of KV heads becomes 1, and the cache size shrinks to 1/H of the multi-head version.

    This design offers two benefits. First, cache capacity drops dramatically, allowing the same memory to support much longer contexts or higher concurrency. Second, the amount of data read per decoding step decreases, reducing bandwidth pressure.

    The trade-off is reduced expressive power. All heads can only see the same set of key-value representations, and the differences between heads now come only from their individual query projections. In practice, converting a multi-head model directly to multi-query generally causes some quality degradation, so additional training (for example, continued pretraining or fine-tuning) is often needed to recover accuracy.

    4. Grouped-Query Attention (GQA): A Balance Between Quality and Memory

    Grouped-query attention divides the query heads into G groups, and all query heads within the same group share a single set of K and V. It sits between multi-head and multi-query attention as a compromise.

    1. def expand_kv_for_groups(k, n_q_heads, n_kv_heads):
    2. # k has shape [seq_len, n_kv_heads, d_head]
    3. # Each KV head serves group_size query heads
    4. group_size = n_q_heads // n_kv_heads
    5. # Expand k to match the number of query heads
    6. k_expanded = k.repeat_interleave(group_size, dim=1)
    7. return k_expanded

    GQA reduces the KV cache by a factor of the group size. With G groups, the cache is 1/G of the MHA size. When G equals the number of query heads, GQA reduces to MHA; when G equals 1, it becomes MQA. This flexibility allows model designers to choose a group size that matches their quality and performance targets.

    In practice, GQA has become a widely used choice for large language models, because it offers a reasonable trade-off: it retains most of the expressiveness of MHA while making long-context inference feasible with limited memory. The exact quality loss depends on the model size and the group size, but many production models adopt GQA as a default.