{"slug": "kv-cache-memory-management", "title": "KV Cache Memory Management", "summary": "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.", "body_md": "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.\n\n[*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.\n\nIn this post, you will learn about:\n\n- How to estimate KV cache capacity under a memory budget\n- How paged blocks, sharing, and copy-on-write manage growing requests\n- How reclamation and offload affect capacity and latency\n\nLet’s get started.\n\n## Overview\n\nThis post is divided into five parts; they are:\n\n- Estimating Cache Capacity\n- Contiguous and Paged Allocation\n- Configuring the KV Cache in vLLM\n- A Block Allocator with Copy-on-Write\n- Reclamation, Offload, and Measurement\n\n## Estimating Cache Capacity\n\nFor 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\n\n$$\n\nM_{KV}(N) = 2 L H_{KV} D N b.\n\n$$\n\nThe 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.\n\nThe 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.\n\nFor 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.\n\n## Contiguous and Paged Allocation\n\nA 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.\n\nA 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.\n\n*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.\n\nBlock 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.\n\n## Configuring the KV Cache in vLLM\n\nvLLM 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:\n\n``` python\nConfigure vLLM KV-cache limits and generate a response.\n\nfrom vllm import LLM, SamplingParams\n\nllm = LLM(\n    model=\"facebook/opt-125m\",\n    max_model_len=512,\n    kv_cache_memory_bytes=512 * 1024**2,\n    block_size=16,\n    kv_cache_dtype=\"auto\",\n    enable_prefix_caching=True,\n)\nparams = SamplingParams(temperature=0, max_tokens=32)\n\nresult = llm.generate(\n    [\"Explain why a KV cache accelerates decoding.\"],\n    params,\n    use_tqdm=False,\n)[0]\nprint(result.outputs[0].text)\n\n123456789101112131415161718\n\nfrom 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)\n```\n\nThe 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.\n\nEach 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.\n\nThe 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.\n\n## A Block Allocator with Copy-on-Write\n\nThe 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.\n\n```\nSimulate block allocation, sharing, and reclamation in a paged cache.\n\nclass PagedCache:\n    def __init__(self, block_tokens, num_blocks):\n        if block_tokens < 1 or num_blocks < 1:\n            raise ValueError(\"block_tokens and num_blocks must be positive\")\n        self.block_tokens = block_tokens\n        self.free = list(range(num_blocks - 1, -1, -1))\n        self.tables = {}\n        self.payload = {}\n        self.refs = {}\n\n    def _allocate(self, initial=()):\n        if not self.free:\n            raise MemoryError(\"KV block pool is full\")\n        block_id = self.free.pop()\n        self.payload[block_id] = list(initial)\n        self.refs[block_id] = 1\n        return block_id\n\n    def create(self, request_id):\n        if request_id in self.tables:\n            raise ValueError(\"request already exists\")\n        self.tables[request_id] = []\n\n    def fork(self, source_id, target_id):\n        if target_id in self.tables:\n            raise ValueError(\"target already exists\")\n        table = self.tables[source_id].copy()\n        for block_id in table:\n            self.refs[block_id] += 1\n        self.tables[target_id] = table\n\n    def append(self, request_id, token_id):\n        table = self.tables[request_id]\n        if not table or len(self.payload[table[-1]]) == self.block_tokens:\n            table.append(self._allocate())\n        elif self.refs[table[-1]] > 1:\n            old_id = table[-1]\n            new_id = self._allocate(self.payload[old_id])\n            self.refs[old_id] -= 1\n            table[-1] = new_id\n        self.payload[table[-1]].append(token_id)\n\n    def release(self, request_id):\n        for block_id in self.tables.pop(request_id):\n            self.refs[block_id] -= 1\n            if self.refs[block_id] == 0:\n                del self.refs[block_id]\n                del self.payload[block_id]\n                self.free.append(block_id)\n\ncache = PagedCache(block_tokens=4, num_blocks=8)\ncache.create(\"A\")\nfor token in range(6):\n    cache.append(\"A\", token)\ncache.fork(\"A\", \"B\")\ncache.append(\"A\", 60)\ncache.append(\"B\", 99)\nprint(\"A:\", cache.tables[\"A\"])\nprint(\"B:\", cache.tables[\"B\"])\nprint(\"live blocks:\", len(cache.refs))\ncache.release(\"A\")\ncache.release(\"B\")\nprint(\"free blocks after cleanup:\", len(cache.free))\n\n12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364\n\nclass 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))\n```\n\nThe 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.\n\nThe 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.\n\n## Reclamation, Offload, and Measurement\n\nThe 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.\n\nWhen 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.\n\n## Further Reading\n\n- 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.\n- 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.\n- vLLM documentation. [Automatic Prefix Caching Design](https://docs.vllm.ai/en/latest/design/prefix_caching/) . Discusses block identity, reference counts, and reuse.\n- vLLM documentation. [Metrics](https://docs.vllm.ai/en/latest/usage/metrics/) . Lists cache usage and preemption measurements.\n\n## Summary\n\nKV 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.", "url": "https://wpnews.pro/news/kv-cache-memory-management", "canonical_source": "https://machinelearningmastery.com/kv-cache-memory-management/", "published_at": "2026-12-06 21:06:59+00:00", "updated_at": "2026-12-06 22:44:39.744825+00:00", "lang": "en", "topics": ["ai-infrastructure", "large-language-models", "machine-learning"], "entities": ["Machine Learning Mastery", "vLLM", "PagedAttention"], "also_reported_by": [], "takeaway": "Estimate KV cache payload as 2·L·H_KV·D·N·b bytes, then divide device memory left after weights, workspace and headroom by the per-request size rounded up to whole blocks to get a conservative concurrency estimate, not a throughput guarantee.", "recommendation": {"advice": "Size KV cache with 2·L·H_KV·D·N·b, subtract weights, workspace and headroom, and divide by per-request size rounded to whole blocks; use paged blocks with copy-on-write to avoid reallocation copies and external fragmentation.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/kv-cache-memory-management", "markdown": "https://wpnews.pro/news/kv-cache-memory-management.md", "text": "https://wpnews.pro/news/kv-cache-memory-management.txt", "jsonld": "https://wpnews.pro/news/kv-cache-memory-management.jsonld"}}