Autoregressive Transformer Serving with KV Caching
Medium · ML System Design · Machine Learning Engineer · Onsite
Prompt
You are building the production token-generation engine for a causal, decoder-only Transformer language model. Walk through how key-value (KV) caching works mathematically and architecturally during step-by-step generation, and design a serving runtime that scales cleanly on modern accelerators.
For example, consider a single GPU simultaneously streaming responses for a short 6-token user query (["Summarize", "quarterly", "cloud", "spend", "by", "region"]), a 4-way branching decoding request, and a 64k-token document analysis job. Your design must support:
- Heterogeneous batching: Concurrent sequences with widely varying prompt and output lengths sharing the same execution batch.
- Branching token trajectories: Decoding strategies where one prefix splits or rolls back, including beam search and draft-then-verify speculative decoding.
- Extended context windows: Sequences scaling from
32kup to128ktokens without stalling concurrent requests or exhausting accelerator memory.
Address the low-level performance mechanics—physical tensor organization, read/write traffic as new K/V vectors arrive, eliminating runtime buffer reallocations and copies, integrating with SRAM-tiled fused attention kernels (such as FlashAttention), and selecting numeric cache formats (bf16, fp16, or 8-bit quantized int8/fp8)—as well as subtle implementation defects that corrupt cached outputs.
Scope & Expectations
- Cache fundamentals & compute profile: Define which per-layer tensors are retained versus discarded, separate prompt prefill from incremental token generation, and quantify the shift in FLOPs and HBM bandwidth.
- Dynamic batching, branching, & 32k–128k scaling: Present a memory-allocation architecture that handles ragged batch lengths without padding waste, supports shared prefixes and rollbacks for beam/speculative decoding, and scales to
32k–128kcontexts. - Accelerator memory & kernel integration: Explain physical memory layouts for coalesced reads/writes, zero-copy slot management, compatibility with tiled fused-attention kernels, and precision trade-offs across
bf16,fp16, andint8/fp8. - Correctness hazards & verification: Identify high-risk implementation bugs—spanning causal mask alignment, RoPE/position offsets, grouped-head indexing, and block reference lifetimes—along with verification against an uncached baseline.
Step-by-step walkthrough
Clarify scope, model shape, and evaluation metrics
Autoregressive decoding means generating text one token at a time, feeding each newly chosen token back into the Transformer to predict the next one. This is an ML systems design problem: we are not training new weights, and our ground-truth "label" for correctness is the exact next-token probability distribution produced by running the uncached model over the full sequence (up to tiny floating-point rounding differences).
Concrete hardware, model, and workload assumptions
- Reference model (Llama-3-8B public architecture): 32 decoder layers, hidden size
d_model = 4,096, 32 query heads and 8 key/value heads (grouped-query attention, GQA—where every 4 query heads share 1 key head and 1 value head to shrink memory 4x),head_dim = 128, rotary position embeddings (RoPE) (encoding token position by rotating query and key pairs by position-dependent angles),bf16(2-byte) weights, vocabulary size128,256. - Reference GPU: One 80 GB H100 SXM GPU (~3.35 TB/s HBM memory bandwidth, ~990 TFLOP/s dense
bf16Tensor Core compute); larger models split across GPUs with tensor parallelism. - Target workloads:
- Multi-user chat (1k–4k prompt tokens, 200–1,000 generated tokens);
- Branching generation: beam search (keeping top
B = 4candidate continuations) and speculative decoding (a tiny fast draft model guessesk = 4tokens that the 8B target model verifies in one parallel pass); - Long-context document QA (32k–128k tokens).
- System metrics we optimize and monitor:
- Numerical equivalence against the uncached reference forward pass;
- TTFT (Time To First Token): latency from request arrival to first output token;
- TPOT (Time Per Output Token): p50 and p99 latency between consecutive streamed tokens;
- Total output tokens/second per GPU and active KV-cache utilization.
- Reference model (Llama-3-8B public architecture): 32 decoder layers, hidden size
KV cache mechanics and compute savings
Why uncached decoding repeats the same work. Inside each Transformer layer, every token's vector is projected into three vectors: a query (
q, "what I am looking for"), a key (k, "what I contain"), and a value (v, "information I pass forward"). Because decoder-only Transformers apply a causal mask (a rule preventing tokenifrom looking at any future tokenj > i), tokeni's hidden state—and therefore itsk_iandv_iin every layer—depends only on tokens0 .. i. Appending tokentnever altersk_0 .. k_{t-1}orv_0 .. v_{t-1}:Uncached generation of 3 output tokens after prompt [W0, W1]: Step 1 (input W0, W1): computes K,V for W0, W1 -> predicts W2 Step 2 (input W0, W1, W2): RECOMPUTES W0, W1 + computes W2 -> predicts W3 Step 3 (input W0, W1, W2, W3): RECOMPUTES W0, W1, W2 + W3 -> predicts W4 With a KV cache: Prefill (input W0, W1): computes & saves K,V for W0, W1 -> predicts W2 Decode (input W2 only): computes K,V for W2, appends -> attends to cached [W0..W2] -> W3 Decode (input W3 only): computes K,V for W3, appends -> attends to cached [W0..W3] -> W4Per-layer stored activations vs. discarded intermediates
- Cached:
K(post-projection, post-RoPE keys) andV(post-projection values) for all tokens processed so far, logically shaped[batch, n_kv_heads, seq_len, head_dim]. - Never cached: Queries
Q(earlier tokens never ask new questions once generated), attention score matrices, MLP intermediate activations, and earlier layer hidden states.
Two distinct execution phases
- Prefill phase (prompt processing): Processes all
Pprompt tokens together using matrix-matrix multiplications ([P, 4096] @ [4096, 4096]). It is compute-bound (limited by GPU math TFLOP/s), populates the initial KV cache for0 .. P-1, and emits the first output token. - Decode phase (token-by-token generation): Feeds only the 1 newest token per sequence using matrix-vector multiplications (
[1, 4096] @ [4096, 4096]). It is memory-bandwidth-bound (limited by how fast the GPU can stream 16 GB of model weights plus every active sequence's KV cache from HBM memory).
Here is how a single new token attends to its sequence's cached keys and values under GQA (
32query heads sharing8KV heads, sogroup_size = 4):import numpy as np def softmax(scores: np.ndarray) -> np.ndarray: # Subtract max score first to prevent exp() overflow without changing probabilities shifted = scores - scores.max(axis=-1, keepdims=True) exps = np.exp(shifted) return exps / exps.sum(axis=-1, keepdims=True) def decode_attention(q_new: np.ndarray, k_cache: np.ndarray, v_cache: np.ndarray) -> np.ndarray: """Compute attention for ONE new token against all cached tokens (including itself). q_new: (n_q_heads, head_dim) -- query of the newest token at position L-1 k_cache: (n_kv_heads, L, head_dim) -- post-RoPE keys for positions 0 .. L-1 v_cache: (n_kv_heads, L, head_dim) -- values for positions 0 .. L-1 """ n_q_heads, head_dim = q_new.shape n_kv_heads = k_cache.shape[0] group_size = n_q_heads // n_kv_heads scale = 1.0 / np.sqrt(head_dim) out = np.empty_like(q_new) for q_head in range(n_q_heads): # GQA mapping: consecutive groups of 4 query heads share 1 KV head kv_head = q_head // group_size # No causal mask needed here: the newest token is allowed to attend to all 0 .. L-1 scores = (k_cache[kv_head] @ q_new[q_head]) * scale probs = softmax(scores) out[q_head] = probs @ v_cache[kv_head] return outComplexity shift for generating
ntokens (with parameter countP = 8B):Metric Without KV cache With KV cache Step t linear work ~2 * P * t FLOPs ~2 * P FLOPs (independent of t!) Step t attention work O(t^2) per layer O(t) per layer (1 query x t keys) Total work for n tokens O(P * n^2 + L * d * n^3) O(P * n + L * d * n^2) 8B model at token 4,096 ~66 TFLOP for that single token ~16 GFLOP + reading 512 MiB of KV cache- Cached:
Back-of-the-envelope numbers
Let us calculate exact byte counts, memory capacity, and step latencies for our Llama-3-8B model on one 80 GB H100 GPU (noting
1 GiB = 1.074 GBwhen dividing by the3.35 TB/s = 3,350 GB/sdecimal bandwidth spec):KV cache memory footprint (bf16 = 2 bytes per value) Per token (all layers) 2 (K & V) x 32 layers x 8 KV heads x 128 dim x 2 B = 131,072 B = 128 KiB Without GQA (32 KV hds) 512 KiB/token (4x larger!) 4k-token sequence 4,096 x 128 KiB = 512 MiB (~0.54 GB decimal) 32k-token sequence 32,768 x 128 KiB = 4 GiB (~4.30 GB decimal) 128k-token sequence 131,072 x 128 KiB = 16 GiB (~17.18 GB decimal) 80 GB GPU memory budget Model weights (bf16) 8.03B params x 2 B = ~16.1 GB Workspace & activations Peak prefill buffers + graphs = ~7.9 GB Available for KV pool 80 - 24 = ~56.0 GB -> ~427,000 token slots total Fits ~104 sequences at 4k, ~13 at 32k, or just ~3 sequences at 128k! Bandwidth-bound decode step latency (lower bound = bytes read / 3,350 GB/s) Batch 1 at 4k (16.1 GB weights + 0.54 GB KV) / 3,350 = ~5.0 ms/step (~200 tok/s) Batch 32 at 4k (16.1 GB weights + 17.2 GB KV) / 3,350 = ~10.0 ms/step (~3,200 tok/s total!) Batch 1 at 128k (bf16) (16.1 GB weights + 17.2 GB KV) / 3,350 = ~10.0 ms/step Batch 1 at 128k (fp8) (16.1 GB weights + 8.6 GB KV) / 3,350 = ~7.4 ms/step (~26% faster + 2x batch) 128k prompt prefill (compute-bound, n = 131,072) Linear projections/MLP 2 x 8.03e9 x 131,072 = ~2.1 PFLOP Causal attention (4 x n^2 x 4,096 / 2) x 32 layers = ~4.5 PFLOP (halved by causal triangle) Total prefill time ~6.6 PFLOP at 50% of 990 TFLOP/s = ~13.3 seconds! Why naive torch.cat([cache, new_kv]) is catastrophic Appending 1 token writes just 128 KiB, while torch.cat READS the old ~560 MiB cache AND WRITES a new ~560 MiB buffer every step -> over 1,000 tokens around 4.5k context, ~1.08 TiB of wasted copy traffic per sequence (2x the ~0.54 TiB that attention itself reads!).Architecture and separation of control plane vs. GPU runner
To support variable lengths, branching, and preemption without moving gigabytes of tensors around, we separate CPU block bookkeeping (deciding which integer slot holds each token) from GPU execution (writing and reading one preallocated pool at startup):
Client requests ---> [ API Server: tokenization, streaming SSE responses ] | v [ Scheduler (runs every ~5-10 ms step) ] - Continuous batching (insert/retire sequences every step) - Token budget & chunked prefill scheduling - Memory pressure preemption (swap to CPU RAM or recompute) | step plan (active seqs + new token counts) v [ KV Cache Manager (CPU) ] - Fixed-size block free list & reference counts - Copy-on-write fork, speculative truncate, prefix hash table | flat GPU metadata: input_ids, positions, | slot_mapping, block_tables, context_lens v [ Model Runner (GPU, preallocated static KV pool) ] - QKV projection -> RoPE -> scatter write K_new, V_new via slot_mapping - Paged attention reads K, V in-place via block_tables - Compute logits ONLY for last token per seq (or k+1 speculative tokens) GPU HBM (80 GB): [ Weights 16 GB ][ Activations/Graphs 8 GB ][ Static KV Block Pool 56 GB ] Host CPU RAM: [ Pinned swap pool for preempted sequences & warm prefix blocks ]Continuous batching means the scheduler updates the running batch on every decode step—as soon as Sequence A emits an end-of-sequence token, its KV blocks return to the free list and waiting Sequence B takes its place on the very next millisecond, rather than waiting for the longest sequence in a static batch to finish.
Deep dive 1: variable sequence lengths with a Paged KV Cache
Why contiguous per-sequence buffers waste almost all GPU memory. If you allocate a rectangular tensor
[batch, n_kv_heads, max_seq_len, head_dim]up front (saymax_seq_len = 32,768), a typical 2,048-token chat sequence leaves30,720slots unused—94% internal fragmentation (reserved memory sitting empty), cutting concurrent batch size and throughput by > 10x! Conversely, starting small and resizing dynamically triggers thetorch.catcopy disaster calculated earlier.Virtual-memory paging (PagedAttention). Just like an operating system maps virtual pages to scattered physical RAM frames, we slice the 56 GB GPU pool once at startup into fixed blocks of
BLOCK_SIZE = 16tokens (16 x 128 KiB = 2 MiBper block across all 32 layers ->~26,700blocks total):Naive rectangular cache (max_len = 8): Paged KV cache (BLOCK_SIZE = 4): Seq A (5 tok): [A0 A1 A2 A3 A4 . . .] Seq A block_table: [blk 3, blk 1] (only 3 empty slots) Seq B (2 tok): [B0 B1 . . . . . .] Seq B block_table: [blk 0] (only 2 empty slots) (9 of 16 slots = 56% wasted!) Physical Pool: blk 0: [B0 B1 . .] blk 2: [free] blk 1: [A4 . . .] blk 3: [A0 A1 A2 A3]Logical token position
pof a sequence lives atphysical_block = block_table[p // 16]andoffset = p % 16. A sequence allocates a new block only whenp % 16 == 0, capping wasted memory at<= 15token slots per sequence (< 0.8% at 2k context) with zero reallocation copies!Here is a clean, self-contained reference implementation of the paged block manager (including copy-on-write for branching, covered in the next step):
import numpy as np BLOCK_SIZE = 16 class SequenceState: """CPU metadata for one active generation sequence.""" def __init__(self, seq_id: int): self.seq_id = seq_id self.block_table: list[int] = [] # logical block index -> physical block ID self.length: int = 0 # total tokens currently stored in KV cache class PagedKVCache: """Preallocated fixed-block KV pool shared across variable-length sequences.""" def __init__(self, num_layers: int, num_blocks: int, num_kv_heads: int, head_dim: int, dtype=np.float16): pool_shape = (num_layers, num_blocks, num_kv_heads, BLOCK_SIZE, head_dim) # Allocated once at server startup; never resized or concatenated self.k_pool = np.zeros(pool_shape, dtype=dtype) self.v_pool = np.zeros(pool_shape, dtype=dtype) self.ref_count = [0] * num_blocks self.free_blocks = list(range(num_blocks)) def _alloc_block(self) -> int: if not self.free_blocks: raise MemoryError("Out of KV blocks; scheduler must preempt or wait") block_id = self.free_blocks.pop() self.ref_count[block_id] = 1 return block_id def _unref_block(self, block_id: int) -> None: self.ref_count[block_id] -= 1 if self.ref_count[block_id] == 0: self.free_blocks.append(block_id) def reserve_next_slot(self, seq: SequenceState) -> tuple[int, int]: """Return (physical_block_id, offset) for appending 1 new token to seq.""" offset = seq.length % BLOCK_SIZE if offset == 0: # Current block is full (or sequence is empty): grab 1 fresh block seq.block_table.append(self._alloc_block()) else: last_block = seq.block_table[-1] # Copy-on-write: if another beam/fork shares this partial block, clone it first if self.ref_count[last_block] > 1: private_copy = self._alloc_block() self.k_pool[:, private_copy] = self.k_pool[:, last_block] self.v_pool[:, private_copy] = self.v_pool[:, last_block] self._unref_block(last_block) seq.block_table[-1] = private_copy seq.length += 1 return seq.block_table[-1], offset def write_kv(self, layer: int, slot: tuple[int, int], k_tok: np.ndarray, v_tok: np.ndarray) -> None: block_id, offset = slot self.k_pool[layer, block_id, :, offset, :] = k_tok self.v_pool[layer, block_id, :, offset, :] = v_tok def gather_for_test(self, layer: int, seq: SequenceState) -> tuple[np.ndarray, np.ndarray]: """Materialize contiguous (n_kv_heads, length, head_dim) arrays for unit testing. Real GPU paged-attention kernels read directly from k_pool/v_pool via block_table.""" if seq.length == 0: empty = np.zeros((self.k_pool.shape[2], 0, self.k_pool.shape[4]), dtype=self.k_pool.dtype) return empty, empty.copy() k_cat = np.concatenate([self.k_pool[layer, b] for b in seq.block_table], axis=1) v_cat = np.concatenate([self.v_pool[layer, b] for b in seq.block_table], axis=1) return k_cat[:, : seq.length, :], v_cat[:, : seq.length, :] def free_sequence(self, seq: SequenceState) -> None: for block_id in seq.block_table: self._unref_block(block_id) seq.block_table.clear() seq.length = 0During mixed batches, token embeddings of all running sequences are flattened into a single ragged 1D stream
input_ids[total_new_tokens]with prefix-sum boundariesquery_start_loc—zero padding tokens are ever computed!Deep dive 2: branching for beam search, shared prefixes, and speculative decoding
Copy-on-write (CoW) for beam search and parallel sampling. In beam search (
width = 4), two surviving beams often descend from the same parent beam. Naively cloning the parent's 512 MiB cache on every fork copies gigabytes per step. With paging,forkcopies only the integer listblock_tableand incrementsref_counton each block:Parent (length = 18 = 16 + 2): block_table = [blk 5 (full, 16 tok), blk 9 (partial, 2 tok)] After fork(Parent -> Child): Parent block_table = [blk 5, blk 9] ref_count[blk 5] = 2 (stays shared forever!) Child block_table = [blk 5, blk 9] ref_count[blk 9] = 2 Next step, Parent appends token 18 (offset = 2 != 0, sees ref_count[blk 9] == 2 > 1): -> Allocates blk 12, copies 2 MiB from blk 9 -> blk 12, decrements ref_count[blk 9] to 1! Parent block_table = [blk 5, blk 12] (writes token 18 into blk 12) Child block_table = [blk 5, blk 9] (ref_count[blk 9] is now 1 -> Child writes in-place!)Forking a 4,096-token sequence copies at most one 2 MiB partial block instead of 512 MiB! The exact same ref-counted blocks power prefix caching: hashing full 16-token blocks (chained with all preceding tokens and model ID) lets 100 chat requests sharing a 2,048-token system prompt share one 256 MiB prompt cache, saving ~24.75 GiB and 99 prefill passes.
def fork_sequence(cache: PagedKVCache, parent: SequenceState, child_id: int) -> SequenceState: """Create a child branch sharing all physical KV blocks via reference counting.""" child = SequenceState(child_id) child.block_table = list(parent.block_table) child.length = parent.length for block_id in child.block_table: cache.ref_count[block_id] += 1 return child def truncate_sequence(cache: PagedKVCache, seq: SequenceState, new_length: int) -> None: """Roll back rejected speculative tokens in O(released_blocks) without copying tensors.""" blocks_needed = (new_length + BLOCK_SIZE - 1) // BLOCK_SIZE for dropped_block in seq.block_table[blocks_needed:]: cache._unref_block(dropped_block) seq.block_table = seq.block_table[:blocks_needed] seq.length = new_lengthSpeculative decoding: optimistic write-ahead + instant rollback
Suppose
Ltokens are already cached in the 8B target model andxis the most recently sampled token (not yet in the cache):- A tiny draft model (using its own tiny KV cache) autoregressively proposes
k = 4draft tokens[d1, d2, d3, d4]. - The target model runs one parallel verification pass over the 5 tokens
[x, d1, d2, d3, d4]at positions[L, L+1, L+2, L+3, L+4], reserving 5 KV slots, writing all 5 K/V pairs, and producing 5 next-token distributions in one shot. - Verification accepts the longest valid prefix
d1 .. dm(0 <= m <= 4) plus 1 corrected/bonus tokent_nextsampled from positionL + m's target distribution. - We call
truncate_sequence(cache, seq, L + 1 + m)so the target cache keeps[x, d1 .. dm]and discardsd_{m+1} .. d4in O(1) metadata ops (stale values pastseq.lengthinside the last kept block are ignored bycontext_lensand overwritten next step), whilet_nextbecomes the next step'sx. - Subtle draft-cache detail: To propose
d1..d4, the draft model only ran forward on[x, d1, d2, d3]—it never computed K/V ford4! When all 4 draft tokens are accepted (m = 4), the next draft step must feed[d4, t_next](2 tokens) into the draft model so its KV cache catches up cleanly.
- A tiny draft model (using its own tiny KV cache) autoregressively proposes
Deep dive 3: scaling to 32k–128k long contexts
Long contexts stress three bottlenecks simultaneously: prefill latency, single-sequence decode utilization, and HBM capacity.
- Chunked prefill vs. disaggregated prefill: A 128k prefill takes ~13.3 s of dense GPU compute; running it monolithically freezes every chat user on that GPU for 13 seconds! Chunked prefill splits the 128k prompt into 2,048-token chunks, piggybacking decode tokens of active chat users onto each chunk step. However, near the end of 128k, a single 2,048-token chunk attending to ~130k cached keys still costs ~0.17 PFLOP (~350 ms at 50% utilization), spiking chat TPOT. For strict < 50 ms TPOT SLAs, disaggregated prefill runs prefills on dedicated prefill GPUs and streams the finished 16 GiB KV cache over 400 Gb/s RDMA (~50 GB/s -> ~0.34 s transfer) to decode GPUs.
- Split-K decoding (FlashDecoding) for GPU occupancy: Decoding 1 sequence at 128k has only 32 query heads, so launching 1 thread block per head leaves 100 of an H100's 132 Streaming Multiprocessors completely idle! Split-K decoding partitions the 128k cached keys into
Sparallel slices across SMs; each slice computes a partial weighted value plus its local(max_score, sum_exp), and a tiny reduction kernel combines them exactly using log-sum-exp rescaling (exp(m_part - m_global)). - Multi-GPU partitioning & preemption: With 8-way tensor parallelism across 8 GPUs, each GPU holds 1 of the 8 KV heads (shrinking 16 GiB to 2 GiB per GPU); beyond 8 GPUs, ring / context parallelism shards along the sequence axis. If concurrent decodes exhaust free blocks, the scheduler preempts the lowest-priority sequence: at 128k, swapping 16 GiB to pinned CPU RAM over PCIe (~25–50 GB/s -> ~0.35–0.7 s) beats recomputing (~13.3 s) by > 20x!
Performance: memory layout, avoiding copies, fused kernels, and precision
Memory layout and read/write asymmetry. Every decode step writes just
128 KiBper sequence (4 KiBper layer) viaslot_mapping, while reading hundreds of megabytes to gigabytes of cached K/V. We therefore optimize physical layout[num_blocks, BLOCK_SIZE, n_kv_heads, head_dim]strictly for coalesced reads:- Placing
head_dim = 128innermost puts all128 x 2 = 256bytes of one head's key or value adjacent in HBM so GPU warps issue wide 128-byte vector loads. - We fuse
"RoPE rotation + scatter-write into k_pool/v_pool"into a single kernel to save HBM round-trips, and inside GQA paged attention, each KV head block is loaded into on-chip SRAM once and reused across all 4 query heads in its group. - Note kernel block-size rules: vLLM's PagedAttention, FlashInfer, and FlashAttention-3 support
BLOCK_SIZE = 16directly, whereas FlashAttention-2's built-in paged API required multiples of256—always alignBLOCK_SIZEwith your chosen kernel backend.
Eliminating allocations and CPU launch overhead with CUDA graphs. After profiling peak workspace memory at startup, we preallocate the static KV pool once so zero
cudaMallocortorch.catcalls ever happen during serving. Because pool addresses are static, we capture the entire decode forward pass into CUDA graphs (recording ~300 small GPU kernel launches into a single replayable GPU command buffer) for power-of-two batch-size buckets (1, 2, 4, ..., 256), eliminating ~1.5 ms of CPU kernel-launch overhead per 5 ms decode step.Fused kernels and bottom-right causal mask alignment. FlashAttention tiles Q, K, and V in SRAM so attention workspace is O(n) instead of O(n^2). Whenever a step feeds
q_lennew tokens (q_len > 1, as in chunked prefill or speculative verification) againstkv_len = L + q_lentotal keys, the causal mask MUST be bottom-right aligned, never top-left aligned:3 new tokens [T5, T6, T7] attending to 5 cached [T0..T4] + 3 new [T5..T7] = 8 keys: WRONG (top-left causal mask): CORRECT (bottom-right causal mask): Keys: T0 T1 T2 T3 T4 T5 T6 T7 Keys: T0 T1 T2 T3 T4 T5 T6 T7 T5 [ 1 0 0 0 0 0 0 0 ] T5 [ 1 1 1 1 1 1 0 0 ] (pos 5 sees 0..5) T6 [ 1 1 0 0 0 0 0 0 ] T6 [ 1 1 1 1 1 1 1 0 ] (pos 6 sees 0..6) T7 [ 1 1 1 0 0 0 0 0 ] T7 [ 1 1 1 1 1 1 1 1 ] (pos 7 sees 0..7) (Hides cached tokens T1..T4!)Cache precision choices (
bf16vsfp16vsfp8/int8)Precision Bytes/token Max tokens in 56 GB Engineering notes bf16 128 KiB ~427,000 Safe default matching bf16 training range (8-bit exponent) fp16 128 KiB ~427,000 Risk of overflow (> 65,504) if model was trained in bf16! fp8 (E4M3) 64 KiB + scl ~854,000 2x batch capacity, ~26% faster 128k decode; needs scaling int8 64 KiB + scl ~854,000 2x capacity; per-head/per-token scales; dequant in registersTwo critical quantization rules: (1) dequantize on the fly in GPU registers inside the attention kernel—dequantizing to a
bf16HBM tensor first wastes the exact memory bandwidth you wanted to save; and (2) keys exhibit strong per-channel outliers while values vary per token (as shown in KIVI), so sub-8-bit schemes quantizeKper channel andVper token.- Placing
Implementation hazards, verification, and rollout
Frequent numerical and state-management bugs
- Position-ID off-by-one: Passing
position = 0on decode steps instead of the sequence's cached token countL(or including left-padding inposition), causing garbled repetition after token 1. - Double or missing RoPE: Caching post-RoPE keys at prefill, then accidentally applying RoPE a second time when reading
k_cacheduring decode (or using dynamic RoPE frequency scaling mid-generation without re-rotating earlier keys). - Top-left causal mask bug during chunked prefill or speculative verification (hiding the cached prompt, as drawn above), or PyTorch
scaled_dot_product_attention(..., is_causal=True)which defaults to top-left unlesscausal_lower_rightis used. - Silent GQA head-mapping or expansion bugs: Materializing
repeat_interleavebefore writing to the cache (silently inflating memory 4x from8to32heads), or indexingkv_head = q_head % n_kv_headsinstead ofq_head // group_size(shapes still match, so it runs without crashing while producing nonsense!). - Reference-count / privacy leaks: Freeing a shared prefix or parent beam block while a sibling still references it, or forgetting to free blocks when a client disconnects—corrupting another user's attention with leaked prompt keys!
- Materializing full-prompt logits: Running the
4,096 -> 128,256vocabulary head on all131,072prefill tokens allocates131,072 x 128,256 x 2 B = 33.6 GBand triggers instant OOM; slice only the final token per sequence before the LM head.
Verification suite, production monitoring, and rollout
- Offline tests: Step-by-step logit equivalence against an uncached reference (
max |diff| < 5e-3inbf16; exact greedy token match wherever top-2 logit margin exceeds rounding noise), single-vs-batched invariance across ragged lengths, forked-beam parity, speculative greedy exactness, random allocator fuzzing (sum(ref_count) == total_table_entries), and 32k–128k needle-in-a-haystack retrieval. - Live monitoring: KV block pool % used, swap/recompute preemptions per minute, leaked block count (must be 0), TTFT and TPOT p50/p99, prefix-cache hit rate, speculative acceptance rate, and NaN/Inf counters.
- Rollout & A/B testing: Lossless systems changes (paging, CUDA graphs, prefix sharing) roll out via CI equivalence -> shadow traffic -> 1% / 10% / 100% canary watching latency and divergence. Lossy changes (
fp8/int8KV quantization or sliding-window eviction) change model outputs and must pass long-context offline benchmarks followed by an online A/B test segmented specifically on 32k–128k traffic (tracking task completion, user thumbs-up/down, and regeneration rate against GPU cost savings).
- Position-ID off-by-one: Passing
Summary of architectural trade-offs
- Paged blocks vs. contiguous tensors: Cuts wasted KV reservation from > 90% to < 1% and enables O(1) forks and rollbacks, trading block-table indirection in attention kernels and strict ref-count bookkeeping.
- Copy-on-write sharing vs. eager buffer copies: Turns 512 MiB beam/sample forks into a single 2 MiB partial-block copy and shares system prompts across users, making ref-count correctness both a reliability and multi-tenant security boundary.
- Chunked prefill vs. disaggregated prefill: Chunked prefill runs on one homogeneous GPU pool but still adds up to ~350 ms jitter on late 128k chunks; disaggregation isolates decode TPOT completely at the cost of RDMA cache transfers (~0.34 s for 16 GiB).
- CPU swap vs. recompute on preemption: Recompute requires zero PCIe traffic (~140 ms at 4k), whereas at 128k swapping (~0.35–0.7 s) beats recomputing (~13.3 s) by an order of magnitude.
bf16vs.fp8/int8KV cache:bf16is lossless relative to model precision; 8-bit caches double concurrency and cut 128k decode time by ~26% when dequantized in registers, requiring empirical quality validation via A/B testing.
Intuition & how it works
Imagine reading a 500-page mystery novel aloud one sentence at a time: if you burned your notes after speaking each word and re-read from Page 1 before choosing the next word, finishing a single paragraph would take all afternoon. In a decoder-only Transformer, causal masking (the rule that token i can only look backward at tokens 0 .. i, never ahead) guarantees that earlier tokens' Key (K) and Value (V) vectors in every layer never change when new tokens are appended. The KV cache is simply the model's margin notes—saving each token's K and V vectors once so each new autoregressive decode step (generating one token at a time) computes projections for only the single newest token and scans the saved notes.
Two naive designs still fail badly in production. Without a KV cache, generating n tokens recomputes the whole history on every step, inflating linear-layer work from O(n) to O(n^2) and attention work from O(n^2) to O(n^3) (~66 TFLOP instead of ~16 GFLOP at token 4,096 of an 8B model). Conversely, allocating a naive contiguous [batch, heads, max_len, head_dim] cache tensor per request either reserves 32k–128k slots for a 2k chat (wasting > 90% of GPU memory) or calls torch.cat on every token (copying the entire multi-hundred-megabyte cache twice per step and fragmenting GPU memory).
Walk through a tiny concrete trace (BLOCK_SIZE = 4 tokens per block) on our 6-token prompt ["Summarize", "quarterly", "cloud", "spend", "by", "region"] ([W0..W5]) to see how a Paged KV Cache handles variable lengths and branching cleanly:
- Prefill (compute-bound): User A sends the 6-token prompt
[W0, W1, W2, W3, W4, W5]. All 6 tokens run in parallel, writing post-RoPE keys (Rotary Position Embeddings—position encoded by rotating key/query pairs) and values into two 4-token blocks from a preallocated GPU pool:block_table = [blk_4 (W0..W3), blk_9 (W4, W5, _, _)],length = 6, emittingW6. - Decode append (bandwidth-bound): On the next step, only
W6(atposition = 6) runs through the model weights. Its newK_6, V_6write directly intoblk_9atoffset = 6 % 4 = 2(length = 7), andW6's query attends acrossblk_4and the first 3 slots ofblk_9—zero reallocation and zero padding! - Copy-on-write fork (beam search): Suppose beam search forks two continuations from
length = 7. Both beams point to[blk_4, blk_9]withref_count = 2. Fullblk_4stays shared forever; when Beam 1 writes atoffset = 3, it seesref_count[blk_9] > 1, clones just that tiny 4-tokenblk_9intoblk_11(copy-on-write), and leaves Beam 2 owningblk_9(ref_count = 1) to write in place. - Speculative rollback: If a draft model proposes 3 extra tokens
[s1, s2, s3]verified in one batch and onlys1is accepted,truncatesimply resetslengthback and frees any trailing overflow block in O(1) integer updates.
Key trade-offs
- GPU memory traded for O(t) compute savings. Caching
KandVremoves a factor-of-trecomputation per token (~66 TFLOP down to ~16 GFLOP att = 4,096on Llama-3-8B), at the cost of128 KiBper token inbf16(already reduced 4x by grouped-query attention, GQA, where 4 query heads share 1 KV head)—totaling512 MiBat 4k and16 GiB(~17.2 GB decimal) for one 128k sequence, making GPU memory capacity and bandwidth the primary throughput bottlenecks. - Paged block pool vs. contiguous rectangular buffers. Virtual-memory-style paging (
BLOCK_SIZE = 16) shrinks internal fragmentation to at most 15 empty slots per sequence (< 1% at 2k tokens) and enables continuous batching (adding/retiring requests on every 5–10 ms decode step), trading indirect block-table lookups inside GPU kernels and reference-counted allocator complexity. - Copy-on-write block sharing vs. eager cache cloning. Sharing full physical blocks across beams,
n-sample generations, and common system prompts reduces a 512 MiB fork to at most a single2 MiBpartial-block copy, at the cost of makingref_countbookkeeping security-critical (a premature free leaks another user's prompt keys). - Chunked prefill vs. disaggregated prefill for 32k–128k prompts. Splitting long prompts into 2,048-token chunks prevents a 13.3 s 128k prefill from freezing all other users on a shared GPU, but late chunks attending to ~130k keys still take ~350 ms and bump TPOT (Time Per Output Token). Running prefills on separate GPUs and shipping the 16 GiB KV cache over 400 Gb/s RDMA (~0.34 s) protects decode latency at the cost of high-speed interconnect bandwidth and cluster orchestration.
- Swapping to CPU RAM vs. recomputing on memory preemption. When concurrent sequences fill all 56 GB of KV blocks, recomputing a 4k sequence later takes ~140 ms of GPU math with zero PCIe traffic, whereas at 128k swapping 16 GiB over PCIe (~0.35–0.7 s) beats recomputing (~13.3 s) by ~20x at the expense of pinned host RAM.
bf16vs.fp8/int8quantized KV cache. Keepingbf16matches uncached model precision; 8-bit KV quantization doubles concurrent batch size (~854kvs~427ktokens) and trims 128k bandwidth-bound decode steps from ~10.0 ms to ~7.4 ms provided dequantization happens in GPU registers inside the attention kernel, trading slight numerical approximation that must be verified on long-context tasks and an online A/B test.- CUDA graphs vs. dynamic tensor shapes. Capturing decode steps into CUDA graphs (replaying ~300 GPU ops from one launch) eliminates ~1.5 ms of CPU launch overhead on small batches, requiring static preallocated pool pointers and padded batch-size buckets (
1, 2, 4, ...).
Common mistakes
- Claiming the KV cache stores
Q, attention weights, or layer hidden states. Only post-projectionK(typically post-RoPE) andVper layer are cached; queries are needed only for the newest token(s), and MLP activations are discarded immediately. - Appending via
torch.cat([k_cache, k_new], dim=2)inside the decode loop, which reads and rewrites the entire growing cache on every single token (~1.08 TiB of wasted HBM copies over 1,000 tokens at ~4.5k context) and fragments the GPU allocator. - Reserving
max_seq_lencontiguously per sequence, wasting > 90% of HBM on average-length chat requests and collapsing batch size. - Passing wrong position IDs or double-applying RoPE, such as passing
pos = 0on decode steps, counting left-padding tokens inpos, or rotating cached keys on read when they were already rotated before write. - Using a top-left causal mask during multi-token steps with a non-empty cache (chunked prefill or speculative verification), which masks out almost the entire cached prompt instead of aligning the causal diagonal to the bottom-right corner
(q_len, L + q_len). - Expanding GQA heads (
repeat_interleavefrom 8 to 32 heads) before caching, silently quadrupling KV memory, or mapping query headhtoh % n_kv_headsinstead ofh // group_size(which passes every tensor shape check while scrambling attention heads). - Forgetting speculative rollback details, either leaving rejected draft K/V active in
seq.lengthor forgetting that when allkdraft tokens are accepted, the draft model never ran forward on the final draft tokend_kand needs[d_k, bonus_token]on its next step. - Running the
128,256-way vocabulary projection on all 128k prompt tokens (~33.6 GB of wastedbf16logits) instead of slicing only the last token per sequence, or testing cached vs. uncached outputs with brittle==equality instead of abf16-aware tolerance.
Follow-up questions
- How do MHA, GQA, MQA, and Multi-Head Latent Attention (MLA) alter the KV cache footprint and attention kernel? KV cache size scales linearly with the number of stored KV dimensions per layer rather than query heads: on our 32-layer, 128-dim model in
bf16, standard MHA (32 KV heads) costs512 KiB/token, GQA (8 KV heads) costs128 KiB/token, and MQA (1 shared KV head) drops to16 KiB/tokenwith a modest quality trade-off. Multi-Head Latent Attention (MLA) (used in DeepSeek-V2/V3) compresses all heads' keys and values jointly into a single low-rank latent vector per token per layer (plus a tiny decoupled RoPE key vector, since position-dependent RoPE cannot be absorbed into static weights during decoding), cutting cache size below MQA while preserving MHA-level quality at the cost of extra projection math. Critically, our entire PagedKVCache allocator, copy-on-write forking, and speculative truncation stay identical—only bytes per slot and the inner attention kernel change. - How can you serve a 128k-token document prompt alongside interactive chat users without breaking a 50 ms per-token latency target? Never run a large chunk of the 128k prompt inside a chat decode batch: near position 128k, a single prefill token costs ~85 GFLOP (~16 GFLOP linear + ~69 GFLOP attending across 128k keys), taking ~0.17 ms at 50% H100 utilization, so even a 2,048-token chunk adds ~350 ms and blows past a 50 ms TPOT budget. You can either throttle the long request's chunk budget dynamically to <= 150–200 tokens per step near 128k (stretching its TTFT—Time To First Token—to ~16–20 s while keeping every shared step < 50 ms), or use disaggregated prefill on dedicated prefill GPUs and transfer the 16 GiB KV cache to a decode GPU in ~0.34 s over 400 Gb/s RDMA. Once in decode, use split-K (FlashDecoding) with log-sum-exp partial reduction so all 132 GPU SMs share the 17.2 GB key/value scan (~10 ms/step), and cap how many 128k sequences can co-reside on one decode GPU.
- How would you deduplicate a shared 4,000-token system prompt across thousands of concurrent calls while handling eviction and tenant isolation? Compute a chained cryptographic hash for every full 16-token block (
H_i = SHA256(H_{i-1} || block_i_tokens || model_version || lora_id))—chainingH_{i-1}is mandatory because self-attention makes blocki's K/V depend on every earlier token and position—and mapH_i -> physical_block_idin a CPU prefix table. Incoming requests look up consecutive hashes, incrementref_counton hits, and prefill only the uncached suffix; when a sequence finishes andref_counthits0, the block stays hashed on an LRU (Least Recently Used) eviction list until the allocator actually needs a free block. In a multi-tenant API, includetenant_id(or API org ID) inside the hash key so Customer B cannot detect via a faster TTFT timing side-channel that Customer A recently sent the exact same confidential prompt prefix.
Follow-up questions
- How do MHA, GQA, MQA, and Multi-Head Latent Attention (MLA) alter the KV cache footprint and attention kernel?
- How can you serve a 128k-token document prompt alongside interactive chat users without breaking a 50 ms per-token latency target?
- How would you deduplicate a shared 4,000-token system prompt across thousands of concurrent calls while handling eviction and tenant isolation?
Similar questions
- Diagnosing and Scaling PyTorch Model Training
- Building Core Activation and Normalization Layers from Scratch
- RAG-Based Product Recommendation API Design
- Integrating Vision-Language Models Safely into Autonomous Driving
- Asynchronous RL Alignment Architecture for Live Chat Models
- Hybrid Talent Search and Ranking Architecture