KV Cache Compression for Long-Context Inference on Shared-Memory Devices

    Long-context LLM inference often breaks down not because the model isn't smart enough, but because the KV cache grows linearly with context length and eventually exceeds the available memory budget. This article walks through the full picture: why long contexts exhaust memory on shared-memory (unified-memory) devices, why weight quantization alone cannot solve the problem, and how three KV cache compression approaches compare—sparse retention and eviction, low-bit group quantization, and random rotation combined with low-bit quantization. It also covers the engineering steps for enabling compression in local inference frameworks, a reusable methodology for measuring whether compression actually helps, and a decision framework for weighing the benefits against the costs.

    Introduction: What stalls long-context inference is usually memory, not intelligence

    When deploying large models locally, the conversation often centers on “is the model smart enough?” But as soon as you actually use a context window beyond 32K, you run into a more basic problem that shows up even earlier:

    • Stretching a document and conversation window from 8K to 32K causes the process to be killed by the operating system (OOM);
    • After pushing the context to 128K, system memory usage keeps climbing, other applications get swapped out frequently, and the whole machine becomes noticeably sluggish;
    • Two models with the same order of parameter count behave differently: one can open up 64K of context, while the other struggles even at 32K.

    These symptoms usually aren’t model quality issues. They happen because the KV cache grows linearly with context length and overruns the available memory budget. A promising approach that has drawn attention recently compresses the KV cache with a two-level scheme of “random rotation + low-bit quantization,” shrinking a 3-bit KV cache to roughly a quarter of its original size. Following the thread of “why it overflows → how to compress it → how to use it → how to verify it,” this article breaks down the practice of KV cache compression in long-context inference.


    1. Start with the ledger: why long context “bursts” memory

    1.1 The “budget” constraint on shared-memory architectures

    On compute devices with a shared-memory (unified-memory) architecture, the CPU, GPU, NPU, and other tasks in the system all draw from the same physical memory. The available capacity is “total minus what’s already used”:

    1. Available memory ≈ total physical memory
    2. - OS, desktop environment, and other applications
    3. - the inference framework's own runtime overhead
    4. - model weights
    5. - KV cache
    6. - temporary activations and buffers during forward passes
    7. - a safety margin

    Two implications follow from this:

    1. The memory capacity on a spec sheet cannot be treated directly as the usable budget. As a conservative estimate, the system and other applications will occupy at least several GB, and only the remainder is what the inference engine can actually use.
    2. The KV cache is the only large item that “keeps growing” over the course of interaction. Weights are a constant, while the KV cache keeps expanding as conversation turns accumulate, long documents get pasted in, and the model generates continuously—until it hits the ceiling.

    1.2 How much memory the KV cache actually takes

    During autoregressive generation, the model needs the Key and Value vectors of all previous tokens at every step, so all of them must be cached. The memory usage can be approximated as:

    1. KV memory ≈ 2 × batch size × context length × layers × KV heads × head dim × bytes per element
    • The coefficient of 2 corresponds to the two caches for K and V;
    • “bytes per element” depends on cache precision: FP16 is 2 bytes, 8-bit is 1 byte, and 3-bit is roughly 0.375 bytes when packed bit by bit.

    A rough estimate looks like this (illustrative only, for order-of-magnitude reference; actual usage varies by architecture and implementation):

    1. def kv_cache_bytes(layers, kv_heads, head_dim, ctx_len,
    2. bits=16, batch=1):
    3. """Estimate KV cache memory usage (in bytes); for capacity planning only."""
    4. bytes_per_elem = bits / 8
    5. # 2: one copy each for K and V
    6. return 2 * batch * ctx_len * layers * kv_heads * head_dim * bytes_per_elem
    7. model = dict(layers=32, kv_heads=8, head_dim=128)
    8. for ctx in (32_768, 131_072, 262_144):
    9. for bits in (16, 3):
    10. gb = kv_cache_bytes(bits=bits, ctx_len=ctx, **model) / 1024**3
    11. print(f"ctx={ctx:>7} kv_bits={bits:>2} KV ≈ {gb:5.2f} GiB")
    12. # ctx= 32768 kv_bits=16 KV ≈ 3.91 GiB
    13. # ctx= 131072 kv_bits=16 KV ≈ 15.63 GiB
    14. # ctx= 262144 kv_bits=16 KV ≈ 31.25 GiB
    15. # ctx= 32768 kv_bits= 3 KV ≈ 0.82 GiB
    16. # ctx= 131072 kv_bits= 3 KV ≈ 3.27 GiB
    17. # ctx= 262144 kv_bits= 3 KV ≈ 6.54 GiB

    This calculation is based on multi-head attention (MHA), the most intuitive upper bound. Models that use grouped-query attention (GQA) cache only a smaller number of KV heads, so actual usage can shrink by the ratio of “actual KV heads / attention heads.”

    1.3 Two easily overlooked amplifiers

    The context window is a hard floor. Many models claim support for 128K or even 256K contexts. For developers, this means:

    • Once you load such a model, the framework often pre-allocates a KV cache pool sized close to the maximum length in one shot;
    • Even if you’ve only chatted for a few turns, memory has long since been reserved at the upper limit;
    • Simply “having opened a long-context model” can itself eat up more than half of the available memory.

    Concurrent requests are a multiplier. The batch size in the formula is not a constant. In a serving deployment, N concurrent requests each carry a near-full-window context, and KV memory scales up by roughly N times. That is why long context plus high concurrency is the combination most likely to trigger OOM.


    2. Why weight quantization doesn’t solve the long-context problem

    A common misconception in practice is: “I’m already using a 4-bit quantized model—why does it still not fit?” To understand this, you need to separate weights from the KV cache:

    Dimension Model weights KV cache
    Changes with context Fixed Grows linearly
    Determined by Parameter count Context length × concurrency × architecture parameters
    Quantization difficulty Done offline, calibrated per block via statistics Produced online, distribution shifts dynamically with input and layer depth
    Common compression methods Group quantization (e.g., 4-bit, 8-bit) Low-bit quantization, sparse retention, eviction, cross-request sharing

    The two kinds of objects have different natures:

    • Weights are fixed after loading, and inference only needs to dequantize per block after quantization, so 4-bit can significantly shrink the footprint;
    • The KV cache is produced in real time by online forward passes, and the Key/Value distributions differ widely across layers and tokens, so quantization must control error while keeping runtime overhead low.

    More critically, there is a “scissor gap” between the two. Take a model on the order of 30 billion parameters: 4-bit weights need about 16–18GB, while a 128K-context KV cache is already close to 16GB at FP16 precision. On shared-memory devices, the KV cache has become the equal of the entire model. Pushing weight bit-width lower only damages model capability first, without buying the room that long context needs.

    KV cache compression is not a substitute for weight quantization—it is an independent optimization dimension for long-context scenarios.


    3. Technical routes for compressing the KV cache

    KV cache compression can be roughly divided into three routes.

    3.1 Route 1: Store less—sparse retention and eviction

    The idea is that “not every historical token is equally important”:

    • Static/heuristic retention: always keep the first few tokens and the tokens within a recent window; this strategy has proven empirically stable on some models;
    • Dynamic retention based on attention scores: pick important tokens according to attention weights, at a higher computational cost;
    • Cross-request sharing: reuse the same KV cache across requests with identical system prompts or identical prefixes.

    These methods can achieve high compression ratios, but they are essentially “selectively discarding” data. For tasks like precise retrieval, verbatim quoting, and code analysis, there is a risk of missing key information or producing errors.

    3.2 Route 2: General low-bit group quantization

    This is the most common and engineering-mature approach in inference frameworks: slice each token’s Key/Value vectors at each layer into several small blocks, compute a scale factor (and a zero point when needed) for each block separately, then quantize to 4-bit or 8-bit.

    Advantages:

    • Simple to implement, mature kernels, compatible with most models;
    • Easy to handle interaction with positional encoding.

    The limitation: the quantization parameters themselves consume memory. Smaller blocks mean less error, but a higher overhead share for the scale factors, so the effective compression ratio takes a hit; larger blocks save metadata but cause more noticeable precision loss.

    3.3 Route 3: Random rotation + low-bit quantization (a two-level scheme)

    In recent years, academia and industry have proposed a data-independent KV compression idea that breaks down roughly into two levels:

    Level 1: Random orthogonal rotation to “square up” the distribution.

    • The biggest enemy of low-bit quantization is outliers—a few values far larger than the rest. To cover them, the whole block is forced to use a very coarse quantization step.
    • The approach rotates the Key/Value vectors with a random orthogonal matrix (equivalent to an orthogonal transform). Rotation doesn’t change the vector lengths or the geometric relationships between vectors, so the inner products that attention scores rely on are largely preserved.
    • At sufficiently large dimensions, an approximately Gaussian vector’s components tend toward being independent and identically distributed after a random orthogonal rotation. The original outliers get “spread out,” and the distribution becomes more favorable to low-bit quantization.

    Level 2: Polar decomposition + binary projection.

    • The rotated vector is decomposed in polar coordinate space. The radius part is quantized separately at higher precision, while the direction part is encoded via the signs of a set of random projections (1 bit per dimension).
    • Random projections approximately preserve the relative relationships between vectors, so the geometric structure needed for attention scoring is retained.

    The engineering value of this scheme lies in being data-independent:

    • It doesn’t require iterating over a calibration dataset, nor does it rely on prior statistics of a particular layer or a particular class of token distribution;
    • Compared with group quantization that “stores a scale factor per block,” it eliminates most of the quantization metadata;
    • Publicly available information indicates that at 3-bit precision it can achieve about 4–5× compression with roughly a 1% increase in perplexity (PPL).

    Of course, every compression scheme has its cost: the rotation transform requires extra computation, and the low-bit format needs corresponding efficient kernels. Whether the rotation matrix is pre-generated and cached per layer also directly affects runtime overhead.

    3.4 Trade-offs among the three routes

    Route Typical compression ratio Impact on attention Engineering maturity Applicable scenarios
    Sparse retention / eviction High, but strategy-dependent May miss discarded tokens Medium Very long conversations, streaming log-type scenarios
    Group quantization About 2–4× Affected by outliers and block size High General use, quick integration
    Random rotation + low-bit About 4–5× (3-bit) Geometric structure largely preserved, needs empirical validation Improving, depends on kernel support Long documents, long codebases, very long multi-turn

    4. Enabling KV cache compression in a local inference framework: engineering essentials

    Whether KV cache compression can actually be deployed depends on whether the runtime environment supports it and on the trade-off between precision and speed.

    4.1 Three checks before enabling

    1. Kernel support: low-bit KV caches need dedicated attention kernels (that quantize and dequantize when writing and reading the cache); pure CPU implementations or generic kernels usually can’t use it directly;
    2. Model structure match: different models have different layer counts, KV head counts, and whether they use GQA, so the compression scheme must be adapted correctly;
    3. Coordination of quantization and cache: a common practice is “quantize only K” while keeping Value at higher precision, or letting the framework decide the quantization ratio for both. Confirm that the framework’s default policy meets your precision requirements.

    4.2 Typical configuration approach

    Parameter names and value ranges differ widely across frameworks. The following uses a product-agnostic configuration to illustrate the idea:

    1. # Example config: pseudocode, field names vary by framework
    2. inference:
    3. context_length: 131072 # maximum declared context
    4. kv_cache:
    5. quantize: true
    6. bits: 3 # common options are 2/3/4 bit
    7. mode: rotation_polar # compression mode: rotation+polar / group quantization / none
    8. quantize_value: true # whether to quantize V as well; affects precision and memory
    9. prefill_chunk_size: 4096 # chunked prefill to control peak memory for long prompts
    10. memory_headroom: 0.15 # fraction of memory reserved for the system and temporary buffers

    Note that the fields above are illustrative only. The actual parameter names, values, and default behavior should follow the official documentation of the framework you use.

    4.3 How to combine it with weight quantization

    Weight quantization and KV cache quantization can be stacked, but the two aren’t simply “the smaller the better”:

    • Weights first: if device memory is plentiful, prioritize compressing the KV cache while keeping weights at higher precision (8-bit or even FP16) to minimize capability loss;
    • Both weights and KV at low bit-width: if device memory is tight, compress both at once, but watch for compounded error. The model’s own quantization error and the KV cache’s quantization error accumulate gradually over long sequences;
    • Combined with sparsity: under extreme long context, you can combine “low-bit KV cache + partial eviction strategy,” but you must re-run quality evaluations, because the two error sources reinforce each other.

    4.4 Two common runtime pitfalls

    Peak memory during prefill. When processing long prompts, attention computation and intermediate activations produce temporary peaks that can trigger OOM before the KV cache itself is full. Mitigations include: enabling chunked prefill (splitting the long prompt into small chunks and computing them section by section), limiting per-request length, and reducing concurrency when necessary.

    System memory headroom. On shared-memory devices, the inference process and the operating system share the same memory pool. Once inference fills up memory, other applications may be forcibly swapped out or even killed. It’s recommended to set an explicit memory cap in the configuration and reserve a 10%–20% safety margin.


    5. Testing methodology: how to tell whether compression actually “helps”

    KV cache compression isn’t a “one-click speedup”—its benefits depend heavily on the use case. Here’s a reusable verification method.

    5.1 Controlling variables

    Fix the model, weight precision, random seed, prompt content, and concurrency, changing only two variables: the “KV cache compression level” and the “context length.”

    5.2 Evaluation metrics

    Category Metric Description
    Memory Peak resident memory of the inference process Includes weights, KV cache, and runtime overhead
    Memory Growth curve as context increases Sampled at points like 2K/8K/32K/64K/128K
    Speed Time to first token (TTFT) Mainly driven by prefill time under long prompts
    Speed Decode throughput (tokens/s) Compare “very short output” against “longer output” scenarios
    Quality Perplexity (PPL) Fast but not comprehensive; mainly reflects overall language modeling quality
    Quality Long-context task set Key information retrieval, multi-point summarization, cross-paragraph quoting, long-code Q&A
    Quality Stability Repeat the same prompt multiple times and check output consistency

    5.3 An executable test workflow

    1. 1. Select 3–5 long documents from the target domain (varying from 8K to 64K tokens)
    2. 2. Design 5–10 questions for each document:
    3. - "Needle in a haystack" questions that require looking back at the beginning/middle
    4. - Aggregation questions that require combining information from multiple places
    5. - Detail questions involving precise numbers, names, or lines of code
    6. 3. Run under three configurations: "no compression / group quantization / rotation+polar compression"
    7. 4. Record peak memory, TTFT, decode throughput, and the number of correct answers per question
    8. 5. Compute: memory reduction, quality retention rate, throughput change

    5.4 Decision criteria

    • Worth enabling: quality retention ≥95%, memory reduction ≥50%, and decode throughput no lower than baseline. Here, compression brings previously unrunnable long contexts into a usable range.
    • Use with caution: quality drops 5%–10%, or accuracy on long-document detail tasks falls noticeably. Move up to 4-bit, or compress only K.
    • Not recommended: clear factual errors appear, or decode throughput drops sharply due to dequantization overhead. Here, “compression buys slower inference,” and you should roll back the approach.

    6. Benefits and costs: a decision framework for long-context compression

    6.1 The benefit side

    1. The context ceiling shifts from “can it open” to “how large can it go”: scenarios that OOM directly at 128K may enter the usable range after compression;
    2. Higher concurrency capacity: with per-request KV memory reduced, the same memory can serve more concurrent requests;
    3. Less paging thrash: once memory pressure drops, interference between the system and the inference process decreases, and interaction becomes smoother.

    6.2 The cost side

    1. Extra computation: rotation transforms and dequantization add computational overhead. Decode is usually memory-bandwidth bound, and after compression the bytes read per token decrease, which may improve throughput; but on devices with ample bandwidth, the extra computation may cancel out or even exceed the gains;
    2. Precision risk: precision at 3-bit and below may show error accumulation on long sequences and multi-turn conversations;
    3. Implementation dependence: some model structures or attention variants may not yet be fully supported;
    4. Engineering complexity: it requires additional configuration, monitoring, and evaluation workflows.

    6.3 Decision checklist

    Before enabling KV cache compression, confirm the following in order:

    • The current bottleneck really is the KV cache (not weights or runtime overhead)
    • The target context length is clear (e.g., “must support 128K input”)
    • The inference kernels support low-bit KV caches
    • A long-context quality evaluation baseline is established
    • System memory safety headroom is reserved
    • Monitoring is configured to observe memory growth and OOM risk

    KV cache compression is moving from an “optional optimization” toward “long-context infrastructure”:

    • Format standardization: low-bit KV caches need a unified format and kernels across frameworks and hardware;
    • Software-hardware co-design: how quantization kernels pair with hardware instruction sets will determine the real-world gains of compression schemes;
    • Controllable precision: tiered compression (high precision for important tokens, low precision for ordinary tokens) is an important direction for balancing precision and efficiency;
    • Combined with retrieval: long-context inference is forming a complementary relationship with retrieval-augmented generation (RAG)—retrieval handles “finding the right information,” compression handles “fitting the information in,” and together they lower the cost of using long context.

    For developers deploying long-context models on shared-memory devices, KV cache compression offers a clear optimization path. But it isn’t a cure-all:

    • Short-term gains: pulling originally unusable 128K and 256K contexts back into a usable range, significantly improving interaction smoothness and concurrency capacity;
    • Long-term key factor: evaluation and validation grounded in real tasks determine whether you can truly use long context with confidence—open it, use it well, and sustain it.

    The recommended path to adoption is: measure the memory composition first → then choose a compression scheme → finally validate quality with a task set. Making every memory saving rest on verifiable data is the right way to engineer long-context inference.