Why LLM Inference Needs KV Cache: Causal Attention, Prefill and Decode

    This article explains why KV Cache is a necessary part of autoregressive LLM inference. It breaks down how generating N tokens requires N forward passes, why causal masking makes historical key and value vectors stable and reusable while query vectors are single-use, and how the prefill and decode stages differ in their compute and memory-bandwidth bottlenecks. It also covers the memory cost of the cache, along with common mitigation techniques such as paged cache management, grouped-query attention, quantization, prefix reuse, speculative decoding, and continuous batching.

    1. The Starting Point: One “Generation” Is Actually Many Forward Passes

    Many beginners assume that LLM inference is a single step: you give the model a prompt, and it returns an answer. But from a computation-graph perspective, generating N tokens with an autoregressive language model is equivalent to running N forward passes, each producing one new token. Saying “a single inference generates the next token” is correct; the mistake is treating “generating the full response” as a single inference.

    This token-by-token process is determined by the training objective. During pretraining, the model learns the conditional distribution of “predict the next token given the preceding context.” Inference follows the same paradigm: append the generated content back to the input and predict the next token. This creates a chain of dependencies:

    1. Step 1: input [x1..xn] -> predict x(n+1)
    2. Step 2: input [x1..xn, x(n+1)] -> predict x(n+2)
    3. Step 3: input [x1..xn, x(n+1), x(n+2)] -> predict x(n+3)
    4. ...

    The input grows longer at every step, while the model weights remain unchanged. This is exactly where KV Cache comes from: since the weights do not change and the representations of historical tokens no longer change either, a large amount of computation is simply repeating the same work.

    2. What Can Actually Be Reused in Attention

    To understand what gets cached, look at the computation inside one Transformer layer during decoding. Let the hidden vector of the current token be x, and the three projection matrices be W^Q, W^K, and W^V:

    1. q = x W^Q
    2. k = x W^K
    3. v = x W^V
    4. Attention(q, K, V) = softmax(q K^T / sqrt(d_k)) V

    The key property comes from the causal mask: the token at position i can only attend to positions 1..i and cannot see anything after it. This means that when a new token arrives, the k and v vectors of all preceding tokens do not change just because there is one more token after them. They are deterministic functions of historical data and can be safely stored and reused.

    Now look at q. Its role is for the current token to “ask a question” to the history, and it only serves the output of the current step. The q computed in the previous step has already done its job and will never be needed again. This is the fundamental reason there is a KV Cache but no Q Cache, which can be summarized in two points:

    1. The new representations of historical tokens are fixed and unaffected by subsequent tokens, so they do not need to be recomputed, and their k and v values are worth caching.
    2. The only thing that actually needs to be computed is the new representation of the current token in the full context, i.e. softmax(q (K ⊕ k)^T / sqrt(d_k)) (V ⊕ v), where only q is one-time.

    In one sentence: K and V are a “dictionary” that is looked up repeatedly, while Q is a “query” written on the fly each time. Caching the dictionary is useful; caching the query is not.

    3. Two-Stage Pipeline: How Prefill and Decode Differ in Compute Profile

    In engineering practice, generation is usually split into two stages with completely different performance bottlenecks.

    Prefill stage: process the entire input prompt at once, generate K and V for every layer and every attention head and write them into the cache, while producing the first new token. This step is a classic large matrix multiplication: compute-intensive, highly parallel, and typically bounded by compute limits.

    Decode stage: input only one token at a time, read all historical K and V to compute attention, then update the cache. Each step’s matrix multiplication is a “vector times matrix” operation with extremely low arithmetic intensity, mainly bounded by memory bandwidth.

    Illustrative pseudocode:

    1. # prefill
    2. k_cache, v_cache = [], []
    3. hidden = model.embed(prompt)
    4. for layer in model.layers:
    5. k, v = layer.split_kv(layer.project_kv(hidden))
    6. k_cache.append(k); v_cache.append(v)
    7. hidden = layer.attn_with_cache(hidden, k, v) # causal mask
    8. logits = model.head(hidden[:, -1, :])
    9. next_token = sample(logits)
    10. # decode
    11. for _ in range(max_new_tokens):
    12. hidden = model.embed(next_token)
    13. for i, layer in enumerate(model.layers):
    14. k, v = layer.split_kv(layer.project_kv(hidden))
    15. k_cache[i] = concat(k_cache[i], k)
    16. v_cache[i] = concat(v_cache[i], v)
    17. hidden = layer.attn_with_cache(hidden, k_cache[i], v_cache[i])
    18. next_token = sample(model.head(hidden[:, -1, :]))

    4. The Cost of KV Cache: Where the Pressure on Hardware Comes From

    KV Cache trades memory for compute, but it is not cheap. The cache size for a single layer and a single head is 2 × seq_len × d_head, and for the full model it is roughly:

    1. memory bytes ≈ 2 (K and V) × num_layers × sequence_length × hidden_dim × batch_size × bytes_per_element

    With common configurations of a hidden dimension in the thousands, dozens of layers, and a sequence length in the thousands, the cache for a single long-context request can reach hundreds of MB to several GB, and it grows linearly with concurrency. This creates three practical pressures:

    • Memory capacity pressure: the cache takes up memory that could otherwise be used for batching, directly lowering the concurrency limit.
    • Bandwidth pressure: every decode step has to read the entire cache, making bandwidth the ceiling on throughput.
    • Fragmentation and scheduling pressure: sequence lengths grow dynamically, so cache blocks must be allocated dynamically, which easily leads to fragmentation and adds scheduling complexity.

    5. Mitigations and Engineering Practices

    Around these bottlenecks, the industry has developed a fairly mature set of optimization directions, all of which are general-purpose techniques:

    1. Paged cache management: split the cache into fixed-size blocks allocated on demand, reducing fragmentation and making sharing and migration easier.
    2. Multi-query / grouped-query attention: let multiple query heads share one set of key and value heads, shrinking the cache size at the model-structure level.
    3. Cache quantization and low-precision storage: trade acceptable precision loss for memory and bandwidth gains.
    4. Prefix reuse: in multi-turn conversations or scenarios with the same system prompt, reuse the cache of the shared prefix to avoid repeated prefill.
    5. Speculative decoding: first use a small model to draft multiple candidate tokens, then have the large model verify them in parallel, turning multi-step serial decoding into single-step parallel verification.
    6. Continuous batching and Paged scheduling: dynamically batch at the request level to improve accelerator utilization.

    When deployed in the cloud, these capabilities typically rely on a container platform to host inference services, object storage to hold models and cache snapshots, and logging services plus monitoring and alerting to track time to first token, time per token, and memory usage. This is a common combination of general-purpose product categories offered by cloud providers such as Baidu AI Cloud.

    6. Summary

    KV Cache is not an implementation detail but an inevitable product of autoregressive generation: the causal structure makes historical keys and values stable and reusable, while query vectors are inherently one-time. Understanding this explains why the decode stage is a bandwidth-intensive workload, why memory rather than compute often becomes the bottleneck first, and how to make the right optimization trade-offs across three levels: model structure, cache management, and batching and scheduling.