KV Cache Quantization on Unified Memory: Getting 128K Context to Run

    Long-context LLM inference often runs out of memory not because the model is too large, but because the KV cache grows linearly with context length—a problem that hits unified-memory devices especially hard. This article explains how to estimate KV cache size, why KV cache quantization is harder than weight quantization, the mainstream techniques behind low-bit KV quantization, how to configure it in practice, how to benchmark it credibly, and the limitations and risks to watch for. It also includes a landing checklist so you can turn long context from "demonstrable" into "budget-controllable."

    1. First, Locate the Problem: It’s the Context That Blows Up Memory, Not the Model

    When deploying long-context models locally, a common misdiagnosis is “I’m out of memory, so the model must be too big.” In reality, model weights are a constant—their footprint doesn’t change after loading. What grows linearly with conversation turns and document length is the KV cache. The attention mechanism has to keep the intermediate representations (the Keys and Values) of every processed token resident in memory so they can be reused.

    This memory can be estimated with a formula that’s independent of any specific model:

    1. KV_bytes ≈ 2 × L × H_kv × D_head × S × (b / 8)
    2. L : number of Transformer layers
    3. H_kv : number of KV heads per layer (far smaller than attention heads under GQA/MQA)
    4. D_head : per-head dimension
    5. S : context length (number of tokens)
    6. b : bit width per value
    7. factor 2 : one copy each for K and V

    Plugging in a common magnitude (L=40, H_kv=8, D_head=128) gives a resident cost of roughly 160 KiB/token at 16 bits.

    Context Length 16-bit KV 3-bit KV (incl. metadata overhead)
    8K ≈ 1.25 GiB ≈ 0.25 GiB
    32K ≈ 5.0 GiB ≈ 1.0 GiB
    128K ≈ 20 GiB ≈ 3.8 GiB
    256K ≈ 40 GiB ≈ 7.5 GiB

    (These estimates don’t include block management, alignment padding, or positional index overhead; in practice, add another 10%~15%.)

    This table explains two commonly misread phenomena. First, why different models can differ by more than 2x in memory usage at the same context length: layer count, KV head count, and whether grouped-query attention is used all directly scale the L and H_kv terms—independent of “who is smarter.” Second, why unified-memory architectures feel it more acutely: the CPU and the accelerator share the same physical memory pool, so KV cache growth doesn’t just squeeze the inference process—it triggers system-wide memory pressure and paging. Once it spills to disk swap, decode throughput falls off a cliff, showing up as “it starts, but every token stalls for seconds.”

    So the value proposition of KV cache compression is clear: it doesn’t make the model smarter, and it doesn’t change computational complexity—it just turns the right column of that table into the left column. The 32K tier is often still tolerable; 128K and above is the line between “can it run” and “it can’t.”

    2. The Technical Lineage: Why KV Cache Quantization Is Harder Than Weight Quantization

    Let me draw the boundary first. The 4-bit and 8-bit quantization we talk about day to day refers to weight quantization: done offline, static, with the error fixed once. Because the weight distribution is fixed, it typically uses group-wise scalar quantization where every 64 or 128 values share a scale factor and zero point, and the block-level metadata is negligible relative to the block data.

    KV cache quantization is a runtime, dynamic, continuously growing process. The difficulties are three:

    1. Online constraint. The K/V of new tokens must be written in real time, and the quantize/dequantize overhead can’t slow down decoding—otherwise the savings get eaten by throughput loss.
    2. Non-stationary distribution and outliers. In attention, a few channels often show significant outlier magnitudes; naive per-tensor scaling squashes most normal values onto very few integer grid points, and quantization noise dominates precision.
    3. Metadata overhead sensitivity. The longer the context, the more blocks there are; if each small block must store a scale factor and zero point, the low-bit savings get offset—which is why the “2~4x compression” often falls short of the theoretical value at long contexts.

    The mainstream approach of the past couple of years can be abstracted into a three-step combination; industry solutions mainly differ in how they combine these steps and in their implementation kernels:

    • Rotation transform: use a random orthogonal (Hadamard-like) transform to scatter the activation distribution, spreading outlier energy across all dimensions so the post-quantization distribution is closer to uniform, which lowers quantization error.
    • Polar / low-bit scalar quantization: perform low-bit quantization in the rotated space; because the distribution becomes smoother, 3 bits can achieve close to the signal-to-noise ratio of higher bit widths.
    • Low-dimensional random projection for residual correction: approximate the quantization residual with a random projection far smaller than the original dimension. Because the projection matrix is data-independent (it can be merged with the rotation matrix and fixed offline), you don’t need to store scaling parameters per block at runtime—so you can reach roughly 4-5x compression around 3 bits while keeping precision loss low.

    About the “minimal precision loss” claim, a stricter statement is needed: the general practice is to look at the relative increase in language-modeling perplexity (PPL), and public research can keep it on the order of one percent under suitable configs. But PPL is not the same as task performance. Long-document retrieval, cross-paragraph citation, and structured extraction are more sensitive to local perturbations; whether the error is acceptable must be validated with your own eval set, not judged by the compression ratio alone.

    3. General Practice Guide for Enabling It

    Different inference frameworks use different toggle names, but the configuration dimensions are highly consistent. Here’s an abstracted configuration model (illustrative pseudo-config, not any specific tool’s real interface):

    1. kv_cache:
    2. quant_enabled: true
    3. bits: 3 # 2/3/4 are common tiers; higher is more stable
    4. group_size: 64 # grouping granularity; smaller is more accurate but costs more metadata
    5. quantize_k: true
    6. quantize_v: true # quantizing only K usually falls clearly short
    7. rotation: hadamard # orthogonal rotation transform; recommended to keep
    8. keep_full_precision_layers: [0, 1] # leave the first/last few layers unquantized—best value
    9. residual_projection: true # low-dimensional projection to correct residuals

    When landing it, proceed in this order:

    Step 1 — Confirm hardware and kernel compatibility. Low-bit KV only truly saves memory when a dedicated dequantization kernel supports it; if it falls back to a generic implementation, you can end up with “memory dropped, but decoding got slower.” Things to check: whether the bit width is supported by the underlying attention kernel, whether quantization coexists with continuous batching, and whether it’s mutually exclusive with prefix cache.

    Step 2 — Do a minimal validation. Fix a long document, run the same sampling parameters before and after the toggle (keep temperature, top-p, and random seed consistent), and compare output differences, whether OOM still triggers, and decode token/s. Don’t push the bit width all the way to 2 bits and then tune back.

    Step 3 — Enable/disable by context-length tier. For short conversations (within 8K), the net gain from enabling quantization is close to zero and it introduces extra dequantization overhead; it makes more sense to set it to auto-switch by context length.

    Step 4 — Build a memory budget table. Use “available memory − weight footprint − system and runtime overhead” as the KV budget cap, then work backward from the formula in Section 1 to the maximum sustainable context, instead of trial-and-error until you hit OOM.

    4. How to Do Credible Benchmarking

    The conclusions floating around online often contradict each other, mostly because variables weren’t controlled. Recommended evaluation criteria:

    • Control variables: the same weights at the same weight precision; fix context tiers at 8K / 32K / 64K / 128K / 256K; fix sampling parameters and random seed; use identical input documents.
    • Must-test metrics: peak memory usage, maximum sustainable context length, prefill throughput (token/s—determines long-document first-token latency), decode throughput (token/s—determines reading experience), task-level metrics (long-document QA accuracy, citation localization accuracy, summary faithfulness), and relative PPL increase.
    • Must-record workload shape: single-request long context and multi-request concurrency are two completely different scenarios. Total KV usage ≈ concurrency × per-request context length × per-token cost; as concurrency rises, the quantization benefit gets diluted, so you need to re-test.
    Tier 16-bit 3-bit Points to Watch
    8K baseline no significant gain overhead may actually increase
    32K usable memory headroom clearly larger good for multi-turn long conversations
    128K often OOM from unusable to usable also check whether prefill is clearly slower
    256K unusable depends on weights and system headroom watch the combined effect of position extrapolation quality and quantization

    An easily overlooked interpretation point: the benefit scales with context length. This is also why many “it didn’t help in testing” conclusions come from short-context tests—at low tiers, the absolute memory saved by quantization is limited, while the fixed cost of dequantization is still paid.

    5. Limitations and Risks

    • It doesn’t solve the O(n²) attention computation. KV quantization only reduces memory bandwidth and capacity pressure; the prefill compute is unchanged, and first-token latency for very long documents can still be long.
    • Error compounds with long-distance extrapolation. When the context exceeds the model’s training length and relies on position extrapolation, quantization error and position-extrapolation error amplify each other, showing up as “it reads the document in but answers wrong.”
    • Incompatible with some advanced features. Prefix cache reuse, speculative decoding, and some attention sparsification strategies may conflict with the low-bit KV storage layout; confirm each one before enabling.
    • Precision regression needs your own eval set. Prepare at least 30~50 long-document task samples covering single-hop retrieval, multi-hop reasoning, cross-paragraph citation, and numeric extraction, and use them as a regression baseline for every tuning round.
    • Don’t expect “lossless.” Any low-bit scheme trades precision for capacity; the goal is to get the maximum context within your business’s acceptable error.

    6. From a Single Machine to a Service

    If long-context capability needs to be offered as a service, the engineering focus shifts from “single-GPU / single-machine memory budget” to capacity and stability governance. This can usually be built from a combination of general cloud service categories: object storage to hold the raw and sliced data of long documents, container platforms to host elastically scaling inference replicas, logging services to analyze the context-length distribution of long-tail requests, monitoring and alerting to track GPU memory watermark and OOM rate, and message queues to queue requests and shave peaks. Platforms such as Baidu AI Cloud provide exactly these general capability categories; specific specs and billing are subject to the official documentation.

    7. Landing Checklist

    1. Calculate your context budget with the formula first, then decide whether to compress—don’t turn compression on and look at the results later.
    2. Prioritize keeping rotation and residual correction, and leave the first/last few layers at full precision—that’s the best value.
    3. Quantize both K and V; quantizing only one side usually falls short.
    4. Default to off for short context, and auto-switch by length.
    5. Run a dual regression with PPL plus your own task set; don’t draw conclusions from PPL alone.
    6. Test concurrency separately; don’t extrapolate single-request conclusions directly.
    7. Write “maximum sustainable context” and “prefill throughput” into your launch baseline as gatekeeper metrics for subsequent version iterations.

    In one sentence: the point of KV cache quantization isn’t to make the model smarter, but to turn long context from “demonstrable” into “budget-controllable.” Calculate the memory ledger first, then talk about 128K or 256K—that’s the sustainable engineering path.