KV Cache Memory Management

KV Cache Memory Management

Every active sequence keeps keys and values from earlier tokens so decode can attend to them without recomputing the whole prompt. This KV cache grows with the retained sequence length. A serving engine must place it, share it when safe, and reclaim it promptly. Attention Variants and Memory Efficiency calculated the cache required by different attention architectures, and Prefix Caching and Prompt Reuse explained prefix reuse. This post focuses on the allocator that turns those requirements into physical storage for many changing requests. In this post, you will learn about: How to estimate KV cache capacity under a memory budget How paged blocks, sharing, and copy-on-write manage growing requests How reclamation and offload affect capacity and latency Let’s get started. KV Cache Memory Management.Photo by Jonny Gios. Some rights reserved. Overview This post is divided into five parts; they are: Estimating Cache Capacity Contiguous and Paged Allocation Configuring the KV Cache in vLLM A Block Allocator with Copy-on-Write Reclamation, Offload, and Measurement Estimating Cache Capacity For a full-attention decoder with $L$ layers, $H_{KV}$ key-value heads, head dimension $D$, $N$ retained tokens, and $b$ bytes per cache element, the approximate KV size is $$ M_{KV}(N) = 2 L H_{KV} D N b. $$ The factor of two is for keys and values. At each attention layer, a token produces a query, a key, and a value. Its query is used immediately to compare that token with the keys of visible tokens. Future tokens do not reuse this query, but they do reuse the earlier token’s key when computing attention scores and its value when forming the attention output. The persistent cache therefore keeps keys and values, while queries can be discarded after the current computation. The equation gives the cache payload size. A block-based allocator rounds token counts up to whole blocks, and a real engine also needs model weights, activations, communication buffers, graph-capture memory, and allocator headroom. Sliding-window and mixed-attention models require a per-layer calculation because not every layer retains the same number of tokens. For a conservative concurrency estimate, subtract weights, workspace, and headroom from the available device memory. Divide the remaining bytes by the per-request KV cache size after rounding the combined prompt and maximum output length to whole blocks. This is a capacity estimate, not a throughput guarantee. A GPU may hold many sequences but run them slowly if their combined decode work exceeds the compute or memory-bandwidth budget. Contiguous and Paged Allocation A contiguous request-sized allocation reserves one region for each sequence. It gives simple indexing, but growth means you need to reallocate the memory and copy it over to a new location. Reserving the maximum sequence length in advance avoids those copies at the cost of unused memory. Separate allocations can also leave free gaps that are too small for a new request even when total free memory is large; this is external fragmentation. A paged cache divides a memory pool into fixed-size blocks. Each request owns a block table that maps logical token blocks to physical cache blocks. The request’s blocks need not be adjacent. This makes allocation and growth easier and allows requests to point to the same prefix blocks. The unused positions in the last block are internal fragmentation. With a block size of $B$, each request wastes fewer than $B$ token slots in its final block, excluding other allocator overhead. PagedAttention is the attention algorithm that makes this noncontiguous layout practical. A conventional attention implementation can treat the cached keys and values for a sequence as one contiguous tensor. PagedAttention instead follows the request’s block table, reads its physical KV blocks, and computes attention over them as one logical token sequence. It therefore avoids gathering the complete cache into a new contiguous allocation before every attention operation. Individual blocks are still contiguous; only the full sequence is allowed to span nonadjacent blocks. Block size is a trade-off. Smaller blocks waste fewer final slots and support finer sharing, but require larger block tables and more address-translation work. Larger blocks reduce metadata and may suit an attention kernel better, but increase final-block waste. The best block size depends on kernel layout and request lengths, not only on the allocator. Configuring the KV Cache in vLLM vLLM creates and manages its KV cache internally. The application does not pass a past_key_values object between decode steps. Instead, cache behavior is configured when the LLM engine is created: 123456789101112131415161718 from vllm import LLM, SamplingParamsllm = LLM( model="facebook/opt-125m", max_model_len=512, kv_cache_memory_bytes=512 * 1024**2, block_size=16, kv_cache_dtype="auto", enable_prefix_caching=True,)params = SamplingParams(temperature=0, max_tokens=32)result = llm.generate( ["Explain why a KV cache accelerates decoding."], params, use_tqdm=False,)[0]print(result.outputs[0].text) The parameter kv_cache_memory_bytes sets the cache-pool size per GPU explicitly; this example reserves 512 MiB. If it is omitted, vLLM infers the cache size from the memory remaining under gpu_memory_utilization. Setting kv_cache_memory_bytes overrides that automatic calculation, so use one sizing method rather than trying to combine them. Each physical block holds 16 token positions because this example sets block_size=16. The setting kv_cache_dtype="auto" uses the model dtype for cache storage. Other supported cache dtypes can reduce memory use, but they require compatible hardware and introduce the numerical trade-offs discussed in Activation and Floating-Point Quantization. The setting enable_prefix_caching=True permits complete matching blocks to be reused across requests. The parameter max_model_len limits the combined prompt and output length of one sequence. It does not reserve that many token slots for every request. vLLM allocates blocks from the shared pool as requests grow, uses the cache automatically during generate(), and returns blocks to the pool when requests finish. A Block Allocator with Copy-on-Write The following example illustrates block ownership with standard Python. It stores token IDs as a stand-in for real per-layer key and value tensors. It demonstrates allocation, sharing, and reclamation; a serving engine supplies the actual KV tensors and attention kernel. 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 class PagedCache: def __init__(self, block_tokens, num_blocks): if block_tokens 1: old_id = table[-1] new_id = self._allocate(self.payload[old_id]) self.refs[old_id] -= 1 table[-1] = new_id self.payload[table[-1]].append(token_id) def release(self, request_id): for block_id in self.tables.pop(request_id): self.refs[block_id] -= 1 if self.refs[block_id] == 0: del self.refs[block_id] del self.payload[block_id] self.free.append(block_id)cache = PagedCache(block_tokens=4, num_blocks=8)cache.create("A")for token in range(6): cache.append("A", token)cache.fork("A", "B")cache.append("A", 60)cache.append("B", 99)print("A:", cache.tables["A"])print("B:", cache.tables["B"])print("live blocks:", len(cache.refs))cache.release("A")cache.release("B")print("free blocks after cleanup:", len(cache.free)) The first full block remains shared. The last block initially contains two tokens, so appending to A creates a private copy before writing. B then writes to the original last block. Reference counts prevent either request from freeing a block still used by the other. This is the same rule needed when beam-search branches or parallel samples diverge after a shared prompt. The example copies token IDs. A real copy-on-write operation copies the affected KV tensors for every relevant layer, head, and position. A production engine may avoid copying a partial last block by delaying sharing until a complete block boundary. Either way, the block table and the tensor payload must stay consistent. Reclamation, Offload, and Measurement The cache manager releases blocks to reclaim memory. It may do so on EOS, output-length limits, cancellation, timeout, and error. Prefix caching is a deliberate exception: inactive blocks may remain reusable, but they must be evictable and must not be mistaken for active request ownership. When cache memory is full, an engine can reject new work or offload some blocks to CPU memory to let the new requests start. Offload saves GPU capacity but adds transfer latency and consumes memory bandwidth. Recomputing saves transfer bandwidth but repeats model work. Efficiently managing the cache memory is the job of the cache manager. Further Reading Woosuk Kwon et al. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. This paper describes block tables, sharing, and the original vLLM allocator design. vLLM documentation. Cache Configuration. Documents cache size, block size, cache dtype, prefix caching, and offloading controls. vLLM documentation. Automatic Prefix Caching Design. Discusses block identity, reference counts, and reuse. vLLM documentation. Metrics. Lists cache usage and preemption measurements. Summary KV cache capacity depends on retained tokens, attention architecture, precision, and allocator overhead. A block table lets a request grow without a contiguous allocation and lets branches share a prefix safely. Correct reference counting and cleanup are as important as the initial capacity estimate: leaked or wrongly shared blocks can exhaust memory or corrupt outputs. No comments yet.

Original Source

Read the full article at Machinelearningmastery →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.