A GPU can have enough FLOPS to serve thousands of generated tokens per second and still sit underutilized because its memory allocator is losing a fight with request length variance. One chat request stops after 40 tokens, another runs for 4,000, and a third branches into eight candidate continuations. A paged KV cache is the memory-management mechanism that makes this workload tractable without reserving a maximum-length attention buffer for every request.

Paged KV Cache Explained: The Bottleneck It Solves

During autoregressive inference, a transformer produces key and value tensors for every layer and every processed token. Future tokens attend to those tensors, so they must remain resident for the life of the sequence. This is the KV cache.

The cache is expensive. Its memory footprint grows approximately with sequence length, layer count, hidden dimensions, attention configuration, precision, and batch size. For a modern model, the KV cache often becomes the practical capacity limit well before model weights exhaust GPU memory. Quantization can reduce weight memory substantially, but it does not eliminate the linear growth of per-request state.

A naive serving runtime allocates one contiguous KV region per sequence, sized for its expected or maximum context length. That design is simple and performs acceptably for fixed-length offline batches. It fails under interactive production traffic because request lengths are unpredictable. Reserved but unused tail capacity becomes internal fragmentation. Freed allocations leave holes of incompatible sizes, creating external fragmentation. Eventually, the scheduler cannot admit a request even when total free memory appears sufficient.

The operational symptom is familiar: GPU utilization is mediocre, queue time rises during mixed workloads, and the service reports out-of-memory failures that do not match a coarse memory dashboard. The problem is not only insufficient VRAM. It is allocating a variable-length object as though it had a fixed lifetime and size.

PagedAttention Changes the Allocation Model

PagedAttention, popularized by vLLM, applies the central idea of virtual memory to attention state. Instead of storing each request’s KV cache in one contiguous buffer, the runtime divides the cache into fixed-size token blocks. Physical GPU blocks are drawn from a shared pool. Each sequence maintains a block table mapping its logical token positions to physical blocks.

If a block holds 16 tokens, a request that has generated 50 tokens needs four blocks. Those blocks can be scattered across GPU memory. Attention kernels use the block table to gather the appropriate key and value data as they compute attention. The sequence experiences logically contiguous context without requiring physically contiguous allocation.

This changes allocation behavior in three useful ways. First, memory is committed incrementally as tokens arrive, rather than pessimistically at request admission. Second, a finished sequence returns whole blocks to the shared pool immediately. Third, fragmentation is bounded by the unused portion of the final block for each active sequence, not by every sequence’s difference between current and maximum context length.

The implementation is more specific than a generic heap allocator. A physical block usually represents token positions across the relevant layers and KV heads, arranged so the attention kernel can process blocks efficiently. The block table is metadata, but it sits on a latency-sensitive path: poor layout, excess indirection, or host-device synchronization can erase some of the gains from better memory utilization.

A concrete allocation example

Assume a server uses 16-token blocks and receives three requests with current lengths of 18, 90, and 1,010 tokens. The runtime assigns two, six, and 64 blocks respectively. The first request wastes 14 token slots in its final block; the second wastes six; the third wastes 14. That is bounded waste, and the block pool can reuse all released full blocks as soon as any request completes.

Under a contiguous reservation model sized to 2,048 tokens, those same requests could reserve 6,144 token positions despite needing only 1,118. The gap is not an academic optimization. It determines whether the scheduler can batch another set of requests or must leave compute capacity idle.

Why Prefix Sharing Makes Paging More Valuable

Paged allocation is particularly effective when requests share prompt prefixes. Consider a coding assistant receiving many requests against the same repository policy, system prompt, tool schema, and long retrieved context. Recomputing the prefix is wasteful, but duplicating its KV cache is often worse.

A paged runtime can let multiple sequences point to the same physical prefix blocks. When sequences diverge, they allocate new blocks for their unique tokens. This is copy-on-write semantics applied to inference state. The same technique is critical for parallel sampling, beam search, and speculative decoding workflows where multiple branches initially share almost all context.

The sharing contract must be explicit. Shared blocks must be immutable once published to another sequence, reference counts must remain correct under cancellation, and eviction cannot reclaim a block until the final dependent sequence releases it. Bugs here are not merely memory leaks. A stale block-table entry can produce cross-request data exposure or corrupt model output, which turns a capacity optimization into a security incident.

Prefix caching also has workload limits. It delivers little when prompts are highly unique, and it can create a skewed cache population where large popular prefixes crowd out new traffic. Admission policy needs to account for reuse probability, tenant isolation, and cache residency cost rather than treating every prefix as equally valuable.

The Scheduler and the Cache Are One System

Paged KV cache design does not independently guarantee throughput. It expands the scheduler’s feasible set. A continuous batching scheduler can admit requests at token boundaries, mix prefill and decode work, and retain many concurrent sequences without requiring identical lengths. But it still needs a policy for when memory pressure arrives.

The scheduler should know the number of free blocks, each request’s next-token allocation requirement, the expected prefill expansion, and any blocks pinned by shared prefixes. At high utilization, admission based only on current free blocks is too optimistic. A large prefill can consume blocks rapidly, starving decode requests that need one more block to preserve latency objectives.

Common mitigations include reserving a block margin for decode traffic, limiting prefill chunk size, separating latency-sensitive and bulk queues, and applying per-tenant quotas. For long-context systems, chunked prefill matters because it prevents a single massive prompt from monopolizing the block pool and delaying hundreds of active decodes.

This is also where seemingly good throughput numbers become misleading. A server can maximize aggregate tokens per second by admitting long prefill jobs aggressively while making interactive time-to-first-token unacceptable. Paged allocation gives operators more room to schedule intelligently; it does not decide which latency metric the product should protect.

Block Size Is a Real Trade-Off

Smaller blocks reduce tail waste and improve memory packing. They also increase block-table entries, allocator activity, reference-count operations, and kernel indirection. Larger blocks simplify metadata and can improve memory access regularity, but they waste more capacity for short sequences and reduce the granularity of prefix sharing.

There is no universal optimal block size. It depends on the distribution of prompt and generation lengths, model architecture, KV precision, kernel implementation, and whether the service relies heavily on beam search or reusable prefixes. A chat service with short responses may prefer smaller blocks. A batch summarization system with long, relatively uniform contexts may accept larger blocks for lower metadata overhead.

GPU architecture also matters. The attention kernel must maintain coalesced memory access and avoid turning a logical gather into a cascade of inefficient loads. Modern implementations often combine paged storage with specialized attention kernels, grouped-query attention, KV-cache quantization, and fused operations. Treating paging as an isolated data structure misses where most serving wins and regressions actually occur.

What to Measure in Production

Do not validate a paged cache solely by checking whether out-of-memory errors decline. Instrument the block pool and connect it to user-facing outcomes. At minimum, track free-block watermark, block allocation failures, final-block waste, prefix-block sharing ratio, per-request KV footprint, cache evictions, and block-table metadata overhead.

Pair those measures with time to first token, inter-token latency, queue delay, batch composition, GPU memory utilization, and GPU compute utilization. A high sharing ratio can look impressive while a popular tenant consumes disproportionate residency. High VRAM utilization can also be unhealthy if it leaves no headroom for normal decode growth and causes admission oscillation.

Test cancellation and failure paths as hard as the happy path. Disconnects during prefill, aborted tool calls, worker restarts, speculative branches that are rejected, and partial batch failures all exercise ownership accounting. Block leaks tend to appear slowly under production concurrency, then present as a capacity cliff hours later.

A paged KV cache is best understood as an allocator, a sharing protocol, and a scheduling primitive combined. Build the observability and admission controls around that reality, and GPU memory stops being a static ceiling. It becomes a managed resource that can be traded deliberately among latency, throughput, context length, and cost.

Fediverse reactions

Leave a Reply