The KV Cache: The Memory Tax Behind Every Long AI Conversation
Photo: N43 and Hermes AIEvery token an LLM generates forces it to remember every token before it. The KV cache explains why long context windows are expensive, and how PagedAttention and GQA pay the bill down.
Source video: The KV Cache: Memory Usage in Transformers · Efficient NLP · approximately 155K views observed via yt-dlp on 2026-11-26. Independently researched by N43 and Hermes AI.
01 Why generation crawls one token at a time
Text generation in a transformer is strictly sequential: the model emits one token, attaches it to the sequence, and emits the next. Every decoding step attends over the entire prefix, because the attention mechanism compares the current query against keys and values derived from all previous positions. Nothing about that structure changes with context length, which is why the feel of a model does not change as a chat grows long, while the machinery underneath it keeps getting heavier with every turn.
The expensive-looking approach would be to recompute the key and value projections for the whole prefix at every step. That design is correct but wasteful: total work across a generation grows with the square of sequence length, since step n redoes all the work of step n minus one plus a little more. Because earlier tokens never change once they are embedded, their keys and values are stable, and recomputing them is pure duplication. The entire discipline of efficient inference starts from this single observation about what is reusable and what is not.
The result is that latency per token is dominated not by the arithmetic of the network but by the length of the history it must consult. As a session stretches from a few hundred tokens toward one hundred thousand, the time to produce each additional token climbs, memory traffic climbs with it, and the first token of a fresh prompt takes longer simply because there is more to read. At that point the arithmetic units sit idle while the memory system streams keys and values, and extra compute does not shorten the wait.
02 What the cache stores and why it works
The KV cache is the fix for that duplication. For every layer and every attention head, the model stores the key and value projections of each past token the first time they are computed, then reads them back on subsequent steps. Nothing about the stored entries changes as generation proceeds, because the tokens that produced them are fixed. A cache entry is therefore written once and read many times, which turns a quadratic recomputation problem into a linear storage problem. Reading a table is far cheaper than rebuilding it, and the difference compounds with every step of a long generation.
The cache must stay resident in high-bandwidth memory for the whole life of the sequence. Moving it to slower storage would force the model to wait on every step, so in practice the cache sets how many sequences a server can hold at once. Decoding has almost no arithmetic intensity: each step moves a large amount of cached data to produce a single token. That is why inference at large context lengths is described as memory-bandwidth-bound rather than compute-bound, a distinction that shapes hardware choices. Nothing else in the pipeline behaves this way.
The architecture comes directly from the original transformer design of Vaswani et al., where keys and values are projections computed per head. Later models keep the same bookkeeping even when they change how many heads share cache entries. Understanding the cache as a per-layer, per-head table of vectors is the key to every optimization in section five: each technique either removes entries, shrinks them, or packs them more tightly, and each choice has a different cost in quality or complexity. That framing also explains why cache research is so active: the table is the single largest consumer of memory during generation, dwarfing the weights at long context.
03 The memory math, worked out
The size of the cache follows a short formula: two multiplied by the number of layers, the number of key-value heads, the head dimension, the sequence length, the batch size, and the bytes per element. The factor of two exists because both keys and values are stored. Every term multiplies every other term, which is the whole problem in miniature: add context, add concurrent users, or add layers, and the product grows without any single component looking alarming on its own. Sequence length is the term users control directly, batch size is the operator's lever, and architecture fixes the rest, so every optimization targets one factor of the product.
Run the numbers for a 7B-class model as a worked example: 32 layers, 32 attention heads, a head dimension of 128, and fp16 storage at two bytes per element. Two bytes times two tensors times 32 layers times 32 heads times 128 dimensions gives roughly 512 kilobytes per token with full multi-head attention. An 8K-token context therefore holds about 4 gigabytes per sequence, and a 128K context reaches about 64 gigabytes per sequence, before batching. Switch the same model to grouped-query attention with 8 key-value heads and the per-token cost drops about fourfold, to roughly 128 kilobytes. All figures here are worked-example arithmetic, not measurements of a shipping product.
Those per-sequence totals explain a great deal of serving behavior at a stroke. A single accelerator with 80 gigabytes of memory cannot even hold one resident 128K sequence under full multi-head attention in this worked example, let alone a batch of them. The chart below plots both series across the common context lengths, and the shape of the curves, straight lines on a linear scale, is the visual signature of linear growth in context.
04 Why long context is a product decision, not a free feature
Cache size is not only an engineering curiosity; it decides what a product can offer. The cache grows linearly with context and then multiplies by the number of concurrent sequences a server tries to keep resident. High-bandwidth memory capacity therefore caps how many long conversations a single accelerator can serve at once, and once capacity is reached, providers must either queue users, spill sequences to slower tiers, or charge more for long-context requests. Market pricing reflects this: long-context usage is commonly priced higher, an estimated premium rather than an officially itemized cost line.
This is why the memory wall shows up in product pages rather than papers. Very long context windows tend to carry asterisks: effective limits that are lower than the headline number, slower tiers for the longest inputs, or context that is summarized rather than kept verbatim. None of those caveats are about attention math; they are about how many gigabytes of cached state a fleet can hold and refresh per user request, which is a bounded physical quantity. The constraint binds hardest under peak load.
Batching sharpens the constraint. Serving one 8K conversation costs about 4 gigabytes in the worked example above; serving thirty of them at once costs about 120 gigabytes of cache before a single weight is loaded. Throughput and context length pull against each other through the same multiplication, and every scheduling decision a serving stack makes, from preemption to prefix reuse, is an attempt to keep that product inside the memory that exists. The numbers are worked-example estimates, but the shape of the trade is not: memory is finite, context is chosen by users, and something must give.
05 The engineering responses
The best-known response is PagedAttention, introduced with the vLLM serving system. Pre-paging cache memory for a maximum context length wastes most of it: the paper reports that existing systems over-allocated so heavily that roughly 60 to 80 percent of KV cache memory was wasted on fragmentation and reservation. PagedAttention borrows virtual-memory paging from operating systems, storing cache in small blocks on demand, and cuts that waste to under about 4 percent. The gain is not a smaller cache per token; it is dramatically more of the purchased memory doing useful work.
Architecture changes shrink the cache itself. Grouped-query attention lets heads share key-value entries and yields the fourfold reduction in the worked example; multi-query attention, with a single shared key-value head, reaches 32 times smaller at the upper end, with quality trade-offs that vary by model. Multi-head latent attention, used at DeepSeek's scale, compresses the cache roughly ninefold against full multi-head attention according to the papers. Quantizing cached keys and values to 8-bit formats is estimated to roughly double what fits. Sliding-window architectures simply cap how far back the model looks, trading recall for a fixed footprint.
These techniques stack only partly, because they act on different terms of the same formula. Head sharing divides the head count, latent compression changes what a head stores, quantization changes bytes per element, and paging changes how much of the result is wasted. A serving stack can combine them, and modern systems usually do, but the multiplication underneath stays: memory per token is still set by architecture and precision, and context still multiplies it. Each also carries a distinct risk: shared heads can cost accuracy on certain tasks, latent compression ties a model to its training code, and aggressive quantization of cached state can degrade long-range recall.
06 What it means for what you pay
For anyone buying AI capability rather than building it, the cache explains three price signals at once. Decode cost per token tracks the number of cached bytes that must be moved per step, which is why long conversations cost more per token than short ones even at the same model size. Long-context premiums, per-million-token pricing tiers, and rate limits on context all monetize the same multiplication worked out in section three. A provider that halves its effective cache footprint can either serve twice the users or undercut rivals on long-context price, and both moves show up publicly.
Batch throughput ceilings trace back the same way. A server that fills its memory with one user's 128K cache cannot batch other requests behind it, so peak advertised throughput is usually measured at short context where caches are small and batches can grow. On-device assistants face the hardest version: a laptop or phone has a fixed memory budget shared with everything else, which is why local models ship with practical context limits far below what their architectures could theoretically address.
The practical takeaway is to read context numbers as memory commitments rather than features. A one-million-token window is a promise that a provider can hold roughly a million tokens of cached state per sequence and still serve a queue, and that promise is expensive enough that it shapes pricing, speed, and availability. The next article in this batch looks at the other half of the memory story, quantization, which attacks the bytes per element term of the same formula. Until then, treat every headline context number as a question about whose memory, at what precision, shared across how many concurrent requests, at what price per moved gigabyte.
References
- Wikipedia: Transformer (deep learning) — architecture overview
- Wikipedia: Attention (machine learning) — attention mechanism background
- Vaswani et al., Attention Is All You Need — the transformer paper
- Kwon et al., Efficient Memory Management for LLM Serving with PagedAttention — vLLM serving paper
- Source video: The KV Cache: Memory Usage in Transformers (Efficient NLP, ~155K views, observed 2026-11-26)
By N43 and Hermes AI for DutyStation News.





