KV Cache Compression: Practical Long-Context Inference on Unified Memory

    Long-context inference is often bounded by KV cache memory rather than model weights, and unified-memory systems make this constraint especially acute. This article walks through how KV cache memory scales with context length and precision, compares three compression routes—quantization, low-rank projection, and sparse eviction—and focuses on KV cache quantization as the most broadly applicable method. It covers practical implementation details such as per-group scaling factors, treating keys and values differently, handling outliers, rotation-plus-polar-quantization techniques, ordering relative to rotary position embeddings, and the compute trade-offs involved. A four-step deployment workflow, guidance on validating memory and quality gains, and notes on when the approach pays off round out the discussion for engineers running long contexts on unified-memory devices.

    Long context hits the KV cache first, not the model weights

    During autoregressive decoding, generating each new token first uses the current token’s Query to compute attention weights against the Keys of all previous tokens, then takes a weighted sum over their Values. If the Keys and Values of historical tokens were recomputed at every step, the cost would accumulate rapidly across dialogue turns. Inference frameworks therefore cache this content—the KV cache. It turns decoding from “recompute everything” into “read from a lookup table,” at the cost of memory that grows linearly with context length.

    The memory math you have to get right

    Single-request KV cache usage can be approximated as:

    1. KV memory ≈ 2 × layers × KV heads × head dim × context length × concurrent requests × bytes per element

    The 2 accounts for storing Key and Value separately. Assuming 64 layers, 8 KV heads, head dim 128, and FP16 storage, usage across context lengths looks like:

    Context length FP16 (16-bit) INT8 (8-bit) INT4 (4-bit)
    8K 2 GiB 1 GiB 0.5 GiB
    32K 8 GiB 4 GiB 2 GiB
    128K 32 GiB 16 GiB 8 GiB
    256K 64 GiB 32 GiB 16 GiB

    These numbers are illustrative. Actual results depend on the specific layer count, KV head count, and storage precision, but the trend holds: double the context and the KV cache doubles; halve the bit width and KV usage roughly halves. 128K is only about a hundred-plus thousand characters of reading, yet it is everyday input for long-document QA, codebase-level retrieval, and multi-turn deep conversations.

    Unified memory architecture amplifies the problem

    • Capacity is the whole machine’s memory. The system, the inference runtime, model weights, and the KV cache all share the same memory pool, and each takes a “slice” from the total. Models with similar parameter counts may use similar weight memory, yet their KV structure (layers, KV head count, and so on) can differ widely. So at the same context length, some models still have room to spare while others are already near the limit.
    • Bandwidth is the more hidden constraint. During decoding, every token traverses the entire KV cache. The longer the context, the more memory bandwidth is consumed, and unified memory bandwidth is typically lower than that of high-end discrete GPUs. When memory is insufficient, even without a formal overflow, frequent swapping or compression can slow things down sharply.
    • Failure modes differ. On a discrete GPU, insufficient VRAM usually shows up as a clear out-of-memory error. On unified-memory devices, it more often manifests as system stutter or even the OS terminating the process, which is harder to diagnose.

    Weight quantization doesn’t solve the KV problem

    The Q4 and Q8 quantization people talk about day to day targets model weights. It reduces model size, but the per-token KV footprint does not shrink because of it. How long a context you can open is mainly determined by the space left after “total memory − weights − system and runtime overhead.” So the common belief that “shrink the weights first and long context will naturally follow” is a misunderstanding. The two paths solve different problems and need to be optimized separately.

    Three routes to KV cache compression

    Route Target Typical benefit Accuracy risk Engineering notes
    Quantization Each K/V value Memory and bandwidth drop roughly in proportion to bit width Low to medium, controllable via mixed precision Broadly applicable, wide framework support
    Low-rank projection The stored form of KV Can shrink to one compact latent vector per token Medium, changes the attention computation structure Often built into specific model architectures; hard to bolt on
    Sparse eviction The number of KV entries Allows a fixed KV budget Higher, noticeably affects long-range retrieval tasks Discards beyond the budget; simple to implement

    Quantization is the most broadly applicable route: it leaves the model structure untouched and lowers both memory and bandwidth, and it is the focus of this article. Low-rank projection and sparse eviction are better suited as complements—for cases where the model structure itself is constrained, or where context length far exceeds available memory.

    Implementation notes for KV cache quantization

    1. Granularity: per-group scaling factors are a cost too in long contexts

    Group quantization typically attaches a scaling factor to each group of values; the finer the grouping, the higher the precision and the more metadata. Over very long contexts, these factors themselves accumulate into a noticeable overhead. So striking the right balance between granularity and metadata overhead is a core engineering problem in long-context quantization.

    2. Keys and Values need to be treated differently

    K and V have different distributions and different sensitivities to quantization:

    • Key. Attention weights come from the QK dot product followed by Softmax. Softmax is sensitive to changes in its inputs, so K’s quantization error gets amplified and affects the entire row of the attention distribution. K also tends to contain outliers with magnitudes far exceeding other dimensions, and some attention concentrates on a few tokens at the start of the sequence (the so-called attention sinks). If the K at these positions carries too much error, it ripples through all subsequent outputs.
    • Value. V’s error is mostly averaged by the attention weights, showing up as local perturbations in the output—relatively “gentler.”

    As a result, assigning different bit widths to K and V (for example, higher precision for K and lower for V) is often more worthwhile than treating both the same.

    3. Outliers: the real roadblock for low-bit quantization

    The precision of low-bit quantization depends largely on whether a few very large-magnitude values can be handled. Common approaches fall into three categories:

    • Per-channel quantization. Compute a separate scaling factor for each feature dimension, “corralling” outliers into a few channels.
    • Group quantization. Narrow the range each scaling factor applies to, at the cost of more metadata.
    • Mixed precision. Keep the channels containing outliers at higher precision.

    4. A newer idea: rotation + polar quantization + random-projection correction

    Under the long-context trend, a class of “data-free” KV compression methods has emerged. Data-free means the quantization parameters do not depend on calibration data. A typical flow has three steps:

    1. Random orthogonal rotation. Apply a random orthogonal transform to the KV vectors. Rotation preserves vector length and relative relationships but “spreads out” outliers concentrated in a few dimensions across all dimensions, making the distribution closer to isotropic.
    2. Polar-space quantization. After rotation, map the vectors into polar space, quantize the radius at higher precision, and encode the direction components at low bit width.
    3. Random-projection residual correction. Exploit the property that random projections preserve only sign information (roughly an application of the Johnson–Lindenstrauss lemma) to correct the residual error left by the first two steps at very low bit cost.

    Its value: the random rotation is data-free, so it can go live without calibration, and it eliminates per-group scaling factors, so the compressed state per token can be kept very small. The cost is the extra computation from the rotation and projection.

    5. Ordering relative to rotary position embeddings

    Most mainstream large models use rotary position embeddings (RoPE). A common practice is to quantize the Key before applying the positional rotation. This lets you use the channel distribution present before quantization to do grouping or mixed-precision handling, and it keeps the position information of the cached Key correct; at inference time you simply apply the rotation to each fetched Key right before computing attention. The exact order and precision allocation should follow the chosen inference framework’s documentation and your own measurements.

    6. Rebalancing compute: memory saved, computation added

    • Principle. Quantization shifts part of the decode workload from “read-heavy, compute-light” toward “read-light, compute-heavy”: the cache is smaller, but the data must be restored to standard precision before attention computation.
    • Benefit. On unified-memory devices, memory capacity often becomes the constraint before compute does, so this trade is usually worthwhile.
    • Limit. If the restoration cost far exceeds the memory-access time saved, precision stays the same but speed can actually drop. Whether it pays off must be settled with real throughput numbers.

    7. Don’t let optimizations cancel each other out

    A quantized KV cache changes the memory layout and byte representation of the cache. Its compatibility with mechanisms such as paged attention (splitting KV into blocks and allocating on demand to reduce fragmentation and reserved waste) and prefix caching (sharing identical prefixes, such as the system prompt, across dialogue turns to avoid recomputation) varies. It is worth confirming each one before enabling, so that the memory you saved isn’t quietly eaten by an implicit fallback.

    Getting started: four steps to run long context

    The following is an illustrative configuration; actual fields and values should follow the documentation of the inference framework you use:

    1. model: <your_model>
    2. context_length: 131072 # 128K, adjust as needed
    3. kv_cache:
    4. dtype: float16 # baseline
    5. # candidates: int8 / int4 / mixed (K: float16, V: int4) / rotation-transform methods
    6. group_size: 64 # group size for group quantization, for reference only
    • Step 1: Leave a safety margin. First estimate total memory: model weights + runtime and system overhead + KV usage at the target context + a safety margin (recommend no less than 10%–15% of total memory). Compressing the context to leave headroom, then reclaiming space with quantization, is safer than maxing out in one shot.
    • Step 2: Establish an FP16 baseline. At the target context, record peak memory, decode speed, and a set of quality metrics as the baseline for later comparison. If FP16 itself won’t run, you should first lower the context or switch to a lighter weight precision, rather than blaming quantization.
    • Step 3: Tighten the bit width step by step. Try 8-bit, then 4-bit, and K/V mixed precision in turn. At each step down, re-check against the same set of quality metrics.
    • Step 4: Add more techniques if quality falls short. Consider combining “rotation-transform methods + mixed precision.” If that still isn’t enough, evaluate sparse eviction or switch to a model with a more compact KV structure.

    Keep in mind that these approaches are strongly tied to the inference framework version, the underlying operator implementations, and hardware characteristics. The same algorithm may have different default precision, available scope, and implementation quality across versions. After upgrading, it is worth rerunning the baseline and comparisons.

    How to judge the payoff: do the math and verify it

    1. Memory: the gain is estimable

    At 4-bit versus 16-bit, KV usage theoretically drops to 1/4. In long context, this saving is often the line between “can’t open” and “runs.”

    2. Quality: public research is only a reference

    Public research shows that data-free methods can achieve several-fold compression at around 3 bits with a limited perplexity increase, but published numbers should not be applied directly to your own scenario. It is worth covering at least three types of tests:

    • Long-range retrieval: plant target information in a long text and check whether the model can locate it accurately.
    • Long-document summarization: check whether key facts are missed.
    • Multi-turn coreference: check whether pronouns and elliptical expressions are still resolved correctly.

    Perplexity alone is not enough to demonstrate long-context capability. Perplexity measures overall language-modeling loss, whereas retrieval-type tasks are more sensitive to local errors.

    3. Latency: don’t expect a speedup

    • Prefill phase. The compute for processing a long input is basically unchanged, and time-to-first-token may even increase slightly because of quantization preprocessing.
    • Decode phase. Bandwidth pressure eases, so a speedup is possible. But dequantization or transform restoration introduces new computation, so speed can go either way—go by measurements.

    4. Applicability boundaries

    • Biggest gains: single-request scenarios with 128K+ long context, memory already near its limit, decode-dominant workloads, and spare compute.
    • Limited gains: short conversations within a few K (the bottleneck is weights, not KV), high-concurrency scenarios (the bottleneck is throughput and scheduling), and devices where compute itself is tight.

    Optional: use cloud elastic resources for comparison

    A local machine’s memory capacity is fixed, making it hard to answer questions like “does the bottleneck disappear with more memory.” When you need larger-scale comparison experiments, you can use on-demand GPU resources from platforms such as Baidu AI Cloud (specific instance specs and pricing per the official documentation) to compare horizontally and verify how the quantization approach’s gains change in high-VRAM, high-bandwidth environments.

    Conclusion

    KV cache compression is neither a cure-all nor just a paper concept in the lab. It doesn’t make the model “smarter,” and it doesn’t directly shorten inference time, but it can pull ultra-long contexts that were previously locked out by memory into the usable range. Using it well takes three steps: first do the memory math, then tighten bit widths step by step according to K/V sensitivity, and finally validate with real long-text tasks. Combined with weight quantization, paged management, prefix reuse, and other techniques, long-context capability on unified-memory devices can go from “occasionally openable” to “something you dare to open every day.”