Models

When a Smaller KV Cache Is Worth the Trade-Off

Calculate the memory your KV cache can use, account for quantization overhead, then test quality and latency at the context you actually need.

Two stacks of translucent glass memory tiles beside a hardware module, illustrating a smaller KV cache.

Compress an LLM’s KV cache when that cache, rather than the model weights, prevents your required context or number of simultaneous requests from fitting in memory. First calculate the space left after the model and other allocations. Then compare a lower-precision cache with the same model, prompt length and workload. A smaller cache is useful only if the complete run fits and its answers and latency still meet your requirements. The cache can approach 5 GB for a 10,000-token Llama 2 7B example in Hugging Face’s implementation article; that is cache memory alone, not the memory bill for every model.

Separate the weights from the growing cache

Model weights and the key-value (KV) cache are different allocations. Weights come from the model file you loaded. The cache holds keys and values from previous tokens so generation can reuse them instead of recomputing those representations. Reducing weight precision changes the first allocation; reducing cache precision changes the second. Hugging Face explains this reuse and gives the basic cache calculation in its KV quantization article. Our guide to choosing a quantized model file deals with weights. Keep that file fixed for the comparison in this article.

For a conventional full-attention layer, a useful first estimate is:

cache bytes ≈ 2 × layers × KV heads × head dimension × bytes per stored value × cached tokens × concurrent sequences

The first factor of two counts keys and values. Hugging Face’s worked Llama 2 example uses 32 layers, 32 KV heads, dimension 128 and two bytes per value. That is 524,288 bytes per token; 10,000 tokens are about 4.88 GiB before other allocations. The maker describes this as roughly 5 GB. The model’s own architecture and runtime determine whether this simple formula applies directly. Sliding-window and chunked attention can stop some layers’ caches from growing after a limit, as the current Transformers cache documentation explains.

The token count must include both the input already processed and room for the output you plan to generate. For two independent requests, budget for both live caches, not just one. A large context setting is a ceiling, not proof that a workload uses every token. Check the actual longest job and concurrency you need. If the weight file itself cannot load, shrinking the cache cannot repair that problem. The local VRAM guide covers that broader memory bill.

Calculate the budget your cache can use

Start with available memory on the device that will hold the cache. Subtract loaded weights and other allocations, including runtime buffers and the headroom you choose to leave. If you measure free memory before loading the model, subtract the loaded model’s memory too. Do not subtract it twice if your measurement was taken after loading. Call the result the cache budget:

cache budget = usable device memory − loaded weights − other allocations and reserve

This illustrative ledger uses hypothetical measurements, not a test of a particular GPU or model. Assume 16 GiB of usable memory, 8 GiB for loaded weights and 2 GiB for runtime allocations and reserve. That leaves 6 GiB for all active caches. Assume a hypothetical architecture whose full-precision cache takes exactly 0.25 MiB per token for one request. The figures below are arithmetic bounds; no actual runtime overhead or fit has been measured.

Cache case, one request Ideal cache bytes per token Ideal 6 GiB token ceiling What is missing from the estimate
Full precision, 16-bit 0.25 MiB 24,576 Runtime allocation behavior
8-bit payload 0.125 MiB 49,152 Scales, padding and other overhead
4-bit payload 0.0625 MiB 98,304 Scales, full-precision residual and other overhead

For example, 6 × 1,024 MiB divided by 0.25 MiB per token equals 24,576 tokens. Halving payload bytes doubles only the ideal cache ceiling. It does not halve total device memory, and it does not establish that 49,152 tokens will fit. With two equally long concurrent requests, halve each ideal per-request ceiling again. Actual memory accounting is the final gate.

The VRAM calculator can help with a first hardware estimate; its result should not be treated as verification of a quantized KV cache’s implementation overhead. Record the loaded weight allocation and peak memory in your own runtime at your target context.

Account for scales and full-precision leftovers

The number of bits in the payload is not necessarily the effective number of bits stored per value. Grouped integer quantization needs scale or zero-point data. A runtime may also retain recent keys and values at their original precision. Hugging Face’s implementation explanation describes a fixed-size residual cache: once it fills, older values are quantized. That residual uses more memory but avoids quantizing and dequantizing the newest values at every generation step. Its size therefore affects both memory and speed.

Return to the illustrative 0.25 MiB-per-token example. Suppose an integer 4-bit implementation retained the latest 128 tokens in full precision. At a 20,000-token context, the raw payload would be (19,872 × 0.0625) + (128 × 0.25) = 1,274 MiB, before scales and other overhead. A naive 20,000 × 0.0625 calculation gives 1,250 MiB. The 24 MiB difference is a property of this assumed residual design, not a measured result or a universal default. If scale storage and allocation overhead are unknown, the honest conclusion is that 1,274 MiB is a lower bound for this hypothetical implementation, not a confirmed fit.

Do not transfer one format’s ratio to another. An FP8 floating-point cache in vLLM, grouped int4 in Transformers and llama.cpp block formats may have different scale handling, supported hardware and kernels. The current Transformers documentation lists hqq, quanto and fp8 backends with different supported precisions and parameters. The current vLLM guide documents FP8 per-tensor and per-attention-head scales. The version and backend you actually run must supply the overhead figure you use.

Check the runtime before changing precision

Select a cache format your installed runtime and attention backend actually support. Transformers accepts cache_implementation="quantized" with a backend-specific cache_config, and warns that cache quantization can hurt latency when context is short and memory is already sufficient. Its FP8 backend is per-tensor and rejects the grouped-integer parameters, including residual length. Those are documented behavior, not interchangeable tuning knobs (Transformers cache strategies).

vLLM’s FP8 path uses kv_cache_dtype="fp8". Its documentation says uncalibrated scales default to 1.0 and recommends dataset calibration for the highest-quality quantization. It also permits some sensitive layers to remain at native precision, which changes the memory bill. The per-attention-head scale pathway is limited to the Flash Attention backend in the current vLLM documentation. Check your installed version’s compatibility rather than assuming that a configuration copied from another runtime will work.

Do not interpret a successful start as proof of a sound setting. A model can load and still run out of memory when the prompt grows, the output continues, or another request arrives. A different attention backend may also change timing. Write down the runtime version, backend, model artifact and cache format so the comparison is reproducible.

Test the longest job you actually need

Use the same model file and weight precision for the full-precision baseline and each cache candidate. Hold the prompt, output allowance, decoding settings, runtime build and concurrency fixed. Test near the longest context that matters to your work. Include tasks whose answer depends on information near the start of that context, not only short questions.

Record for each run Why it matters
Exact model artifact and weight format Prevents a weight or model change from masquerading as a cache effect
Runtime build, attention backend and cache K/V types Identifies which implementation produced the result
Input tokens, output allowance and concurrent requests Defines the actual memory load
Peak memory and completion or out-of-memory status Tests the complete fit rather than payload arithmetic
Time to first token and decode time Separates prefill response from ongoing generation speed
Required-answer checks at the target context Tests whether saved memory costs accuracy that matters

Agree on the required-answer checks before you compare outputs. For example, in a long document question, specify the facts the answer must retrieve and what counts as a miss. That is a proposed test design, not a test we ran. Repeat the same cases for the baseline and candidate. If the baseline itself fails a required check, you cannot blame a candidate’s failure on cache quantization alone.

Hugging Face’s published comparison found that its int4 implementation stayed close to FP16 on the particular perplexity and LongBench tasks it reported, while int2 degraded on some tasks. It also reported a generation-speed cost in parts of its setup (Hugging Face’s published measurements). These are evidence for testing both quality and speed, not a guarantee for another model, context, backend or workload. The independent articles in the search sample also used different methods and hardware; their results are not substitutes for your own acceptance test.

Keep the smallest change that passes

Make the decision in order. If the full-precision cache fits the required workload with acceptable latency, it is the simplest reference point. If it fails only on cache capacity, try a supported lower-precision setting, measure peak memory at the target context and concurrency, then compare answer checks and timing. Keep the least aggressive change that clears all three gates: fit, quality and latency. If none clears them, reduce context or concurrency, choose a different model or revise the hardware budget. The multi-GPU memory guide explains why adding card capacities without checking each allocation can still fail.

The decision is specific to the deployed model, workload and runtime. A 4-bit label cannot promise four times as much context because the weights, reserve, scales, residual cache and allocation behavior remain. Record the measured outcome and revisit it when the model artifact or runtime changes. That keeps a memory-saving setting from becoming an unexplained quality or latency regression.

Sources

All pages read on November 29, 2026.

Free toolCan my GPU run this model?Check my GPU
DailyTech Editorial Team

We explain AI with numbers you can check. Every price, limit and benchmark links to its source and the date we read it. How we work · Report an error