KV Cache Quantization for Long-Context LLM Inference on Unified Memory: A Practical Guide

    Loading a model does not guarantee that it can handle long inputs on a local machine. This guide explains how the key-value (KV) cache grows with context length, why unified memory makes the problem harder, and how KV cache quantization differs from weight quantization. It also covers how to estimate cache size, confirm that quantization is active, measure memory and latency by stage, and test output quality on long-context tasks.

    1. Start with the Problem: A Model That Fits in Memory Does Not Mean Long Contexts Will Run

    When developers deploy a large language model locally, they usually focus first on parameter count and weight quantization precision. They check how much memory the device has, whether the model loads, and how many resources it uses after startup. Once the workload moves to long document analysis, sustained conversations, or multi-file retrieval, however, memory demand keeps growing.

    Inference needs more than model weights. It also maintains the key-value (KV) cache used by the attention mechanism. As the number of processed tokens increases, this cache usually grows as well. A model that loads successfully only shows that its static resource requirements are met. It does not show that the model can reliably process inputs at the target length.

    This problem deserves particular attention on unified memory devices. The processor, the GPU, and other system components share one physical memory pool. The inference process must compete with the operating system for resources, and it also needs room for temporary tensors, compute workspaces, and other applications. When memory pressure becomes too high, the program may start swapping, slow down noticeably, or exit because an allocation fails.

    Long-context optimization is therefore a resource management problem first and a speed problem second. The main value of cache quantization is that it reduces the cache cost of each token. This frees space for longer inputs or more concurrent requests. It does not directly improve the model’s knowledge or reasoning ability.

    2. Why the KV Cache Becomes a Memory Bottleneck

    1. The cache avoids repeated computation but must store history

    During autoregressive generation, the model computes attention over the preceding context each time it generates a new token. If the keys and values for past tokens are kept, they do not need to be recomputed at every step.

    This is a classic trade-off between time and space. Higher memory use reduces repeated computation.

    For models that use global attention and keep the full history in cache, you can estimate cache size with the following approximate formula:

    Cache bytes ≈ 2 × number of layers × effective batch size × number of cached tokens × number of KV heads × head dimension × bytes per element

    The factor of 2 accounts for storing both keys and values. Real implementations may also include block alignment, quantization metadata, memory pool reservations, and other management overhead.

    The formula also shows that two models with similar parameter counts can have very different cache requirements. Differences in layer count, number of KV heads, attention structure, and caching strategy can produce large differences in long-context memory use. Model weight size alone cannot tell you whether runtime cache usage will be lower.

    2. Context length is not the only variable

    If the cache structure stays the same, doubling the number of cached tokens roughly doubles the theoretical cache size. Real deployments, however, also depend on the following factors:

    • Effective concurrency: Multiple active requests usually each need their own cache space.
    • Generation budget: After the input ends, newly generated output can keep extending the cache.
    • Attention type: Sliding-window, local, or hybrid attention can change how the cache grows.
    • Allocation strategy: On-demand allocation, pre-allocation, and block-based management all affect the actual peak.
    • Prefix reuse: Shared prefixes can reduce duplicate storage, but the benefit depends on the framework implementation and how similar the requests are.

    Capacity planning should therefore cover the full run of the target task. Measuring static memory right after the model loads is not enough.

    3. KV Cache Quantization Is Different from Weight Quantization

    Weight quantization compresses model parameters. It mainly affects the size of the loaded model and the computation tied to parameters. KV cache quantization compresses the historical state produced during inference. It mainly affects runtime memory for long contexts.

    The two techniques can be used together, but neither replaces the other. Even when weights use low-bit representations, the cache may still use higher precision. For long inputs, that cache can take up a large share of memory.

    KV cache quantization usually involves two key steps. First, continuous values are mapped to a smaller set of discrete codes. Second, approximate values are recovered when attention needs them, or part of the computation runs directly on the compressed representation.

    Its error does not stay in storage. Errors in keys can change attention scores, and errors in values can change the aggregated output. To judge whether a method works, you cannot look only at file size or memory reduction. You must also check the final task quality.

    1. Distinguish theoretical compression from actual compression

    Suppose the original cache stores each element in 16 bits, and after quantization the average encoding uses 4 bits. If you count only the data payload, capacity drops to one quarter of the original.

    In practice, the cache may also store scales, group information, outliers, or other auxiliary data. Memory alignment can add further overhead. For this reason, the bit-width ratio should not be treated as the reduction in total memory.

    Total memory can be roughly broken down as follows:

    Total memory ≈ model weights + KV cache + temporary compute space + framework overhead + system headroom

    If the KV cache accounts for only a small share of total memory, even significant compression may yield limited overall savings. With very long contexts, where the cache is the main consumer, compression is worth much more.

    2. Lower bit width is not always better

    Lower bit widths usually mean lower storage cost. They can also bring larger representation error, more complex computation paths, and extra conversion overhead.

    The goal is not to set the bit width as low as possible. The goal is to choose a cache representation that meets your task quality and response time requirements.

    4. Why Rotation Transforms Help Low-Bit Quantization

    The dimensions of a cache vector often have uneven value distributions. A few large elements can force the quantizer to use a wider range, so most ordinary elements get only coarse resolution.

    A common approach is to apply a suitable orthogonal transform before quantization. The transform spreads magnitude that was concentrated in a few dimensions more evenly. If the transform matrix is orthogonal, applying the same transform to two vectors preserves their inner product when no quantization is involved:

    (Rx)ᵀ(Ry) = xᵀy

    This gives the rotation transform an important property. It changes how values are distributed across dimensions while preserving some of the geometric relationships that attention depends on.

    However, this equation describes the transform itself. It does not mean that quantization introduces no error. Low-bit encoding still introduces approximation, and the actual effect depends on the quantization method, the data distribution, the model architecture, and the implementation.

    Some methods also combine non-uniform encoding, residual processing, or error correction to reduce distortion at