0%
LLM Inference and Serving: GPUs, Batching, and Cost
Hardware and Memory
Making Inference Fast
Serving Systems
The KV Cache
The KV cache is the most important data structure in LLM serving. It makes token by token generation affordable, it is the largest consumer of GPU memory after the weights, it sets the batch size and therefore the throughput of every deployment, and almost every serving optimization from paged attention to disaggregated serving is a way of managing it better. This lesson explains what the cache holds, how to size it, why it limits batches and how systems shrink and manage it.
Generation without a cache
Recall that each attention layer computes a key and a value for every position, and that the newest position attends over the keys and values of all earlier positions. Without a cache, generating token n would require running the entire sequence of n minus one tokens through the model again to recompute those keys and values, even though they are identical to what was computed one step earlier. The work for one token would grow linearly with the length so far, and the total work for a response would grow with the square of its length. A 2,000 token response after a 2,000 token prompt would cost thousands of full prefill passes.
What the cache stores
The KV cache stores, for every layer, every key value head and every position processed so far, the key vector and the value vector. When a new token is generated, the model computes the query, key and value only for that token at each layer, appends the new key and value to the cache and computes attention between the new query and all cached keys and values. The work per step is now proportional to the parameters plus a read of the cache, rather than a full pass over the sequence. That is the difference between generation being practical and impractical.
Only keys and values are cached, not queries, because a query is used only once, by the position that produced it, at the moment it is produced. Earlier queries are never needed again. Keys and values, by contrast, are needed by every future position. Intermediate activations such as the feed forward outputs are also not cached, since their effect has already been added to the residual stream and later positions do not read them directly.
The trade the cache makes
The cache trades compute for memory. Instead of recomputing keys and values, it stores them, and every decode step reads them. This trade is overwhelmingly worth it, but it moves the bottleneck. Generation becomes limited by how much cache can be held in memory, which caps the batch, and by how fast it can be read, which adds to the time of every step. A large part of serving engineering is the management of this memory: deciding how much to allocate, where to put it, when to evict it and how to share it.
Prefill fills the cache
During prefill the engine processes the whole prompt in one pass and writes keys and values for every prompt position into the cache. That is why the first token of a response costs a full prefill, and why every subsequent token is cheap by comparison. After prefill, the cache holds the complete state of the conversation so far. If the same prompt were sent again, the same keys and values would be computed, which is the observation behind prefix caching: keep the cache of common prefixes and skip their prefill on later requests. Lesson nine covers prefix caching in detail.
The cache is per sequence
Each sequence has its own cache, because each sequence has its own tokens. Two users chatting with the same model share the weights but not their caches, unless their prompts start with identical tokens, in which case the cached prefix can be shared. This is the fundamental asymmetry of serving memory: weights are shared by all users and loaded once, while cache memory grows with every concurrent user and with the length of each conversation. Capacity planning for a deployment is therefore mostly capacity planning for the cache.
The cache is the conversation state
In a stateless API, each turn of a conversation resends the full history, and the server rebuilds the cache with a new prefill unless it can reuse a cached prefix. The cache is therefore the real state of a conversation in the server, even when the API presents itself as stateless. Engineers who understand this see why multi turn chat benefits so much from prefix caching and from routing each conversation back to the same replica, where its cache may still be resident. They also see why very long conversations become slow and expensive: every turn reads, and possibly rebuilds, a cache that keeps growing.
Why the cache is not optional
Some engines expose a flag to disable caching for debugging, and some research systems recompute selected parts of the cache to save memory, but no production LLM serving runs without a KV cache. The question in practice is never whether to cache, but how many bytes each token costs, how much memory is available, how the memory is allocated among sequences and what to do when it runs out. The remaining sections answer those questions in turn.
The cache in numbers
A useful habit is to keep a few reference numbers in mind. Llama 3 8B stores about 128 kilobytes per token in 16 bit precision, so a 4,000 token conversation holds about half a gigabyte of cache. Llama 3 70B stores about 320 kilobytes per token, so the same conversation holds about 1.3 gigabytes and a full 128,000 token context holds about 40 gigabytes, more than a quarter of its own weights. Older models without grouped query attention, such as Llama 2 13B, stored about 800 kilobytes per token. These numbers explain at a glance why long contexts, large batches and older architectures are expensive.
A step with and without the cache
Consider the work at decode step 3,001 of a 3,000 token prompt. Without a cache, the model would process 3,001 positions through all 32 layers, roughly 48 trillion FLOPs for an 8B model, just to produce one token. With a cache, it processes one position, about 16 billion FLOPs, and reads 3,000 cached entries per layer, about 375 megabytes. The cached step does three thousand times less arithmetic and finishes in a few milliseconds instead of a sizable fraction of a second. Repeated over a 1,000 token answer, the difference is between a response in seconds and a response in many minutes. Every production engine relies on this, and every design decision in the rest of the course assumes it.
Where the cache physically lives
The cache lives in GPU high bandwidth memory, the same memory that holds the weights, because attention kernels read it at every step and only HBM is fast enough. It is laid out per layer, so that the attention kernel for layer 12 reads only the keys and values for layer 12. Within a layer, engines store keys and values for each block of tokens together, with the head and head dimension as inner axes, so that a kernel reading one sequence touches contiguous memory. These layout details are invisible to users but explain why engines pick particular block sizes and why caches from one engine cannot simply be loaded into another.
Cache and response quality
The cache does not change what the model computes. A response generated with a cache is mathematically the same as one generated by recomputing everything, apart from tiny floating point differences from a different order of operations. Teams sometimes suspect caching when outputs vary between runs, but the usual causes are sampling settings, batch composition affecting numerics or a changed prompt, not the cache itself.
Weights are shared by every user, but each sequence brings its own cache that grows with every token. Serving capacity is mostly a question of how many cache bytes fit and how quickly they can be read.