Inference: Memory Optimizations
By Ludovico Bessi, Senior ML Engineer at Google Β· Updated
Shrinking the two things that fill GPU memory at serving time: the KV cache and the model weights.
The Memory Budget
At serving time, GPU memory holds three things:
GPU memory β weights + KV cache (all active requests) + activations/workspace
Weights are fixed for a given model and precision. The KV cache grows with context length Γ concurrent requests. Activations and framework overhead are a smaller, roughly constant slice (often 10β20% of memory once you count the CUDA graphs, workspace and fragmentation).
Every byte saved on weights is a byte available for KV cache, and more KV cache means larger batches and higher throughput. Every byte saved per token also speeds up decode, because decode is bound by how many bytes it reads per step. For a practical sizing guide, see How Much GPU Memory Do You Need to Serve an LLM?
This chapter covers two families of techniques: KV cache optimizations and model compression.
Part 1: KV Cache Optimizations
Reusing the cache: RadixAttention and prefix caching
The cheapest KV entry is the one you do not compute twice. Prefix caching keeps the KV blocks of common prefixes (system prompts, documents, earlier conversation turns) and reuses them across requests. SGLang's RadixAttention stores cached prefixes in a radix tree with LRU eviction and schedules requests to maximize reuse. The details are in Attention Optimizations.
The memory question is a policy question: cached prefixes compete with active requests for the same GPU memory. Engines keep cached blocks only while memory is free and evict them first under pressure.
Predictive caching and tiered KV storage
GPU memory is small; CPU memory and local SSDs are large. Tiered KV caching moves KV blocks that are not needed right now β paused requests, idle conversation sessions, cached prefixes β to CPU memory or disk, and brings them back when needed.
The challenge is latency: transferring a long context's KV cache over PCIe can take longer than recomputing it. Predictive caching addresses this by anticipating which KV blocks will be needed next and prefetching them before the request needs them, for example:
- prefetching a conversation's cached history as soon as the user starts a new turn,
- keeping prefixes that many requests share (by observed frequency) in the fastest tier,
- loading the next layer's KV blocks from CPU while the GPU computes the current layer.
Done well, the transfer overlaps with compute and the user never waits for it. Systems such as LMCache and Mooncake-style KV stores apply these ideas across a whole serving cluster.
Parallel KV cache generation
The KV cache must be built before decoding can start, and for long prompts this prefill dominates time to first token. Parallel KV cache generation spreads that work across several GPUs or processes.
KV-Runahead (Cho et al., 2024) is one example: instead of splitting each layer's computation across devices (tensor parallelism), it assigns different chunks of the prompt to different processes. Each process computes the KV cache for its chunk, using the KV cache handed to it by the process with the earlier chunk. Causal attention makes this a natural pipeline, and chunk boundaries can be load-balanced because later chunks have more attention work. The authors reported over 1.4Γ and 1.6Γ speedups on Llama 7B and Falcon 7B compared with tensor and sequential parallelism. Context parallelism with Ring Attention achieves a similar goal for very long prompts.
Cross-layer KV sharing
Adjacent transformer layers often produce similar keys and values. Cross-Layer Attention (CLA; Brandon et al., 2024) lets groups of adjacent layers share a single set of KV heads, so only one layer in each group writes to the cache. Sharing across pairs of layers halves the KV cache, and it combines with GQA/MQA for further savings. Like GQA, it must be trained in.
YOCO ("You Only Cache Once", Sun et al., 2024) goes further: the first half of the network builds one global KV cache, and the second half reuses it through cross-attention, so the cache is stored once rather than per layer.
Quantizing the KV cache
Storing keys and values in FP8 instead of FP16 halves the cache with little quality loss and is supported by major serving engines. INT4 or 2-bit KV quantization saves more but needs care: keys have outlier channels, so methods like KIVI quantize keys per channel and values per token. A small number of recent tokens is often kept in full precision.
Eviction and compression
When context is very long, not every cached token matters. Eviction policies keep the tokens that receive the most attention plus the most recent ones (H2O, for example), or keep a few initial "attention sink" tokens plus a recent window (StreamingLLM). These cap memory at the cost of exact recall, so they suit streaming and summarization better than precise retrieval.
Part 2: Model Compression
Weight memory sets a fixed floor, and for small batches it dominates decode time. Quantization stores weights in fewer bits. For a practical comparison of methods, see LLM Quantization Explained: GPTQ vs AWQ vs GGUF.
Weight-only vs. weight-and-activation quantization
- Weight-only (W4A16, W8A16): weights stored in 4 or 8 bits and dequantized to 16-bit inside the matmul kernel. Cuts memory and memory traffic, which is what decode needs. This is the most common setup.
- Weights and activations (W8A8, FP8): both operands in 8-bit, so Tensor Cores run faster too. Helps compute-bound prefill and large-batch decode. Activations have outliers that make this harder; SmoothQuant moves the difficulty from activations into weights with a per-channel rescaling.
AWQ: activation-aware weight quantization
AWQ (Lin et al., 2023) observes that a small fraction of weight channels β those multiplied by large activations β matter far more than the rest. Rather than keeping them in higher precision (which is hardware-unfriendly), AWQ scales up those salient channels before quantization and scales the activations down to compensate. The salient weights then lose relatively less precision. AWQ needs only a small calibration set to measure activation magnitudes, does no backpropagation, and generalizes well across domains. It is widely used for 4-bit GPU serving.
SqueezeLLM: dense-and-sparse, non-uniform quantization
SqueezeLLM (Kim et al., 2023) makes two observations:
- Uniform grids waste precision. Weight values cluster, so SqueezeLLM uses non-uniform quantization: it places the quantization levels with a k-means clustering weighted by each weight's sensitivity (estimated from the Fisher information), so that important weights land near a level.
- Outliers wreck small bit-widths. It applies a dense-and-sparse decomposition: a tiny fraction of outlier and highly sensitive weights is kept in full precision in a sparse matrix, and the dense remainder is quantized aggressively.
The authors reported near-lossless compression down to 3 bits, cutting the perplexity gap to FP16 by up to 2.1Γ compared with other methods at the same memory, and up to 2.3Γ speedup on an A6000 GPU. Because decode is memory-bound, the lookup-table dequantization cost is hidden.
GPTQ and GGUF
GPTQ quantizes weights column by column, using approximate second-order (Hessian) information to adjust the remaining weights to compensate for each rounding error. GGUF is the llama.cpp file format and family of mixed-precision schemes (Q4_K_M, Q5_K_M, Q8_0) for CPU and Apple Silicon inference. Both are compared in detail in the quantization deep dive.
Block-wise quantization
Nearly every modern quantization scheme is block-wise (or group-wise): weights are split into small groups (32β128 values), each with its own scale. An outlier then only hurts its own group. The idea was popularized for optimizer states by 8-bit optimizers (Dettmers et al., 2021), which use block-wise quantization to store Adam's moment estimates in 8 bits. That is a training-time and fine-tuning technique β inference has no optimizer state β but the same block-wise idea, through the bitsandbytes library, underlies NF4 weights and QLoRA fine-tuning. See Memory Efficiency.
Other compression
- Pruning removes weights. Unstructured sparsity rarely speeds up GPUs; 2:4 structured sparsity does on recent NVIDIA hardware but costs more quality.
- Distillation trains a smaller student model to mimic a larger one β often the biggest win of all if quality permits.
Putting It Together
| Technique | Saves | Quality risk | Effort |
|---|---|---|---|
| Prefix caching / RadixAttention | Repeated prefill and KV memory | None | Turn on in engine |
| Tiered / predictive KV caching | GPU KV memory for idle sessions | None | Infrastructure work |
| FP8 KV cache | 2Γ KV memory | Very low | Engine flag |
| INT4/2-bit KV cache | 4β8Γ KV memory | Lowβmoderate | Method-specific |
| Cross-layer KV sharing | 2Γ or more KV memory | Low (trained in) | Model architecture |
| INT8/FP8 weights | 2Γ weight memory | Very low | Easy |
| 4-bit weights (AWQ, GPTQ, SqueezeLLM) | 4Γ weight memory | Low | Calibration step |
A sensible order: enable prefix caching and FP8 KV cache, quantize weights to 8 bits, move to 4-bit weights if memory is still the limit, and only then consider eviction or architecture changes. Always evaluate on your own tasks.
Key Takeaways
- Memory saved on weights or per cached token becomes larger batches and faster decode.
- Reuse KV entries (prefix caching, RadixAttention), move idle ones to cheaper tiers with predictive prefetching, and build them in parallel for long prompts.
- Cross-layer sharing and KV quantization shrink the cache; eviction caps it at some cost to recall.
- AWQ protects salient channels by rescaling; SqueezeLLM uses sensitivity-weighted non-uniform levels plus a sparse outlier matrix.
- Block-wise quantization is the common thread, from 8-bit optimizers to 4-bit weights.