New Tool Radar

AI Concepts

How to Shrink llama.cpp’s KV Cache for Long Contexts

Quantize the KV cache with --cache-type-k and --cache-type-v so a long context fits in the memory you have.

Schematic diagram with four steps: pick the K and V cache types, start the server with them, load a long context, then compare memory use and answer quality.

A long context eats memory through the KV cache: every token’s keys and values stay in memory for the whole conversation. The server lets you quantize that cache with --cache-type-k and --cache-type-v, trading a little precision for a much smaller memory footprint.

Set the K and V cache types

Start the server with the cache types you want, for example --cache-type-k q8_0 --cache-type-v q8_0. The allowed values are f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0 and q5_1, and the default for both is f16. The V cache tolerates aggressive compression better than the K cache, so a common shape is to keep K at higher precision and compress V harder.

llama-server -m model.gguf -c 32768 \
  --cache-type-k q8_0 --cache-type-v q8_0

Cache quantization is a quality trade: the smaller the type, the more memory you save and the more the model’s long-context answers can drift. Test with your own long prompts before settling on a type, and keep the full-precision default for short chats where memory is not the constraint.

Try it: four checks

Check What you should see If you do not see it
Types accepted The server starts with the cache types Use an allowed value from the list
Context fits A long context loads without an out-of-memory error Lower the cache type if it does not
Memory lower Memory use is lower than with f16 Compare the same context at both settings
Answers sane Long-context answers stay sensible Raise the precision if they drift

Expected result. We checked the llama.cpp server README, which lists the –cache-type-k and –cache-type-v options, their allowed values and the f16 default. We did not run the server on this machine.

Limits

This guide covers the cache types only. The quality cost of a given type depends on the model and the task. We did not test any setting ourselves.

Sources

See all