MLA Inference Optimization: Matrix Absorption and KV Cache

    This article explains why KV cache dominates LLM decoding, how MLA differs from MHA and MQA, and how matrix absorption turns MLA decoding into an MQA-like computation. It also covers KV cache storage, memory estimates using the public DeepSeek-V2 configuration, scaling details, and implementation considerations for a custom MLA decoding kernel.

    1. Why KV Cache Matters During Inference

    Large language models generate tokens one at a time. When generating each new token, attention must read the keys and values of all previous tokens, so these historical KVs must be cached in GPU memory. This cache is called the KV cache. The longer the context, the more GPU memory the KV cache consumes, and the more data each decoding step must read.

    Inference has two stages. The prefill stage processes the entire prompt at once, so the query length equals the KV length and the compute workload is large. The decoding stage generates one token per step, so the query length is 1 and the compute workload is small, but it must read the full historical KV. The bottleneck usually falls on memory bandwidth. The two stages have different optimization priorities, and this article focuses on decoding.

    MLA (Multi-head Latent Attention) reduces the KV cache by changing how KVs are stored. Two symbols are used below: (d_c) is the dimension of the compressed latent vector, and (d_r) is the dimension that carries rotary position encoding (RoPE).

    2. Differences Between MHA, MQA, and MLA

    The table below compares key inference characteristics of the three structures.

    Structure What each token caches Number of KV heads during inference Main characteristics
    MHA Independent K and V for each head Same as Q, denoted as H Strong expressiveness, largest cache
    MQA One shared set of K and V for all heads 1 Small cache, all heads share KV, weaker expressiveness than MHA
    MLA One latent vector (c_{KV}) ((d_c) dimensions) plus one RoPE key (k_R) ((d_r) dimensions) Equivalent to 1 after matrix absorption Small cache while retaining multi-head expressiveness

    Matrix absorption is used only during inference. During training, MLA is computed in a way close to MHA, without absorption.

    3. Matrix Absorption: How the Computation Becomes MQA-Like

    Let the input hidden state of a layer be (h). MLA first compresses (h) into a latent vector (c{KV}) with dimension (d_c). Each head then uses up-projection matrices (W{UK}) and (W_{UV}) to reconstruct the non-positional parts of the key and value. The RoPE part is computed separately to obtain the key (k_R), which is shared by all heads.

    For each head, let the non-positional part of the query be (q{nope}), the non-positional part of the key be (k{nope} = W{UK} \cdot c{KV}), and the RoPE part of the query be (q_{rope}). The attention score is:

    [
    \text{score} = q{nope} \cdot k{nope} + q_{rope} \cdot k_R
    ]

    Using the associativity of matrix multiplication, move the up-projection matrix from the key side to the query side:

    [
    q{nope} \cdot (W{UK} \cdot c{KV}) = (W{UK}^T \cdot q{nope}) \cdot c{KV}
    ]

    Let (q{latent} = W{UK}^T \cdot q_{nope}). The score becomes:

    [
    \text{score} = [q{latent}; q{rope}] \cdot [c_{KV}; k_R]
    ]

    This step is matrix absorption. During computation, there is no need to expand the full key for each head; only (c_{KV}) and (k_R) from the cache need to be read.

    The value side works similarly. The value of the (j)-th token is (W{UV} \cdot c{KV,j}). After weighted summation:

    [
    o = W{UV} \cdot \sum_j p_j \cdot c{KV,j}
    ]

    The weighted sum is performed in latent space. (W_{UV}) only needs to be applied once and can be merged with the output projection matrix (W_O).

    After absorption, the tensor shapes are as follows:

    • Q: [Batch, q_len, H, d_c + d_r]
    • K: [Batch, kv_len, 1, d_c + d_r], containing [c_KV; k_R]
    • V: [Batch, kv_len, 1, d_c], containing c_KV

    K has one head, which is the MQA form. After absorption, V is the first (dc) dimensions of K, so both read the same cache. Before absorption, V must be obtained from (c{KV}) through an up-projection.

    The softmax scaling factor must use the original per-head dimension, i.e. (1/\sqrt{d{nope} + d_r}), not (1/\sqrt{d_c + d_r}). For example, in the public DeepSeek-V2 configuration, (d{nope}) is 128 and (d_r) is 64, so the scaling factor should be (1/\sqrt{192}).

    Why is a dedicated kernel needed? Many generic MQA implementations assume that V and K have the same head dimension. In MLA, K has dimension (d_c + d_r), while V has dimension (d_c). The two are not equal, and the second half of K must be processed with RoPE. Therefore, generic implementations often cannot be used directly, and a custom kernel is required.

    Matrix absorption also has a cost. After absorption, the attention dimension per head increases from (d_{nope} + d_r) (for example, 192) to (d_c + d_r) (for example, 576), so the floating-point computation in attention increases. The main bottleneck in decoding is memory access, and whether the extra computation is offset by memory savings must be confirmed by measurement. In prefill, queries are longer and computation accounts for a higher share, so implementations often use the unabsorbed form.

    4. KV Cache Storage Structure and Size

    After absorption, each token only needs to cache (c_{KV}) and (k_R) per layer, for a total of (d_c + d_r) elements. V does not need separate storage.

    The number of elements that each token must cache per layer can be compared as follows:

    • MHA: (2 \times H \times d_h)
    • MLA: (d_c + d_r)

    Using the public DeepSeek-V2 configuration as an example: (H) is 128, (d_h) is 128, (d_c) is 512, and (d_r) is 64. MHA caches 32,768 elements per token per layer, while MLA needs only 576, about 1/57 of the former.

    Overall GPU memory can be estimated as:

    [
    \text{cache bytes} \approx \text{Batch} \times \text{sequence length} \times \text{layers} \times \text{elements per token per layer} \times \text{bytes per element}
    ]

    Assuming Batch is 1, sequence length is 32,768, layers is 61, and the data type is bf16 (2 bytes per element), the MHA KV cache is about 122 GiB, while MLA is about 2.14 GiB. This comparison only counts the KV cache itself and does not include model weights, activations, or other caches.

    5. Implementation Notes for the Decoding Kernel

    The pseudocode below is only intended to illustrate the data flow and is not directly runnable. The code assumes that the query has already undergone matrix absorption and that all heads share the same KV cache.

    1. # Conceptual sketch only; not runnable code
    2. # q_latent: [H, d_c], q_rope: [H, d_r]
    3. # kv_cache: [S, d_c + d_r], one entry per token, shared by all heads
    4. # scale: 1 / sqrt(d_nope + d_r), using the original per-head dimension
    5. def mla_decode_sketch(q_latent, q_rope, kv_cache, scale, d_c, tile_size):
    6. H = q_latent.shape[0]
    7. S = kv_cache.shape[0]
    8. out = zeros(H, d_c) # output accumulator in latent space
    9. run_max = full(H, -inf) # current max score per head
    10. run_sum = zeros(H) # softmax denominator per head
    11. for start in range(0, S, tile_size):
    12. tile = kv_cache[start:start + tile_size]