Multi-Head Latent Attention: KV Cache Compression Principles and Practice

    This article explains why KV cache becomes an inference bottleneck, compares MHA, GQA, and MLA, and details how MLA compresses keys and values into a low-dimensional latent vector. It covers matrix absorption, positional encoding, reported performance results and their caveats, key engineering decisions, and an evaluation checklist for assessing MLA in production LLM inference.

    1. Why KV Cache Becomes an Inference Bottleneck

    During autoregressive generation, each output token requires the model to compute attention between the new token’s query vector and the keys and values of all previous tokens. To avoid repeated computation, inference systems store the keys and values of historical tokens. This storage is called the KV cache.

    The cache size can be estimated with the following formula:

    cache_bytes = 2 × layers × heads × head_dim × sequence_length × batch_size × bytes_per_element

    The coefficient 2 means that both keys and values are stored. Consider a hypothetical configuration: 32 layers, 32 heads, head dimension 128, 16-bit floating-point storage, sequence length 8192, and batch size 1. Each token occupies 2 × 32 × 128 × 2 = 16384 bytes per layer. Across 32 layers, this is about 512 KiB per token. For 8192 tokens, the total is about 4 GiB. As batch size or sequence length grows further, the cache quickly fills GPU memory, forcing batch size down and limiting throughput.

    2. Two Common Paths to Reduce Cache Size

    Multi-head attention (MHA) stores independent keys and values for each head. It offers the strongest expressiveness but also the largest cache.

    Grouped-query attention (GQA) lets multiple query heads share the same group of key-value heads. The number of stored key-value heads decreases, so the cache shrinks. However, each group of query heads sees the same key-value information, which can reduce expressiveness.

    Multi-head latent attention (MLA) takes a different route. It retains a relatively large number of attention heads but does not store full keys and values directly. Instead, it compresses them into a low-dimensional latent vector for storage. The difference can be summarized as follows: GQA reduces how many key-value groups are stored, while MLA reduces how much data is stored per group.

    3. Core Principles of MLA

    Let the hidden state of the t-th token be h_t. MLA uses a down-projection matrix W_DKV to map it to a low-dimensional latent vector:

    c_t = h_t · W_DKV

    During inference, only c_t is cached. When attention is computed, two up-projection matrices reconstruct the keys and values:

    K_t = c_t · W_UK

    V_t = c_t · W_UV

    Suppose a latent vector with total dimension d_c replaces the keys and values of n_h heads with head dimension d_h. Then the number of cached elements per layer per token drops from 2 · n_h · d_h to d_c. The compression ratio depends on the choice of d_c.

    For example, with n_h = 32 and d_h = 128, the original cache has 8192 elements. If d_c = 512, the compressed cache has 512 elements, for a theoretical compression ratio of about 16×. Practical designs usually also store a small component that carries positional information for rotary position embedding (RoPE). If this component has dimension 64, the total cache is 576 elements, for a compression ratio of about 14.2×. These numbers come from the hypothetical configuration above and do not represent measured results from any published model.

    The key engineering technique is matrix absorption. Attention scores are inner products between queries and keys, so the up-projection matrix W_UK can be merged in advance with the query projection matrix. Similarly, W_UV can be merged with the output projection matrix. This means inference does not need to explicitly materialize full keys and values in GPU memory, eliminating extra memory-access overhead.

    The following code is a single-head illustration. It shows the cache structure and a single decode step; it is not a complete, runnable implementation:

    1. class LatentKVCache:
    2. def __init__(self):
    3. self.c_kv = [] # low-dimensional latent vector for each token
    4. self.k_rope = [] # small position-related component for each token
    5. def append(self, c_t, k_r_t):
    6. self.c_kv.append(c_t)
    7. self.k_rope.append(k_r_t)
    8. def decode_step(x_t, cache, w, d_h, d_r):
    9. # 1. Compress the current token into a latent vector and write it to cache
    10. c_t = x_t @ w["W_DKV"]
    11. pos = len(cache.c_kv)
    12. k_r_t = apply_rope(x_t @ w["W_KR"], pos)
    13. cache.append(c_t, k_r_t)
    14. # 2. Read all historical latent vectors
    15. C = stack(cache.c_kv) # shape [seq_len, d_c]
    16. K_r = stack(cache.k_rope) # shape [seq_len, d_r]
    17. # 3. The query uses the projection with W_UK absorbed and directly computes inner products with latent vectors
    18. q_c = x_t @ w["W_Q_absorbed"]
    19. q_r = apply_rope(x_t @ w["W_QR"], pos)
    20. scores = (C @ q_c + K_r @ q_r) / sqrt(d_h + d_r)
    21. # 4. Aggregate in latent space, then output through the matrix with W_UV and W_O absorbed
    22. attn = softmax(scores)
    23. ctx = attn @ C
    24. return ctx @ w["W_UV_O_absorbed"]

    In the code, apply_rope, stack, and softmax are placeholders for common functions. The multi-head case also needs to handle concatenation and summation across head dimensions; those details are omitted here.

    4. Understanding the Performance Benefits

    The decode phase is usually memory-bandwidth bound. Each generated token requires reading a large amount of cached data from memory, and the read volume is proportional to the cache size. A smaller cache reduces the number of bytes read per step, allowing the same hardware to support a larger batch size and higher throughput.

    One public measurement report provides the following results for reference:

    • At a sequence length of 8K, cache usage dropped from about 12 GB to about 3 GB, a reduction of about 4×.
    • Inference throughput increased from about 120 tokens/s to about 280 tokens/s.
    • On long-context evaluation sets, compared with conventional multi-head attention, inference speed improved by about 1.8× to 2.3×, KV cache memory dropped by 42% to 57%, and task accuracy remained roughly flat.
    • These results were consistent across multiple mainstream acceleration hardware platforms.

    These numbers need to be interpreted carefully. Different reports use different baselines: some compare against same-size multi-head attention, while others compare against previous-generation models with different parameter counts. Another report uses a larger-scale previous-generation model as the baseline and gives a cache reduction of about 93.3%. That comparison mixes differences in parameter count and architecture, so it should not be directly compared with the data above. Model size, batch size, sequence length, and hardware all affect results. When evaluating, keep comparison conditions fixed and change only the attention mechanism itself.

    5. Key Engineering Decisions

    1. Training from scratch or retrofitting. For models trained from scratch with MLA, the architecture and training pipeline can be designed together, which makes it easiest to ensure effectiveness. For existing pretrained models with GQA architecture, research on post-training conversion has shown that existing key-value projections can be reparameterized into latent projections. Such conversion usually requires additional calibration training and must be validated for accuracy on the target task.

    2. Compute versus memory access. Up-projections and matrix absorption change the floating-point operation count. In memory-bound scenarios such as decoding, memory savings usually outweigh the increase in computation. In the prefill phase with long prompts, computation accounts for a higher share and must be measured separately.

    3. Numerical precision. Quantization error in the latent vector affects the outputs of all heads simultaneously. When using low-precision storage, check whether outputs remain stable on long-context tasks.

    4. Positional encoding. The separate design of the positional component is error-prone. Use per-position unit tests to compare the output of the compressed implementation against an uncompressed reference implementation.

    6. Evaluation Checklist

    • Fix the model and data, and compare peak cache memory, time to first token, and generated tokens per second before and after compression.
    • Check changes in accuracy and throughput at different sequence lengths, such as 1K, 8K, and 32K.
    • Increase batch size incrementally and observe memory usage to find the service capacity limit.
    • Connect these metrics to service monitoring and set alert thresholds for memory and latency so performance regressions can be detected promptly.

    7. Summary

    Multi-head latent attention shifts the cache-compression idea from reducing the number of key-value heads to compressing the representation of each head. It preserves multi-head expressiveness while significantly reducing memory usage for long-sequence inference. Understanding matrix absorption and the handling of positional encoding is key to judging whether it can be deployed in real serving systems.