Serving Language Models
KV caches, paging, continuous batching and latent attention.
Training is one enormous batch job. Serving is thousands of conversations at once, each with its own prompt length, output length and latency budget, sharing a few accelerators. The weights fit easily; what runs out is memory for the conversations' KV caches and the bandwidth to read them. This lesson builds the cost model of serving and follows the ideas that serving systems of the mid-2020s combine: continuous batching, paged caches, chunked and disaggregated prefill, smaller keys and values through grouped-query and latent attention, and compressed caches.
What you’ll learn
- Model the time of a prefill and of a decoding step from FLOPs and bytes, define time to first token and time per output token, and derive how throughput and latency change with batch size and context length.
- Compute the KV-cache memory of a published configuration and the batch it allows, and the savings of multi-query, grouped-query and multi-head latent attention, including the weight absorption that lets latent attention work on the cached latents directly.
- Explain PagedAttention's block tables, why they nearly remove fragmentation and allow sharing, and iteration-level scheduling with selective batching.
- Compare chunked prefill with prefill–decode disaggregation, and cache compression by quantization and by eviction, with the evidence for each.
Latency, throughput and the cache
A request arrives with a prompt of tokens and asks for up to new ones. Serving it takes one prefill, a forward pass over the prompt that writes its KV cache and produces the first new token, then decoding steps of one token each. Two latencies matter to a user: the time to first token (TTFT), queueing plus prefill, and the time per output token (TPOT), the duration of a decoding step. The operator cares about throughput, tokens per second over all users, or about goodput, the rate of requests served within both latency targets.
Efficient Transformers showed that prefill is compute-bound and that decoding a single sequence is memory-bound by the ridge factor. Batching decoding sequences helps only partly, as a count on the illustrative accelerator ( FLOP/s, B/s) shows.
With 16-bit numbers, a step reads all bytes of weights once for the whole batch, plus each sequence's own cache, bytes at context length ; it computes FLOPs per sequence:
At short contexts the weights dominate the bytes, and the step time barely grows with until the compute term catches up near , a few hundred: batching buys throughput almost for free. But every sequence adds its own cache traffic and its own arithmetic. Once the first exceeds the second, adding sequences adds more memory time than compute time, and no batch size makes the step compute-bound. The attention FLOPs are tiny next to the cache bytes, so this happens beyond about
For the 7B model (, , ) is about 77 tokens with 32 key–value heads and about 310 with 8 (keeping fixed). Beyond it the cache sets a ceiling: throughput tends to as grows, while TPOT grows linearly in . At the ceiling is about 1,400 tokens per second with multi-head attention and 5,600 with 8 key–value heads:
Memory caps the batch before that. An 80 GB accelerator holding the model's 13.5 GB of weights fits 30 multi-head caches of 4,096 tokens, or 123 with 8 key–value heads. Pope et al. (2023) describe the same regimes at scale: loading weights dominates at small batches and short contexts, loading the cache at large ones; for a 500B+ model with multi-head attention, a batch of 512 at context 2,048 needs a 3 TB cache, three times the size of the weights.
A server runs an OPT-13B-like model: layers of width , full multi-head attention, a 16-bit cache. How many GiB of KV cache does a batch of 32 requests need at 2,048 tokens each?
Show the answer
50 GiB
Per token bytes KiB, so one 2,048-token request needs 1.6 GB, the example Kwon et al. (2023) give, and 32 requests need KiB GiB: about twice the model's 26 GB of 16-bit weights. Doubling the context or the batch doubles it again.
Smaller keys and values: MQA, GQA and latent attention
Sharing key–value heads is the cheapest way to shrink . Multi-query attention keeps a single key head and value head for all query heads (Shazeer, 2019). Grouped-query attention keeps of them, each shared by a group of query heads, and converts a multi-head checkpoint by mean-pooling each group's key and value heads and continuing pretraining with about 5% of the original compute; uptrained this way it came close to multi-head quality at nearly the speed of multi-query attention (Ainslie et al., 2023). Both divide the cache by , and both raise decoding attention's intensity to FLOPs per byte (Efficient Transformers).
Multi-head latent attention (MLA), introduced with DeepSeek-V2 (DeepSeek-AI, 2024), compresses instead of sharing. Each token's hidden state is projected to one latent vector , and every head's keys and values are linear functions of it:
Head 's score for a cached token moves the up-projection onto the query, which is computed once per step:
The weighted sum of values moves the other up-projection outside the sum, where it can be merged into the output projection :
So keys and values never need to be materialized: the paper notes that can be absorbed into and into at inference. Rotary embeddings would break the first identity, because the rotation between and depends on both positions and cannot be folded into a fixed matrix. MLA therefore adds a small decoupled key , shared by all heads and rotated by RoPE, with a matching rotated part of each query:
DeepSeek-V2 uses heads of size , and in 60 layers: 576 cached numbers per token and layer against for multi-head attention, 57 times fewer and as small as grouped-query attention with 2.25 groups. Absorption trades bytes for FLOPs: from the published shapes, the 128 heads do FLOPs per cached token and layer on 1,152 bytes (16-bit), an intensity near the ridge instead of 1:
In DeepSeek-AI's ablations, multi-head attention beat grouped-query attention with 8 groups on dense 7B models, and MLA beat multi-head attention on mixture-of-experts models at two scales while caching 4–14% as much. Relative to their earlier dense 67B model, DeepSeek-V2's KV cache was 93.3% smaller, and, served with FP8 weights and a cache quantized to about 6 bits per element, its maximum generation throughput was 5.76 times higher. These are one group's measurements on its own models; independent comparisons of latent attention with well-tuned grouped-query attention at equal training compute are few, so the comparison is less settled.
Why does MLA carry a separate rotary key instead of applying RoPE to the keys reconstructed from the latent?
- A position-dependent rotation would sit between the query and , so the up-projection could no longer be absorbed into a fixed query-side matrix, and every cached token's keys would have to be rebuilt
- RoPE needs 32-bit numbers, which the latent cache does not store
- A latent vector of dimension 512 cannot be rotated in pairs
- Applying RoPE to the reconstructed keys would make the cache larger
Show the answer
A. A position-dependent rotation would sit between the query and , so the up-projection could no longer be absorbed into a fixed query-side matrix, and every cached token's keys would have to be rebuilt
With RoPE, the score is , and differs for every pair, so no single matrix maps the query into the latent space for all cached tokens. A small shared rotated key carries the positions instead, and the absorbed content part stays position-free.
Paging the cache
Serving systems before PagedAttention stored each request's cache as one contiguous tensor, reserved up front for the longest output the request might produce, because most kernels expect contiguous tensors. That wastes memory three ways: slots reserved for tokens not yet generated, internal fragmentation when the request stops early, and external fragmentation between reservations of different sizes. Profiling such systems, Kwon et al. (2023) found that only 20.4–38.2% of the cache memory held actual token states.
PagedAttention, the core of their vLLM system, borrows virtual memory from operating systems. The cache is a pool of fixed-size blocks, 16 tokens each by default, and each sequence keeps a block table that maps its logical blocks to physical blocks anywhere in the pool. A new block is taken only when the last one fills, so each sequence wastes less than one block (under 12 MiB in the OPT-13B example, against 1.3 GiB for a request that reserves 2,048 slots and uses 300), and since all blocks have the same size there is no external fragmentation. In their experiments 96.3% of the cache memory held token states. The attention kernel follows a sequence's block table and computes attention block by block, so the blocks can sit anywhere in memory; by the merge of FlashAttention in Depth, splitting the keys into blocks changes nothing in the result.
import torch
class PagedKVCache:
"""Keys and values in fixed-size blocks from one shared pool; each sequence keeps a block table."""
def __init__(self, num_blocks, block_size, n_kv_heads, d_k):
self.B = block_size
self.k = torch.zeros(num_blocks, block_size, n_kv_heads, d_k)
self.v = torch.zeros_like(self.k)
self.free = list(range(num_blocks)) # physical blocks not in use
self.table, self.length = {}, {} # per sequence: logical -> physical blocks
def append(self, seq, k_t, v_t): # one new token's keys and values: (n_kv_heads, d_k)
n = self.length.get(seq, 0)
if n % self.B == 0: # last block full (or none yet): take any free block
self.table.setdefault(seq, []).append(self.free.pop())
block, slot = self.table[seq][n // self.B], n % self.B
self.k[block, slot], self.v[block, slot] = k_t, v_t
self.length[seq] = n + 1
def view(self, seq): # what the attention kernel reads, block by block
n, blocks = self.length[seq], self.table[seq]
return self.k[blocks].flatten(0, 1)[:n], self.v[blocks].flatten(0, 1)[:n]
def release(self, seq): # a finished sequence returns its blocks at once
self.free += self.table.pop(seq)
del self.length[seq]A sketch of the bookkeeping. A real kernel reads the blocks in place through the table instead of copying them into one tensor, and blocks shared between sequences carry reference counts.
The indirection also makes sharing cheap. Samples drawn in parallel from one prompt, or the beams of a beam search, point to the same physical blocks for their common prefix; a reference count per block and copy-on-write duplicate a block only when one sequence writes into a shared one. A prompt prefix shared by many requests, such as a long system prompt, can be cached once. When memory runs out, vLLM preempts whole sequences, either swapping their blocks to CPU memory or dropping them and recomputing them later. Together these let vLLM serve 2–4 times the throughput of FasterTransformer and Orca at the same latency (Kwon et al., 2023).
Scheduling: continuous batching, chunked and split prefill
Early serving systems batched whole requests: a batch ran until its longest request finished, so finished requests could not leave and new ones could not join. Orca (Yu, Jeong, Kim, Kim & Chun, 2022) schedules iterations instead. After every forward pass the scheduler may return finished requests and admit new ones, so the batch stays full: continuous batching. The obstacle was that the requests of one iteration are in different phases and have different lengths, so their tensors cannot be stacked. Orca's selective batching flattens the tokens of all requests into one matrix for every operation that treats tokens independently (the linear layers, normalization, activations, residual additions) and splits the batch only for attention, which must keep requests apart. On GPT-3 175B, Orca reported 36.9 times the throughput of FasterTransformer at the same latency.
Continuous batching creates a new conflict. A newly admitted request's prefill, thousands of tokens of compute-bound work, runs in the same iteration as everyone else's decoding step and stalls it: the time per output token spikes whenever a long prompt arrives. Two remedies are in use:
- Chunked prefill. Sarathi-Serve (Agrawal et al., 2024) splits each prompt into chunks and fills every iteration, up to a fixed token budget, with all pending decodes plus a chunk of prefill. Decodes never stall, iterations stay uniform, and the prefill's matrix products use arithmetic that the memory-bound decodes leave idle. Against vLLM the authors reported 2.6 times the serving capacity for Mistral-7B on one A100 and up to 3.7 times for Yi-34B on two, under tail-latency targets.
- Disaggregation. Prefill and decoding run on different GPUs, and the KV cache is shipped from one to the other. DistServe (Zhong et al., 2024) chooses the resources and parallelism of each phase separately for given TTFT and TPOT targets and reported up to 7.4 times more requests served within them; Splitwise (Patel et al., 2024) also puts the phases on different machine types, since decoding does not need the arithmetic of the newest accelerators.
The choice is a trade-off: chunking keeps one pool of GPUs but lets the two phases share every iteration; disaggregation isolates them at the price of moving caches between machines.
Think first Selective batching runs the linear layers on all the tokens of an iteration as one matrix, whatever request they belong to, but splits the batch for attention. Why can the linear layers mix requests while attention cannot?
A linear layer, a normalization or an activation acts on each token's vector separately with shared weights, so stacking tokens from different requests computes exactly what processing them one request at a time would. Attention combines tokens with each other: a token may attend only to its own request's cache, so each request needs its own scores and its own cache, of its own length.
Compressing the cache
When the cache still does not fit, store it in fewer bits or keep fewer tokens.
Quantization. Keys and values tolerate low precision, with one subtlety. Liu et al. (2024) found that keys have a few fixed channels of very large magnitude, consistent with the outlier features of Attention Sinks & Massive Activations, while values have no such pattern. Their KIVI therefore quantizes keys per channel, in groups of 32 tokens, and values per token, to 2 bits with a scale and a zero point per group, and keeps a window of up to 128 recent tokens in full precision. Across Llama, Falcon and Mistral models, quality stayed almost unchanged while peak memory, weights included, fell 2.6-fold, allowing batches up to 4 times larger and 2.35–3.47 times the throughput.
Eviction. H2O (Zhang et al., 2023) observed that a small set of tokens receives most of the attention, and that these heavy hitters correlate with frequently co-occurring tokens. It keeps a budget of recent tokens plus the tokens with the largest accumulated attention scores, and evicts the rest; keeping 20% of the cache as heavy hitters, it reported up to 29 times the throughput of DeepSpeed Zero-Inference and Hugging Face Accelerate, and 3 times that of FlexGen, on OPT-6.7B and OPT-30B. Keeping the first few tokens plus a recent window, the streaming recipe of Attention Sinks & Massive Activations, is the simplest such rule. Every eviction policy bets that what it drops will not be needed later; a question about an early detail of a long document can lose that bet, so eviction must be judged on the tasks a system will actually serve.
Key takeaways
- A request is one compute-bound prefill, which sets the time to first token, and many memory-bound decoding steps, which set the time per output token. Batching amortizes the weights but not the caches, so beyond a context of a few hundred tokens decoding stays memory-bound at any batch, and throughput tends to .
- KV memory, numbers per sequence (800 KiB per token for OPT-13B), caps the batch. MQA and GQA divide it by ; MLA caches one latent of numbers per token and layer, 576 against 32,768 in DeepSeek-V2, with the up-projections absorbed into the query and output sides.
- PagedAttention stores caches in fixed-size blocks behind block tables: less than one block of waste per sequence (96.3% of cache memory used, against 20–38% before), with prefix sharing through copy-on-write.
- Iteration-level scheduling with selective batching keeps batches full; chunked prefill and prefill–decode disaggregation stop long prompts from stalling everyone else's decoding.
- Quantization (keys per channel, values per token, down to about 2 bits with a full-precision recent window) and eviction (heavy hitters, or sinks plus a window) shrink caches further; eviction bets that what it drops will not be needed.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Under continuous batching, a request with a 16,000-token prompt is admitted while 50 other conversations are decoding. Without chunking, what happens to the others, and what does chunked prefill change?
- Their time to first token grows; chunked prefill shortens the prompt
- Their time per output token spikes during the long prefill; chunked prefill caps the prefill tokens per iteration so their decoding steps keep running
- Nothing: decoding is memory-bound, so a prefill cannot slow it
- Their throughput rises, since the batch now does more arithmetic
Show the answer
B. Their time per output token spikes during the long prefill; chunked prefill caps the prefill tokens per iteration so their decoding steps keep running
The iteration that runs the whole prefill is long and compute-bound, and every decoding sequence waits for it. Chunked prefill spreads the prompt over several iterations under a token budget, so each iteration stays short, and the prefill's arithmetic fills compute that the memory-bound decodes leave idle.
At long contexts and large batches, decoding throughput approaches , the memory bandwidth over the cache bytes per sequence. Which change raises this ceiling?
- A larger batch
- An accelerator with twice the peak FLOP/s and the same bandwidth
- A faster prefill kernel
- Grouped-query or latent attention, or a cache stored in fewer bits
Show the answer
D. Grouped-query or latent attention, or a cache stored in fewer bits
The ceiling is where cache reads use all the bandwidth, so only fewer bytes per cached token (fewer key–value heads, a latent, fewer bits, fewer tokens) or more bandwidth raise it. With 8 key–value heads instead of 32, the 7B model's ceiling at 4,096 tokens rises from about 1,400 to about 5,600 tokens per second.
What does PagedAttention change about the KV cache?
- It stores each sequence's cache in fixed-size blocks anywhere in memory, found through a block table, so at most one partly filled block per sequence is wasted and common prefixes can share blocks
- It compresses each key and value into a lower-dimensional vector
- It evicts the tokens that have received the least attention
- It moves the cache to CPU memory after every decoding step
Show the answer
A. It stores each sequence's cache in fixed-size blocks anywhere in memory, found through a block table, so at most one partly filled block per sequence is wasted and common prefixes can share blocks
Allocating blocks on demand removes reserved and fragmented space: Kwon et al. measured 96.3% of cache memory holding token states, against 20.4–38.2% in earlier systems. Reference counts and copy-on-write let parallel samples, beams and shared prompts reuse blocks.
With its up-projections absorbed, what does MLA's decoding attention read from the cache for each earlier token, in each layer?
- The keys and values of all heads, reconstructed from the latent
- The token's hidden state
- The latent and the shared rotary key : 576 numbers in DeepSeek-V2
- Only the shared rotary key
Show the answer
C. The latent and the shared rotary key : 576 numbers in DeepSeek-V2
Each head maps its query into the latent space once, , scores it against directly, sums latents with the attention weights and applies , merged into , afterwards. The decoupled key adds the positional part: numbers instead of .
Further reading
- W. Kwon, Z. Li, S. Zhuang, Y. Sheng, L. Zheng, C. H. Yu, J. E. Gonzalez, H. Zhang & I. Stoica, "Efficient memory management for large language model serving with PagedAttention," SOSP (2023).
- G.-I. Yu, J. S. Jeong, G.-W. Kim, S. Kim & B.-G. Chun, "Orca: A distributed serving system for transformer-based generative models," OSDI (2022).
- R. Pope et al., "Efficiently scaling transformer inference," MLSys (2023).
- DeepSeek-AI, "DeepSeek-V2: A strong, economical, and efficient mixture-of-experts language model," arXiv:2405.04434 (2024).
- A. Agrawal et al., "Taming throughput-latency tradeoff in LLM inference with Sarathi-Serve," OSDI (2024).
- Z. Liu et al., "KIVI: A tuning-free asymmetric 2bit quantization for KV cache," ICML (2024).