KV Cache Quantization: A Memory-Saving Approach for Long-Context Local Inference

    This article explores KV cache quantization as a practical technique for reducing memory usage during long-context inference on local hardware. It explains why long contexts exhaust memory, how quantization works, its trade-offs in output quality, and what to check before enabling it. Readers will also learn how to evaluate the results through measurable metrics and what to do when memory pressure remains high.

    Why Long Contexts Exhaust Memory First

    When running large language models locally, memory is consumed by two main components: model weights and the KV cache, which grows continuously during inference. Model weights occupy a fixed amount of memory once loaded. The KV cache, however, expands as the model processes more tokens—it stores the Key and Value vectors for every token the model has already processed, allowing new tokens to be generated by reading this cached data directly instead of recomputing it.

    The size of the KV cache grows linearly with context length. Increasing context from 2,048 tokens to 65,536 tokens means the cache grows 32 times larger. While this is linear growth, the base numbers are large enough that the total quickly becomes significant.

    Users with dedicated GPUs can rely on VRAM capacity to cope. On unified-memory devices, such as Apple Silicon Macs where CPU and GPU share the same memory pool, the system also needs to reserve space for other applications. When model weights plus cache approach the memory limit, the system may first compress or swap out memory pages, and in severe cases, it may terminate the inference process entirely. That is why long-context failures typically manifest as sudden process exits rather than simply slower responses.

    What KV Cache Quantization Is

    Weight quantization is already familiar to many—for example, compressing model weights from 16-bit down to 4-bit or 8-bit. KV cache quantization follows the same principle, but applied to the cache generated during inference. Since the cache is continuously written and read during generation, quantizing and dequantizing must be fast enough, and the added computational overhead needs to be taken into account.

    A common approach is group quantization. Data is split into blocks, each block stores a scaling factor, and values are stored as low-bit integers. This method is simple and reliable, but the scaling factors themselves take up space. The lower the bit width, the larger this overhead becomes relative to the total size.

    Recent research has attempted to reduce this extra overhead. The general approach involves two steps: first, apply a random orthogonal transformation to the vectors to spread out outlier values and make the distribution more uniform, then perform low-bit quantization; second, apply residual correction to the quantization error—for instance, using a 1-bit projection method to compensate for part of the error. For specific algorithm details, formulas, and compression ratio calculations, refer to the original papers, as definitions of “compression ratio” vary considerably between papers—whether scaling factors are counted, whether residual storage is included, and other factors can change the final numbers. When reading these papers, first clarify the calculation conventions before comparing figures.

    The Cost of Quantization

    Compression comes with trade-offs. Lower precision in the KV cache can affect several types of tasks:

    • Long-range information retrieval, such as details from the middle of a document.
    • Precise references to numbers, dates, and proper nouns.
    • Correspondences between variable names and functions in code.

    The lower the bit width, the higher the risk. Different models also vary in their sensitivity to quantization—a configuration that works well on one model may not hold up on another.

    In short-context scenarios, the cache itself is small, so the memory savings from quantization are limited, and gains in speed or quality are usually negligible. Keeping default settings is the more straightforward choice in these cases.

    What to Check Before Enabling KV Cache Quantization

    1. Confirm whether your framework supports KV cache quantization, and which bit widths and strategies are available. Parameter names differ across frameworks, so consult the documentation or command-line help output for your specific version.
    2. Record the framework version, model name and quantization format, Mac model, and unified memory size. Without this information, others cannot reproduce your results, and you cannot compare outcomes if you switch machines.
    3. Start with a small context to verify basic functionality, then gradually increase the length.
    4. Back up configuration files before making changes so you can quickly roll back if problems arise.

    For example, in llama.cpp, the options --cache-type-k and --cache-type-v control the types for the K cache and V cache respectively, with common values including q8_0 and q4_0. Quantizing the V cache typically requires enabling Flash Attention as well. For exact parameter names, acceptable values, and dependencies, refer to the --help output for your specific version, as these may change between releases.

    How to Evaluate the Results

    Do not rely on intuition—measure the actual numbers. On a Mac, Activity Monitor shows memory pressure and swap usage. During testing, track the following metrics:

    • Memory pressure curve and swap usage.
    • Time to first token (TTFT), the time from submitting a prompt to receiving the first output token.
    • Decoding speed, measured in tokens generated per second.
    • Output quality, checked with several questions whose answers are known in advance, ideally including a question about details located in the middle of a document.

    For testing, run the same set of prompts multiple times with quantization disabled and enabled, and record both averages and variance. A single run provides limited reference value. Also record the test conditions—model, framework version, quantization configuration, machine model, and memory size.

    What to Do When Memory Is Still Insufficient

    If memory pressure remains high after quantization, consider these options:

    • Shorten the context, or split long documents into sections, generate summaries for each section, and then combine them.
    • Switch to a smaller model, or apply lower-bit weight quantization.
    • Close other memory-consuming applications.

    When memory pressure rises, the system begins using swap space. The process may not crash immediately, but generation speed can drop noticeably, and disk I/O will increase. Relying on swap for extended operation will degrade both experience and stability.

    Some frameworks use memory mapping (mmap) to load model files. Mapping means placing the file into the virtual address space and letting the system read data pages into memory on demand, rather than loading the entire file at startup. When memory is tight, the system may reclaim these pages and re-read them from disk when needed, which affects speed. Memory mapping cannot replace sufficient physical memory, nor can it magically make a model that does not fit fit into memory.

    Conclusion

    KV cache quantization can, under certain conditions, reduce the memory footprint of long-context inference, allowing configurations that would otherwise fail to run. Its effectiveness depends on the model, framework version, task type, and hardware. For tasks like long-document summarization or codebase analysis, it is recommended to run small-scale tests with your own material, check output quality and resource usage, and gradually extend the context length after confirming reliability. Published numbers from others can serve as a reference but should not be treated as results for your specific machine.