KV Cache Memory Management A Machine Learning Mastery post details how serving engines should manage KV cache memory, giving the formula M_KV(N) = 2·L·H_KV·D·N·b for estimating cache size for a full-attention decoder with L layers, H_KV key-value heads, head dimension D, N retained tokens and b bytes per element. The post contrasts contiguous request-sized allocation, which requires reallocation and copying as sequences grow and suffers external fragmentation, with paged allocation in which each request holds a block table mapping logical token blocks to noncontiguous physical blocks, wasting fewer than B token slots in its final block for block size B. It also covers configuring the KV cache in vLLM, a block allocator with copy-on-write, and reclamation, offload and measurement. 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 https://machinelearningmastery.com/attention-variants-for-efficient-inference/ calculated the cache required by different attention architectures, and Prefix Caching and Prompt Reuse https://machinelearningmastery.com/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. 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: python Configure vLLM KV-cache limits and generate a response. from vllm import LLM, SamplingParams llm = 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 123456789101112131415161718 from vllm import LLM, SamplingParams llm = 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 https://machinelearningmastery.com/activation-kv-cache-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. Simulate block allocation, sharing, and reclamation in a paged cache. class PagedCache: def init self, block tokens, num blocks : if block tokens < 1 or num blocks < 1: raise ValueError "block tokens and num blocks must be positive" self.block tokens = block tokens self.free = list range num blocks - 1, -1, -1 self.tables = {} self.payload = {} self.refs = {} def allocate self, initial= : if not self.free: raise MemoryError "KV block pool is full" block id = self.free.pop self.payload block id = list initial self.refs block id = 1 return block id def create self, request id : if request id in self.tables: raise ValueError "request already exists" self.tables request id = def fork self, source id, target id : if target id in self.tables: raise ValueError "target already exists" table = self.tables source id .copy for block id in table: self.refs block id += 1 self.tables target id = table def append self, request id, token id : table = self.tables request id if not table or len self.payload table -1 == self.block tokens: table.append self. allocate elif self.refs table -1 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 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 class PagedCache: def init self, block tokens, num blocks : if block tokens < 1 or num blocks < 1: raise ValueError "block tokens and num blocks must be positive" self.block tokens = block tokens self.free = list range num blocks - 1, -1, -1 self.tables = {} self.payload = {} self.refs = {} def allocate self, initial= : if not self.free: raise MemoryError "KV block pool is full" block id = self.free.pop self.payload block id = list initial self.refs block id = 1 return block id def create self, request id : if request id in self.tables: raise ValueError "request already exists" self.tables request id = def fork self, source id, target id : if target id in self.tables: raise ValueError "target already exists" table = self.tables source id .copy for block id in table: self.refs block id += 1 self.tables target id = table def append self, request id, token id : table = self.tables request id if not table or len self.payload table -1 == self.block tokens: table.append self. allocate elif self.refs table -1 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 https://arxiv.org/abs/2309.06180 . This paper describes block tables, sharing, and the original vLLM allocator design. - vLLM documentation. Cache Configuration https://docs.vllm.ai/en/latest/api/vllm/config/cache/ . Documents cache size, block size, cache dtype, prefix caching, and offloading controls. - vLLM documentation. Automatic Prefix Caching Design https://docs.vllm.ai/en/latest/design/prefix caching/ . Discusses block identity, reference counts, and reuse. - vLLM documentation. Metrics https://docs.vllm.ai/en/latest/usage/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.