Source publication. Illustration placeholders and evidence labels are preserved as supplied.
The KV Cache: The Memory Behind Every Token
Understanding KV-cache storage, memory requirements, allocation, fragmentation, and prompt caching in LLM inference.
Publication 03 in the series on AI, LLM and neural-network engineering. Publication 01 covered the GPU economics of LLM inference. Publication 02 explained prefill and decode, the two different workloads behind every response. This one looks at the memory system that connects them.
1. Introduction: The Memory Behind Every Token
Ask most people how much GPU memory a language model needs and they will answer with the size of the weights. A 27-billion-parameter model at 4-bit precision is roughly 16 GB, so a 24 GB card "should fit it".
Then the server starts, a long prompt arrives, and the GPU runs out of memory.
The weights are only the first line of the bill. While a model generates text, the inference engine has to remember something about every token it has already processed. That memory grows with the conversation. It is multiplied by the number of requests being served at once. And it competes with the weights, the temporary working buffers and the runtime itself for the same GPU.
My notes use a library analogy that I find useful:
- The weights are the librarian's learned knowledge. They are large, fixed and loaded once.
- The runtime state is what the librarian is keeping track of about the current conversation. This is where the KV cache lives.
- The working memory is the desk space for the task at hand: temporary buffers for matrix work.
You can have a great librarian and still be unable to serve readers because the desk is full of notes.
This article is about the notes. We will look at what the KV cache stores, how to calculate its size, how architectural choices such as grouped-query attention change it, why "context window" and "memory in use" are different things, how runtimes allocate and fragment it, and how prompt caching reuses it. We finish with a practical checklist and two deployment examples, including what their numbers can and cannot tell us.
2. What Exactly Is the KV Cache?
Queries, keys and values in one paragraph
Inside every attention layer, each token position is projected into three vectors. My notes describe them like this:
- Query (Q): what this token is looking for in other positions.
- Key (K): what this token offers, an indexed description of the information it holds.
- Value (V): the actual information that gets passed along if another token decides this one is relevant.
Attention compares the current query with the keys of the permitted positions, turns those similarity scores into weights with softmax, and uses the weights to combine the values:
Attention(Q, K, V) = softmax( Q · Kᵀ / √d_k ) · V
Here d_k is the width of a key vector. Dividing by √d_k keeps the scores in a range where softmax does not saturate.
What gets stored, and what does not
During generation, the model produces one new token at a time. To produce it, the new token's query must be compared with the keys of every earlier token, and the new token must be able to read their values.
Here is the key observation. In a decoder with causal masking, the keys and values of earlier tokens do not change when a new token arrives. Position 500's K and V depend only on positions 1 to 500. So the engine computes them once and keeps them.
- Stored: the K and V vectors for every cached token position, for every layer that has a cache, for every KV head.
- Not stored as cache: the query (only the current token's query is needed, and it is used once), the attention score matrix, and the temporary activations. These live in working buffers and are discarded.
That stored collection is the KV cache.
An analogy: reference cards
Imagine reading a book and keeping an index card for every page you have read. Each card has two parts: a short description of the page (the key) and the content worth remembering (the value). When you reach a new page, you do not re-read the whole book. You scan the cards, decide which are relevant, and pull from those.
That is the KV cache. The cost is that the stack of cards grows with every page.
Why the cache grows
Every new token adds one more K and V vector per layer and per KV head. The cache therefore grows linearly with the number of tokens held in context, both prompt tokens and generated tokens. [VERIFIED] in my notes: memory is proportional to the context length C.
AI-assisted diagram: simplified cache lifecycle within one attention layer.
What the cache does and does not save
Warning: One line in my notes says the cache turns "quadratic O(n²) computation growth into linear O(n)". This is a common simplification and needs a more careful statement.
Without a cache, producing each new token would mean re-running the whole history through every layer: recomputing every old token's K and V and its MLP work. With a cache, the engine does that heavy per-token work only for the new token.
What the cache does not remove:
- Attention over history. The new token's query must still be scored against all
ncached keys, and the weights applied to allnvalues. That is linear innper step, and it adds up to roughly quadratic work across a whole generation. - Reading the cache. Every decode step has to read the cache from GPU memory. As context grows, so does the amount of data read per token. This is part of why decode is usually described as memory-bandwidth-bound, as Publication 02 explained.
So the KV cache avoids repeated computation. It does not make attention free, and it does not make decode constant-time. Techniques such as FlashAttention reduce the memory traffic and temporary memory of the attention computation, but they do not remove the cache itself.
3. Understanding the GPU Memory Budget
The KV cache is one tenant in a shared building. A useful conceptual budget, taken from my notes and extended with the graph category, is:
M_GPU ≈ M_weights + M_KV + M_SSM + M_compute + M_graph + M_other
AI-assisted diagram: conceptual categories, not proportional allocations.
What each term means:
- M_weights: the learned parameters loaded onto the GPU. This is usually the largest, most stable allocation. Its size depends on parameter count, quantization, which layers are offloaded to CPU, and tensor layout.
- M_KV: the attention key/value cache, the subject of this article.
- M_SSM: recurrent and convolution state for state-space-model layers, in architectures that have them. Unlike a KV cache, it does not grow per token in the same way (see Section 13).
- M_compute: temporary buffers for matrix multiplications, attention computation, intermediate activations, and batch and micro-batch processing. Some of this scales with the number of tokens processed at once, not with total context.
- M_graph: memory used when the runtime captures and replays CUDA graphs. A CUDA graph records a sequence of GPU operations so they can be replayed with less CPU launch overhead. Capturing and replaying can need extra memory for its own allocations.
- M_other: CUDA runtime contexts, allocator overhead and fragmentation, runtime metadata, and any other processes sharing the GPU.
Important: This is a conceptual budget, not a universal allocator equation. Different runtimes and profilers draw the category boundaries differently, and some memory (such as allocator slack) does not belong cleanly to any single term. Do not expect a profiler to report these six numbers.
A CUDA graph is a GPU execution mechanism. It is not the same thing as the neural network's computational graph, which is a mathematical description of operations and dependencies.
This is also why servers deliberately leave GPU memory unallocated. Maximum allocation is not the same as maximum reliability. The runtime needs room to execute operations, respond to changing workloads, and absorb allocator behaviour. Filling every byte with cache invites out-of-memory failures at the worst moment.
4. Calculating KV-Cache Memory Requirements
The basic formula
For a model where every layer has the same attention layout, the raw KV payload for one sequence is:
M_KV = 2 × L × C × H_KV × d_head × B
Every variable:
2: one K vector and one V vector are stored per position.L: the number of attention layers that keep a cache.C: the number of cached tokens in the sequence.H_KV: the number of key/value heads (not the number of query heads).d_head: the number of dimensions in each head's K or V vector.B: bytes per stored element. FP16 uses 2 bytes.
A handy intermediate is the cost of one token:
bytes per token = 2 × L × H_KV × d_head × B
Worked example
[CALCULATED] Assumptions: 32 layers, 8 KV heads, head dimension 128, FP16 (2 bytes), 8,192 tokens, one sequence.
Per token:
2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KiB
For 8,192 tokens:
131,072 × 8,192 = 1,073,741,824 bytes = 1 GiB
Here 1 GiB means 2³⁰ bytes, which is about 1.07 GB in decimal units. I use GiB throughout so the arithmetic is exact.
Because the relationship is linear in C, doubling the context doubles the cache:
Context Tokens Raw KV payload (one sequence)
8K 8,192 1 GiB
16K 16,384 2 GiB
32K 32,768 4 GiB

Supplied chart showing the illustrative raw KV payload calculated above.
Important: This is the raw payload: only the K and V numbers. It is not the total GPU memory a runtime will use. Real allocations add padding and alignment, block metadata, allocator overhead, and potentially extra memory for alternative cache layouts. On top of that, the weights, compute buffers and graph buffers from Section 3 still need room. Treat the formula as a lower bound for the cache, not a prediction of
nvidia-smi.
Generalising for real architectures
The uniform formula assumes every layer caches the same number of tokens with the same heads. Many modern models break that assumption. Some layers use sliding-window attention and only retain recent tokens. Some layers share another layer's cache. Some have different head counts or dimensions in different layers.
The general form simply sums over layers:
M_KV = 2 × Σ over layers l of ( C_l × H_KV,l × d_head,l × B_l )
Here each layer l has its own effective cached length C_l, KV-head count H_KV,l, head dimension d_head,l and precision B_l. If the layers differ, calculate each one separately and add the results, as my notes put it.
This is why a single "KV size per token" number published for one architecture cannot be reused for another, and why we return to this in Section 13.
5. MHA, GQA and MQA: Why the Number of KV Heads Matters
An attention layer runs several heads in parallel. Each head has its own learned projections. The three common layouts differ in how many K/V heads there are compared to query heads:
- Multi-Head Attention (MHA): every query head has its own K and V head. If there are 32 query heads, there are 32 KV heads.
- Multi-Query Attention (MQA): all query heads share a single K/V head. Introduced by Shazeer (2019).
- Grouped-Query Attention (GQA): query heads are divided into groups, and each group shares one K/V head. It sits between MHA and MQA. Introduced by Ainslie et al. (2023).
AI-assisted diagram: summarized head-sharing relationships for the stated example.
Only K and V are cached, so the number of KV heads, not query heads, drives cache size. Query heads affect compute, not cache storage.
The illustrative example from my notes
Assume 32 query heads, head dimension 128, and FP16. The cost per token per layer is 2 × H_KV × d_head × B:
[CALCULATED]
MHA (32 KV heads): 2 × 32 × 128 × 2 = 16,384 bytes
GQA ( 8 KV heads): 2 × 8 × 128 × 2 = 4,096 bytes
MQA ( 1 KV head ): 2 × 1 × 128 × 2 = 512 bytes
The ratios, relative to MHA:
- GQA with 8 KV heads uses 4,096 / 16,384 = 1/4 of the storage.
- MQA uses 512 / 16,384 = 1/32 of the storage.
Warning: My notes say "GQA allow 1 Query to share ...". The figure used in the notes (8 KV heads) means each KV head serves 32 ÷ 8 = 4 query heads, so the sentence should read "each KV head is shared by 4 query heads". This looks like a transcription slip. The arithmetic itself is correct.
To connect with Section 4, multiply by 32 layers and 8,192 tokens:
Layout Per token (32 layers) At 8,192 tokens
MHA 512 KiB 4 GiB
GQA 128 KiB 1 GiB
MQA 16 KiB 128 MiB
The GQA row is the 1 GiB example from Section 4. The same model shape with full MHA would need four times the cache. That saving can be spent on longer contexts or more concurrent requests.
Two cautions:
- GQA and MQA are architectural properties set when a model is designed and trained (or converted and further trained, which Ainslie et al. call uptraining). You cannot switch them on for an existing checkpoint at inference time.
- The trade-off is that sharing K/V heads can reduce model quality compared with full MHA. GQA was proposed because it recovers most of MHA's quality at close to MQA's speed. The exact balance depends on the model.
6. Context Window Is Not the Same as Memory Occupancy
"Context window" is a number in a configuration file. "Memory in use" is a number in a profiler. They are related, but they are not the same.
My notes ask a good question: why does an 8K context consume memory before you send an 8K-token prompt? The answer is that several different quantities hide behind the word "context":
- Configured context capacity: the maximum number of tokens the server has been told to support.
- Cache capacity reserved at startup: memory set aside for the cache when the server starts, often sized from the configured context and the number of parallel sequences.
- Cache capacity allocated dynamically: memory that is grown or assigned only as requests need it.
- Actual occupied cache payload: the bytes that currently hold real K/V data for tokens that exist.
- Peak GPU memory: the highest total usage seen over a run, including weights, cache, compute buffers and spikes.
AI-assisted diagram: configured tokens and allocated bytes have different units; peak memory is a separate measurement.
Why a runtime may reserve memory early
Reserving the cache up front makes behaviour predictable. The server can refuse to start if the configuration cannot fit, instead of failing at 3 a.m. when a long request arrives. Allocating one large region once is also simpler and faster than repeated small allocations.
Implementations differ
Important: Do not assume every inference engine behaves the same way.
- Some runtimes, in typical configurations, allocate a KV buffer sized from the configured context at startup. The llama.cpp server is an example: the context size and slot settings determine the size of its cache buffer, and the startup log reports it. Check your own build's log, because details change between versions.
- Other runtimes, such as vLLM, typically measure how much memory remains after loading the model and reserve a pool of cache blocks from it. Blocks are then assigned to sequences as they need them, so the pool is reserved even though the occupied portion is smaller.
- Others allocate or grow regions dynamically.
For engineering reports, the distinction matters. A good report states the configured context, the cache capacity allocated at startup, the cache currently occupied, and the peak memory observed during real inference. Mixing these up is the most common way to misread a memory graph.
7. Parallel Slots and Shared KV Allocation
A slot (or sequence) is a logical position the inference server uses to track one request's context and generation state. Four users sending requests at the same time means four sequences in flight, and each one needs its own cache.
How concurrency multiplies the cache
If each of four slots supports 8,192 tokens, the theoretical sum of per-sequence capacities is:
[CALCULATED]
4 × 8,192 = 32,768 tokens
Warning: My notes give this total as "32,168". The correct product is 32,768, so that is the figure used here. It looks like a transcription slip.
For a conventional attention cache, a simplified upper bound on aggregate cache size is:
M_KV,aggregate ≈ N_slots × M_KV,per slot
With the model from Section 4 (1 GiB per 8K sequence), four full 8K slots would be about 4 GiB of raw payload.
Static partitioning versus a shared pool
How the configured context relates to the number of slots depends on the server's allocation policy.
- Static partitioning: the context budget is divided among slots. In the llama.cpp server, when the cache is not unified, a context size of 32,768 with 8 parallel slots gives each slot 4,096 tokens.
- Unified (shared) allocation: all sequences draw from one shared pool. In llama.cpp this is the
--kv-unifiedoption. My notes describe its advantage as better utilisation when sequences have different lengths.
An illustration, using the same 32,768-token budget and four slots:
[CALCULATED]
Requests in flight (tokens): 1,000 2,000 4,000 20,000
Total needed: 27,000 tokens
Static partition (8,192 per slot):
the 20,000-token request does not fit its slot
Shared pool (32,768 total):
27,000 ≤ 32,768, so all four fit
A rigid allocation that reserves the same maximum for every slot can leave a lot of capacity unused in short sequences. A shared allocation can use the available blocks more efficiently, depending on the implementation.
Important: Do not assume that setting four slots gives you four independent 8K caches. The meaning of "context size", "per-sequence context" and "slot count" depends on the server configuration. Some configurations define a total budget across sequences; others expose per-sequence capacity. Read your runtime's documentation and its startup log.
8. Memory Fragmentation
Fragmentation is wasted memory that the allocator cannot easily use. It comes in two forms.
External fragmentation: free memory exists, but it is split into separate, non-contiguous regions. If an allocation needs one sufficiently large contiguous region, the allocator may fail even though the total free memory is enough. This only bites allocators that require contiguity.
Internal fragmentation: memory is allocated in fixed-size blocks, and a request does not fill its last block. The unused remainder is allocated but wasted.
The block-waste example from my notes
Suppose a runtime manages the KV cache in blocks of 256 tokens, and a sequence needs 300 tokens.
[CALCULATED]
Blocks needed: ceil(300 / 256) = 2
Positions allocated: 2 × 256 = 512
Unused positions: 512 − 300 = 212 (about 41% of the allocation)

Supplied chart illustrating the hypothetical 256-token block example.
Important: This is an illustration of internal block waste. It does not prove that any particular runtime uses 256-token blocks. Block sizes vary. vLLM, for example, has historically used small blocks of 16 tokens by default, which would reduce this waste.
The general rule is:
waste per sequence = ceil(T / b) × b − T
where T is the tokens in the sequence and b is the block size. With b = 16, the same 300-token sequence needs 19 blocks (304 positions) and wastes only 4. Smaller blocks waste less per sequence but mean more blocks to track, more metadata and more indirection. That is the central trade-off of block design.
Warning: Fragmentation is not the explanation for every out-of-memory failure. Many OOMs have simpler causes: the weights plus the cache simply exceed the card; a large batch causes a spike in compute buffers; CUDA graph capture needs more than expected; or another process holds GPU memory. Before blaming fragmentation, look for evidence: total free memory versus the largest allocation that failed, and allocator statistics where available.
9. PagedAttention and Block-Based KV Allocation
Early serving systems stored each request's KV cache in one contiguous chunk, usually pre-allocated to the request's maximum possible length. That creates both kinds of fragmentation: space reserved for tokens that may never be generated, and gaps between requests of different sizes.
PagedAttention, introduced with the vLLM system by Kwon et al. (2023), borrows an idea from operating-system virtual memory. The cache of each sequence is divided into fixed-size blocks, each holding the keys and values for a fixed number of tokens. The paper's analogy: blocks are pages, tokens are bytes, and sequences are processes.
Logical blocks and physical blocks
- Logical blocks are how a sequence sees its own cache: block 0 holds tokens 0 to 15, block 1 holds tokens 16 to 31, and so on, in order.
- Physical blocks are where those blocks actually sit in GPU memory. They do not have to be adjacent or in order.
- A block table maps each sequence's logical blocks to physical blocks. The attention kernel follows this mapping to gather the keys and values it needs.

Source: Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention, Figure 6. This example shows one request's mapping.
What this buys
- Allocation on demand. A new block is assigned only when a sequence fills its current one, so memory follows actual usage instead of the worst case.
- Easy reclamation. When a sequence finishes, its blocks return to a free pool and can be assigned to anyone.
- No large contiguous requirement. Any free block will do, which removes most external fragmentation.
- Sharing. Several sequences can point their logical blocks at the same physical block when the content is identical, for example a shared prompt prefix or parallel sampling from the same prompt.
[VERIFIED] by the paper: existing systems it profiled used only about 20.4% to 38.2% of reserved KV memory for actual token states, and vLLM achieved near-zero waste in KV cache memory, with throughput 2 to 4 times higher at the same latency compared with the systems it measured. These are the paper's reported results on its own workloads. Your gains depend on your model, traffic and baseline.
What block-based allocation does not eliminate
Important: "Near-zero waste" is not "zero waste".
- Internal fragmentation remains in each sequence's last, partly filled block (Section 8).
- Metadata overhead remains: block tables, reference counts and hash tables.
- Capacity limits remain. If the pool of blocks is full, new work must wait, be preempted or be rejected.
- Other memory pressure remains: weights, compute buffers and graph memory are untouched.
- The indirection has a cost in the attention kernel, which must gather from scattered blocks.
Also be careful not to conflate the general idea of block-based allocation with one implementation. PagedAttention is a specific algorithm; the vLLM block manager is one design built on it. Other runtimes manage the KV cache with different structures, and their behaviour should be checked in their own documentation.
10. Prompt Caching and Prefix Reuse
The KV cache is useful within a single request. It becomes much more valuable when it can be reused across requests.
The idea
A shared prefix is a run of tokens at the start of a prompt that is identical across requests. During prefill, the model computes K and V for every prompt token. If a later request begins with the same token sequence, the runtime can reuse the stored K/V state for that part and process only the new suffix. Without prompt caching, the model repeats the prefill for the shared prefix on every request.
My notes use an exam analogy: a student who has already prepared notes does not need to re-read the entire textbook before every question.
Why exact token identity matters
Reuse is only valid because K and V at a position depend on all tokens before it. If any earlier token differs, every later K and V is different.
So prefix caching depends on the exact token prefix, not on similar wording. Two prompts that mean the same thing but tokenize differently are not cache-compatible. Neither are prompts that are semantically similar but differ in a single early token. A cache hit is determined by token identity, not by meaning.
vLLM's automatic prefix caching shows one way of doing this. Each cache block is identified by the tokens inside it plus the tokens in the prefix before it, via a hash that chains from the start of the prompt. Lookup proceeds block by block until the first mismatch, and only the contiguous matching prefix is reused. Identical text appearing later in a different prompt gives no match.
Practical consequences:
- Only full blocks are reused in this design. A partly filled final block of a prefix must be recomputed. Reuse granularity depends on block size.
- Anything that changes tokens early in the prompt can break reuse from that point onward: editing system instructions, reordering repository files in the context, inserting a timestamp near the top, or reordering tool definitions.
- Cache entries are limited by capacity, so something must be evicted. In vLLM's documented policy, blocks no running request is using are candidates, and the least recently used are evicted first. Other runtimes use other policies.
- Sliding-window and recurrent layers complicate reuse, because their state at an earlier position cannot simply be recovered from the final state. Runtimes often handle this with snapshots or checkpoints of the cache. llama.cpp's server, for instance, documents prompt checkpoints for recurrent and sliding-window models. Check what your runtime does for your architecture.
Important: Prefix caching is an exact-match optimisation. If your cache hit rate is lower than expected, look first at what changed early in the prompt.
A practical example: an AI coding assistant
A coding assistant naturally builds prompts with a large stable part and a small changing part:
- System instructions.
- Repository rules and conventions.
- A workspace architecture summary and directory structure.
- Selected, relatively stable source files.
- The user's new request (changes every time).
Items 1 to 4 form a reusable prefix, and item 5 is the suffix. Put the stable material first and the volatile material last.
[CALCULATED] Illustrative assumptions: the stable prefix is 9,000 tokens, the new request is 300 tokens, blocks are 16 tokens, and prefill runs at a constant 3,000 tokens per second. These are invented round numbers chosen to show the arithmetic.
Uncached prefill: 9,300 tokens ÷ 3,000 tok/s = 3.10 s
Reusable full blocks: floor(9,000 / 16) = 562 blocks = 8,992 tokens
Tokens still to prefill: 9,300 − 8,992 = 308
Cached prefill: 308 ÷ 3,000 tok/s ≈ 0.10 s
The speedup relationship is:
Speedup = T_uncached / T_cached
Here that is about 3.10 / 0.103 ≈ 30. Note how the 8 leftover prefix tokens (9,000 minus 8,992) are recomputed because they do not fill a block.
Warning: This number measures the improvement in prompt-evaluation time under the compared conditions. It is not automatically the speedup of the whole response. Decode time is unchanged.
To see why, suppose the answer is 500 tokens at 30 tokens per second (about 16.7 s of decoding):
[CALCULATED]
Uncached total: 3.10 + 16.67 = 19.77 s
Cached total: 0.10 + 16.67 = 16.77 s
End-to-end speedup ≈ 1.18×
The time to first token improves dramatically, which changes how responsive the assistant feels, but the end-to-end gain is modest when responses are long. Real prefill is also not at a constant rate, because attention over a long cached prefix still has a cost.
The memory cost of keeping a prefix
Reusable state is not free. It occupies cache capacity for as long as it is retained.
[CALCULATED] Using the model shape from Section 4 (128 KiB per token):
9,000 tokens × 128 KiB = 1,152,000 KiB ≈ 1.10 GiB
So keeping that one prefix warm costs about 1.1 GiB of raw payload. More retained cache potentially means less repeated prefill, but also less capacity for other sequences. My notes use a desk analogy: keeping frequently used books on the desk saves trips to the library, but the desk has limited space.
AI-assisted diagram: physical sharing depends on matching token prefixes and runtime support.
Prefix reuse is also offered above the runtime level. Managed APIs expose prompt caching with the same exact-prefix principle, and research systems such as SGLang's RadixAttention organise cached prefixes in a tree. The details and any pricing differ between providers, so consult their documentation.
11. Prompt Caching vs Context Compaction
These two techniques are often mentioned together but solve different problems.
- Prefix caching reuses previously computed state. The prompt stays the same. It saves compute.
- Context compaction reduces or restructures the information kept in the active context. The prompt gets shorter or different. It saves context capacity (and therefore cache memory).
My notes organise context into three layers for a coding assistant:
- Persistent project knowledge, stored outside the active prompt and retrieved when relevant: architecture summaries, repository instructions, build and test procedures.
- Task-specific evidence: the smallest sufficient set for the current task, such as relevant source files, tests, call paths, configuration, recent changes and tool output.
- Active working context: what the model needs to do right now, such as the current request, reasoning, immediate findings and pending steps.
The total context can be thought of as a sum of its parts:
C_total ≈ C_system + C_tools + C_history + C_retrieved + C_request + C_output
Warning: The component labels in this formula were partly illegible in my handwritten notes, and the pairing of labels to terms was reconstructed. Treat the exact term names as a sketch of what typically fills a context window, not as a quotation.
How they interact
They complement each other, but compaction can interfere with caching. If you summarise or rewrite old history, the tokens after the stable prefix change, and the cache can only be reused up to the point of divergence.
A sensible design:
- Keep layer 1 stable and at the front, so it forms a reusable prefix.
- Compact the volatile tail (old conversation turns and tool output) instead of rewriting the front of the prompt.
- Retrieve layer 2 evidence in a deterministic order, so identical tasks produce identical token sequences.
Use caching to make repeated prefixes cheap. Use compaction to stop the context from growing without limit. Neither replaces the other.
12. KV-Cache Quantization and Precision
Two different optimisations
Important: Weight quantization and KV-cache quantization are independent optimisations with different memory problems. They should be benchmarked independently.
- Weight quantization changes how the model's learned parameters are stored. It reduces model size and weight-memory traffic.
- KV-cache quantization changes how the temporary K/V data is stored while sequences are processed. It reduces cache memory but also reduces the precision of retained attention information.
A Q8_0 model can use an FP16 KV cache, and an FP16 model can use a quantized KV cache, provided the runtime supports the combination. The weight format does not decide the cache format. In llama.cpp, for example, K and V cache types are set separately from the model file, and they default to FP16.
Bytes per element
Block-quantized formats store a block of values with a shared scale. The scale is extra storage, so the formats are not exactly one byte or half a byte per value.
Format Layout per 32-element block Bytes/element
FP16 32 × 2 bytes 2.0
Q8_0 32 × 1 byte + 2-byte scale = 34 1.0625
Q4_0 16 bytes + 2-byte scale = 18 0.5625
Warning: My notes give Q4_0 as 0.5535 bytes per element. With a 16-byte payload (32 four-bit values) plus a 2-byte scale, 18 bytes per 32 elements gives 0.5625, so I use that figure. This looks like a transcription or arithmetic slip. Also, these block layouts describe common ggml formats; do not treat them as universal specifications. Always read your runtime's actual cache format and allocation report.
Applied to the 8K, 32-layer, 8-KV-head example from Section 4:
[CALCULATED]
FP16: 1 GiB = 1,024 MiB
Q8_0: 1 GiB × (1.0625 / 2) = 544 MiB
Q4_0: 1 GiB × (0.5625 / 2) = 288 MiB
Compare with the naive "half" and "quarter" figures of 512 MiB and 256 MiB: the scale overhead is real, but small.
Savings versus approximation
Quantization maps values to a smaller representation, so it introduces numerical error. A simple uniform scheme is q = round(x / S) and x̂ = q × S, with error E = x − x̂. The question is not whether individual values change. It is whether those changes affect the model's output.
Possible consequences include reduced numerical fidelity, shifted token probabilities, degraded reasoning or instruction following, more errors on difficult tasks, and different behaviour on long-context workloads. It does not necessarily cause visibly worse output on every task. Research on KV quantization (for example KIVI and KVQuant) finds that keys and values have different statistics and benefit from different treatment, which is one reason simple settings are not equally safe for K and V.
Lower precision does not automatically mean faster
Smaller data can reduce memory traffic, which may improve decode speed when decode is bandwidth-bound. But the speed result depends on:
- whether the GPU and the runtime have efficient kernels for that format;
- dequantization overhead (values must be converted back to a usable precision);
- batch size, prompt length and context length;
- whether the workload is compute-bound or memory-bound.
[REPORTED] A community discussion in the llama.cpp repository describes a CUDA setup where decode with a Q8_0 KV cache and the unified cache was slower than with FP16, attributed by the reporter to the kernel path that quantized data takes. This is a single user's observation, not a general rule, and it may have changed since. It is included to show why you should measure on your own hardware.
When you compare configurations, keep these dimensions separate: weight format and model memory; KV-cache format and cache allocation; prompt-processing speed and time to first token; generation speed and inter-token latency; output quality; and stability (OOM failures, errors, repeatability).
13. Hybrid Attention and SSM Architectures
A single full-attention KV formula cannot be applied blindly to modern models. Several architectural techniques change what is cached, and where.
- Full-attention layers keep K and V for every token in the context. Their cache grows with the whole context.
- Sliding-window attention limits each token to the most recent
Wpositions, so a layer's cache can be bounded by the window instead of the full context. The cost is that a token cannot directly attend beyond the window within that layer. - Shared KV layers reuse the K and V produced by an earlier layer instead of computing and storing their own. This is the idea of cross-layer attention (Brandon et al., 2024).
- State-space-model (SSM) layers do not keep per-token keys and values. They compress history into a fixed-size recurrent state that is updated at each step. My notes give the simplified recurrence
h_t = A·h_(t−1) + B·x_t, with outputy_t = C·h_t, and a state memory ofM_SSM = Σ D_i × N_i × B_i(channels, state elements per channel, bytes per element, summed over SSM layers). This state can stay approximately constant as the sequence grows. - Architecture-specific buffers such as convolution state and temporary tensors still occupy memory.
Warning: Real selective SSMs are more sophisticated than the simplified recurrence, with multiple state dimensions, channels and implementation-specific layouts. Use the formula to build intuition, not to size a production system.
A carefully qualified example: Gemma 4 E4B
I use this architecture to show why layer-aware reasoning matters. The architecture numbers below were supplied from an extraction of the deployed model: 42 blocks; 35 sliding-window blocks and 7 full-attention blocks; 18 shared KV layers and 24 physical KV layers; 8 query heads and 2 KV heads; and 512-dimensional key/value heads.
[REPORTED] The block counts, KV-layer split and head counts match public descriptions of this model family that I checked (Raschka's architecture gallery lists 35 sliding-window and 7 global layers, the first 24 layers producing the KV cache for all 42, and 2 KV heads).
Two details are not settled, and I flag them rather than hide them:
- [UNKNOWN] The head dimension. Public descriptions I found list a head dimension of 256 for sliding-window layers and 512 for the global layers, and a sliding window of 512 tokens. The extraction reports 512-dimensional heads. The number 512 appears in both the window size and the global head dimension, so it is plausible the two were conflated, but I cannot tell from the evidence. The authoritative source is the model's own metadata (see the checklist).
- [UNKNOWN] The exact split between sliding-window and full-attention layers is described as 35/7 in one source and 36/6 in another.
Why a uniform estimate misleads
[CALCULATED] Illustration, not a measurement. Assumptions: 2 KV heads; sliding layers use head dimension 256 and global layers use 512; the 7 global layers sit at every sixth position (6, 12, ..., 42), which puts 20 sliding and 4 global layers among the 24 layers that own a cache; FP16; one sequence of 32,768 tokens; sliding layers retain only a 512-token window.
Sliding layer, per token: 2 × 2 heads × 256 × 2 B = 2,048 B
Global layer, per token: 2 × 2 heads × 512 × 2 B = 4,096 B
Cache-owning layers per token:
20 × 2,048 + 4 × 4,096 = 57,344 B = 56 KiB
That 56 KiB per token matches the per-token figure listed in the public architecture gallery, which supports these assumptions, though it is not a measurement of any deployment. Now three ways to estimate 32,768 tokens:
Estimate Raw payload
A. Naive: all 42 layers full attention,
2 KV heads, 512-dim heads 5.25 GiB
B. Shared KV + GQA, no window savings 1.75 GiB
C. B, with sliding layers capped at a
512-token window ~0.52 GiB
The arithmetic: A is 2 × 42 × 2 × 512 × 2 B = 172,032 B per token, times 32,768 = 5.25 GiB. B is 57,344 B × 32,768 = 1.75 GiB. C is 4 global layers × 4,096 B × 32,768 = 512 MiB, plus 20 sliding layers × 2,048 B × 512 = 20 MiB, about 532 MiB.
The naive estimate overstates this architecture's raw cache by roughly an order of magnitude, under these assumptions. Real runtimes may retain more for sliding layers than the strict window (for instance, llama.cpp has an option for a full-size sliding-window cache), and Q8_0 or other precisions would change B. So estimate C is a lower-end figure, not a promise.
Important: No actual measured KV-cache footprint was established for this deployment. The table shows why layer-aware reasoning is necessary. It does not tell you what the server used.
14. Deployment Experiences: What the Numbers Can and Cannot Tell Us
Two deployments were supplied to me. They are separate. I do not carry hardware, region or benchmark claims from one to the other.
Deployment 1: Qwen3.8-27B qualification
[REPORTED] configuration:
- Model weights: Q4_K_M.
- K/V cache: Q8_0.
- Context configuration: 8,192 tokens.
- Instance:
ml.g5.4xlargeinus-east-1, using llama.cpp. - Reported qualification summaries: 6 of 10 completed runs in one phase and 9 of 15 in another.
What this can tell us: under that configuration, a reported 60% of runs completed in each phase (6/10 and 9/15). These are small samples, so the difference between the phases and the underlying rate are both uncertain.
What this cannot tell us: these are aggregate qualification results. They are not measurements of KV-cache occupancy, fragmentation or per-request memory allocation. They do not say why the other runs did not complete. Failures could come from many causes (timeouts, tool-call errors, quality failures, or memory), and the summaries do not separate them.
Warning: Do not read these results as evidence about cache memory consumption, and do not infer OOM or fragmentation from them. That would be a hypothesis, not a finding.
[UNKNOWN] I did not calculate a KV estimate for this model. The formulas need its layer count, KV-head count, head dimension and attention structure, and I have not verified its architecture; newer model families increasingly mix attention types. The honest next step is to read the metadata from the model file and the startup log.
Deployment 2: Gemma 4 E4B
[REPORTED] configuration:
- Separate deployment in
eu-north-1on an NVIDIA L4. - Model: Q8_0 GGUF. This describes the weight file; the KV-cache precision was not stated.
- Later configuration: 32,768 context, one slot, prefix caching enabled.
- Architecture extraction: as described in Section 13.
What this can tell us: the architecture is hybrid, so memory estimates must be layer-aware. With one slot and prefix caching enabled, concurrency is minimal and the reuse of stable prompt prefixes is in play, which matters for coding-assistant-style workloads.
What this cannot tell us: [UNKNOWN] the actual KV footprint, the cache precision, how much memory the runtime reserved, how much was occupied, or whether prefix-cache hits occurred at any particular rate. Nothing in the supplied evidence measured them.
Keeping the deployments apart
Both use llama.cpp-style tooling, but that is the only thing they share. Different models, different GPUs, different regions, different context sizes and different measurements. Any comparison between them would be unsupported.
15. Practical Engineering Checklist
Use this list to investigate KV-cache behaviour in your own deployment. Work through it in order and write the answers down.
- Model architecture and KV-head configuration. Read the layer count, query heads, KV heads and head dimension from the model's metadata, not from memory or a blog post.
- Layer types. Which layers are full attention, sliding window, shared KV or SSM? Calculate them separately.
- Context length. Record configured context, the largest prompt you actually see, and the largest response.
- Concurrency. How many slots or concurrent sequences? Is the context budget per slot or shared?
- KV-cache precision. What are the K and V types? Are they different from the weight format?
- Allocation policy. Is the cache reserved at startup, grown on demand or pooled? Is it unified across sequences? Does the runtime use fixed blocks, and of what size?
- Sliding-window and hybrid behaviour. Does the runtime cap sliding layers at the window, or keep more?
- Prefix caching. Is it enabled? What is the hit rate? Is your prompt ordered so stable content comes first? What is the eviction policy?
- GPU memory breakdown. Weights, KV cache, compute buffers, graph buffers, other. Check the startup log for buffer sizes; wording varies between runtimes and versions.
- Peak versus steady state. Record memory under idle, typical load and worst-case load, over time.
- OOM behaviour and fragmentation evidence. When failures occur, record free memory, the size of the failing allocation and what else was running. Do not assume fragmentation without evidence.
- Prefill and decode metrics. Track time to first token, prompt-processing speed, inter-token latency and tokens per second separately.
- Quality and stability. After any precision or cache change, re-run quality checks and repeated runs. Check for errors, timeouts and out-of-memory events.
Two commands help with items 1 and 9:
nvidia-smi --query-gpu=memory.used,memory.total --format=csv -l 1
gguf-dump model.gguf | grep -iE "block_count|head_count|key_length|sliding|context_length"
The second command assumes a GGUF model file and the gguf Python package. Metadata key names vary by architecture, so adjust the pattern.
16. Conclusion
The KV cache is easy to overlook because it never shows up in the model's parameter count. Yet it determines how long a context you can serve, how many requests you can run at once, how much memory is left for everything else, how fast the first token appears, and in the end what a deployment costs.
The main lessons:
- Model weights are not the whole memory story. The cache grows with every token and every concurrent sequence.
- The size is calculable:
2 × L × C × H_KV × d_head × B, generalised layer by layer for hybrid architectures. - The number of KV heads, not query heads, drives cache size. That is why GQA and MQA matter.
- Configured context, reserved memory, occupied cache and peak usage are four different numbers.
- Allocation policy matters as much as raw size. Static partitioning, unified pools and block-based schemes behave differently under uneven traffic, and block-based allocation reduces waste without removing it.
- Prefix caching turns repeated prefill into reuse, but only for exact token prefixes, and it costs memory to keep.
- Lower precision saves memory but is not automatically faster, and it must be tested for quality.
- Evidence matters. A benchmark summary is not a memory measurement.
17. How to read the evidence labels
Some numbers in this article are measured, some are calculated, and some are just plausible. I tag them so you can tell which is which.
- [VERIFIED]: supported by a source I inspected (a paper, official documentation, or my own research notes).
- [CALCULATED]: derived by arithmetic from assumptions I state explicitly. Not a measurement.
- [REPORTED]: a result supplied to me from a deployment or benchmark that I have not reproduced.
- [HYPOTHESIS]: a plausible explanation that has not been demonstrated.
- [UNKNOWN]: the evidence available is not enough to say.
Important: The worked examples use illustrative model shapes and round numbers. They show how the arithmetic works. They are not benchmark results.
The main source for this article is my own research notes, which were digitised from handwritten pages by OCR. Where the notes contain a slip or an unclear passage, I say so in a Warning note and show the correction. External references are listed at the end and kept separate from the notes.
18. References and Further Reading
Author's research notes (primary source for this article)
- Author's OCR-digitised research notes on LLM inference, memory, attention and quantization (unpublished). Source of the notes-based formulas, the MHA/GQA/MQA example, the block-waste example, the slot example, the context-compaction layers and the analogies. Corrections to the notes are flagged in the text.
Papers
- Vaswani et al. (2017). Attention Is All You Need. arXiv:1706.03762.
- Shazeer (2019). Fast Transformer Decoding: One Write-Head Is All You Need (multi-query attention). arXiv:1911.02150.
- Ainslie et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. arXiv:2305.13245.
- Kwon et al. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. SOSP 2023. arXiv:2309.06180.
- Zheng et al. (2023). SGLang: Efficient Execution of Structured Language Model Programs (RadixAttention). arXiv:2312.07104.
- Dao et al. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135.
- Brandon et al. (2024). Reducing Transformer Key-Value Cache Size with Cross-Layer Attention. arXiv:2405.12981.
- Jiang et al. (2023). Mistral 7B (sliding-window attention). arXiv:2310.06825.
- Gu and Dao (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. arXiv:2312.00752.
- Liu et al. (2024). KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache. arXiv:2402.02750.
- Hooper et al. (2024). KVQuant: Towards 10 Million Context Length LLM Inference with KV Cache Quantization. arXiv:2401.18079.
Official documentation and implementation material
- vLLM documentation, Automatic Prefix Caching (design). https://docs.vllm.ai/en/v0.9.1/design/automatic_prefix_caching.html
- llama.cpp server documentation (parallel slots, unified KV cache, KV-cache types, SWA cache options, prompt checkpoints). https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md
- Anthropic, Prompt caching documentation. https://docs.claude.com/en/docs/build-with-claude/prompt-caching
- NVIDIA, CUDA C++ Programming Guide: CUDA Graphs. https://docs.nvidia.com/cuda/cuda-c-programming-guide/
Secondary and community sources (lower authority; used for cross-checks only)
- Sebastian Raschka, LLM Architecture Gallery: Gemma 4 E4B and KV sharing. https://sebastianraschka.com/llm-architecture-gallery/models/gemma-4-e4b/ and https://sebastianraschka.com/llm-architecture-gallery/kv-sharing/
- Hugging Face model card for a quantized Gemma-4-E4B-IT build, which lists a different sliding/full split (36/6) from the sources above. https://huggingface.co/ariacompute/gemma-4-e4b-it_q8
- llama.cpp discussion #32226 (user-reported decode slowdown with quantized KV and unified cache on CUDA). https://github.com/ggml-org/llama.cpp/discussions/32226