Guides · 4 min read

Stretch your context: flash attention and KV cache quantization

Two settings that cut the memory a long conversation needs, with the flags for Ollama and llama.cpp.

Once the model fits, the next thing to grow is the KV cache (why it grows). Two settings in llama.cpp-based apps keep it in check.

Flash attention

Flash attention computes attention in a way that avoids building a large intermediate table, which saves memory and often time at long context. Many apps turn it on by default for supported hardware. You mostly meet it because quantizing the V half of the cache needs it.

KV cache quantization

By default the cache is stored at 16 bits. Storing it at 8 bits (q8_0) roughly halves it, and 4 bits (q4_0) cuts it to roughly a quarter. One published example for a 32B model at 32K tokens: about 8.6 GB at 16 bits, 4.3 GB at 8 bits and 2.1 GB at 4 bits. The 8-bit setting usually costs very little quality; 4-bit can show up as small errors on long, exacting tasks, so try 8-bit first.

AppHow to set it
llama.cppllama-server -m model.gguf -c 32768 -fa on -ctk q8_0 -ctv q8_0. The flags are -ctk and -ctv for the K and V cache types and -fa for flash attention.
OllamaSet OLLAMA_FLASH_ATTENTION=1 and OLLAMA_KV_CACHE_TYPE=q8_0 before starting the server. It applies to every model that server loads.
LM Studio, Jan and othersLook for flash attention and cache type options in the model’s load settings; availability depends on the version.

Flag names change between versions. If one is rejected, check the app’s current documentation.

What it does not do

Estimates come from published hardware specs and our open formulas, not from running the model on your machine. Real speed varies with runtime, drivers and settings. Numbers marked “Measured” come from a linked benchmark.