Simple Algorithm
Deep Learning · Emergence · 26 min

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 PP tokens and asks for up to GG 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 G−1G-1 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 BB decoding sequences helps only partly, as a count on the illustrative accelerator (Π=1015\Pi=10^{15} FLOP/s, β=3×1012\beta=3\times10^{12} B/s) shows.

DerivationA decoding step with batch B
  1. tstep(B) ≥ max⁡(2N+B κ(t)β, B (2N+4Ltd)Π),throughput=Btstep(B)t_{\text{step}}(B)\ \ge\ \max\Big(\frac{2N+B\,\kappa(t)}{\beta},\ \frac{B\,(2N+4Ltd)}{\Pi}\Big),\qquad\text{throughput}=\frac{B}{t_{\text{step}}(B)}

    With 16-bit numbers, a step reads all 2N2N bytes of weights once for the whole batch, plus each sequence's own cache, κ(t)=4LtHkvdk\kappa(t)=4LtH_{kv}d_k bytes at context length tt; it computes 2N+4Ltd2N+4Ltd FLOPs per sequence:

  2. t∗≈2NΠ⋅β4LHkvdkt^*\approx\frac{2N}{\Pi}\cdot\frac{\beta}{4LH_{kv}d_k}

    At short contexts the weights dominate the bytes, and the step time barely grows with BB until the compute term catches up near B≈Π/βB\approx\Pi/\beta, a few hundred: batching buys throughput almost for free. But every sequence adds its own cache traffic κ(t)/β\kappa(t)/\beta 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

  3. lim⁡B→∞Btstep(B)=βκ(t)≈3×10122.15×109≈1.4×103  tokens/s\lim_{B\to\infty}\frac{B}{t_{\text{step}}(B)}=\frac{\beta}{\kappa(t)}\approx\frac{3\times10^{12}}{2.15\times10^{9}}\approx1.4\times10^{3}\ \ \text{tokens/s}

    For the 7B model (N≈6.74×109N\approx6.74\times10^9, L=32L=32, dk=128d_k=128) t∗t^* is about 77 tokens with 32 key–value heads and about 310 with 8 (keeping NN fixed). Beyond it the cache sets a ceiling: throughput tends to β/κ(t)\beta/\kappa(t) as BB grows, while TPOT grows linearly in BB. At t=4096t=4096 the ceiling is about 1,400 tokens per second with multi-head attention and 5,600 with 8 key–value heads:

  4. Bmax⁡=⌊80×109−1.35×10102.15×109⌋=30B_{\max}=\Big\lfloor\frac{80\times10^{9}-1.35\times10^{10}}{2.15\times10^{9}}\Big\rfloor=30

    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.

Predict before you look

A server runs an OPT-13B-like model: L=40L=40 layers of width d=5,120d=5{,}120, 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 2×40×5,120×2=819,2002\times40\times5{,}120\times2=819{,}200 bytes =800=800 KiB, so one 2,048-token request needs 1.6 GB, the example Kwon et al. (2023) give, and 32 requests need 32×2,048×80032\times2{,}048\times800 KiB =50=50 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 κ(t)\kappa(t). Multi-query attention keeps a single key head and value head for all HH query heads (Shazeer, 2019). Grouped-query attention keeps HkvH_{kv} of them, each shared by a group of H/HkvH/H_{kv} 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 H/HkvH/H_{kv}, and both raise decoding attention's intensity to H/HkvH/H_{kv} 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 ht\mathbf h_t is projected to one latent vector ct=WDKVht∈Rdc\mathbf c_t=W^{DKV}\mathbf h_t\in\R^{d_c}, and every head's keys and values are linear functions of it:

kt(i)=WiUK ct,vt(i)=WiUV ct,i=1,…,nh\mathbf k^{(i)}_t=W^{UK}_i\,\mathbf c_t,\qquad\mathbf v^{(i)}_t=W^{UV}_i\,\mathbf c_t,\qquad i=1,\dots,n_h
Only ct\mathbf c_t is cached. WiUK,WiUV∈Rdh×dcW^{UK}_i,W^{UV}_i\in\R^{d_h\times d_c} are head ii's up-projections and dhd_h its head size.
DerivationAttending in the latent space
  1. qt(i)⊤kj(i)=qt(i)⊤WiUKcj=(WiUK⊤qt(i)) ⁣⊤cj=q~t(i)⊤cj\mathbf q^{(i)\top}_t\mathbf k^{(i)}_j=\mathbf q^{(i)\top}_tW^{UK}_i\mathbf c_j=\big(W^{UK\top}_i\mathbf q^{(i)}_t\big)^{\!\top}\mathbf c_j=\tilde{\mathbf q}^{(i)\top}_t\mathbf c_j

    Head ii's score for a cached token jj moves the up-projection onto the query, which is computed once per step:

  2. ∑jatj vj(i)=WiUV(∑jatj cj)\sum_ja_{tj}\,\mathbf v^{(i)}_j=W^{UV}_i\Big(\sum_ja_{tj}\,\mathbf c_j\Big)

    The weighted sum of values moves the other up-projection outside the sum, where it can be merged into the output projection WOW_O:

  3. stj(i)=q~t(i)⊤cj+qtR(i)⊤kjRdh+dhR,cached per token and layer: dc+dhR numberss^{(i)}_{tj}=\frac{\tilde{\mathbf q}^{(i)\top}_t\mathbf c_j+\mathbf q^{R(i)\top}_t\mathbf k^R_j}{\sqrt{d_h+d^R_h}},\qquad\text{cached per token and layer: }d_c+d^R_h\ \text{numbers}

    So keys and values never need to be materialized: the paper notes that WUKW^{UK} can be absorbed into WQW^Q and WUVW^{UV} into WOW^O at inference. Rotary embeddings would break the first identity, because the rotation between qt\mathbf q_t and kj\mathbf k_j depends on both positions and cannot be folded into a fixed matrix. MLA therefore adds a small decoupled key ktR∈RdhR\mathbf k^R_t\in\R^{d^R_h}, shared by all heads and rotated by RoPE, with a matching rotated part of each query:

  4. IMLA=128×(4×512+2×64)2×(512+64)≈242  FLOPs per byteI_{\text{MLA}}=\frac{128\times(4\times512+2\times64)}{2\times(512+64)}\approx242\ \ \text{FLOPs per byte}

    DeepSeek-V2 uses nh=128n_h=128 heads of size dh=128d_h=128, dc=512d_c=512 and dhR=64d^R_h=64 in 60 layers: 576 cached numbers per token and layer against 2nhdh=32,7682n_hd_h=32{,}768 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 nh(4dc+2dhR)≈2.8×105n_h(4d_c+2d^R_h)\approx2.8\times10^5 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.

Check your understanding

Why does MLA carry a separate rotary key kR\mathbf k^R instead of applying RoPE to the keys reconstructed from the latent?

  1. A position-dependent rotation would sit between the query and WUKW^{UK}, 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
  2. RoPE needs 32-bit numbers, which the latent cache does not store
  3. A latent vector of dimension 512 cannot be rotated in pairs
  4. 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 WUKW^{UK}, 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 qt⊤Rt⊤Rj WUKcj=qt⊤Rj−tWUKcj\mathbf q_t^\top R_t^\top R_j\,W^{UK}\mathbf c_j=\mathbf q_t^\top R_{j-t}W^{UK}\mathbf c_j, and Rj−tR_{j-t} 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.

python
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 [∑rLr, d]\big[\sum_rL_r,\,d\big] 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 β/κ(t)\beta/\kappa(t).
  • KV memory, 2LtHkvdk2LtH_{kv}d_k numbers per sequence (800 KiB per token for OPT-13B), caps the batch. MQA and GQA divide it by H/HkvH/H_{kv}; MLA caches one latent of dc+dhRd_c+d^R_h 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.

Question 1

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?

  1. Their time to first token grows; chunked prefill shortens the prompt
  2. Their time per output token spikes during the long prefill; chunked prefill caps the prefill tokens per iteration so their decoding steps keep running
  3. Nothing: decoding is memory-bound, so a prefill cannot slow it
  4. 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.

Question 2

At long contexts and large batches, decoding throughput approaches β/κ(t)\beta/\kappa(t), the memory bandwidth over the cache bytes per sequence. Which change raises this ceiling?

  1. A larger batch
  2. An accelerator with twice the peak FLOP/s and the same bandwidth
  3. A faster prefill kernel
  4. 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.

Question 3

What does PagedAttention change about the KV cache?

  1. 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
  2. It compresses each key and value into a lower-dimensional vector
  3. It evicts the tokens that have received the least attention
  4. 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.

Question 4

With its up-projections absorbed, what does MLA's decoding attention read from the cache for each earlier token, in each layer?

  1. The keys and values of all heads, reconstructed from the latent
  2. The token's hidden state hj\mathbf h_j
  3. The latent cj\mathbf c_j and the shared rotary key kjR\mathbf k^R_j: 576 numbers in DeepSeek-V2
  4. Only the shared rotary key kjR\mathbf k^R_j
Show the answer

C. The latent cj\mathbf c_j and the shared rotary key kjR\mathbf k^R_j: 576 numbers in DeepSeek-V2

Each head maps its query into the latent space once, q~=WUK⊤q\tilde{\mathbf q}=W^{UK\top}\mathbf q, scores it against cj\mathbf c_j directly, sums latents with the attention weights and applies WUVW^{UV}, merged into WOW_O, afterwards. The decoupled key adds the positional part: 512+64512+64 numbers instead of 2nhdh=32,7682n_hd_h=32{,}768.

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).